text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "include/flutter/flutter_engine.h"
#include <algorithm>
#include <iostream>
#include "binary_messenger_impl.h"
namespace flutter {
FlutterEngine::FlutterEngine(const DartProject& project) {
FlutterDesktopEngineProperties c_engine_properties = {};
c_engine_properties.assets_path = project.assets_path().c_str();
c_engine_properties.icu_data_path = project.icu_data_path().c_str();
c_engine_properties.aot_library_path = project.aot_library_path().c_str();
c_engine_properties.dart_entrypoint = project.dart_entrypoint().c_str();
const std::vector<std::string>& entrypoint_args =
project.dart_entrypoint_arguments();
std::vector<const char*> entrypoint_argv;
std::transform(
entrypoint_args.begin(), entrypoint_args.end(),
std::back_inserter(entrypoint_argv),
[](const std::string& arg) -> const char* { return arg.c_str(); });
c_engine_properties.dart_entrypoint_argc =
static_cast<int>(entrypoint_argv.size());
c_engine_properties.dart_entrypoint_argv =
entrypoint_argv.empty() ? nullptr : entrypoint_argv.data();
engine_ = FlutterDesktopEngineCreate(&c_engine_properties);
auto core_messenger = FlutterDesktopEngineGetMessenger(engine_);
messenger_ = std::make_unique<BinaryMessengerImpl>(core_messenger);
}
FlutterEngine::~FlutterEngine() {
ShutDown();
}
bool FlutterEngine::Run() {
return Run(nullptr);
}
bool FlutterEngine::Run(const char* entry_point) {
if (!engine_) {
std::cerr << "Cannot run an engine that failed creation." << std::endl;
return false;
}
if (has_been_run_) {
std::cerr << "Cannot run an engine more than once." << std::endl;
return false;
}
bool run_succeeded = FlutterDesktopEngineRun(engine_, entry_point);
if (!run_succeeded) {
std::cerr << "Failed to start engine." << std::endl;
}
has_been_run_ = true;
return run_succeeded;
}
void FlutterEngine::ShutDown() {
if (engine_ && owns_engine_) {
FlutterDesktopEngineDestroy(engine_);
}
engine_ = nullptr;
}
std::chrono::nanoseconds FlutterEngine::ProcessMessages() {
return std::chrono::nanoseconds(FlutterDesktopEngineProcessMessages(engine_));
}
void FlutterEngine::ReloadSystemFonts() {
FlutterDesktopEngineReloadSystemFonts(engine_);
}
FlutterDesktopPluginRegistrarRef FlutterEngine::GetRegistrarForPlugin(
const std::string& plugin_name) {
if (!engine_) {
std::cerr << "Cannot get plugin registrar on an engine that isn't running; "
"call Run first."
<< std::endl;
return nullptr;
}
return FlutterDesktopEngineGetPluginRegistrar(engine_, plugin_name.c_str());
}
void FlutterEngine::SetNextFrameCallback(std::function<void()> callback) {
next_frame_callback_ = std::move(callback);
FlutterDesktopEngineSetNextFrameCallback(
engine_,
[](void* user_data) {
FlutterEngine* self = static_cast<FlutterEngine*>(user_data);
self->next_frame_callback_();
self->next_frame_callback_ = nullptr;
},
this);
}
std::optional<LRESULT> FlutterEngine::ProcessExternalWindowMessage(
HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam) {
LRESULT result;
if (FlutterDesktopEngineProcessExternalWindowMessage(
engine_, hwnd, message, wparam, lparam, &result)) {
return result;
}
return std::nullopt;
}
FlutterDesktopEngineRef FlutterEngine::RelinquishEngine() {
owns_engine_ = false;
return engine_;
}
} // namespace flutter
| engine/shell/platform/windows/client_wrapper/flutter_engine.cc/0 | {
"file_path": "engine/shell/platform/windows/client_wrapper/flutter_engine.cc",
"repo_id": "engine",
"token_count": 1321
} | 422 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include <vector>
#include "flutter/impeller/renderer/backend/gles/gles.h"
#include "flutter/shell/platform/windows/compositor_opengl.h"
#include "flutter/shell/platform/windows/egl/manager.h"
#include "flutter/shell/platform/windows/flutter_windows_view.h"
#include "flutter/shell/platform/windows/testing/egl/mock_context.h"
#include "flutter/shell/platform/windows/testing/egl/mock_manager.h"
#include "flutter/shell/platform/windows/testing/egl/mock_window_surface.h"
#include "flutter/shell/platform/windows/testing/engine_modifier.h"
#include "flutter/shell/platform/windows/testing/flutter_windows_engine_builder.h"
#include "flutter/shell/platform/windows/testing/mock_window_binding_handler.h"
#include "flutter/shell/platform/windows/testing/view_modifier.h"
#include "flutter/shell/platform/windows/testing/windows_test.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
namespace {
using ::testing::AnyNumber;
using ::testing::Return;
const unsigned char* MockGetString(GLenum name) {
switch (name) {
case GL_VERSION:
case GL_SHADING_LANGUAGE_VERSION:
return reinterpret_cast<const unsigned char*>("3.0");
default:
return reinterpret_cast<const unsigned char*>("");
}
}
void MockGetIntegerv(GLenum name, int* value) {
*value = 0;
}
GLenum MockGetError() {
return GL_NO_ERROR;
}
void DoNothing() {}
const impeller::ProcTableGLES::Resolver kMockResolver = [](const char* name) {
std::string function_name{name};
if (function_name == "glGetString") {
return reinterpret_cast<void*>(&MockGetString);
} else if (function_name == "glGetIntegerv") {
return reinterpret_cast<void*>(&MockGetIntegerv);
} else if (function_name == "glGetError") {
return reinterpret_cast<void*>(&MockGetError);
} else {
return reinterpret_cast<void*>(&DoNothing);
}
};
class CompositorOpenGLTest : public WindowsTest {
public:
CompositorOpenGLTest() = default;
virtual ~CompositorOpenGLTest() = default;
protected:
FlutterWindowsEngine* engine() { return engine_.get(); }
FlutterWindowsView* view() { return view_.get(); }
egl::MockManager* egl_manager() { return egl_manager_; }
egl::MockContext* render_context() { return render_context_.get(); }
egl::MockWindowSurface* surface() { return surface_; }
void UseHeadlessEngine() {
auto egl_manager = std::make_unique<egl::MockManager>();
render_context_ = std::make_unique<egl::MockContext>();
egl_manager_ = egl_manager.get();
EXPECT_CALL(*egl_manager_, render_context)
.Times(AnyNumber())
.WillRepeatedly(Return(render_context_.get()));
FlutterWindowsEngineBuilder builder{GetContext()};
engine_ = builder.Build();
EngineModifier modifier{engine_.get()};
modifier.SetEGLManager(std::move(egl_manager));
}
void UseEngineWithView(bool add_surface = true) {
UseHeadlessEngine();
auto window = std::make_unique<MockWindowBindingHandler>();
EXPECT_CALL(*window.get(), SetView).Times(1);
EXPECT_CALL(*window.get(), GetWindowHandle).WillRepeatedly(Return(nullptr));
view_ = std::make_unique<FlutterWindowsView>(kImplicitViewId, engine_.get(),
std::move(window));
if (add_surface) {
auto surface = std::make_unique<egl::MockWindowSurface>();
surface_ = surface.get();
EXPECT_CALL(*surface_, Destroy).Times(AnyNumber());
ViewModifier modifier{view_.get()};
modifier.SetSurface(std::move(surface));
}
EngineModifier modifier{engine_.get()};
modifier.SetImplicitView(view_.get());
}
private:
std::unique_ptr<FlutterWindowsEngine> engine_;
std::unique_ptr<FlutterWindowsView> view_;
std::unique_ptr<egl::MockContext> render_context_;
egl::MockWindowSurface* surface_;
egl::MockManager* egl_manager_;
FML_DISALLOW_COPY_AND_ASSIGN(CompositorOpenGLTest);
};
} // namespace
TEST_F(CompositorOpenGLTest, CreateBackingStore) {
UseHeadlessEngine();
auto compositor = CompositorOpenGL{engine(), kMockResolver};
FlutterBackingStoreConfig config = {};
FlutterBackingStore backing_store = {};
EXPECT_CALL(*render_context(), MakeCurrent).WillOnce(Return(true));
ASSERT_TRUE(compositor.CreateBackingStore(config, &backing_store));
ASSERT_TRUE(compositor.CollectBackingStore(&backing_store));
}
TEST_F(CompositorOpenGLTest, InitializationFailure) {
UseHeadlessEngine();
auto compositor = CompositorOpenGL{engine(), kMockResolver};
FlutterBackingStoreConfig config = {};
FlutterBackingStore backing_store = {};
EXPECT_CALL(*render_context(), MakeCurrent).WillOnce(Return(false));
EXPECT_FALSE(compositor.CreateBackingStore(config, &backing_store));
}
TEST_F(CompositorOpenGLTest, Present) {
UseEngineWithView();
auto compositor = CompositorOpenGL{engine(), kMockResolver};
FlutterBackingStoreConfig config = {};
FlutterBackingStore backing_store = {};
EXPECT_CALL(*render_context(), MakeCurrent).WillOnce(Return(true));
ASSERT_TRUE(compositor.CreateBackingStore(config, &backing_store));
FlutterLayer layer = {};
layer.type = kFlutterLayerContentTypeBackingStore;
layer.backing_store = &backing_store;
const FlutterLayer* layer_ptr = &layer;
EXPECT_CALL(*surface(), IsValid).WillRepeatedly(Return(true));
EXPECT_CALL(*surface(), MakeCurrent).WillOnce(Return(true));
EXPECT_CALL(*surface(), SwapBuffers).WillOnce(Return(true));
EXPECT_TRUE(compositor.Present(view()->view_id(), &layer_ptr, 1));
ASSERT_TRUE(compositor.CollectBackingStore(&backing_store));
}
TEST_F(CompositorOpenGLTest, PresentEmpty) {
UseEngineWithView();
auto compositor = CompositorOpenGL{engine(), kMockResolver};
// The context will be bound twice: first to initialize the compositor, second
// to clear the surface.
EXPECT_CALL(*render_context(), MakeCurrent).WillOnce(Return(true));
EXPECT_CALL(*surface(), IsValid).WillRepeatedly(Return(true));
EXPECT_CALL(*surface(), MakeCurrent).WillOnce(Return(true));
EXPECT_CALL(*surface(), SwapBuffers).WillOnce(Return(true));
EXPECT_TRUE(compositor.Present(view()->view_id(), nullptr, 0));
}
TEST_F(CompositorOpenGLTest, HeadlessPresentIgnored) {
UseHeadlessEngine();
auto compositor = CompositorOpenGL{engine(), kMockResolver};
FlutterBackingStoreConfig config = {};
FlutterBackingStore backing_store = {};
EXPECT_CALL(*render_context(), MakeCurrent).WillOnce(Return(true));
ASSERT_TRUE(compositor.CreateBackingStore(config, &backing_store));
FlutterLayer layer = {};
layer.type = kFlutterLayerContentTypeBackingStore;
layer.backing_store = &backing_store;
const FlutterLayer* layer_ptr = &layer;
EXPECT_FALSE(compositor.Present(kImplicitViewId, &layer_ptr, 1));
ASSERT_TRUE(compositor.CollectBackingStore(&backing_store));
}
TEST_F(CompositorOpenGLTest, UnknownViewIgnored) {
UseEngineWithView();
auto compositor = CompositorOpenGL{engine(), kMockResolver};
FlutterBackingStoreConfig config = {};
FlutterBackingStore backing_store = {};
EXPECT_CALL(*render_context(), MakeCurrent).WillOnce(Return(true));
ASSERT_TRUE(compositor.CreateBackingStore(config, &backing_store));
FlutterLayer layer = {};
layer.type = kFlutterLayerContentTypeBackingStore;
layer.backing_store = &backing_store;
const FlutterLayer* layer_ptr = &layer;
FlutterViewId unknown_view_id = 123;
ASSERT_NE(view()->view_id(), unknown_view_id);
ASSERT_EQ(engine()->view(unknown_view_id), nullptr);
EXPECT_FALSE(compositor.Present(unknown_view_id, &layer_ptr, 1));
ASSERT_TRUE(compositor.CollectBackingStore(&backing_store));
}
TEST_F(CompositorOpenGLTest, NoSurfaceIgnored) {
UseEngineWithView(/*add_surface = */ false);
auto compositor = CompositorOpenGL{engine(), kMockResolver};
FlutterBackingStoreConfig config = {};
FlutterBackingStore backing_store = {};
EXPECT_CALL(*render_context(), MakeCurrent).WillOnce(Return(true));
ASSERT_TRUE(compositor.CreateBackingStore(config, &backing_store));
FlutterLayer layer = {};
layer.type = kFlutterLayerContentTypeBackingStore;
layer.backing_store = &backing_store;
const FlutterLayer* layer_ptr = &layer;
EXPECT_FALSE(compositor.Present(view()->view_id(), &layer_ptr, 1));
ASSERT_TRUE(compositor.CollectBackingStore(&backing_store));
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/windows/compositor_opengl_unittests.cc/0 | {
"file_path": "engine/shell/platform/windows/compositor_opengl_unittests.cc",
"repo_id": "engine",
"token_count": 2967
} | 423 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_EGL_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_EGL_H_
#include <string_view>
namespace flutter {
namespace egl {
/// Log the last EGL error with an error message.
void LogEGLError(std::string_view message);
/// Log the last EGL error.
void LogEGLError(std::string_view file, int line);
#define WINDOWS_LOG_EGL_ERROR LogEGLError(__FILE__, __LINE__);
} // namespace egl
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_EGL_H_
| engine/shell/platform/windows/egl/egl.h/0 | {
"file_path": "engine/shell/platform/windows/egl/egl.h",
"repo_id": "engine",
"token_count": 241
} | 424 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:io' as io;
import 'dart:typed_data' show ByteData, Endian, Uint8List;
import 'dart:ui' as ui;
import 'dart:convert';
// Signals a waiting latch in the native test.
@pragma('vm:external-name', 'Signal')
external void signal();
// Signals a waiting latch in the native test, passing a boolean value.
@pragma('vm:external-name', 'SignalBoolValue')
external void signalBoolValue(bool value);
// Signals a waiting latch in the native test, passing a string value.
@pragma('vm:external-name', 'SignalStringValue')
external void signalStringValue(String value);
// Signals a waiting latch in the native test, which returns a value to the fixture.
@pragma('vm:external-name', 'SignalBoolReturn')
external bool signalBoolReturn();
// Notify the native test that the first frame has been scheduled.
@pragma('vm:external-name', 'NotifyFirstFrameScheduled')
external void notifyFirstFrameScheduled();
void main() {}
@pragma('vm:entry-point')
void hiPlatformChannels() {
ui.channelBuffers.setListener('hi',
(ByteData? data, ui.PlatformMessageResponseCallback callback) async {
ui.PlatformDispatcher.instance.sendPlatformMessage('hi', data,
(ByteData? reply) {
ui.PlatformDispatcher.instance
.sendPlatformMessage('hi', reply, (ByteData? reply) {});
});
callback(data);
});
}
/// Returns a future that completes when
/// `PlatformDispatcher.instance.onSemanticsEnabledChanged` fires.
Future<void> get semanticsChanged {
final Completer<void> semanticsChanged = Completer<void>();
ui.PlatformDispatcher.instance.onSemanticsEnabledChanged =
semanticsChanged.complete;
return semanticsChanged.future;
}
@pragma('vm:entry-point')
void sendAccessibilityAnnouncement() async {
// Wait until semantics are enabled.
if (!ui.PlatformDispatcher.instance.semanticsEnabled) {
await semanticsChanged;
}
// Standard message codec magic number identifiers.
// See: https://github.com/flutter/flutter/blob/ee94fe262b63b0761e8e1f889ae52322fef068d2/packages/flutter/lib/src/services/message_codecs.dart#L262
const int valueMap = 13, valueString = 7;
// Corresponds to: {"type": "announce", "data": {"message": "hello"}}
// See: https://github.com/flutter/flutter/blob/b781da9b5822de1461a769c3b245075359f5464d/packages/flutter/lib/src/semantics/semantics_event.dart#L86
final Uint8List data = Uint8List.fromList([
// Map with 2 entries
valueMap, 2,
// Map key: "type"
valueString, 'type'.length, ...'type'.codeUnits,
// Map value: "announce"
valueString, 'announce'.length, ...'announce'.codeUnits,
// Map key: "data"
valueString, 'data'.length, ...'data'.codeUnits,
// Map value: map with 1 entry
valueMap, 1,
// Map key: "message"
valueString, 'message'.length, ...'message'.codeUnits,
// Map value: "hello"
valueString, 'hello'.length, ...'hello'.codeUnits,
]);
final ByteData byteData = data.buffer.asByteData();
ui.PlatformDispatcher.instance.sendPlatformMessage(
'flutter/accessibility',
byteData,
(ByteData? _) => signal(),
);
}
@pragma('vm:entry-point')
void sendAccessibilityTooltipEvent() async {
// Wait until semantics are enabled.
if (!ui.PlatformDispatcher.instance.semanticsEnabled) {
await semanticsChanged;
}
// Standard message codec magic number identifiers.
// See: https://github.com/flutter/flutter/blob/ee94fe262b63b0761e8e1f889ae52322fef068d2/packages/flutter/lib/src/services/message_codecs.dart#L262
const int valueMap = 13, valueString = 7;
// Corresponds to: {"type": "tooltip", "data": {"message": "hello"}}
// See: https://github.com/flutter/flutter/blob/b781da9b5822de1461a769c3b245075359f5464d/packages/flutter/lib/src/semantics/semantics_event.dart#L120
final Uint8List data = Uint8List.fromList([
// Map with 2 entries
valueMap, 2,
// Map key: "type"
valueString, 'type'.length, ...'type'.codeUnits,
// Map value: "tooltip"
valueString, 'tooltip'.length, ...'tooltip'.codeUnits,
// Map key: "data"
valueString, 'data'.length, ...'data'.codeUnits,
// Map value: map with 1 entry
valueMap, 1,
// Map key: "message"
valueString, 'message'.length, ...'message'.codeUnits,
// Map value: "hello"
valueString, 'hello'.length, ...'hello'.codeUnits,
]);
final ByteData byteData = data.buffer.asByteData();
ui.PlatformDispatcher.instance.sendPlatformMessage(
'flutter/accessibility',
byteData,
(ByteData? _) => signal(),
);
}
@pragma('vm:entry-point')
void exitTestExit() async {
final Completer<ByteData?> closed = Completer<ByteData?>();
ui.channelBuffers.setListener('flutter/platform', (ByteData? data, ui.PlatformMessageResponseCallback callback) async {
final String jsonString = json.encode(<Map<String, String>>[{'response': 'exit'}]);
final ByteData responseData = ByteData.sublistView(utf8.encode(jsonString));
callback(responseData);
closed.complete(data);
});
await closed.future;
}
@pragma('vm:entry-point')
void exitTestCancel() async {
final Completer<ByteData?> closed = Completer<ByteData?>();
ui.channelBuffers.setListener('flutter/platform', (ByteData? data, ui.PlatformMessageResponseCallback callback) async {
final String jsonString = json.encode(<Map<String, String>>[{'response': 'cancel'}]);
final ByteData responseData = ByteData.sublistView(utf8.encode(jsonString));
callback(responseData);
closed.complete(data);
});
await closed.future;
// Because the request was canceled, the below shall execute.
final Completer<ByteData?> exited = Completer<ByteData?>();
final String jsonString = json.encode(<String, dynamic>{
'method': 'System.exitApplication',
'args': <String, dynamic>{
'type': 'required', 'exitCode': 0
}
});
ui.PlatformDispatcher.instance.sendPlatformMessage(
'flutter/platform',
ByteData.sublistView(utf8.encode(jsonString)),
(ByteData? reply) {
exited.complete(reply);
});
await exited.future;
}
@pragma('vm:entry-point')
void enableLifecycleTest() async {
final Completer<ByteData?> finished = Completer<ByteData?>();
ui.channelBuffers.setListener('flutter/lifecycle', (ByteData? data, ui.PlatformMessageResponseCallback callback) async {
if (data != null) {
ui.PlatformDispatcher.instance.sendPlatformMessage(
'flutter/unittest',
data,
(ByteData? reply) {
finished.complete();
});
}
});
await finished.future;
}
@pragma('vm:entry-point')
void enableLifecycleToFrom() async {
ui.channelBuffers.setListener('flutter/lifecycle', (ByteData? data, ui.PlatformMessageResponseCallback callback) async {
if (data != null) {
ui.PlatformDispatcher.instance.sendPlatformMessage(
'flutter/unittest',
data,
(ByteData? reply) {});
}
});
final Completer<ByteData?> enabledLifecycle = Completer<ByteData?>();
ui.PlatformDispatcher.instance.sendPlatformMessage('flutter/platform', ByteData.sublistView(utf8.encode('{"method":"System.initializationComplete"}')), (ByteData? data) {
enabledLifecycle.complete(data);
});
}
@pragma('vm:entry-point')
void sendCreatePlatformViewMethod() async {
// The platform view method channel uses the standard method codec.
// See https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/services/message_codecs.dart#L262
// for the implementation of the encoding and magic number identifiers.
const int valueString = 7;
const int valueMap = 13;
const int valueInt32 = 3;
const String method = 'create';
const String typeKey = 'viewType';
const String typeValue = 'type';
const String idKey = 'id';
final List<int> data = <int>[
// Method name
valueString, method.length, ...utf8.encode(method),
// Method arguments: {'type': 'type':, 'id': 0}
valueMap, 2,
valueString, typeKey.length, ...utf8.encode(typeKey),
valueString, typeValue.length, ...utf8.encode(typeValue),
valueString, idKey.length, ...utf8.encode(idKey),
valueInt32, 0, 0, 0, 0,
];
final Completer<ByteData?> completed = Completer<ByteData?>();
final ByteData bytes = ByteData.sublistView(Uint8List.fromList(data));
ui.PlatformDispatcher.instance.sendPlatformMessage('flutter/platform_views', bytes, (ByteData? response) {
completed.complete(response);
});
await completed.future;
}
@pragma('vm:entry-point')
void customEntrypoint() {}
@pragma('vm:entry-point')
void verifyNativeFunction() {
signal();
}
@pragma('vm:entry-point')
void verifyNativeFunctionWithParameters() {
signalBoolValue(true);
}
@pragma('vm:entry-point')
void verifyNativeFunctionWithReturn() {
bool value = signalBoolReturn();
signalBoolValue(value);
}
@pragma('vm:entry-point')
void readPlatformExecutable() {
signalStringValue(io.Platform.executable);
}
@pragma('vm:entry-point')
void drawHelloWorld() {
ui.PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final ui.ParagraphBuilder paragraphBuilder =
ui.ParagraphBuilder(ui.ParagraphStyle())..addText('Hello world');
final ui.Paragraph paragraph = paragraphBuilder.build();
paragraph.layout(const ui.ParagraphConstraints(width: 800.0));
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Canvas canvas = ui.Canvas(recorder);
canvas.drawParagraph(paragraph, ui.Offset.zero);
final ui.Picture picture = recorder.endRecording();
final ui.SceneBuilder sceneBuilder = ui.SceneBuilder()
..addPicture(ui.Offset.zero, picture)
..pop();
ui.window.render(sceneBuilder.build());
};
ui.PlatformDispatcher.instance.scheduleFrame();
notifyFirstFrameScheduled();
}
| engine/shell/platform/windows/fixtures/main.dart/0 | {
"file_path": "engine/shell/platform/windows/fixtures/main.dart",
"repo_id": "engine",
"token_count": 3460
} | 425 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/windows/flutter_windows_texture_registrar.h"
#include <mutex>
#include "flutter/fml/logging.h"
#include "flutter/shell/platform/embedder/embedder_struct_macros.h"
#include "flutter/shell/platform/windows/external_texture_d3d.h"
#include "flutter/shell/platform/windows/external_texture_pixelbuffer.h"
#include "flutter/shell/platform/windows/flutter_windows_engine.h"
namespace {
static constexpr int64_t kInvalidTexture = -1;
}
namespace flutter {
FlutterWindowsTextureRegistrar::FlutterWindowsTextureRegistrar(
FlutterWindowsEngine* engine,
std::shared_ptr<egl::ProcTable> gl)
: engine_(engine), gl_(std::move(gl)) {}
int64_t FlutterWindowsTextureRegistrar::RegisterTexture(
const FlutterDesktopTextureInfo* texture_info) {
if (!gl_) {
return kInvalidTexture;
}
if (texture_info->type == kFlutterDesktopPixelBufferTexture) {
if (!texture_info->pixel_buffer_config.callback) {
FML_LOG(ERROR) << "Invalid pixel buffer texture callback.";
return kInvalidTexture;
}
return EmplaceTexture(std::make_unique<flutter::ExternalTexturePixelBuffer>(
texture_info->pixel_buffer_config.callback,
texture_info->pixel_buffer_config.user_data, gl_));
} else if (texture_info->type == kFlutterDesktopGpuSurfaceTexture) {
const FlutterDesktopGpuSurfaceTextureConfig* gpu_surface_config =
&texture_info->gpu_surface_config;
auto surface_type = SAFE_ACCESS(gpu_surface_config, type,
kFlutterDesktopGpuSurfaceTypeNone);
if (surface_type == kFlutterDesktopGpuSurfaceTypeDxgiSharedHandle ||
surface_type == kFlutterDesktopGpuSurfaceTypeD3d11Texture2D) {
auto callback = SAFE_ACCESS(gpu_surface_config, callback, nullptr);
if (!callback) {
FML_LOG(ERROR) << "Invalid GPU surface descriptor callback.";
return kInvalidTexture;
}
auto user_data = SAFE_ACCESS(gpu_surface_config, user_data, nullptr);
return EmplaceTexture(std::make_unique<flutter::ExternalTextureD3d>(
surface_type, callback, user_data, engine_->egl_manager(), gl_));
}
}
FML_LOG(ERROR) << "Attempted to register texture of unsupport type.";
return kInvalidTexture;
}
int64_t FlutterWindowsTextureRegistrar::EmplaceTexture(
std::unique_ptr<ExternalTexture> texture) {
int64_t texture_id = texture->texture_id();
{
std::lock_guard<std::mutex> lock(map_mutex_);
textures_[texture_id] = std::move(texture);
}
engine_->task_runner()->RunNowOrPostTask([engine = engine_, texture_id]() {
engine->RegisterExternalTexture(texture_id);
});
return texture_id;
}
void FlutterWindowsTextureRegistrar::UnregisterTexture(int64_t texture_id,
fml::closure callback) {
engine_->task_runner()->RunNowOrPostTask([engine = engine_, texture_id]() {
engine->UnregisterExternalTexture(texture_id);
});
bool posted = engine_->PostRasterThreadTask([this, texture_id, callback]() {
{
std::lock_guard<std::mutex> lock(map_mutex_);
auto it = textures_.find(texture_id);
if (it != textures_.end()) {
textures_.erase(it);
}
}
if (callback) {
callback();
}
});
if (!posted && callback) {
callback();
}
}
bool FlutterWindowsTextureRegistrar::MarkTextureFrameAvailable(
int64_t texture_id) {
engine_->task_runner()->RunNowOrPostTask([engine = engine_, texture_id]() {
engine->MarkExternalTextureFrameAvailable(texture_id);
});
return true;
}
bool FlutterWindowsTextureRegistrar::PopulateTexture(
int64_t texture_id,
size_t width,
size_t height,
FlutterOpenGLTexture* opengl_texture) {
flutter::ExternalTexture* texture;
{
std::lock_guard<std::mutex> lock(map_mutex_);
auto it = textures_.find(texture_id);
if (it == textures_.end()) {
return false;
}
texture = it->second.get();
}
return texture->PopulateTexture(width, height, opengl_texture);
}
}; // namespace flutter
| engine/shell/platform/windows/flutter_windows_texture_registrar.cc/0 | {
"file_path": "engine/shell/platform/windows/flutter_windows_texture_registrar.cc",
"repo_id": "engine",
"token_count": 1570
} | 426 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_KEYBOARD_KEY_HANDLER_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_KEYBOARD_KEY_HANDLER_H_
#include <windows.h>
#include <deque>
#include <map>
#include <memory>
#include <string>
#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/keyboard_handler_base.h"
namespace flutter {
// Handles key events.
//
// This class detects whether an incoming event is a redispatched one,
// dispatches native events to delegates and collect their responses,
// and redispatches events unhandled by Flutter back to the system.
// See |KeyboardHook| for more information about dispatching.
//
// This class owns multiple |KeyboardKeyHandlerDelegate|s, which
// implements the exact behavior to asynchronously handle events. In
// reality, this design is only to support sending events through
// "channel" (RawKeyEvent) and "embedder" (KeyEvent) simultaneously,
// the former of which shall be removed after the deprecation window
// of the RawKeyEvent system.
class KeyboardKeyHandler : public KeyboardHandlerBase {
public:
// An interface for concrete definition of how to asynchronously handle key
// events.
class KeyboardKeyHandlerDelegate {
public:
// Defines how to how to asynchronously handle key events.
//
// |KeyboardHook| should invoke |callback| with the response (whether the
// event is handled) later for exactly once.
virtual void KeyboardHook(int key,
int scancode,
int action,
char32_t character,
bool extended,
bool was_down,
KeyEventCallback callback) = 0;
virtual void SyncModifiersIfNeeded(int modifiers_state) = 0;
virtual std::map<uint64_t, uint64_t> GetPressedState() = 0;
virtual ~KeyboardKeyHandlerDelegate();
};
// Create a |KeyboardKeyHandler| by specifying the messenger
// through which the messages are sent.
explicit KeyboardKeyHandler(flutter::BinaryMessenger* messenger);
~KeyboardKeyHandler();
// Init the keyboard channel used to answer to pressed state queries.
void InitKeyboardChannel();
// Add a delegate that handles events received by |KeyboardHook|.
void AddDelegate(std::unique_ptr<KeyboardKeyHandlerDelegate> delegate);
// Synthesize modifier keys events if needed.
void SyncModifiersIfNeeded(int modifiers_state) override;
// Handles a key event.
//
// Returns whether this handler claims to handle the event, which is true if
// and only if the event is a non-synthesized event.
//
// Windows requires a synchronous response of whether a key event should be
// handled, while the query to Flutter is always asynchronous. This is
// resolved by the "redispatching" algorithm: by default, the response to a
// fresh event is always true. The event is then sent to the framework.
// If the framework later decides not to handle the event, this class will
// create an identical event and dispatch it to the system, and remember all
// synthesized events. The fist time an exact event (by |ComputeEventHash|) is
// received in the future, the new event is considered a synthesized one,
// causing |KeyboardHook| to return false to fall back to other keyboard
// handlers.
//
// Whether a non-synthesized event is considered handled by the framework is
// decided by dispatching the event to all delegates, simultaneously,
// unconditionally, in insertion order, and collecting their responses later.
// It's not supported to prevent any delegates to process the events, because
// in reality this will only support 2 hardcoded delegates, and only to
// continue supporting the legacy API (channel) during the deprecation window,
// after which the channel delegate should be removed.
//
// Inherited from |KeyboardHandlerBase|.
void KeyboardHook(int key,
int scancode,
int action,
char32_t character,
bool extended,
bool was_down,
KeyEventCallback callback) override;
// Returns the keyboard pressed state.
//
// Returns the keyboard pressed state. The dictionary contains one entry per
// pressed keys, mapping from the logical key to the physical key.
std::map<uint64_t, uint64_t> GetPressedState() override;
private:
struct PendingEvent {
// Self-incrementing ID attached to an event sent to the framework.
uint64_t sequence_id;
// The number of delegates that haven't replied.
size_t unreplied;
// Whether any replied delegates reported true (handled).
bool any_handled;
// Where to report the delegates' result to.
//
// Typically a callback provided by KeyboardManager32.
KeyEventCallback callback;
};
void ResolvePendingEvent(uint64_t sequence_id, bool handled);
// Called when a method is called on |channel_|;
void HandleMethodCall(
const flutter::MethodCall<EncodableValue>& method_call,
std::unique_ptr<flutter::MethodResult<EncodableValue>> result);
std::vector<std::unique_ptr<KeyboardKeyHandlerDelegate>> delegates_;
// The queue of key events that have been sent to the framework but have not
// yet received a response.
std::deque<std::unique_ptr<PendingEvent>> pending_responds_;
// The sequence_id attached to the last event sent to the framework.
uint64_t last_sequence_id_;
// The Flutter system channel for keyboard state messages.
std::unique_ptr<flutter::MethodChannel<EncodableValue>> channel_;
FML_DISALLOW_COPY_AND_ASSIGN(KeyboardKeyHandler);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_KEYBOARD_KEY_HANDLER_H_
| engine/shell/platform/windows/keyboard_key_handler.h/0 | {
"file_path": "engine/shell/platform/windows/keyboard_key_handler.h",
"repo_id": "engine",
"token_count": 1969
} | 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.
#include "flutter/shell/platform/windows/sequential_id_generator.h"
namespace flutter {
namespace {
// Removes |key| from |first|, and |first[key]| from |second|.
template <typename T>
void Remove(uint32_t key, T* first, T* second) {
auto iter = first->find(key);
if (iter == first->end())
return;
uint32_t second_key = iter->second;
first->erase(iter);
iter = second->find(second_key);
second->erase(iter);
}
} // namespace
SequentialIdGenerator::SequentialIdGenerator(uint32_t min_id, uint32_t max_id)
: min_id_(min_id), min_available_id_(min_id), max_id_(max_id) {}
SequentialIdGenerator::~SequentialIdGenerator() {}
uint32_t SequentialIdGenerator::GetGeneratedId(uint32_t number) {
auto it = number_to_id_.find(number);
if (it != number_to_id_.end())
return it->second;
auto id = GetNextAvailableId();
number_to_id_.emplace(number, id);
id_to_number_.emplace(id, number);
return id;
}
bool SequentialIdGenerator::HasGeneratedIdFor(uint32_t number) const {
return number_to_id_.find(number) != number_to_id_.end();
}
void SequentialIdGenerator::ReleaseNumber(uint32_t number) {
if (number_to_id_.count(number) > 0U) {
UpdateNextAvailableIdAfterRelease(number_to_id_[number]);
Remove(number, &number_to_id_, &id_to_number_);
}
}
void SequentialIdGenerator::ReleaseId(uint32_t id) {
if (id_to_number_.count(id) > 0U) {
UpdateNextAvailableIdAfterRelease(id);
Remove(id_to_number_[id], &number_to_id_, &id_to_number_);
}
}
uint32_t SequentialIdGenerator::GetNextAvailableId() {
while (id_to_number_.count(min_available_id_) > 0 &&
min_available_id_ < max_id_) {
++min_available_id_;
}
if (min_available_id_ >= max_id_)
min_available_id_ = min_id_;
return min_available_id_;
}
void SequentialIdGenerator::UpdateNextAvailableIdAfterRelease(uint32_t id) {
if (id < min_available_id_) {
min_available_id_ = id;
}
}
} // namespace flutter
| engine/shell/platform/windows/sequential_id_generator.cc/0 | {
"file_path": "engine/shell/platform/windows/sequential_id_generator.cc",
"repo_id": "engine",
"token_count": 800
} | 428 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_EGL_MOCK_PROC_TABLE_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_EGL_MOCK_PROC_TABLE_H_
#include "flutter/fml/macros.h"
#include "flutter/shell/platform/windows/egl/proc_table.h"
#include "gmock/gmock.h"
namespace flutter {
namespace testing {
namespace egl {
/// Mock for the |ProcTable| base class.
class MockProcTable : public ::flutter::egl::ProcTable {
public:
MockProcTable() = default;
virtual ~MockProcTable() = default;
MOCK_METHOD(void,
GenTextures,
(GLsizei n, GLuint* textures),
(const override));
MOCK_METHOD(void,
DeleteTextures,
(GLsizei n, const GLuint* textures),
(const override));
MOCK_METHOD(void,
BindTexture,
(GLenum target, GLuint texture),
(const override));
MOCK_METHOD(void,
TexParameteri,
(GLenum target, GLenum pname, GLint param),
(const override));
MOCK_METHOD(void,
TexImage2D,
(GLenum target,
GLint level,
GLint internalformat,
GLsizei width,
GLsizei height,
GLint border,
GLenum format,
GLenum type,
const void* data),
(const override));
private:
FML_DISALLOW_COPY_AND_ASSIGN(MockProcTable);
};
} // namespace egl
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_EGL_MOCK_PROC_TABLE_H_
| engine/shell/platform/windows/testing/egl/mock_proc_table.h/0 | {
"file_path": "engine/shell/platform/windows/testing/egl/mock_proc_table.h",
"repo_id": "engine",
"token_count": 821
} | 429 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/windows/testing/test_keyboard.h"
#include <rapidjson/document.h>
#include "flutter/fml/logging.h"
#include "flutter/shell/platform/common/json_message_codec.h"
#include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h"
namespace flutter {
namespace testing {
char* clone_string(const char* string) {
if (string == nullptr) {
return nullptr;
}
size_t len = strlen(string);
char* result = new char[len + 1];
strcpy(result, string);
return result;
}
namespace {
std::string _print_character(const char* s) {
if (s == nullptr) {
return "nullptr";
}
return std::string("\"") + s + "\"";
}
std::unique_ptr<std::vector<uint8_t>> _keyHandlingResponse(bool handled) {
rapidjson::Document document;
auto& allocator = document.GetAllocator();
document.SetObject();
document.AddMember("handled", handled, allocator);
return flutter::JsonMessageCodec::GetInstance().EncodeMessage(document);
}
static std::string ordinal(int num) {
switch (num) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
}
} // namespace
#define _RETURN_IF_NOT_EQUALS(val1, val2) \
if ((val1) != (val2)) { \
return ::testing::AssertionFailure() \
<< "Expected equality of these values:\n " #val1 "\n " << val2 \
<< "\n Actual: \n " << val1; \
}
::testing::AssertionResult _EventEquals(const char* expr_event,
const char* expr_expected,
const FlutterKeyEvent& event,
const FlutterKeyEvent& expected) {
_RETURN_IF_NOT_EQUALS(event.struct_size, sizeof(FlutterKeyEvent));
_RETURN_IF_NOT_EQUALS(event.type, expected.type);
_RETURN_IF_NOT_EQUALS(event.physical, expected.physical);
_RETURN_IF_NOT_EQUALS(event.logical, expected.logical);
if ((event.character == nullptr) != (expected.character == nullptr) ||
strcmp(event.character, expected.character) != 0) {
return ::testing::AssertionFailure()
<< "Expected equality of these values:\n expected.character\n "
<< _print_character(expected.character) << "\n Actual: \n "
<< _print_character(event.character);
}
_RETURN_IF_NOT_EQUALS(event.synthesized, expected.synthesized);
return ::testing::AssertionSuccess();
}
LPARAM CreateKeyEventLparam(USHORT scancode,
bool extended,
bool was_down,
USHORT repeat_count,
bool context_code,
bool transition_state) {
return ((LPARAM(transition_state) << 31) | (LPARAM(was_down) << 30) |
(LPARAM(context_code) << 29) | (LPARAM(extended ? 0x1 : 0x0) << 24) |
(LPARAM(scancode) << 16) | LPARAM(repeat_count));
}
static std::shared_ptr<MockKeyResponseController> stored_response_controller;
// Set EngineModifier, listen to event messages that go through the channel and
// the embedder API, while disabling other methods so that the engine can be
// run headlessly.
//
// The |channel_handler| and |embedder_handler| should return a boolean
// indicating whether the framework decides to handle the event.
void MockEmbedderApiForKeyboard(
EngineModifier& modifier,
std::shared_ptr<MockKeyResponseController> response_controller) {
stored_response_controller = response_controller;
// This mock handles channel messages.
modifier.embedder_api()
.SendPlatformMessage = [](FLUTTER_API_SYMBOL(FlutterEngine) engine,
const FlutterPlatformMessage* message) {
if (std::string(message->channel) == std::string("flutter/settings")) {
return kSuccess;
}
if (std::string(message->channel) == std::string("flutter/keyevent")) {
stored_response_controller->HandleChannelMessage([message](bool handled) {
auto response = _keyHandlingResponse(handled);
auto response_handle = message->response_handle;
if (response_handle->callback != nullptr) {
response_handle->callback(response->data(), response->size(),
response_handle->user_data);
}
});
return kSuccess;
}
if (std::string(message->channel) == std::string("flutter/textinput")) {
std::unique_ptr<rapidjson::Document> document =
flutter::JsonMessageCodec::GetInstance().DecodeMessage(
message->message, message->message_size);
if (document == nullptr) {
return kInvalidArguments;
}
stored_response_controller->HandleTextInputMessage(std::move(document));
return kSuccess;
}
return kSuccess;
};
// This mock handles key events sent through the embedder API.
modifier.embedder_api().SendKeyEvent =
[](FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterKeyEvent* event,
FlutterKeyEventCallback callback, void* user_data) {
stored_response_controller->HandleEmbedderMessage(
event, [callback, user_data](bool handled) {
if (callback != nullptr) {
callback(handled, user_data);
}
});
return kSuccess;
};
// The following mocks enable channel mocking.
modifier.embedder_api().PlatformMessageCreateResponseHandle =
[](auto engine, auto data_callback, auto user_data, auto response_out) {
auto response_handle = new FlutterPlatformMessageResponseHandle();
response_handle->user_data = user_data;
response_handle->callback = data_callback;
*response_out = response_handle;
return kSuccess;
};
modifier.embedder_api().PlatformMessageReleaseResponseHandle =
[](FLUTTER_API_SYMBOL(FlutterEngine) engine,
FlutterPlatformMessageResponseHandle* response) {
delete response;
return kSuccess;
};
// The following mock disables responses for method channels sent from the
// embedding to the framework. (No code uses the response yet.)
modifier.embedder_api().SendPlatformMessageResponse =
[](FLUTTER_API_SYMBOL(FlutterEngine) engine,
const FlutterPlatformMessageResponseHandle* handle,
const uint8_t* data, size_t data_length) { return kSuccess; };
// The following mocks allows RunWithEntrypoint to be run, which creates a
// non-empty FlutterEngine and enables SendKeyEvent.
modifier.embedder_api().Run =
[](size_t version, const FlutterRendererConfig* config,
const FlutterProjectArgs* args, void* user_data,
FLUTTER_API_SYMBOL(FlutterEngine) * engine_out) {
*engine_out = reinterpret_cast<FLUTTER_API_SYMBOL(FlutterEngine)>(1);
return kSuccess;
};
// Any time the associated EmbedderEngine will be mocked, such as here,
// the Update accessibility features must not attempt to actually push the
// update
modifier.embedder_api().UpdateAccessibilityFeatures =
[](FLUTTER_API_SYMBOL(FlutterEngine) engine,
FlutterAccessibilityFeature flags) { return kSuccess; };
modifier.embedder_api().UpdateLocales =
[](auto engine, const FlutterLocale** locales, size_t locales_count) {
return kSuccess;
};
modifier.embedder_api().SendWindowMetricsEvent =
[](auto engine, const FlutterWindowMetricsEvent* event) {
return kSuccess;
};
modifier.embedder_api().Shutdown = [](auto engine) { return kSuccess; };
modifier.embedder_api().NotifyDisplayUpdate =
[](auto engine, const FlutterEngineDisplaysUpdateType update_type,
const FlutterEngineDisplay* embedder_displays,
size_t display_count) { return kSuccess; };
}
void MockMessageQueue::PushBack(const Win32Message* message) {
_pending_messages.push_back(*message);
}
LRESULT MockMessageQueue::DispatchFront() {
FML_DCHECK(!_pending_messages.empty())
<< "Called DispatchFront while pending message queue is empty";
Win32Message message = _pending_messages.front();
_pending_messages.pop_front();
_sent_messages.push_back(message);
LRESULT result =
Win32SendMessage(message.message, message.wParam, message.lParam);
if (message.expected_result != kWmResultDontCheck) {
EXPECT_EQ(result, message.expected_result)
<< " This is the " << _sent_messages.size()
<< ordinal(_sent_messages.size()) << " event, with\n " << std::hex
<< "Message 0x" << message.message << " LParam 0x" << message.lParam
<< " WParam 0x" << message.wParam;
}
return result;
}
BOOL MockMessageQueue::Win32PeekMessage(LPMSG lpMsg,
UINT wMsgFilterMin,
UINT wMsgFilterMax,
UINT wRemoveMsg) {
for (auto iter = _pending_messages.begin(); iter != _pending_messages.end();
++iter) {
if (iter->message >= wMsgFilterMin && iter->message <= wMsgFilterMax) {
*lpMsg = MSG{
.message = iter->message,
.wParam = iter->wParam,
.lParam = iter->lParam,
};
if ((wRemoveMsg & PM_REMOVE) == PM_REMOVE) {
_pending_messages.erase(iter);
}
return TRUE;
}
}
return FALSE;
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/windows/testing/test_keyboard.cc/0 | {
"file_path": "engine/shell/platform/windows/testing/test_keyboard.cc",
"repo_id": "engine",
"token_count": 3925
} | 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.
#include "flutter/shell/platform/windows/text_input_plugin.h"
#include <rapidjson/document.h>
#include <windows.h>
#include <memory>
#include "flutter/fml/macros.h"
#include "flutter/shell/platform/common/json_message_codec.h"
#include "flutter/shell/platform/common/json_method_codec.h"
#include "flutter/shell/platform/windows/flutter_windows_view.h"
#include "flutter/shell/platform/windows/testing/engine_modifier.h"
#include "flutter/shell/platform/windows/testing/flutter_windows_engine_builder.h"
#include "flutter/shell/platform/windows/testing/mock_window_binding_handler.h"
#include "flutter/shell/platform/windows/testing/test_binary_messenger.h"
#include "flutter/shell/platform/windows/testing/windows_test.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
namespace {
using ::testing::Return;
static constexpr char kScanCodeKey[] = "scanCode";
static constexpr int kHandledScanCode = 20;
static constexpr int kUnhandledScanCode = 21;
static constexpr char kTextPlainFormat[] = "text/plain";
static constexpr int kDefaultClientId = 42;
// Should be identical to constants in text_input_plugin.cc.
static constexpr char kChannelName[] = "flutter/textinput";
static constexpr char kEnableDeltaModel[] = "enableDeltaModel";
static constexpr char kSetClientMethod[] = "TextInput.setClient";
static constexpr char kAffinityDownstream[] = "TextAffinity.downstream";
static constexpr char kTextKey[] = "text";
static constexpr char kSelectionBaseKey[] = "selectionBase";
static constexpr char kSelectionExtentKey[] = "selectionExtent";
static constexpr char kSelectionAffinityKey[] = "selectionAffinity";
static constexpr char kSelectionIsDirectionalKey[] = "selectionIsDirectional";
static constexpr char kComposingBaseKey[] = "composingBase";
static constexpr char kComposingExtentKey[] = "composingExtent";
static constexpr char kUpdateEditingStateMethod[] =
"TextInputClient.updateEditingState";
static std::unique_ptr<std::vector<uint8_t>> CreateResponse(bool handled) {
auto response_doc =
std::make_unique<rapidjson::Document>(rapidjson::kObjectType);
auto& allocator = response_doc->GetAllocator();
response_doc->AddMember("handled", handled, allocator);
return JsonMessageCodec::GetInstance().EncodeMessage(*response_doc);
}
static std::unique_ptr<rapidjson::Document> EncodedClientConfig(
std::string type_name,
std::string input_action) {
auto arguments = std::make_unique<rapidjson::Document>(rapidjson::kArrayType);
auto& allocator = arguments->GetAllocator();
arguments->PushBack(kDefaultClientId, allocator);
rapidjson::Value config(rapidjson::kObjectType);
config.AddMember("inputAction", input_action, allocator);
config.AddMember(kEnableDeltaModel, false, allocator);
rapidjson::Value type_info(rapidjson::kObjectType);
type_info.AddMember("name", type_name, allocator);
config.AddMember("inputType", type_info, allocator);
arguments->PushBack(config, allocator);
return arguments;
}
static std::unique_ptr<rapidjson::Document> EncodedEditingState(
std::string text,
TextRange selection) {
auto model = std::make_unique<TextInputModel>();
model->SetText(text);
model->SetSelection(selection);
auto arguments = std::make_unique<rapidjson::Document>(rapidjson::kArrayType);
auto& allocator = arguments->GetAllocator();
arguments->PushBack(kDefaultClientId, allocator);
rapidjson::Value editing_state(rapidjson::kObjectType);
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);
int composing_base =
model->composing() ? model->composing_range().base() : -1;
int composing_extent =
model->composing() ? model->composing_range().extent() : -1;
editing_state.AddMember(kComposingBaseKey, composing_base, allocator);
editing_state.AddMember(kComposingExtentKey, composing_extent, allocator);
editing_state.AddMember(kTextKey,
rapidjson::Value(model->GetText(), allocator).Move(),
allocator);
arguments->PushBack(editing_state, allocator);
return arguments;
}
class MockFlutterWindowsView : public FlutterWindowsView {
public:
MockFlutterWindowsView(FlutterWindowsEngine* engine,
std::unique_ptr<WindowBindingHandler> window)
: FlutterWindowsView(kImplicitViewId, engine, std::move(window)) {}
virtual ~MockFlutterWindowsView() = default;
MOCK_METHOD(void, OnCursorRectUpdated, (const Rect&), (override));
MOCK_METHOD(void, OnResetImeComposing, (), (override));
private:
FML_DISALLOW_COPY_AND_ASSIGN(MockFlutterWindowsView);
};
} // namespace
class TextInputPluginTest : public WindowsTest {
public:
TextInputPluginTest() = default;
virtual ~TextInputPluginTest() = default;
protected:
FlutterWindowsEngine* engine() { return engine_.get(); }
MockFlutterWindowsView* view() { return view_.get(); }
MockWindowBindingHandler* window() { return window_; }
void UseHeadlessEngine() {
FlutterWindowsEngineBuilder builder{GetContext()};
engine_ = builder.Build();
}
void UseEngineWithView() {
FlutterWindowsEngineBuilder builder{GetContext()};
auto window = std::make_unique<MockWindowBindingHandler>();
window_ = window.get();
EXPECT_CALL(*window_, SetView).Times(1);
EXPECT_CALL(*window, GetWindowHandle).WillRepeatedly(Return(nullptr));
engine_ = builder.Build();
view_ = std::make_unique<MockFlutterWindowsView>(engine_.get(),
std::move(window));
EngineModifier modifier{engine_.get()};
modifier.SetImplicitView(view_.get());
}
private:
std::unique_ptr<FlutterWindowsEngine> engine_;
std::unique_ptr<MockFlutterWindowsView> view_;
MockWindowBindingHandler* window_;
FML_DISALLOW_COPY_AND_ASSIGN(TextInputPluginTest);
};
TEST_F(TextInputPluginTest, TextMethodsWorksWithEmptyModel) {
UseEngineWithView();
auto handled_message = CreateResponse(true);
auto unhandled_message = CreateResponse(false);
int received_scancode = 0;
TestBinaryMessenger messenger(
[&received_scancode, &handled_message, &unhandled_message](
const std::string& channel, const uint8_t* message,
size_t message_size, BinaryReply reply) {});
int redispatch_scancode = 0;
TextInputPlugin handler(&messenger, engine());
handler.KeyboardHook(VK_RETURN, 100, WM_KEYDOWN, '\n', false, false);
handler.ComposeBeginHook();
std::u16string text;
text.push_back('\n');
handler.ComposeChangeHook(text, 1);
handler.ComposeEndHook();
// Passes if it did not crash
}
TEST_F(TextInputPluginTest, ClearClientResetsComposing) {
UseEngineWithView();
TestBinaryMessenger messenger([](const std::string& channel,
const uint8_t* message, size_t message_size,
BinaryReply reply) {});
BinaryReply reply_handler = [](const uint8_t* reply, size_t reply_size) {};
TextInputPlugin handler(&messenger, engine());
EXPECT_CALL(*view(), OnResetImeComposing());
auto& codec = JsonMethodCodec::GetInstance();
auto message = codec.EncodeMethodCall({"TextInput.clearClient", nullptr});
messenger.SimulateEngineMessage(kChannelName, message->data(),
message->size(), reply_handler);
}
// Verify that clear client fails if in headless mode.
TEST_F(TextInputPluginTest, ClearClientRequiresView) {
UseHeadlessEngine();
TestBinaryMessenger messenger([](const std::string& channel,
const uint8_t* message, size_t message_size,
BinaryReply reply) {});
std::string reply;
BinaryReply reply_handler = [&reply](const uint8_t* reply_bytes,
size_t reply_size) {
reply = std::string(reinterpret_cast<const char*>(reply_bytes), reply_size);
};
TextInputPlugin handler(&messenger, engine());
auto& codec = JsonMethodCodec::GetInstance();
auto message = codec.EncodeMethodCall({"TextInput.clearClient", nullptr});
messenger.SimulateEngineMessage(kChannelName, message->data(),
message->size(), reply_handler);
EXPECT_EQ(reply,
"[\"Internal Consistency Error\",\"Text input is not available in "
"Windows headless mode\",null]");
}
// Verify that the embedder sends state update messages to the framework during
// IME composing.
TEST_F(TextInputPluginTest, VerifyComposingSendStateUpdate) {
UseEngineWithView();
bool sent_message = false;
TestBinaryMessenger messenger(
[&sent_message](const std::string& channel, const uint8_t* message,
size_t message_size,
BinaryReply reply) { sent_message = true; });
BinaryReply reply_handler = [](const uint8_t* reply, size_t reply_size) {};
TextInputPlugin handler(&messenger, engine());
auto& codec = JsonMethodCodec::GetInstance();
// Call TextInput.setClient to initialize the TextInputModel.
auto arguments = std::make_unique<rapidjson::Document>(rapidjson::kArrayType);
auto& allocator = arguments->GetAllocator();
arguments->PushBack(kDefaultClientId, allocator);
rapidjson::Value config(rapidjson::kObjectType);
config.AddMember("inputAction", "done", allocator);
config.AddMember("inputType", "text", allocator);
config.AddMember(kEnableDeltaModel, false, allocator);
arguments->PushBack(config, allocator);
auto message =
codec.EncodeMethodCall({"TextInput.setClient", std::move(arguments)});
messenger.SimulateEngineMessage("flutter/textinput", message->data(),
message->size(), reply_handler);
// ComposeBeginHook should send state update.
sent_message = false;
handler.ComposeBeginHook();
EXPECT_TRUE(sent_message);
// ComposeChangeHook should send state update.
sent_message = false;
handler.ComposeChangeHook(u"4", 1);
EXPECT_TRUE(sent_message);
// ComposeCommitHook should NOT send state update.
//
// Commit messages are always immediately followed by a change message or an
// end message, both of which will send an update. Sending intermediate state
// with a collapsed composing region will trigger the framework to assume
// composing has ended, which is not the case until a WM_IME_ENDCOMPOSING
// event is received in the main event loop, which will trigger a call to
// ComposeEndHook.
sent_message = false;
handler.ComposeCommitHook();
EXPECT_FALSE(sent_message);
// ComposeEndHook should send state update.
sent_message = false;
handler.ComposeEndHook();
EXPECT_TRUE(sent_message);
}
TEST_F(TextInputPluginTest, VerifyInputActionNewlineInsertNewLine) {
UseEngineWithView();
// Store messages as std::string for convenience.
std::vector<std::string> messages;
TestBinaryMessenger messenger(
[&messages](const std::string& channel, const uint8_t* message,
size_t message_size, BinaryReply reply) {
std::string last_message(reinterpret_cast<const char*>(message),
message_size);
messages.push_back(last_message);
});
BinaryReply reply_handler = [](const uint8_t* reply, size_t reply_size) {};
TextInputPlugin handler(&messenger, engine());
auto& codec = JsonMethodCodec::GetInstance();
// Call TextInput.setClient to initialize the TextInputModel.
auto set_client_arguments =
EncodedClientConfig("TextInputType.multiline", "TextInputAction.newline");
auto message = codec.EncodeMethodCall(
{"TextInput.setClient", std::move(set_client_arguments)});
messenger.SimulateEngineMessage("flutter/textinput", message->data(),
message->size(), reply_handler);
// Simulate a key down event for '\n'.
handler.KeyboardHook(VK_RETURN, 100, WM_KEYDOWN, '\n', false, false);
// Two messages are expected, the first is TextInput.updateEditingState and
// the second is TextInputClient.performAction.
EXPECT_EQ(messages.size(), 2);
// Editing state should have been updated.
auto encoded_arguments = EncodedEditingState("\n", TextRange(1));
auto update_state_message = codec.EncodeMethodCall(
{kUpdateEditingStateMethod, std::move(encoded_arguments)});
EXPECT_TRUE(std::equal(update_state_message->begin(),
update_state_message->end(),
messages.front().begin()));
// TextInputClient.performAction should have been called.
auto arguments = std::make_unique<rapidjson::Document>(rapidjson::kArrayType);
auto& allocator = arguments->GetAllocator();
arguments->PushBack(kDefaultClientId, allocator);
arguments->PushBack(
rapidjson::Value("TextInputAction.newline", allocator).Move(), allocator);
auto invoke_action_message = codec.EncodeMethodCall(
{"TextInputClient.performAction", std::move(arguments)});
EXPECT_TRUE(std::equal(invoke_action_message->begin(),
invoke_action_message->end(),
messages.back().begin()));
}
// Regression test for https://github.com/flutter/flutter/issues/125879.
TEST_F(TextInputPluginTest, VerifyInputActionSendDoesNotInsertNewLine) {
UseEngineWithView();
std::vector<std::vector<uint8_t>> messages;
TestBinaryMessenger messenger(
[&messages](const std::string& channel, const uint8_t* message,
size_t message_size, BinaryReply reply) {
int length = static_cast<int>(message_size);
std::vector<uint8_t> last_message(length);
memcpy(&last_message[0], &message[0], length * sizeof(uint8_t));
messages.push_back(last_message);
});
BinaryReply reply_handler = [](const uint8_t* reply, size_t reply_size) {};
TextInputPlugin handler(&messenger, engine());
auto& codec = JsonMethodCodec::GetInstance();
// Call TextInput.setClient to initialize the TextInputModel.
auto set_client_arguments =
EncodedClientConfig("TextInputType.multiline", "TextInputAction.send");
auto message = codec.EncodeMethodCall(
{"TextInput.setClient", std::move(set_client_arguments)});
messenger.SimulateEngineMessage("flutter/textinput", message->data(),
message->size(), reply_handler);
// Simulate a key down event for '\n'.
handler.KeyboardHook(VK_RETURN, 100, WM_KEYDOWN, '\n', false, false);
// Only a call to TextInputClient.performAction is expected.
EXPECT_EQ(messages.size(), 1);
// TextInputClient.performAction should have been called.
auto arguments = std::make_unique<rapidjson::Document>(rapidjson::kArrayType);
auto& allocator = arguments->GetAllocator();
arguments->PushBack(kDefaultClientId, allocator);
arguments->PushBack(
rapidjson::Value("TextInputAction.send", allocator).Move(), allocator);
auto invoke_action_message = codec.EncodeMethodCall(
{"TextInputClient.performAction", std::move(arguments)});
EXPECT_TRUE(std::equal(invoke_action_message->begin(),
invoke_action_message->end(),
messages.front().begin()));
}
TEST_F(TextInputPluginTest, TextEditingWorksWithDeltaModel) {
UseEngineWithView();
auto handled_message = CreateResponse(true);
auto unhandled_message = CreateResponse(false);
int received_scancode = 0;
TestBinaryMessenger messenger(
[&received_scancode, &handled_message, &unhandled_message](
const std::string& channel, const uint8_t* message,
size_t message_size, BinaryReply reply) {});
int redispatch_scancode = 0;
TextInputPlugin handler(&messenger, engine());
auto args = std::make_unique<rapidjson::Document>(rapidjson::kArrayType);
auto& allocator = args->GetAllocator();
args->PushBack(123, allocator); // client_id
rapidjson::Value client_config(rapidjson::kObjectType);
client_config.AddMember(kEnableDeltaModel, true, allocator);
args->PushBack(client_config, allocator);
auto encoded = JsonMethodCodec::GetInstance().EncodeMethodCall(
MethodCall<rapidjson::Document>(kSetClientMethod, std::move(args)));
EXPECT_TRUE(messenger.SimulateEngineMessage(
kChannelName, encoded->data(), encoded->size(),
[](const uint8_t* reply, size_t reply_size) {}));
handler.KeyboardHook(VK_RETURN, 100, WM_KEYDOWN, '\n', false, false);
handler.ComposeBeginHook();
std::u16string text;
text.push_back('\n');
handler.ComposeChangeHook(text, 1);
handler.ComposeEndHook();
handler.KeyboardHook(0x4E, 100, WM_KEYDOWN, 'n', false, false);
handler.ComposeBeginHook();
std::u16string textN;
text.push_back('n');
handler.ComposeChangeHook(textN, 1);
handler.KeyboardHook(0x49, 100, WM_KEYDOWN, 'i', false, false);
std::u16string textNi;
text.push_back('n');
text.push_back('i');
handler.ComposeChangeHook(textNi, 2);
handler.KeyboardHook(VK_RETURN, 100, WM_KEYDOWN, '\n', false, false);
std::u16string textChineseCharacter;
text.push_back(u'\u4F60');
handler.ComposeChangeHook(textChineseCharacter, 1);
handler.ComposeCommitHook();
handler.ComposeEndHook();
// Passes if it did not crash
}
// Regression test for https://github.com/flutter/flutter/issues/123749
TEST_F(TextInputPluginTest, CompositionCursorPos) {
UseEngineWithView();
int selection_base = -1;
TestBinaryMessenger messenger([&](const std::string& channel,
const uint8_t* message, size_t size,
BinaryReply reply) {
auto method = JsonMethodCodec::GetInstance().DecodeMethodCall(
std::vector<uint8_t>(message, message + size));
if (method->method_name() == kUpdateEditingStateMethod) {
const auto& args = *method->arguments();
const auto& editing_state = args[1];
auto base = editing_state.FindMember(kSelectionBaseKey);
auto extent = editing_state.FindMember(kSelectionExtentKey);
ASSERT_NE(base, editing_state.MemberEnd());
ASSERT_TRUE(base->value.IsInt());
ASSERT_NE(extent, editing_state.MemberEnd());
ASSERT_TRUE(extent->value.IsInt());
selection_base = base->value.GetInt();
EXPECT_EQ(extent->value.GetInt(), selection_base);
}
});
TextInputPlugin plugin(&messenger, engine());
auto args = std::make_unique<rapidjson::Document>(rapidjson::kArrayType);
auto& allocator = args->GetAllocator();
args->PushBack(123, allocator); // client_id
rapidjson::Value client_config(rapidjson::kObjectType);
args->PushBack(client_config, allocator);
auto encoded = JsonMethodCodec::GetInstance().EncodeMethodCall(
MethodCall<rapidjson::Document>(kSetClientMethod, std::move(args)));
EXPECT_TRUE(messenger.SimulateEngineMessage(
kChannelName, encoded->data(), encoded->size(),
[](const uint8_t* reply, size_t reply_size) {}));
plugin.ComposeBeginHook();
EXPECT_EQ(selection_base, 0);
plugin.ComposeChangeHook(u"abc", 3);
EXPECT_EQ(selection_base, 3);
plugin.ComposeCommitHook();
plugin.ComposeEndHook();
EXPECT_EQ(selection_base, 3);
plugin.ComposeBeginHook();
plugin.ComposeChangeHook(u"1", 1);
EXPECT_EQ(selection_base, 4);
plugin.ComposeChangeHook(u"12", 2);
EXPECT_EQ(selection_base, 5);
plugin.ComposeChangeHook(u"12", 1);
EXPECT_EQ(selection_base, 4);
plugin.ComposeChangeHook(u"12", 2);
EXPECT_EQ(selection_base, 5);
}
TEST_F(TextInputPluginTest, TransformCursorRect) {
UseEngineWithView();
// A position of `EditableText`.
double view_x = 100;
double view_y = 200;
// A position and size of marked text, in `EditableText` local coordinates.
double ime_x = 3;
double ime_y = 4;
double ime_width = 50;
double ime_height = 60;
// Transformation matrix.
std::array<std::array<double, 4>, 4> editabletext_transform = {
1.0, 0.0, 0.0, view_x, //
0.0, 1.0, 0.0, view_y, //
0.0, 0.0, 0.0, 0.0, //
0.0, 0.0, 0.0, 1.0};
TestBinaryMessenger messenger([](const std::string& channel,
const uint8_t* message, size_t message_size,
BinaryReply reply) {});
BinaryReply reply_handler = [](const uint8_t* reply, size_t reply_size) {};
TextInputPlugin handler(&messenger, engine());
auto& codec = JsonMethodCodec::GetInstance();
EXPECT_CALL(*view(), OnCursorRectUpdated(Rect{{view_x, view_y}, {0, 0}}));
{
auto arguments =
std::make_unique<rapidjson::Document>(rapidjson::kObjectType);
auto& allocator = arguments->GetAllocator();
rapidjson::Value transoform(rapidjson::kArrayType);
for (int i = 0; i < 4 * 4; i++) {
// Pack 2-dimensional array by column-major order.
transoform.PushBack(editabletext_transform[i % 4][i / 4], allocator);
}
arguments->AddMember("transform", transoform, allocator);
auto message = codec.EncodeMethodCall(
{"TextInput.setEditableSizeAndTransform", std::move(arguments)});
messenger.SimulateEngineMessage(kChannelName, message->data(),
message->size(), reply_handler);
}
EXPECT_CALL(*view(),
OnCursorRectUpdated(Rect{{view_x + ime_x, view_y + ime_y},
{ime_width, ime_height}}));
{
auto arguments =
std::make_unique<rapidjson::Document>(rapidjson::kObjectType);
auto& allocator = arguments->GetAllocator();
arguments->AddMember("x", ime_x, allocator);
arguments->AddMember("y", ime_y, allocator);
arguments->AddMember("width", ime_width, allocator);
arguments->AddMember("height", ime_height, allocator);
auto message = codec.EncodeMethodCall(
{"TextInput.setMarkedTextRect", std::move(arguments)});
messenger.SimulateEngineMessage(kChannelName, message->data(),
message->size(), reply_handler);
}
}
TEST_F(TextInputPluginTest, SetMarkedTextRectRequiresView) {
UseHeadlessEngine();
TestBinaryMessenger messenger([](const std::string& channel,
const uint8_t* message, size_t message_size,
BinaryReply reply) {});
std::string reply;
BinaryReply reply_handler = [&reply](const uint8_t* reply_bytes,
size_t reply_size) {
reply = std::string(reinterpret_cast<const char*>(reply_bytes), reply_size);
};
TextInputPlugin handler(&messenger, engine());
auto& codec = JsonMethodCodec::GetInstance();
auto arguments =
std::make_unique<rapidjson::Document>(rapidjson::kObjectType);
auto& allocator = arguments->GetAllocator();
arguments->AddMember("x", 0, allocator);
arguments->AddMember("y", 0, allocator);
arguments->AddMember("width", 0, allocator);
arguments->AddMember("height", 0, allocator);
auto message = codec.EncodeMethodCall(
{"TextInput.setMarkedTextRect", std::move(arguments)});
messenger.SimulateEngineMessage(kChannelName, message->data(),
message->size(), reply_handler);
EXPECT_EQ(reply,
"[\"Internal Consistency Error\",\"Text input is not available in "
"Windows headless mode\",null]");
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/windows/text_input_plugin_unittest.cc/0 | {
"file_path": "engine/shell/platform/windows/text_input_plugin_unittest.cc",
"repo_id": "engine",
"token_count": 8578
} | 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.
#ifndef FLUTTER_SHELL_PROFILING_SAMPLING_PROFILER_H_
#define FLUTTER_SHELL_PROFILING_SAMPLING_PROFILER_H_
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include "flutter/fml/synchronization/count_down_latch.h"
#include "flutter/fml/task_runner.h"
#include "flutter/fml/trace_event.h"
namespace flutter {
/**
* @brief CPU usage stats. `num_threads` is the number of threads owned by the
* process. It is to be noted that this is not per shell, there can be multiple
* shells within the process. `total_cpu_usage` is the percentage (between [0,
* 100]) cpu usage of the application. This is across all the cores, for example
* an application using 100% of all the core will report `total_cpu_usage` as
* `100`, if it has 100% across 2 cores and 0% across the other cores, embedder
* must report `total_cpu_usage` as `50`.
*/
struct CpuUsageInfo {
uint32_t num_threads;
double total_cpu_usage;
};
/**
* @brief Memory usage stats. `dirty_memory_usage` is the memory usage (in
* MB) such that the app uses its physical memory for dirty memory. Dirty memory
* is the memory data that cannot be paged to disk. `owned_shared_memory_usage`
* is the memory usage (in MB) such that the app uses its physical memory for
* shared memory, including loaded frameworks and executables. On iOS, it's
* `physical memory - dirty memory`.
*/
struct MemoryUsageInfo {
double dirty_memory_usage;
double owned_shared_memory_usage;
};
/**
* @brief Polled information related to the usage of the GPU.
*/
struct GpuUsageInfo {
double percent_usage;
};
/**
* @brief Container for the metrics we collect during each run of `Sampler`.
* This currently holds `CpuUsageInfo` and `MemoryUsageInfo` but the intent
* is to expand it to other metrics.
*
* @see flutter::Sampler
*/
struct ProfileSample {
std::optional<CpuUsageInfo> cpu_usage;
std::optional<MemoryUsageInfo> memory_usage;
std::optional<GpuUsageInfo> gpu_usage;
};
/**
* @brief Sampler is run during `SamplingProfiler::SampleRepeatedly`. Each
* platform should implement its version of a `Sampler` if they decide to
* participate in gathering profiling metrics.
*
* @see flutter::SamplingProfiler::SampleRepeatedly
*/
using Sampler = std::function<ProfileSample(void)>;
/**
* @brief a Sampling Profiler that runs peridically and calls the `Sampler`
* which servers as a value function to gather various profiling metrics as
* represented by `ProfileSample`. These profiling metrics are then posted to
* the Dart VM Service timeline.
*
*/
class SamplingProfiler {
public:
/**
* @brief Construct a new Sampling Profiler object
*
* @param thread_label Dart VM Service prefix to be set for the profiling task
* runner.
* @param profiler_task_runner the task runner to service sampling requests.
* @param sampler the value function to collect the profiling metrics.
* @param num_samples_per_sec number of times you wish to run the sampler per
* second.
*
* @see fml::TaskRunner
*/
SamplingProfiler(const char* thread_label,
fml::RefPtr<fml::TaskRunner> profiler_task_runner,
Sampler sampler,
int num_samples_per_sec);
~SamplingProfiler();
/**
* @brief Starts the SamplingProfiler by triggering `SampleRepeatedly`.
*
*/
void Start();
void Stop();
private:
const std::string thread_label_;
const fml::RefPtr<fml::TaskRunner> profiler_task_runner_;
const Sampler sampler_;
const uint32_t num_samples_per_sec_;
bool is_running_ = false;
std::atomic<fml::AutoResetWaitableEvent*> shutdown_latch_ = nullptr;
void SampleRepeatedly(fml::TimeDelta task_delay) const;
/**
* @brief This doesn't update the underlying OS thread name for the thread
* backing `profiler_task_runner_`. Instead, this is just additional metadata
* for the VM Service to show the thread name of the isolate.
*
*/
void UpdateDartVMServiceThreadName() const;
FML_DISALLOW_COPY_AND_ASSIGN(SamplingProfiler);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PROFILING_SAMPLING_PROFILER_H_
| engine/shell/profiling/sampling_profiler.h/0 | {
"file_path": "engine/shell/profiling/sampling_profiler.h",
"repo_id": "engine",
"token_count": 1363
} | 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.
flutter_defines = [
# Flutter always wants this https://github.com/flutter/flutter/issues/11402
"SK_ENABLE_DUMP_GPU",
# Remove software rasterizers to save some code size.
"SK_FORCE_AAA",
# Staging
"SK_LEGACY_IGNORE_DRAW_VERTICES_BLEND_WITH_NO_SHADER",
"SK_DISABLE_LEGACY_GRDIRECTCONTEXT_BOOLS",
"SK_DISABLE_LEGACY_GRDIRECTCONTEXT_FLUSH",
"SK_RESOLVE_FILTERS_BEFORE_RESTORE",
# Fast low-precision software rendering isn't a priority for Flutter.
"SK_DISABLE_LEGACY_SHADERCONTEXT",
"SK_DISABLE_LOWP_RASTER_PIPELINE",
"SK_FORCE_RASTER_PIPELINE_BLITTER",
# When running Metal, ensure that command buffers are scheduled before
# returning from submit.
"SK_METAL_WAIT_UNTIL_SCHEDULED",
# Staging for b/305780908
"SK_DEFAULT_TYPEFACE_IS_EMPTY",
"SK_DISABLE_LEGACY_DEFAULT_TYPEFACE",
"SK_DISABLE_LEGACY_FONTMGR_FACTORY",
"SK_DISABLE_LEGACY_FONTMGR_REFDEFAULT",
]
if (!is_fuchsia) {
flutter_defines += [ "SK_DISABLE_EFFECT_DESERIALIZATION" ]
}
| engine/skia/flutter_defines.gni/0 | {
"file_path": "engine/skia/flutter_defines.gni",
"repo_id": "engine",
"token_count": 457
} | 433 |
name: sky_engine
version: 0.0.99
author: Flutter Authors <[email protected]>
description: Dart SDK extensions for dart:ui
homepage: http://flutter.io
# sky_engine requires sdk_ext support in the analyzer which was added in 1.11.x
environment:
sdk: '>=3.2.0-0 <4.0.0'
| engine/sky/packages/sky_engine/pubspec.yaml/0 | {
"file_path": "engine/sky/packages/sky_engine/pubspec.yaml",
"repo_id": "engine",
"token_count": 102
} | 434 |
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="dev.flutter.testing.{{apk-library-name}}"
android:versionCode="1"
android:versionName="1.0"
>
<uses-sdk android:minSdkVersion="23"/>
<application android:hasCode="false">
<activity android:name="android.app.NativeActivity"
android:configChanges="orientation|keyboardHidden"
android:exported="true">
<meta-data android:name="android.app.lib_name"
android:value="{{apk-library-name}}" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
| engine/testing/android/native_activity/AndroidManifest.xml.template/0 | {
"file_path": "engine/testing/android/native_activity/AndroidManifest.xml.template",
"repo_id": "engine",
"token_count": 325
} | 435 |
apply plugin: 'com.android.application'
android {
namespace 'dev.flutter.android_background_image'
lintOptions {
abortOnError true
checkAllWarnings true
showAll true
warningsAsErrors true
checkTestSources true
htmlReport false
xmlReport true
xmlOutput file("${rootProject.buildDir}/reports/lint-results.xml")
// UnpackedNativeCode can break stack unwinding - see b/193408481
// NewerVersionAvailable and GradleDependency need to be taken care of
// by a roller rather than as part of CI.
// The others are irrelevant for a test application.
disable 'UnpackedNativeCode','MissingApplicationIcon','GoogleAppIndexingApiWarning','GoogleAppIndexingWarning','GradleDependency','NewerVersionAvailable'
}
buildToolsVersion = '34.0.0'
compileSdkVersion 34
compileOptions {
sourceCompatibility JavaVersion.VERSION_11
targetCompatibility JavaVersion.VERSION_11
}
defaultConfig {
applicationId 'dev.flutter.android_background_image'
minSdkVersion 21
targetSdkVersion 34
versionCode 1
versionName '1.0'
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
sourceSets.main {
assets.srcDirs += "${project.buildDir}/assets"
if (project.hasProperty('libapp')) {
jni.srcDirs = []
jniLibs.srcDirs = [project.property('libapp')]
}
}
}
dependencies {
// Please *don't* add embedding dependencies to this file.
// The embedding dependencies are configured in tools/androidx/files.json.
// Only add test dependencies.
implementation files(project.property('flutter_jar'))
}
// Configure the embedding dependencies.
apply from: new File(rootDir, '../../../tools/androidx/configure.gradle').absolutePath;
configureDependencies(new File(rootDir, '../../..')) { dependency ->
dependencies {
implementation "$dependency"
}
}
| engine/testing/android_background_image/android/app/build.gradle/0 | {
"file_path": "engine/testing/android_background_image/android/app/build.gradle",
"repo_id": "engine",
"token_count": 812
} | 436 |
# Running and Processing DisplayList Benchmarks
The DisplayList benchmarks for Flutter are used to determine the relative
cost of operations in order to assign scores to each op for the raster
cache’s cache admission algorithm.
Due to the nature of benchmarking, these need to be run on actual devices in
order to get representative results, and because of the more locked-down
nature of the iOS and Android platforms it’s a little involved getting the
benchmark suite to run.
This document will detail the steps involved in getting the benchmarks to run
on both iOS and Android, and how to process the resulting data.
## iOS
iOS does not allow you to run unsigned code or arbitrary executables, so the
approach here is to build a dylib that contains the benchmarking code which
will then be linked to a skeleton test app in Xcode. The dylib contains an
exported C function, void RunBenchmarks(int argc, char **argv) that should
be called from the skeleton test app to run the benchmarks.
The dylib is not built by default and it will need to be specified as a
target manually when calling ninja.
The target name is ios_display_list_benchmarks, e.g.:
$ ninja -C out/ios_profile ios_display_list_benchmarks
Once that dylib exists, the IosBenchmarks test app in flutter/testing/ios can
be loaded in Xcode. Ensure that the team is set appropriately so the code can
be signed and that FLUTTER_ENGINE matches the Flutter Engine build you wish to
use (e.g. ios_profile).
Once that is done, you can just hit the Run button and the JSON output will be
sent to the Xcode console. Copy that elsewhere and save it as a .json file.
Note: you may need to delete some errors from the console output that are
unrelated to the JSON output.
## Android
On Android, even on non-rooted devices, it is possible to execute unsigned
binaries using adb. As a result, there is a build target that will build a
binary that can be pushed to device using adb and executed using adb shell.
The only caveat is that the binary needs to be on a volume that isn’t mounted
as noexec, which typically rules out the sd card. /data/local/tmp seems like
an option that is typically available.
The build target is called display_list_benchmarks and will create a binary
called display_list_benchmarks in the root output directory
(e.g. android_profile_arm64).
$ adb push out/android_profile_arm64/display_list_benchmarks /data/local/tmp/display_list_benchmarks
$ adb shell /data/local/tmp/display_list_benchmarks --benchmark_format=json | tee android-results.json
The results in android-results.json can then be processed.
## Processing Results
There is a script in flutter/testing/benchmark called
displaylist_benchmark_parser.py which will take the JSON file and output a PDF
with graphs of all the benchmark series, as well as a CSV that can be imported
into a spreadsheet for further analysis.
This can then be manually analysed to determine the relative weightings for the
raster cache’s cache admission algorithm. | engine/testing/benchmark/README_displaylist.md/0 | {
"file_path": "engine/testing/benchmark/README_displaylist.md",
"repo_id": "engine",
"token_count": 773
} | 437 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui';
import 'package:litetest/litetest.dart';
class NotAColor extends Color {
const NotAColor(super.value);
}
void main() {
test('color accessors should work', () {
const Color foo = Color(0x12345678);
expect(foo.alpha, equals(0x12));
expect(foo.red, equals(0x34));
expect(foo.green, equals(0x56));
expect(foo.blue, equals(0x78));
});
test('paint set to black', () {
const Color c = Color(0x00000000);
final Paint p = Paint();
p.color = c;
expect(c.toString(), equals('Color(0x00000000)'));
});
test('color created with out of bounds value', () {
const Color c = Color(0x100 << 24);
final Paint p = Paint();
p.color = c;
});
test('color created with wildly out of bounds value', () {
const Color c = Color(1 << 1000000);
final Paint p = Paint();
p.color = c;
});
test('two colors are only == if they have the same runtime type', () {
expect(const Color(0x12345678), equals(const Color(0x12345678)));
expect(const Color(0x12345678), equals(Color(0x12345678))); // ignore: prefer_const_constructors
expect(const Color(0x12345678), notEquals(const Color(0x87654321)));
expect(const Color(0x12345678), notEquals(const NotAColor(0x12345678)));
expect(const NotAColor(0x12345678), notEquals(const Color(0x12345678)));
expect(const NotAColor(0x12345678), equals(const NotAColor(0x12345678)));
});
test('Color.lerp', () {
expect(
Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), 0.0),
const Color(0x00000000),
);
expect(
Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), 0.5),
const Color(0x7F7F7F7F),
);
expect(
Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), 1.0),
const Color(0xFFFFFFFF),
);
expect(
Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), -0.1),
const Color(0x00000000),
);
expect(
Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), 1.1),
const Color(0xFFFFFFFF),
);
// Prevent regression: https://github.com/flutter/flutter/issues/67423
expect(
Color.lerp(const Color(0xFFFFFFFF), const Color(0xFFFFFFFF), 0.04),
const Color(0xFFFFFFFF),
);
});
test('Color.alphaBlend', () {
expect(
Color.alphaBlend(const Color(0x00000000), const Color(0x00000000)),
const Color(0x00000000),
);
expect(
Color.alphaBlend(const Color(0x00000000), const Color(0xFFFFFFFF)),
const Color(0xFFFFFFFF),
);
expect(
Color.alphaBlend(const Color(0xFFFFFFFF), const Color(0x00000000)),
const Color(0xFFFFFFFF),
);
expect(
Color.alphaBlend(const Color(0xFFFFFFFF), const Color(0xFFFFFFFF)),
const Color(0xFFFFFFFF),
);
expect(
Color.alphaBlend(const Color(0x80FFFFFF), const Color(0xFF000000)),
const Color(0xFF808080),
);
expect(
Color.alphaBlend(const Color(0x80808080), const Color(0xFFFFFFFF)),
const Color(0xFFBFBFBF),
);
expect(
Color.alphaBlend(const Color(0x80808080), const Color(0xFF000000)),
const Color(0xFF404040),
);
expect(
Color.alphaBlend(const Color(0x01020304), const Color(0xFF000000)),
const Color(0xFF000000),
);
expect(
Color.alphaBlend(const Color(0x11223344), const Color(0xFF000000)),
const Color(0xFF020304),
);
expect(
Color.alphaBlend(const Color(0x11223344), const Color(0x80000000)),
const Color(0x88040608),
);
});
test('compute gray luminance', () {
// Each color component is at 20%.
const Color lightGray = Color(0xFF333333);
// Relative luminance's formula is just the linearized color value for gray.
// ((0.2 + 0.055) / 1.055) ^ 2.4.
expect(lightGray.computeLuminance(), equals(0.033104766570885055));
});
test('compute color luminance', () {
const Color brightRed = Color(0xFFFF3B30);
// 0.2126 * ((1.0 + 0.055) / 1.055) ^ 2.4 +
// 0.7152 * ((0.23137254902 +0.055) / 1.055) ^ 2.4 +
// 0.0722 * ((0.18823529411 + 0.055) / 1.055) ^ 2.4
expect(brightRed.computeLuminance(), equals(0.24601329637099723));
});
}
| engine/testing/dart/color_test.dart/0 | {
"file_path": "engine/testing/dart/color_test.dart",
"repo_id": "engine",
"token_count": 1775
} | 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:async';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';
import 'package:litetest/litetest.dart';
import 'package:path/path.dart' as path;
void main() {
bool assertsEnabled = false;
assert(() {
assertsEnabled = true;
return true;
}());
test('no resize by default', () async {
final Uint8List bytes = await readFile('2x2.png');
final Codec codec = await instantiateImageCodec(bytes);
final FrameInfo frame = await codec.getNextFrame();
final int codecHeight = frame.image.height;
final int codecWidth = frame.image.width;
expect(codecHeight, 2);
expect(codecWidth, 2);
});
test('resize width with constrained height', () async {
final Uint8List bytes = await readFile('2x2.png');
final Codec codec = await instantiateImageCodec(bytes, targetHeight: 1);
final FrameInfo frame = await codec.getNextFrame();
final int codecHeight = frame.image.height;
final int codecWidth = frame.image.width;
expect(codecHeight, 1);
expect(codecWidth, 1);
});
test('resize height with constrained width', () async {
final Uint8List bytes = await readFile('2x2.png');
final Codec codec = await instantiateImageCodec(bytes, targetWidth: 1);
final FrameInfo frame = await codec.getNextFrame();
final int codecHeight = frame.image.height;
final int codecWidth = frame.image.width;
expect(codecHeight, 1);
expect(codecWidth, 1);
});
test('upscale image by 5x', () async {
final Uint8List bytes = await readFile('2x2.png');
final Codec codec = await instantiateImageCodec(bytes, targetWidth: 10);
final FrameInfo frame = await codec.getNextFrame();
final int codecHeight = frame.image.height;
final int codecWidth = frame.image.width;
expect(codecHeight, 10);
expect(codecWidth, 10);
});
test('upscale image by 5x - no upscaling', () async {
final Uint8List bytes = await readFile('2x2.png');
final Codec codec = await instantiateImageCodec(bytes, targetWidth: 10, allowUpscaling: false);
final FrameInfo frame = await codec.getNextFrame();
final int codecHeight = frame.image.height;
final int codecWidth = frame.image.width;
expect(codecHeight, 2);
expect(codecWidth, 2);
});
test('upscale image varying width and height', () async {
final Uint8List bytes = await readFile('2x2.png');
final Codec codec =
await instantiateImageCodec(bytes, targetWidth: 10, targetHeight: 1);
final FrameInfo frame = await codec.getNextFrame();
final int codecHeight = frame.image.height;
final int codecWidth = frame.image.width;
expect(codecHeight, 1);
expect(codecWidth, 10);
});
test('upscale image varying width and height - no upscaling', () async {
final Uint8List bytes = await readFile('2x2.png');
final Codec codec =
await instantiateImageCodec(bytes, targetWidth: 10, targetHeight: 1, allowUpscaling: false);
final FrameInfo frame = await codec.getNextFrame();
final int codecHeight = frame.image.height;
final int codecWidth = frame.image.width;
expect(codecHeight, 1);
expect(codecWidth, 2);
});
test('pixels: no resize by default', () async {
final BlackSquare blackSquare = BlackSquare.create();
final Image resized = await blackSquare.resize();
expect(resized.height, blackSquare.height);
expect(resized.width, blackSquare.width);
});
test('pixels: resize width with constrained height', () async {
final BlackSquare blackSquare = BlackSquare.create();
final Image resized = await blackSquare.resize(targetHeight: 1);
expect(resized.height, 1);
expect(resized.width, 1);
});
test('pixels: resize height with constrained width', () async {
final BlackSquare blackSquare = BlackSquare.create();
final Image resized = await blackSquare.resize(targetWidth: 1);
expect(resized.height, 1);
expect(resized.width, 1);
});
test('pixels: upscale image by 5x', () async {
final BlackSquare blackSquare = BlackSquare.create();
final Image resized = await blackSquare.resize(targetWidth: 10, allowUpscaling: true);
expect(resized.height, 10);
expect(resized.width, 10);
});
test('pixels: upscale image by 5x - no upscaling', () async {
final BlackSquare blackSquare = BlackSquare.create();
bool threw = false;
try {
decodeImageFromPixels(
blackSquare.pixels,
blackSquare.width,
blackSquare.height,
PixelFormat.rgba8888,
(Image image) {},
targetHeight: 10,
allowUpscaling: false,
);
} catch (e) {
expect(e is AssertionError, true);
threw = true;
}
expect(threw, true);
}, skip: !assertsEnabled);
test('pixels: upscale image varying width and height', () async {
final BlackSquare blackSquare = BlackSquare.create();
final Image resized =
await blackSquare.resize(targetHeight: 1, targetWidth: 10, allowUpscaling: true);
expect(resized.height, 1);
expect(resized.width, 10);
});
test('pixels: upscale image varying width and height - no upscaling', () async {
final BlackSquare blackSquare = BlackSquare.create();
bool threw = false;
try {
decodeImageFromPixels(
blackSquare.pixels,
blackSquare.width,
blackSquare.height,
PixelFormat.rgba8888,
(Image image) {},
targetHeight: 10,
targetWidth: 1,
allowUpscaling: false,
);
} catch (e) {
expect(e is AssertionError, true);
threw = true;
}
expect(threw, true);
}, skip: !assertsEnabled);
test('pixels: large negative dimensions', () async {
final BlackSquare blackSquare = BlackSquare.create();
final Image resized = await blackSquare.resize(targetHeight: -100, targetWidth: -99999);
expect(resized.height, 2);
expect(resized.width, 2);
});
}
class BlackSquare {
BlackSquare._(this.width, this.height, this.pixels);
factory BlackSquare.create({int width = 2, int height = 2}) {
final Uint8List pixels =
Uint8List.fromList(List<int>.filled(width * height * 4, 0));
return BlackSquare._(width, height, pixels);
}
Future<Image> resize({int? targetWidth, int? targetHeight, bool allowUpscaling = false}) async {
final Completer<Image> imageCompleter = Completer<Image>();
decodeImageFromPixels(
pixels,
width,
height,
PixelFormat.rgba8888,
(Image image) => imageCompleter.complete(image),
targetHeight: targetHeight,
targetWidth: targetWidth,
allowUpscaling: allowUpscaling,
);
return imageCompleter.future;
}
final int width;
final int height;
final Uint8List pixels;
}
Future<Uint8List> readFile(String fileName) async {
final File file =
File(path.join('flutter', 'testing', 'resources', fileName));
return file.readAsBytes();
}
| engine/testing/dart/image_resize_test.dart/0 | {
"file_path": "engine/testing/dart/image_resize_test.dart",
"repo_id": "engine",
"token_count": 2467
} | 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:ui';
import 'package:litetest/litetest.dart';
void main() {
test('Should be able to build and layout a paragraph', () {
final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle());
builder.addText('Hello');
final Paragraph paragraph = builder.build();
expect(paragraph, isNotNull);
paragraph.layout(const ParagraphConstraints(width: 800.0));
expect(paragraph.width, isNonZero);
expect(paragraph.height, isNonZero);
});
test('PushStyle should not segfault after build()', () {
final ParagraphBuilder paragraphBuilder =
ParagraphBuilder(ParagraphStyle());
paragraphBuilder.build();
expect(() { paragraphBuilder.pushStyle(TextStyle()); }, throwsStateError);
});
test('GetRectsForRange smoke test', () {
final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle());
builder.addText('Hello');
final Paragraph paragraph = builder.build();
expect(paragraph, isNotNull);
paragraph.layout(const ParagraphConstraints(width: 800.0));
expect(paragraph.width, isNonZero);
expect(paragraph.height, isNonZero);
final List<TextBox> boxes = paragraph.getBoxesForRange(0, 3);
expect(boxes.length, 1);
expect(boxes.first.left, 0.0);
expect(boxes.first.top, 0.0);
expect(boxes.first.right, 42.0);
expect(boxes.first.bottom, 14.0);
expect(boxes.first.direction, TextDirection.ltr);
});
test('LineMetrics smoke test', () {
final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle());
builder.addText('Hello');
final Paragraph paragraph = builder.build();
expect(paragraph, isNotNull);
paragraph.layout(const ParagraphConstraints(width: 800.0));
expect(paragraph.width, isNonZero);
expect(paragraph.height, isNonZero);
final List<LineMetrics> metrics = paragraph.computeLineMetrics();
expect(metrics.length, 1);
expect(metrics.first.hardBreak, true);
expect(metrics.first.ascent, 10.5);
expect(metrics.first.descent, 3.5);
expect(metrics.first.unscaledAscent, 10.5);
expect(metrics.first.height, 14.0);
expect(metrics.first.width, 70.0);
expect(metrics.first.left, 0.0);
expect(metrics.first.baseline, 10.5);
expect(metrics.first.lineNumber, 0);
});
}
| engine/testing/dart/paragraph_builder_test.dart/0 | {
"file_path": "engine/testing/dart/paragraph_builder_test.dart",
"repo_id": "engine",
"token_count": 825
} | 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:async';
import 'package:litetest/litetest.dart';
void main() {
test('Message loop flushes microtasks between iterations', () async {
final List<int> tasks = <int>[];
tasks.add(1);
// Flush 0 microtasks.
await Future<void>.delayed(Duration.zero);
scheduleMicrotask(() {
tasks.add(3);
});
scheduleMicrotask(() {
tasks.add(4);
});
tasks.add(2);
// Flush 2 microtasks.
await Future<void>.delayed(Duration.zero);
scheduleMicrotask(() {
tasks.add(6);
});
scheduleMicrotask(() {
tasks.add(7);
});
scheduleMicrotask(() {
tasks.add(8);
});
tasks.add(5);
// Flush 3 microtasks.
await Future<void>.delayed(Duration.zero);
tasks.add(9);
expect(tasks, <int>[1, 2, 3, 4, 5, 6, 7, 8, 9]);
});
}
| engine/testing/dart/task_order_test.dart/0 | {
"file_path": "engine/testing/dart/task_order_test.dart",
"repo_id": "engine",
"token_count": 400
} | 441 |
#!/usr/bin/env vpython3
# [VPYTHON:BEGIN]
# python_version: "3.8"
# wheel <
# name: "infra/python/wheels/pyyaml/${platform}_${py_python}_${py_abi}"
# version: "version:5.4.1.chromium.1"
# >
# [VPYTHON:END]
# 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 argparse
import logging
import os
import sys
from subprocess import CompletedProcess
from typing import Any, Iterable, List, Mapping, NamedTuple, Set
# The import is coming from vpython wheel and pylint cannot find it.
import yaml # pylint: disable=import-error
# The imports are coming from fuchsia/test_scripts and pylint cannot find them
# without setting a global init-hook which is less favorable.
# But this file will be executed as part of the CI, its correctness of importing
# is guaranteed.
sys.path.insert(
0, os.path.join(os.path.dirname(__file__), '../../tools/fuchsia/test_scripts/test/')
)
# pylint: disable=import-error, wrong-import-position
import run_test
from common import DIR_SRC_ROOT
from run_executable_test import ExecutableTestRunner
from test_runner import TestRunner
if len(sys.argv) == 2:
VARIANT = sys.argv[1]
sys.argv.pop()
elif len(sys.argv) == 1:
VARIANT = 'fuchsia_debug_x64'
else:
assert False, 'Expect only one parameter as the compile output directory.'
OUT_DIR = os.path.join(DIR_SRC_ROOT, 'out', VARIANT)
# Visible for testing
class TestCase(NamedTuple):
package: str
args: str = ''
class _BundledTestRunner(TestRunner):
# private, use bundled_test_runner_of function instead.
def __init__(self, target_id: str, package_deps: Set[str], tests: List[TestCase], logs_dir: str):
super().__init__(OUT_DIR, [], None, target_id, list(package_deps))
self.tests = tests
self.logs_dir = logs_dir
def run_test(self) -> CompletedProcess:
returncode = 0
for test in self.tests:
assert test.package.endswith('.cm')
test_runner = ExecutableTestRunner(
OUT_DIR, test.args.split(), test.package, self._target_id, None, self.logs_dir, [], None
)
# pylint: disable=protected-access
test_runner._package_deps = self._package_deps
result = test_runner.run_test().returncode
logging.info('Result of test %s is %s', test, result)
if result != 0:
returncode = result
return CompletedProcess(args='', returncode=returncode)
# Visible for testing
def resolve_packages(tests: Iterable[Mapping[str, Any]]) -> Set[str]:
packages = set()
for test in tests:
if 'package' in test:
packages.add(test['package'])
else:
assert 'packages' in test, \
'Expect either one package or a list of packages'
packages.update(test['packages'])
resolved_packages = set()
for package in packages:
if package.endswith('-0.far'):
# Make a symbolic link to match the name of the package itself without the
# '-0.far' suffix.
new_package = os.path.join(OUT_DIR, package.replace('-0.far', '.far'))
try:
# Remove the old one if it exists, usually happen on the devbox, so
# ignore the FileNotFoundError.
os.remove(new_package)
except FileNotFoundError:
pass
os.symlink(package, new_package)
resolved_packages.add(new_package)
else:
resolved_packages.add(os.path.join(OUT_DIR, package))
return resolved_packages
# Visible for testing
def build_test_cases(tests: Iterable[Mapping[str, Any]]) -> List[TestCase]:
test_cases = []
for test in [t['test_command'] for t in tests]:
assert test.startswith('test run ')
test = test[len('test run '):]
if ' -- ' in test:
package, args = test.split(' -- ', 1)
test_cases.append(TestCase(package=package, args=args))
else:
test_cases.append(TestCase(package=test))
return test_cases
def _bundled_test_runner_of(target_id: str) -> _BundledTestRunner:
log_dir = os.environ.get('FLUTTER_LOGS_DIR', '/tmp/log')
with open(os.path.join(os.path.dirname(__file__), 'test_suites.yaml'), 'r') as file:
tests = yaml.safe_load(file)
# TODO(zijiehe-google-com): Run all tests in release build,
# https://github.com/flutter/flutter/issues/140179.
def variant(test) -> bool:
return 'variant' not in test or test['variant'] in VARIANT
tests = [t for t in tests if variant(t)]
return _BundledTestRunner(target_id, resolve_packages(tests), build_test_cases(tests), log_dir)
def _get_test_runner(runner_args: argparse.Namespace, *_) -> TestRunner:
return _bundled_test_runner_of(runner_args.target_id)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
logging.info('Running tests in %s', OUT_DIR)
sys.argv.append('--out-dir=' + OUT_DIR)
if VARIANT.endswith('_arm64'):
sys.argv.append('--product=terminal.qemu-arm64')
# The 'flutter-test-type' is a place holder and has no specific meaning; the
# _get_test_runner is overrided.
sys.argv.append('flutter-test-type')
run_test._get_test_runner = _get_test_runner # pylint: disable=protected-access
sys.exit(run_test.main())
| engine/testing/fuchsia/run_tests.py/0 | {
"file_path": "engine/testing/fuchsia/run_tests.py",
"repo_id": "engine",
"token_count": 1910
} | 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 'src/test_suite.dart';
export 'package:async_helper/async_minitest.dart' hide test;
export 'package:expect/expect.dart';
export 'src/matchers.dart';
final TestSuite _testSuite = TestSuite();
/// Describes the test named [name] given by the function [body].
///
/// After all tests are described, they will be run. All calls to [test] must be
/// made in the same event as the program's `main()` function.
void test(
String name,
dynamic Function() body, {
bool skip = false,
}) {
_testSuite.test(name, body, skip: skip);
}
| engine/testing/litetest/lib/litetest.dart/0 | {
"file_path": "engine/testing/litetest/lib/litetest.dart",
"repo_id": "engine",
"token_count": 224
} | 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.
package dev.flutter.scenariosui;
import android.app.Instrumentation;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import androidx.annotation.NonNull;
import androidx.test.filters.LargeTest;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.rule.ActivityTestRule;
import androidx.test.runner.AndroidJUnit4;
import dev.flutter.scenarios.PlatformViewsActivity;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
@LargeTest
public class PlatformTextureUiTests {
private Instrumentation instrumentation;
private Intent intent;
@Rule @NonNull
public ActivityTestRule<PlatformViewsActivity> activityRule =
new ActivityTestRule<>(
PlatformViewsActivity.class, /*initialTouchMode=*/ false, /*launchActivity=*/ false);
private static String goldName(String suffix) {
return "PlatformTextureUiTests_" + suffix;
}
@Before
public void setUp() {
instrumentation = InstrumentationRegistry.getInstrumentation();
intent = new Intent(Intent.ACTION_MAIN);
// Render a texture.
intent.putExtra("use_android_view", false);
intent.putExtra("view_type", PlatformViewsActivity.TEXT_VIEW_PV);
}
@Test
public void testPlatformView() throws Exception {
intent.putExtra("scenario_name", "platform_view");
ScreenshotUtil.capture(activityRule.launchActivity(intent), goldName("testPlatformView"));
}
@Test
public void testPlatformViewMultiple() throws Exception {
intent.putExtra("scenario_name", "platform_view_multiple");
ScreenshotUtil.capture(
activityRule.launchActivity(intent), goldName("testPlatformViewMultiple"));
}
@Test
public void testPlatformViewMultipleBackgroundForeground() throws Exception {
intent.putExtra("scenario_name", "platform_view_multiple_background_foreground");
ScreenshotUtil.capture(
activityRule.launchActivity(intent),
goldName("testPlatformViewMultipleBackgroundForeground"));
}
@Test
public void testPlatformViewCliprect() throws Exception {
intent.putExtra("scenario_name", "platform_view_cliprect");
ScreenshotUtil.capture(
activityRule.launchActivity(intent), goldName("testPlatformViewCliprect"));
}
@Test
public void testPlatformViewCliprrect() throws Exception {
intent.putExtra("scenario_name", "platform_view_cliprrect");
ScreenshotUtil.capture(
activityRule.launchActivity(intent), goldName("testPlatformViewCliprrect"));
}
@Test
public void testPlatformViewClippath() throws Exception {
intent.putExtra("scenario_name", "platform_view_clippath");
ScreenshotUtil.capture(
activityRule.launchActivity(intent), goldName("testPlatformViewClippath"));
}
@Test
public void testPlatformViewTransform() throws Exception {
intent.putExtra("scenario_name", "platform_view_transform");
ScreenshotUtil.capture(
activityRule.launchActivity(intent), goldName("testPlatformViewTransform"));
}
@Test
public void testPlatformViewOpacity() throws Exception {
intent.putExtra("scenario_name", "platform_view_opacity");
ScreenshotUtil.capture(
activityRule.launchActivity(intent), goldName("testPlatformViewOpacity"));
}
@Test
public void testPlatformViewRotate() throws Exception {
intent.putExtra("scenario_name", "platform_view_rotate");
PlatformViewsActivity activity = activityRule.launchActivity(intent);
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
instrumentation.waitForIdleSync();
ScreenshotUtil.capture(activity, goldName("testPlatformViewRotate"));
}
@Test
public void testPlatformViewMultipleWithoutOverlays() throws Exception {
intent.putExtra("scenario_name", "platform_view_multiple_without_overlays");
ScreenshotUtil.capture(
activityRule.launchActivity(intent), goldName("testPlatformViewMultipleWithoutOverlays"));
}
@Test
public void testPlatformViewTwoIntersectingOverlays() throws Exception {
intent.putExtra("scenario_name", "platform_view_two_intersecting_overlays");
ScreenshotUtil.capture(
activityRule.launchActivity(intent), goldName("testPlatformViewTwoIntersectingOverlays"));
}
@Test
public void testPlatformViewWithoutOverlayIntersection() throws Exception {
intent.putExtra("scenario_name", "platform_view_no_overlay_intersection");
ScreenshotUtil.capture(
activityRule.launchActivity(intent),
goldName("testPlatformViewWithoutOverlayIntersection"));
}
}
| engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/PlatformTextureUiTests.java/0 | {
"file_path": "engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/PlatformTextureUiTests.java",
"repo_id": "engine",
"token_count": 1507
} | 444 |
# Scenario App Android Test Runner
This directory contains code specific to running Android integration tests.
The tests are uploaded and run on the device using `adb`, and screenshots are
captured and compared using Skia Gold (if available, for example on CI).
See [running the tests](../android/README.md#running-the-tests) for more information.
| engine/testing/scenario_app/bin/README.md/0 | {
"file_path": "engine/testing/scenario_app/bin/README.md",
"repo_id": "engine",
"token_count": 84
} | 445 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>arm64</string>
</array>
<key>UIRequiresFullScreen</key>
<true/>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>FLTEnableImpeller</key>
<false/>
</dict>
</plist>
| engine/testing/scenario_app/ios/Scenarios/Scenarios/Info.plist/0 | {
"file_path": "engine/testing/scenario_app/ios/Scenarios/Scenarios/Info.plist",
"repo_id": "engine",
"token_count": 591
} | 446 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <XCTest/XCTest.h>
@interface ScenariosTests : XCTestCase
@end
@implementation ScenariosTests
- (void)setUp {
// Put setup code here. This method is called before the invocation of each test method in the
// class.
}
- (void)tearDown {
// Put teardown code here. This method is called after the invocation of each test method in the
// class.
}
- (void)testExample {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
- (void)testPerformanceExample {
// This is an example of a performance test case.
[self measureBlock:^{
// Put the code you want to measure the time of here.
}];
}
@end
| engine/testing/scenario_app/ios/Scenarios/ScenariosTests/ScenariosTests.m/0 | {
"file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosTests/ScenariosTests.m",
"repo_id": "engine",
"token_count": 265
} | 447 |
// Copyright 2020 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "GoldenPlatformViewTests.h"
@interface SpawnEngineTest : XCTestCase
@end
@implementation SpawnEngineTest
- (void)testSpawnEngineWorks {
self.continueAfterFailure = NO;
XCUIApplication* application = [[XCUIApplication alloc] init];
application.launchArguments = @[ @"--spawn-engine-works" ];
[application launch];
XCUIElement* addTextField = application.textFields[@"ready"];
XCTAssertTrue([addTextField waitForExistenceWithTimeout:30]);
GoldenTestManager* manager =
[[GoldenTestManager alloc] initWithLaunchArg:@"--spawn-engine-works"];
[manager checkGoldenForTest:self rmesThreshold:kDefaultRmseThreshold];
}
@end
| engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/SpawnEngineTest.m/0 | {
"file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/SpawnEngineTest.m",
"repo_id": "engine",
"token_count": 250
} | 448 |
// This is a stub file used to create App.framework for JIT mode.
__attribute__((unused)) static const int kMoo = 88;
| engine/testing/scenario_app/ios/app_stub.c/0 | {
"file_path": "engine/testing/scenario_app/ios/app_stub.c",
"repo_id": "engine",
"token_count": 35
} | 449 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui';
import 'channel_util.dart';
import 'scenario.dart';
/// A scenario that sends back messages when touches are received.
class TouchesScenario extends Scenario {
/// Constructor for `TouchesScenario`.
TouchesScenario(super.view);
final Map<int, int> _knownDevices = <int, int>{};
int _sequenceNo = 0;
@override
void onBeginFrame(Duration duration) {
// It is necessary to render frames for touch events to work properly on iOS
final Scene scene = SceneBuilder().build();
view.render(scene);
scene.dispose();
}
@override
void onPointerDataPacket(PointerDataPacket packet) {
for (final PointerData datum in packet.data) {
final int deviceId =
_knownDevices.putIfAbsent(datum.device, () => _knownDevices.length);
sendJsonMessage(
dispatcher: view.platformDispatcher,
channel: 'display_data',
json: <String, dynamic>{
'data': '$_sequenceNo,${datum.change},device=$deviceId,buttons=${datum.buttons},signalKind=${datum.signalKind}',
},
);
_sequenceNo++;
}
}
}
| engine/testing/scenario_app/lib/src/touches_scenario.dart/0 | {
"file_path": "engine/testing/scenario_app/lib/src/touches_scenario.dart",
"repo_id": "engine",
"token_count": 452
} | 450 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_TESTING_TEST_METAL_CONTEXT_H_
#define FLUTTER_TESTING_TEST_METAL_CONTEXT_H_
#include <map>
#include <mutex>
#include "third_party/skia/include/gpu/GrDirectContext.h"
#include "third_party/skia/include/ports/SkCFObject.h"
namespace flutter {
class TestMetalContext {
public:
struct TextureInfo {
int64_t texture_id;
void* texture;
};
TestMetalContext();
~TestMetalContext();
void* GetMetalDevice() const;
void* GetMetalCommandQueue() const;
sk_sp<GrDirectContext> GetSkiaContext() const;
/// Returns texture_id = -1 when texture creation fails.
TextureInfo CreateMetalTexture(const SkISize& size);
bool Present(int64_t texture_id);
TextureInfo GetTextureInfo(int64_t texture_id);
private:
void* device_;
void* command_queue_;
sk_sp<GrDirectContext> skia_context_;
std::mutex textures_mutex_;
int64_t texture_id_ctr_ = 1; // guarded by textures_mutex
std::map<int64_t, sk_cfp<void*>> textures_; // guarded by textures_mutex
};
} // namespace flutter
#endif // FLUTTER_TESTING_TEST_METAL_CONTEXT_H_
| engine/testing/test_metal_context.h/0 | {
"file_path": "engine/testing/test_metal_context.h",
"repo_id": "engine",
"token_count": 451
} | 451 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//build/compiled_action.gni")
import("//flutter/build/dart/rules.gni")
import("//flutter/common/config.gni")
is_aot_test =
flutter_runtime_mode == "profile" || flutter_runtime_mode == "release"
# Build unit tests when any of the following are true:
# * host_toolchain: non-cross-compile, so we can run tests on the host.
# * is_mac: arm64 builds can run x64 binaries.
# * is_fuchsia: build unittests for testing on device.
declare_args() {
enable_unittests = current_toolchain == host_toolchain || is_fuchsia || is_mac
}
# Creates a translation unit that defines the flutter::testing::GetFixturesPath
# method that tests can use to locate their fixtures.
#
# Arguments
# assets_dir (required): The assets directory
template("fixtures_location") {
testonly = true
assert(defined(invoker.assets_dir), "The assets directory.")
location_path = rebase_path(invoker.assets_dir)
testing_assets_path = rebase_path("$root_out_dir/gen/flutter/testing/assets")
source_path = rebase_path("//")
# Array of source lines. We use a list to ensure a trailing newline is
# emitted by write_file() to comply with -Wnewline-eof.
location_source = [
"namespace flutter { namespace testing { ",
"const char* GetSourcePath() {return \"$source_path\";} ",
"const char* GetFixturesPath() {return \"$location_path\";} ",
"const char* GetTestingAssetsPath() {return \"$testing_assets_path\";} ",
"}}",
]
location_source_path = "$target_gen_dir/_fl_$target_name.cc"
write_file(location_source_path, location_source)
source_set(target_name) {
public = []
sources = [ location_source_path ]
}
}
# Generates the Dart kernel snapshot.
#
# Arguments
# dart_main (required): The Main Dart file.
#
# dart_kernel (required): The path to the output kernel snapshot in the out
# directory.
template("dart_snapshot_kernel") {
testonly = true
assert(defined(invoker.dart_main), "The Dart Main file must be specified")
assert(defined(invoker.dart_kernel),
"The Dart Kernel file location must be specified")
args = []
if (flutter_runtime_mode == "release" ||
flutter_runtime_mode == "jit_release") {
args += [ "-Ddart.vm.product=true" ]
}
if (is_aot_test) {
args += [
"--aot",
# type flow analysis
"--tfa",
]
}
flutter_frontend_server(target_name) {
testonly = true
main_dart = invoker.dart_main
kernel_output = invoker.dart_kernel
extra_args = args
}
}
# Generates an AOT snapshot from a kernel snapshot.
#
# Arguments:
#
# dart_kernel (required): The path to the kernel snapshot.
#
# dart_elf_filename (required): The filename of the AOT ELF snapshot.
template("dart_snapshot_aot") {
testonly = true
assert(defined(invoker.dart_kernel),
"The Dart Kernel file location must be specified")
assert(defined(invoker.dart_elf_filename),
"The main Dart ELF filename must be specified.")
compiled_action(target_name) {
testonly = true
tool = "$dart_src/runtime/bin:gen_snapshot"
pool = "//flutter/build/dart:dart_pool"
inputs = [ invoker.dart_kernel ]
# Custom ELF loader is used for Mac and Windows.
elf_object = "$target_gen_dir/assets/${invoker.dart_elf_filename}"
loading_unit_manifest = "$target_gen_dir/assets/loading_unit_manifest.json"
outputs = [ elf_object ]
args = [
"--deterministic",
"--snapshot_kind=app-aot-elf",
"--loading_unit_manifest=" + rebase_path(loading_unit_manifest),
"--elf=" + rebase_path(elf_object),
rebase_path(invoker.dart_kernel),
]
forward_variables_from(invoker, [ "deps" ])
}
}
# Generates a kernel or AOT snapshot as necessary from the main Dart file.
# Other Dart dependencies referenced by that main Dart file will be tracked.
#
# Arguments:
#
# dart_main (required): The path to the main Dart file.
#
# dart_kernel_filename (required): The filename of the kernel blob.
#
# dart_elf_filename (required): The filename of the AOT ELF snapshot only if is_aot_test is true.
template("dart_snapshot") {
assert(defined(invoker.dart_main), "The main Dart file must be specified.")
assert(defined(invoker.dart_kernel_filename),
"The main Dart kernel filename must be specified.")
testonly = true
dart_snapshot_kernel_target_name = "_dsk_$target_name"
dart_snapshot_kernel_path =
"$target_gen_dir/assets/${invoker.dart_kernel_filename}"
dart_snapshot_kernel(dart_snapshot_kernel_target_name) {
dart_main = invoker.dart_main
dart_kernel = dart_snapshot_kernel_path
}
snapshot_deps = []
snapshot_public_deps = [ ":$dart_snapshot_kernel_target_name" ]
if (is_aot_test) {
assert(defined(invoker.dart_elf_filename),
"The main Dart ELF filename must be specified.")
dart_snapshot_aot_target_name = "_dsa_$target_name"
dart_snapshot_aot(dart_snapshot_aot_target_name) {
dart_kernel = dart_snapshot_kernel_path
dart_elf_filename = invoker.dart_elf_filename
deps = [ ":$dart_snapshot_kernel_target_name" ]
}
snapshot_deps += [ ":$dart_snapshot_aot_target_name" ]
}
group(target_name) {
testonly = true
deps = snapshot_deps
public_deps = snapshot_public_deps
}
}
# Copies a (potentially empty) list of fixtures to the fixtures directory for
# the unit test.
#
# Arguments:
#
# fixtures (required): The list of fixtures to copy.
#
# dest (optional): When specified, the fixtures are placed under an
# 'assets' subdirectory of this path rather than an
# 'assets' subdirectory of target_gen_dir.
template("copy_fixtures") {
testonly = true
assert(defined(invoker.fixtures), "The test fixtures must be specified.")
dest = target_gen_dir
if (defined(invoker.dest)) {
dest = invoker.dest
}
has_fixtures = false
foreach(fixture, invoker.fixtures) {
has_fixtures = true
}
if (has_fixtures) {
copy(target_name) {
sources = invoker.fixtures
outputs = [ "$dest/assets/{{source_file_part}}" ]
forward_variables_from(invoker, [ "deps" ])
}
} else {
group(target_name) {
# The copy target cannot accept an empty list.
}
}
}
# Specifies the fixtures to copy to a location known by the specific unit test.
# Test executable can only depend on one such target. You can use either one of
# both arguments to expand this template. If you have none, then you'll see the
# unused invoker scope error. In such cases specify the fixtures using an empty
# array.
#
# The targets which generate the outputs from these test fixtures (e.g. the
# Dart kernel snapshot) are exposed as public dependencies of the test fixture
# target. This is so that users can depend on the test fixture target directly
# and be able to access the generated outputs without needing to know about the
# internal dependency structure generated by this template.
#
# Arguments:
#
# fixtures (optional): The list of test fixtures. An empty list may be
# specified.
#
# dart_main (optional): The path to the main Dart file. If specified, it is
# snapshotted.
#
# use_target_as_artifact_prefix(optional): If true, adds the target name as
# prefix of the kernel and AOT ELF snapshot filename.
#
# dest (optional): When specified, the fixtures are placed under an
# 'assets' subdirectory of this path rather than an
# 'assets' subdirectory of target_gen_dir.
template("test_fixtures") {
dest = target_gen_dir
if (defined(invoker.dest)) {
dest = invoker.dest
}
# Not all paths use 'dest'
not_needed([ "dest" ])
# Even if no fixtures are present, the location of the fixtures directory
# must always be known to tests.
fixtures_location_target_name = "_fl_$target_name"
fixtures_location(fixtures_location_target_name) {
if (is_fuchsia) {
assets_dir = "/pkg/data/assets"
} else {
assets_dir = "$dest/assets"
}
}
test_deps = [ ":$fixtures_location_target_name" ]
test_public_deps = []
# If the fixtures are specified, copy them to the assets directory.
if (defined(invoker.fixtures)) {
copy_fixtures_target_name = "_cf_$target_name"
copy_fixtures(copy_fixtures_target_name) {
fixtures = invoker.fixtures
dest = dest
forward_variables_from(invoker, [ "deps" ])
}
test_public_deps += [ ":$copy_fixtures_target_name" ]
}
# If a Dart file is specified, snapshot it and place it in the generated
# assets directory.
if (defined(invoker.dart_main)) {
if (defined(invoker.use_target_as_artifact_prefix) &&
invoker.use_target_as_artifact_prefix) {
artifact_prefix = "${target_name}_"
} else {
artifact_prefix = ""
}
dart_snapshot_target_name = "_ds_$target_name"
dart_snapshot(dart_snapshot_target_name) {
dart_main = invoker.dart_main
dart_kernel_filename = "${artifact_prefix}kernel_blob.bin"
if (is_aot_test) {
dart_elf_filename = "${artifact_prefix}app_elf_snapshot.so"
}
}
test_public_deps += [ ":$dart_snapshot_target_name" ]
}
group(target_name) {
testonly = true
deps = test_deps
public_deps = test_public_deps
}
}
| engine/testing/testing.gni/0 | {
"file_path": "engine/testing/testing.gni",
"repo_id": "engine",
"token_count": 3482
} | 452 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ax_event_generator.h"
#include "base/logging.h"
#include "gtest/gtest.h"
#include "ax_enums.h"
#include "ax_node.h"
namespace ui {
namespace {
bool HasEvent(AXEventGenerator& src,
AXEventGenerator::Event event_type,
int32_t id) {
for (const auto& targeted_event : src) {
if (targeted_event.event_params.event == event_type &&
targeted_event.node->id() == id)
return true;
}
return false;
}
} // namespace
TEST(AXEventGeneratorTest, LoadCompleteSameTree) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].relative_bounds.bounds = gfx::RectF(0, 0, 800, 600);
initial_state.has_tree_data = true;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate load_complete_update = initial_state;
load_complete_update.tree_data.loaded = true;
ASSERT_TRUE(tree.Unserialize(load_complete_update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::LOAD_COMPLETE, 1));
}
TEST(AXEventGeneratorTest, LoadCompleteNewTree) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
initial_state.has_tree_data = true;
initial_state.tree_data.loaded = true;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate load_complete_update;
load_complete_update.root_id = 2;
load_complete_update.nodes.resize(1);
load_complete_update.nodes[0].id = 2;
load_complete_update.nodes[0].relative_bounds.bounds =
gfx::RectF(0, 0, 800, 600);
load_complete_update.has_tree_data = true;
load_complete_update.tree_data.loaded = true;
ASSERT_TRUE(tree.Unserialize(load_complete_update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::LOAD_COMPLETE, 2));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 2));
// Load complete should not be emitted for sizeless roots.
load_complete_update.root_id = 3;
load_complete_update.nodes.resize(1);
load_complete_update.nodes[0].id = 3;
load_complete_update.nodes[0].relative_bounds.bounds = gfx::RectF(0, 0, 0, 0);
load_complete_update.has_tree_data = true;
load_complete_update.tree_data.loaded = true;
ASSERT_TRUE(tree.Unserialize(load_complete_update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 3));
// TODO(accessibility): http://crbug.com/888758
// Load complete should not be emitted for chrome-search URLs.
load_complete_update.root_id = 4;
load_complete_update.nodes.resize(1);
load_complete_update.nodes[0].id = 4;
load_complete_update.nodes[0].relative_bounds.bounds =
gfx::RectF(0, 0, 800, 600);
load_complete_update.nodes[0].AddStringAttribute(
ax::mojom::StringAttribute::kUrl, "chrome-search://foo");
load_complete_update.has_tree_data = true;
load_complete_update.tree_data.loaded = true;
ASSERT_TRUE(tree.Unserialize(load_complete_update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::LOAD_COMPLETE, 4));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 4));
}
TEST(AXEventGeneratorTest, LoadStart) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].relative_bounds.bounds = gfx::RectF(0, 0, 800, 600);
initial_state.has_tree_data = true;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate load_start_update;
load_start_update.root_id = 2;
load_start_update.nodes.resize(1);
load_start_update.nodes[0].id = 2;
load_start_update.nodes[0].relative_bounds.bounds =
gfx::RectF(0, 0, 800, 600);
load_start_update.has_tree_data = true;
load_start_update.tree_data.loaded = false;
ASSERT_TRUE(tree.Unserialize(load_start_update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::LOAD_START, 2));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 2));
}
TEST(AXEventGeneratorTest, DocumentSelectionChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
initial_state.has_tree_data = true;
initial_state.tree_data.sel_focus_object_id = 1;
initial_state.tree_data.sel_focus_offset = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.tree_data.sel_focus_offset = 2;
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::DOCUMENT_SELECTION_CHANGED, 1));
}
TEST(AXEventGeneratorTest, DocumentTitleChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
initial_state.has_tree_data = true;
initial_state.tree_data.title = "Before";
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.tree_data.title = "After";
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::DOCUMENT_TITLE_CHANGED, 1));
}
// Do not emit a FOCUS_CHANGED event if focus_id is unchanged.
TEST(AXEventGeneratorTest, FocusIdUnchanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(2);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
initial_state.has_tree_data = true;
initial_state.tree_data.focus_id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.tree_data.focus_id = 1;
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_FALSE(
HasEvent(event_generator, AXEventGenerator::Event::FOCUS_CHANGED, 1));
}
// Emit a FOCUS_CHANGED event if focus_id changes.
TEST(AXEventGeneratorTest, FocusIdChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(2);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
initial_state.has_tree_data = true;
initial_state.tree_data.focus_id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.tree_data.focus_id = 2;
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::FOCUS_CHANGED, 2));
}
TEST(AXEventGeneratorTest, ExpandedAndRowCount) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(4);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[0].child_ids.push_back(4);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kTable;
initial_state.nodes[1].child_ids.push_back(3);
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kRow;
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kPopUpButton;
initial_state.nodes[3].AddState(ax::mojom::State::kExpanded);
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[2].AddState(ax::mojom::State::kExpanded);
update.nodes[3].state = 0;
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator, AXEventGenerator::Event::COLLAPSED, 4));
EXPECT_TRUE(HasEvent(event_generator, AXEventGenerator::Event::EXPANDED, 3));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::ROW_COUNT_CHANGED, 2));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::STATE_CHANGED, 3));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::WIN_IACCESSIBLE_STATE_CHANGED,
3));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::STATE_CHANGED, 4));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::WIN_IACCESSIBLE_STATE_CHANGED,
4));
}
TEST(AXEventGeneratorTest, SelectedAndSelectedChildren) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(4);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[0].child_ids.push_back(4);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kMenu;
initial_state.nodes[1].child_ids.push_back(3);
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kMenuItem;
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kListBoxOption;
initial_state.nodes[3].AddBoolAttribute(ax::mojom::BoolAttribute::kSelected,
true);
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[2].AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true);
update.nodes.pop_back();
update.nodes.emplace_back();
update.nodes[3].id = 4;
update.nodes[3].role = ax::mojom::Role::kListBoxOption;
update.nodes[3].AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, false);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::SELECTED_CHILDREN_CHANGED, 2));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SELECTED_CHANGED, 3));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::WIN_IACCESSIBLE_STATE_CHANGED,
3));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SELECTED_CHANGED, 4));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::WIN_IACCESSIBLE_STATE_CHANGED,
4));
}
TEST(AXEventGeneratorTest, StringValueChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kTextField;
initial_state.nodes[0].AddStringAttribute(ax::mojom::StringAttribute::kValue,
"Before");
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].string_attributes.clear();
update.nodes[0].AddStringAttribute(ax::mojom::StringAttribute::kValue,
"After");
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::VALUE_CHANGED, 1));
}
TEST(AXEventGeneratorTest, FloatValueChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kSlider;
initial_state.nodes[0].AddFloatAttribute(
ax::mojom::FloatAttribute::kValueForRange, 1.0);
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].float_attributes.clear();
update.nodes[0].AddFloatAttribute(ax::mojom::FloatAttribute::kValueForRange,
2.0);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::VALUE_CHANGED, 1));
}
TEST(AXEventGeneratorTest, InvalidStatusChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kTextField;
initial_state.nodes[0].AddStringAttribute(ax::mojom::StringAttribute::kValue,
"Text");
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].SetInvalidState(ax::mojom::InvalidState::kTrue);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::INVALID_STATUS_CHANGED, 1));
}
TEST(AXEventGeneratorTest, AddLiveRegionAttribute) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddStringAttribute(ax::mojom::StringAttribute::kLiveStatus,
"polite");
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::LIVE_STATUS_CHANGED, 1));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::LIVE_REGION_CREATED, 1));
event_generator.ClearEvents();
update.nodes[0].AddStringAttribute(ax::mojom::StringAttribute::kLiveStatus,
"assertive");
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::LIVE_STATUS_CHANGED, 1));
event_generator.ClearEvents();
update.nodes[0].AddStringAttribute(ax::mojom::StringAttribute::kLiveStatus,
"off");
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::LIVE_STATUS_CHANGED, 1));
}
TEST(AXEventGeneratorTest, CheckedStateChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kCheckBox;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].SetCheckedState(ax::mojom::CheckedState::kTrue);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::CHECKED_STATE_CHANGED, 1));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::WIN_IACCESSIBLE_STATE_CHANGED,
1));
}
TEST(AXEventGeneratorTest, ActiveDescendantChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(3);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kListBox;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[0].child_ids.push_back(3);
initial_state.nodes[0].AddIntAttribute(
ax::mojom::IntAttribute::kActivedescendantId, 2);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kListBoxOption;
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kListBoxOption;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].int_attributes.clear();
update.nodes[0].AddIntAttribute(ax::mojom::IntAttribute::kActivedescendantId,
3);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::ACTIVE_DESCENDANT_CHANGED, 1));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::RELATED_NODE_CHANGED, 1));
}
TEST(AXEventGeneratorTest, CreateAlertAndLiveRegion) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes.resize(4);
update.nodes[0].child_ids.push_back(2);
update.nodes[0].child_ids.push_back(3);
update.nodes[0].child_ids.push_back(4);
update.nodes[1].id = 2;
update.nodes[1].AddStringAttribute(ax::mojom::StringAttribute::kLiveStatus,
"polite");
// Blink should automatically add aria-live="assertive" to elements with role
// kAlert, but we should fire an alert event regardless.
update.nodes[2].id = 3;
update.nodes[2].role = ax::mojom::Role::kAlert;
// Elements with role kAlertDialog will *not* usually have a live region
// status, but again, we should always fire an alert event.
update.nodes[3].id = 4;
update.nodes[3].role = ax::mojom::Role::kAlertDialog;
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator, AXEventGenerator::Event::ALERT, 3));
EXPECT_TRUE(HasEvent(event_generator, AXEventGenerator::Event::ALERT, 4));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::CHILDREN_CHANGED, 1));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::LIVE_REGION_CREATED, 2));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 2));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 3));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 4));
}
TEST(AXEventGeneratorTest, LiveRegionChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(3);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].AddStringAttribute(
ax::mojom::StringAttribute::kLiveStatus, "polite");
initial_state.nodes[0].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[0].child_ids.push_back(3);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kStaticText;
initial_state.nodes[1].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
initial_state.nodes[1].AddStringAttribute(ax::mojom::StringAttribute::kName,
"Before 1");
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kStaticText;
initial_state.nodes[2].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
initial_state.nodes[2].AddStringAttribute(ax::mojom::StringAttribute::kName,
"Before 2");
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[1].string_attributes.clear();
update.nodes[1].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
update.nodes[1].AddStringAttribute(ax::mojom::StringAttribute::kName,
"After 1");
update.nodes[2].string_attributes.clear();
update.nodes[2].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
update.nodes[2].AddStringAttribute(ax::mojom::StringAttribute::kName,
"After 2");
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::LIVE_REGION_CHANGED, 1));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::LIVE_REGION_NODE_CHANGED, 2));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::LIVE_REGION_NODE_CHANGED, 3));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::NAME_CHANGED, 2));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::NAME_CHANGED, 3));
}
TEST(AXEventGeneratorTest, LiveRegionOnlyTextChanges) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(3);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].AddStringAttribute(
ax::mojom::StringAttribute::kLiveStatus, "polite");
initial_state.nodes[0].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[0].child_ids.push_back(3);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kStaticText;
initial_state.nodes[1].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
initial_state.nodes[1].AddStringAttribute(ax::mojom::StringAttribute::kName,
"Before 1");
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kStaticText;
initial_state.nodes[2].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
initial_state.nodes[2].AddStringAttribute(ax::mojom::StringAttribute::kName,
"Before 2");
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[1].AddStringAttribute(ax::mojom::StringAttribute::kDescription,
"Description 1");
update.nodes[2].SetCheckedState(ax::mojom::CheckedState::kTrue);
// Note that we do NOT expect a LIVE_REGION_CHANGED event here, because
// the name did not change.
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::CHECKED_STATE_CHANGED, 3));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::WIN_IACCESSIBLE_STATE_CHANGED,
3));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::DESCRIPTION_CHANGED, 2));
}
TEST(AXEventGeneratorTest, BusyLiveRegionChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(3);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].AddStringAttribute(
ax::mojom::StringAttribute::kLiveStatus, "polite");
initial_state.nodes[0].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
initial_state.nodes[0].AddBoolAttribute(ax::mojom::BoolAttribute::kBusy,
true);
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[0].child_ids.push_back(3);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kStaticText;
initial_state.nodes[1].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
initial_state.nodes[1].AddStringAttribute(ax::mojom::StringAttribute::kName,
"Before 1");
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kStaticText;
initial_state.nodes[2].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
initial_state.nodes[2].AddStringAttribute(ax::mojom::StringAttribute::kName,
"Before 2");
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[1].string_attributes.clear();
update.nodes[1].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
update.nodes[1].AddStringAttribute(ax::mojom::StringAttribute::kName,
"After 1");
update.nodes[2].string_attributes.clear();
update.nodes[2].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
update.nodes[2].AddStringAttribute(ax::mojom::StringAttribute::kName,
"After 2");
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::NAME_CHANGED, 2));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::NAME_CHANGED, 3));
}
TEST(AXEventGeneratorTest, AddChild) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(2);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes.resize(3);
update.nodes[0].child_ids.push_back(3);
update.nodes[2].id = 3;
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::CHILDREN_CHANGED, 1));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 3));
}
TEST(AXEventGeneratorTest, RemoveChild) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(3);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[0].child_ids.push_back(3);
initial_state.nodes[1].id = 2;
initial_state.nodes[2].id = 3;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes.resize(2);
update.nodes[0].child_ids.clear();
update.nodes[0].child_ids.push_back(2);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::CHILDREN_CHANGED, 1));
}
TEST(AXEventGeneratorTest, ReorderChildren) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(3);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[0].child_ids.push_back(3);
initial_state.nodes[1].id = 2;
initial_state.nodes[2].id = 3;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].child_ids.clear();
update.nodes[0].child_ids.push_back(3);
update.nodes[0].child_ids.push_back(2);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::CHILDREN_CHANGED, 1));
}
TEST(AXEventGeneratorTest, ScrollHorizontalPositionChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddIntAttribute(ax::mojom::IntAttribute::kScrollX, 10);
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator,
AXEventGenerator::Event::SCROLL_HORIZONTAL_POSITION_CHANGED, 1));
}
TEST(AXEventGeneratorTest, ScrollVerticalPositionChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddIntAttribute(ax::mojom::IntAttribute::kScrollY, 10);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator,
AXEventGenerator::Event::SCROLL_VERTICAL_POSITION_CHANGED, 1));
}
TEST(AXEventGeneratorTest, TextAttributeChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(17);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].child_ids = {2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17};
initial_state.nodes[1].id = 2;
initial_state.nodes[2].id = 3;
initial_state.nodes[3].id = 4;
initial_state.nodes[4].id = 5;
initial_state.nodes[5].id = 6;
initial_state.nodes[6].id = 7;
initial_state.nodes[7].id = 8;
initial_state.nodes[8].id = 9;
initial_state.nodes[9].id = 10;
initial_state.nodes[10].id = 11;
initial_state.nodes[11].id = 12;
initial_state.nodes[12].id = 13;
initial_state.nodes[13].id = 14;
initial_state.nodes[14].id = 15;
initial_state.nodes[15].id = 16;
initial_state.nodes[16].id = 17;
// To test changing the start and end of existing markers.
initial_state.nodes[11].AddIntListAttribute(
ax::mojom::IntListAttribute::kMarkerTypes,
{static_cast<int32_t>(ax::mojom::MarkerType::kTextMatch)});
initial_state.nodes[11].AddIntListAttribute(
ax::mojom::IntListAttribute::kMarkerStarts, {5});
initial_state.nodes[11].AddIntListAttribute(
ax::mojom::IntListAttribute::kMarkerEnds, {10});
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[1].AddIntAttribute(ax::mojom::IntAttribute::kColor, 0);
update.nodes[2].AddIntAttribute(ax::mojom::IntAttribute::kBackgroundColor, 0);
update.nodes[3].AddIntAttribute(
ax::mojom::IntAttribute::kTextDirection,
static_cast<int32_t>(ax::mojom::WritingDirection::kRtl));
update.nodes[4].AddIntAttribute(
ax::mojom::IntAttribute::kTextPosition,
static_cast<int32_t>(ax::mojom::TextPosition::kSuperscript));
update.nodes[5].AddIntAttribute(
ax::mojom::IntAttribute::kTextStyle,
static_cast<int32_t>(ax::mojom::TextStyle::kBold));
update.nodes[6].AddIntAttribute(
ax::mojom::IntAttribute::kTextOverlineStyle,
static_cast<int32_t>(ax::mojom::TextDecorationStyle::kSolid));
update.nodes[7].AddIntAttribute(
ax::mojom::IntAttribute::kTextStrikethroughStyle,
static_cast<int32_t>(ax::mojom::TextDecorationStyle::kWavy));
update.nodes[8].AddIntAttribute(
ax::mojom::IntAttribute::kTextUnderlineStyle,
static_cast<int32_t>(ax::mojom::TextDecorationStyle::kDotted));
update.nodes[9].AddIntListAttribute(
ax::mojom::IntListAttribute::kMarkerTypes,
{static_cast<int32_t>(ax::mojom::MarkerType::kSpelling)});
update.nodes[10].AddIntListAttribute(
ax::mojom::IntListAttribute::kMarkerTypes,
{static_cast<int32_t>(ax::mojom::MarkerType::kGrammar)});
update.nodes[11].AddIntListAttribute(ax::mojom::IntListAttribute::kMarkerEnds,
{11});
update.nodes[12].AddIntListAttribute(
ax::mojom::IntListAttribute::kMarkerTypes,
{static_cast<int32_t>(ax::mojom::MarkerType::kActiveSuggestion)});
update.nodes[13].AddIntListAttribute(
ax::mojom::IntListAttribute::kMarkerTypes,
{static_cast<int32_t>(ax::mojom::MarkerType::kSuggestion)});
update.nodes[14].AddFloatAttribute(ax::mojom::FloatAttribute::kFontSize,
12.0f);
update.nodes[15].AddFloatAttribute(ax::mojom::FloatAttribute::kFontWeight,
600.0f);
update.nodes[16].AddStringAttribute(ax::mojom::StringAttribute::kFontFamily,
"sans");
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::TEXT_ATTRIBUTE_CHANGED, 2));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::TEXT_ATTRIBUTE_CHANGED, 3));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::TEXT_ATTRIBUTE_CHANGED, 4));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::TEXT_ATTRIBUTE_CHANGED, 5));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::TEXT_ATTRIBUTE_CHANGED, 6));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::TEXT_ATTRIBUTE_CHANGED, 7));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::TEXT_ATTRIBUTE_CHANGED, 8));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::TEXT_ATTRIBUTE_CHANGED, 9));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::TEXT_ATTRIBUTE_CHANGED, 10));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::TEXT_ATTRIBUTE_CHANGED, 11));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::TEXT_ATTRIBUTE_CHANGED, 12));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::TEXT_ATTRIBUTE_CHANGED, 13));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::TEXT_ATTRIBUTE_CHANGED, 14));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::TEXT_ATTRIBUTE_CHANGED, 15));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::TEXT_ATTRIBUTE_CHANGED, 16));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::TEXT_ATTRIBUTE_CHANGED, 17));
}
TEST(AXEventGeneratorTest, ObjectAttributeChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(3);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].child_ids = {2, 3};
initial_state.nodes[1].id = 2;
initial_state.nodes[2].id = 3;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[1].AddIntAttribute(ax::mojom::IntAttribute::kTextAlign, 2);
update.nodes[2].AddFloatAttribute(ax::mojom::FloatAttribute::kTextIndent,
10.0f);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator,
AXEventGenerator::Event::ATK_TEXT_OBJECT_ATTRIBUTE_CHANGED, 2));
EXPECT_TRUE(
HasEvent(event_generator,
AXEventGenerator::Event::ATK_TEXT_OBJECT_ATTRIBUTE_CHANGED, 3));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::OBJECT_ATTRIBUTE_CHANGED, 2));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::OBJECT_ATTRIBUTE_CHANGED, 3));
}
TEST(AXEventGeneratorTest, OtherAttributeChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(6);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[0].child_ids.push_back(3);
initial_state.nodes[0].child_ids.push_back(4);
initial_state.nodes[0].child_ids.push_back(5);
initial_state.nodes[0].child_ids.push_back(6);
initial_state.nodes[1].id = 2;
initial_state.nodes[2].id = 3;
initial_state.nodes[3].id = 4;
initial_state.nodes[4].id = 5;
initial_state.nodes[5].id = 6;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[1].AddStringAttribute(ax::mojom::StringAttribute::kLanguage,
"de");
update.nodes[2].AddIntAttribute(ax::mojom::IntAttribute::kAriaCellColumnIndex,
7);
update.nodes[3].AddFloatAttribute(ax::mojom::FloatAttribute::kFontSize,
12.0f);
update.nodes[4].AddBoolAttribute(ax::mojom::BoolAttribute::kModal, true);
std::vector<int> ids = {2};
update.nodes[5].AddIntListAttribute(ax::mojom::IntListAttribute::kControlsIds,
ids);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::CONTROLS_CHANGED, 6));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::LANGUAGE_CHANGED, 2));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::OTHER_ATTRIBUTE_CHANGED, 3));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::TEXT_ATTRIBUTE_CHANGED, 4));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::OTHER_ATTRIBUTE_CHANGED, 5));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::RELATED_NODE_CHANGED, 6));
}
TEST(AXEventGeneratorTest, NameChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(2);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[1].AddStringAttribute(ax::mojom::StringAttribute::kName,
"Hello");
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::NAME_CHANGED, 2));
}
TEST(AXEventGeneratorTest, DescriptionChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddStringAttribute(ax::mojom::StringAttribute::kDescription,
"Hello");
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::DESCRIPTION_CHANGED, 1));
}
TEST(AXEventGeneratorTest, RoleChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].role = ax::mojom::Role::kCheckBox;
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::ROLE_CHANGED, 1));
}
TEST(AXEventGeneratorTest, MenuItemSelected) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(3);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kMenu;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[0].child_ids.push_back(3);
initial_state.nodes[0].AddIntAttribute(
ax::mojom::IntAttribute::kActivedescendantId, 2);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kMenuListOption;
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kMenuListOption;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].int_attributes.clear();
update.nodes[0].AddIntAttribute(ax::mojom::IntAttribute::kActivedescendantId,
3);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::ACTIVE_DESCENDANT_CHANGED, 1));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::MENU_ITEM_SELECTED, 3));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::RELATED_NODE_CHANGED, 1));
}
TEST(AXEventGeneratorTest, NodeBecomesIgnored) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(5);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kArticle;
initial_state.nodes[1].child_ids.push_back(3);
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kGroup;
initial_state.nodes[2].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[2].child_ids.push_back(4);
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kGroup;
initial_state.nodes[3].child_ids.push_back(5);
initial_state.nodes[4].id = 5;
initial_state.nodes[4].role = ax::mojom::Role::kStaticText;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[3].AddState(ax::mojom::State::kIgnored);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::CHILDREN_CHANGED, 2));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 4));
}
TEST(AXEventGeneratorTest, NodeBecomesIgnored2) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(5);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kArticle;
initial_state.nodes[1].child_ids.push_back(3);
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kGroup;
initial_state.nodes[2].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[2].child_ids.push_back(4);
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kGroup;
initial_state.nodes[3].child_ids.push_back(5);
initial_state.nodes[4].id = 5;
initial_state.nodes[4].role = ax::mojom::Role::kStaticText;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
// Marking as ignored should fire CHILDREN_CHANGED on 2
update.nodes[3].AddState(ax::mojom::State::kIgnored);
// Remove node id 5 so it also fires CHILDREN_CHANGED on 4.
update.nodes.pop_back();
update.nodes[3].child_ids.clear();
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::CHILDREN_CHANGED, 2));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 4));
}
TEST(AXEventGeneratorTest, NodeBecomesUnignored) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(5);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kArticle;
initial_state.nodes[1].child_ids.push_back(3);
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kGroup;
initial_state.nodes[2].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[2].child_ids.push_back(4);
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kGroup;
initial_state.nodes[3].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[3].child_ids.push_back(5);
initial_state.nodes[4].id = 5;
initial_state.nodes[4].role = ax::mojom::Role::kStaticText;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[3].state = 0;
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::CHILDREN_CHANGED, 2));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 4));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 4));
}
TEST(AXEventGeneratorTest, NodeBecomesUnignored2) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(5);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kArticle;
initial_state.nodes[1].child_ids.push_back(3);
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kGroup;
initial_state.nodes[2].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[2].child_ids.push_back(4);
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kGroup;
initial_state.nodes[3].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[3].child_ids.push_back(5);
initial_state.nodes[4].id = 5;
initial_state.nodes[4].role = ax::mojom::Role::kStaticText;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
// Marking as no longer ignored should fire CHILDREN_CHANGED on 2
update.nodes[3].state = 0;
// Remove node id 5 so it also fires CHILDREN_CHANGED on 4.
update.nodes.pop_back();
update.nodes[3].child_ids.clear();
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::CHILDREN_CHANGED, 2));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 4));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 4));
}
TEST(AXEventGeneratorTest, SubtreeBecomesUnignored) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(3);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kArticle;
initial_state.nodes[1].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[1].child_ids.push_back(3);
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kGroup;
initial_state.nodes[2].AddState(ax::mojom::State::kIgnored);
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[1].RemoveState(ax::mojom::State::kIgnored);
update.nodes[2].RemoveState(ax::mojom::State::kIgnored);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::CHILDREN_CHANGED, 1));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 2));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 2));
}
TEST(AXEventGeneratorTest, TwoNodesSwapIgnored) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(3);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kArticle;
initial_state.nodes[1].child_ids.push_back(3);
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kGroup;
initial_state.nodes[2].AddState(ax::mojom::State::kIgnored);
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[1].AddState(ax::mojom::State::kIgnored);
update.nodes[2].RemoveState(ax::mojom::State::kIgnored);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::CHILDREN_CHANGED, 1));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 2));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 3));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 3));
}
TEST(AXEventGeneratorTest, TwoNodesSwapIgnored2) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(3);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kArticle;
initial_state.nodes[1].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[1].child_ids.push_back(3);
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kGroup;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[1].RemoveState(ax::mojom::State::kIgnored);
update.nodes[2].AddState(ax::mojom::State::kIgnored);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::CHILDREN_CHANGED, 1));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 2));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 3));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 2));
}
TEST(AXEventGeneratorTest, IgnoredChangedFiredOnAncestorOnly1) {
// BEFORE
// 1 (IGN)
// / \
// 2 3 (IGN)
// AFTER
// 1 (IGN)
// / \
// 2 (IGN) 3
// IGNORED_CHANGED expected on #2, #3
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(3);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[0].child_ids = {2, 3};
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kStaticText;
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kStaticText;
initial_state.nodes[2].AddState(ax::mojom::State::kIgnored);
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[1].AddState(ax::mojom::State::kIgnored);
update.nodes[2].RemoveState(ax::mojom::State::kIgnored);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 2));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 3));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 3));
}
TEST(AXEventGeneratorTest, IgnoredChangedFiredOnAncestorOnly2) {
// BEFORE
// 1
// |
// 2
// / \
// 3 4 (IGN)
// AFTER
// 1
// |
// 2 ___
// / \
// 3 (IGN) 4
// IGNORED_CHANGED expected on #3, #4
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(4);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids = {2};
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kGroup;
initial_state.nodes[1].child_ids = {3, 4};
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kStaticText;
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kStaticText;
initial_state.nodes[3].AddState(ax::mojom::State::kIgnored);
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[2].AddState(ax::mojom::State::kIgnored);
update.nodes[3].RemoveState(ax::mojom::State::kIgnored);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::CHILDREN_CHANGED, 2));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 3));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 4));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 4));
}
TEST(AXEventGeneratorTest, IgnoredChangedFiredOnAncestorOnly3) {
// BEFORE
// 1
// |
// 2 ___
// / \
// 3 (IGN) 4
// AFTER
// 1 (IGN)
// |
// 2
// / \
// 3 4 (IGN)
// IGNORED_CHANGED expected on #1, #3
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(4);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids = {2};
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kGroup;
initial_state.nodes[1].child_ids = {3, 4};
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kStaticText;
initial_state.nodes[2].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kStaticText;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddState(ax::mojom::State::kIgnored);
update.nodes[2].RemoveState(ax::mojom::State::kIgnored);
update.nodes[3].AddState(ax::mojom::State::kIgnored);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::CHILDREN_CHANGED, 2));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 1));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 3));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 3));
}
TEST(AXEventGeneratorTest, IgnoredChangedFiredOnAncestorOnly4) {
// BEFORE
// 1 (IGN)
// |
// 2
// |
// 3 (IGN)
// |
// 4 (IGN)
// |
// ____ 5 _____
// / | \
// 6 (IGN) 7 (IGN) 8
// AFTER
// 1 (IGN)
// |
// 2
// |
// 3 (IGN)
// |
// 4 (IGN)
// |
// ____ 5 _____
// / | \
// 6 7 8 (IGN)
// IGNORED_CHANGED expected on #6, #7, #8
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(8);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids = {2};
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kGroup;
initial_state.nodes[1].child_ids = {3};
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kGroup;
initial_state.nodes[2].child_ids = {4};
initial_state.nodes[2].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kGroup;
initial_state.nodes[3].child_ids = {5};
initial_state.nodes[3].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[4].id = 5;
initial_state.nodes[4].role = ax::mojom::Role::kGroup;
initial_state.nodes[4].child_ids = {6, 7, 8};
initial_state.nodes[5].id = 6;
initial_state.nodes[5].role = ax::mojom::Role::kStaticText;
initial_state.nodes[5].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[6].id = 7;
initial_state.nodes[6].role = ax::mojom::Role::kStaticText;
initial_state.nodes[6].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[7].id = 8;
initial_state.nodes[7].role = ax::mojom::Role::kStaticText;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[5].RemoveState(ax::mojom::State::kIgnored);
update.nodes[6].RemoveState(ax::mojom::State::kIgnored);
update.nodes[7].AddState(ax::mojom::State::kIgnored);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::CHILDREN_CHANGED, 5));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 6));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 7));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 6));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 7));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 8));
}
TEST(AXEventGeneratorTest, IgnoredChangedFiredOnAncestorOnly5) {
// BEFORE
// 1
// |
// 2
// |
// 3 (IGN)
// |
// 4 (IGN)
// |
// ____ 5 _____
// / | \
// 6 (IGN) 7 8
// AFTER
// 1 (IGN)
// |
// 2
// |
// 3 (IGN)
// |
// 4 (IGN)
// |
// ____ 5 _____
// / | \
// 6 7 (IGN) 8 (IGN)
// IGNORED_CHANGED expected on #1, #6
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(8);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids = {2};
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kGroup;
initial_state.nodes[1].child_ids = {3};
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kGroup;
initial_state.nodes[2].child_ids = {4};
initial_state.nodes[2].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kGroup;
initial_state.nodes[3].child_ids = {5};
initial_state.nodes[3].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[4].id = 5;
initial_state.nodes[4].role = ax::mojom::Role::kGroup;
initial_state.nodes[4].child_ids = {6, 7, 8};
initial_state.nodes[5].id = 6;
initial_state.nodes[5].role = ax::mojom::Role::kStaticText;
initial_state.nodes[5].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[6].id = 7;
initial_state.nodes[6].role = ax::mojom::Role::kStaticText;
initial_state.nodes[7].id = 8;
initial_state.nodes[7].role = ax::mojom::Role::kStaticText;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddState(ax::mojom::State::kIgnored);
update.nodes[5].RemoveState(ax::mojom::State::kIgnored);
update.nodes[6].AddState(ax::mojom::State::kIgnored);
update.nodes[7].AddState(ax::mojom::State::kIgnored);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::CHILDREN_CHANGED, 5));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 6));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 1));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 6));
}
TEST(AXEventGeneratorTest, IgnoredChangedFiredOnAncestorOnly6) {
// BEFORE
// 1 (IGN)
// |
// 2
// |
// 3
// |
// 4
// |
// ____ 5 _____
// / | \
// 6 (IGN) 7 (IGN) 8
// AFTER
// 1
// |
// 2
// |
// 3
// |
// 4
// |
// ____ 5 _____
// / | \
// 6 7 8 (IGN)
// IGNORED_CHANGED expected on #1, #8
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(8);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids = {2};
initial_state.nodes[0].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kGroup;
initial_state.nodes[1].child_ids = {3};
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kGroup;
initial_state.nodes[2].child_ids = {4};
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kGroup;
initial_state.nodes[3].child_ids = {5};
initial_state.nodes[4].id = 5;
initial_state.nodes[4].role = ax::mojom::Role::kGroup;
initial_state.nodes[4].child_ids = {6, 7, 8};
initial_state.nodes[5].id = 6;
initial_state.nodes[5].role = ax::mojom::Role::kStaticText;
initial_state.nodes[5].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[6].id = 7;
initial_state.nodes[6].role = ax::mojom::Role::kStaticText;
initial_state.nodes[6].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[7].id = 8;
initial_state.nodes[7].role = ax::mojom::Role::kStaticText;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].RemoveState(ax::mojom::State::kIgnored);
update.nodes[5].RemoveState(ax::mojom::State::kIgnored);
update.nodes[6].RemoveState(ax::mojom::State::kIgnored);
update.nodes[7].AddState(ax::mojom::State::kIgnored);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::CHILDREN_CHANGED, 5));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 1));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 6));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 7));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 1));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 8));
}
TEST(AXEventGeneratorTest, IgnoredChangedFiredOnAncestorOnly7) {
// BEFORE
// 1 (IGN)
// |
// 2 (IGN)
// |
// 3
// |
// __ 4 ___
// / \
// 5 (IGN) 6 (IGN)
// AFTER
// 1
// |
// 2
// |
// 3 (IGN)
// |
// __ 4 (IGN)
// / \
// 5 (IGN) 6 (IGN)
// IGNORED_CHANGED expected on #1, #3
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(6);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids = {2};
initial_state.nodes[0].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kGroup;
initial_state.nodes[1].child_ids = {3};
initial_state.nodes[1].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kGroup;
initial_state.nodes[2].child_ids = {4};
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kGroup;
initial_state.nodes[3].child_ids = {5, 6};
initial_state.nodes[4].id = 5;
initial_state.nodes[4].role = ax::mojom::Role::kStaticText;
initial_state.nodes[4].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[5].id = 6;
initial_state.nodes[5].role = ax::mojom::Role::kStaticText;
initial_state.nodes[5].AddState(ax::mojom::State::kIgnored);
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].RemoveState(ax::mojom::State::kIgnored);
update.nodes[1].RemoveState(ax::mojom::State::kIgnored);
update.nodes[2].AddState(ax::mojom::State::kIgnored);
update.nodes[3].AddState(ax::mojom::State::kIgnored);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 1));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 1));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 3));
}
TEST(AXEventGeneratorTest, IgnoredChangedFiredOnAncestorOnly8) {
// BEFORE
// ____ 1 ____
// | |
// 2 (IGN) 7
// |
// 3 (IGN)
// |
// 4 (IGN)
// |
// 5 (IGN)
// |
// 6 (IGN)
// AFTER
// ____ 1 ____
// | |
// 2 7 (IGN)
// |
// 3
// |
// 4
// |
// 5
// |
// 6
// IGNORED_CHANGED expected on #2, #7
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(7);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids = {2, 7};
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kGroup;
initial_state.nodes[1].child_ids = {3};
initial_state.nodes[1].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kGroup;
initial_state.nodes[2].child_ids = {4};
initial_state.nodes[2].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kGroup;
initial_state.nodes[3].child_ids = {5};
initial_state.nodes[3].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[4].id = 5;
initial_state.nodes[4].role = ax::mojom::Role::kGroup;
initial_state.nodes[4].child_ids = {6};
initial_state.nodes[4].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[5].id = 5;
initial_state.nodes[5].role = ax::mojom::Role::kStaticText;
initial_state.nodes[5].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[6].id = 7;
initial_state.nodes[6].role = ax::mojom::Role::kStaticText;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[1].RemoveState(ax::mojom::State::kIgnored);
update.nodes[2].RemoveState(ax::mojom::State::kIgnored);
update.nodes[3].RemoveState(ax::mojom::State::kIgnored);
update.nodes[4].RemoveState(ax::mojom::State::kIgnored);
update.nodes[5].RemoveState(ax::mojom::State::kIgnored);
update.nodes[6].AddState(ax::mojom::State::kIgnored);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::CHILDREN_CHANGED, 1));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SUBTREE_CREATED, 2));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 2));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::IGNORED_CHANGED, 7));
}
TEST(AXEventGeneratorTest, ActiveDescendantChangeOnDescendant) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(5);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kGenericContainer;
initial_state.nodes[1].child_ids.push_back(3);
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kGroup;
initial_state.nodes[2].AddIntAttribute(
ax::mojom::IntAttribute::kActivedescendantId, 4);
initial_state.nodes[2].child_ids.push_back(4);
initial_state.nodes[2].child_ids.push_back(5);
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kGroup;
initial_state.nodes[4].id = 5;
initial_state.nodes[4].role = ax::mojom::Role::kGroup;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
initial_state.nodes[2].RemoveIntAttribute(
ax::mojom::IntAttribute::kActivedescendantId);
initial_state.nodes[2].AddIntAttribute(
ax::mojom::IntAttribute::kActivedescendantId, 5);
AXTreeUpdate update = initial_state;
update.node_id_to_clear = 2;
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::ACTIVE_DESCENDANT_CHANGED, 3));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::RELATED_NODE_CHANGED, 3));
}
TEST(AXEventGeneratorTest, ImageAnnotationChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddStringAttribute(
ax::mojom::StringAttribute::kImageAnnotation, "Hello");
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::IMAGE_ANNOTATION_CHANGED, 1));
}
TEST(AXEventGeneratorTest, ImageAnnotationStatusChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].SetImageAnnotationStatus(
ax::mojom::ImageAnnotationStatus::kAnnotationSucceeded);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::IMAGE_ANNOTATION_CHANGED, 1));
}
TEST(AXEventGeneratorTest, StringPropertyChanges) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
struct {
ax::mojom::StringAttribute id;
std::string old_value;
std::string new_value;
} attributes[] = {
{ax::mojom::StringAttribute::kAccessKey, "a", "b"},
{ax::mojom::StringAttribute::kClassName, "a", "b"},
{ax::mojom::StringAttribute::kKeyShortcuts, "a", "b"},
{ax::mojom::StringAttribute::kLanguage, "a", "b"},
{ax::mojom::StringAttribute::kPlaceholder, "a", "b"},
};
for (auto&& attrib : attributes) {
initial_state.nodes.push_back({});
initial_state.nodes.back().id = initial_state.nodes.size();
initial_state.nodes.back().AddStringAttribute(attrib.id, attrib.old_value);
initial_state.nodes[0].child_ids.push_back(initial_state.nodes.size());
}
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
int index = 1;
for (auto&& attrib : attributes) {
initial_state.nodes[index++].AddStringAttribute(attrib.id,
attrib.new_value);
}
AXTreeUpdate update = initial_state;
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::ACCESS_KEY_CHANGED, 2));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::CLASS_NAME_CHANGED, 3));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::KEY_SHORTCUTS_CHANGED, 4));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::LANGUAGE_CHANGED, 5));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::PLACEHOLDER_CHANGED, 6));
}
TEST(AXEventGeneratorTest, IntPropertyChanges) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
struct {
ax::mojom::IntAttribute id;
int old_value;
int new_value;
} attributes[] = {
{ax::mojom::IntAttribute::kHierarchicalLevel, 1, 2},
{ax::mojom::IntAttribute::kPosInSet, 1, 2},
{ax::mojom::IntAttribute::kSetSize, 1, 2},
};
for (auto&& attrib : attributes) {
initial_state.nodes.push_back({});
initial_state.nodes.back().id = initial_state.nodes.size();
initial_state.nodes.back().AddIntAttribute(attrib.id, attrib.old_value);
initial_state.nodes[0].child_ids.push_back(initial_state.nodes.size());
}
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
int index = 1;
for (auto&& attrib : attributes)
initial_state.nodes[index++].AddIntAttribute(attrib.id, attrib.new_value);
AXTreeUpdate update = initial_state;
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::HIERARCHICAL_LEVEL_CHANGED, 2));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::POSITION_IN_SET_CHANGED, 3));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::SET_SIZE_CHANGED, 4));
}
TEST(AXEventGeneratorTest, IntListPropertyChanges) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
struct {
ax::mojom::IntListAttribute id;
std::vector<int> old_value;
std::vector<int> new_value;
} attributes[] = {
{ax::mojom::IntListAttribute::kDescribedbyIds, {1}, {2}},
{ax::mojom::IntListAttribute::kFlowtoIds, {1}, {2}},
{ax::mojom::IntListAttribute::kLabelledbyIds, {1}, {2}},
};
for (auto&& attrib : attributes) {
initial_state.nodes.push_back({});
initial_state.nodes.back().id = initial_state.nodes.size();
initial_state.nodes.back().AddIntListAttribute(attrib.id, attrib.old_value);
initial_state.nodes[0].child_ids.push_back(initial_state.nodes.size());
}
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
int index = 1;
for (auto&& attrib : attributes) {
initial_state.nodes[index++].AddIntListAttribute(attrib.id,
attrib.new_value);
}
AXTreeUpdate update = initial_state;
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::DESCRIBED_BY_CHANGED, 2));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::FLOW_FROM_CHANGED, 1));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::FLOW_FROM_CHANGED, 2));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::FLOW_TO_CHANGED, 3));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::LABELED_BY_CHANGED, 4));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::RELATED_NODE_CHANGED, 2));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::RELATED_NODE_CHANGED, 3));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::RELATED_NODE_CHANGED, 4));
}
TEST(AXEventGeneratorTest, AriaBusyChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
initial_state.nodes[0].AddBoolAttribute(ax::mojom::BoolAttribute::kBusy,
true);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddBoolAttribute(ax::mojom::BoolAttribute::kBusy, false);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::BUSY_CHANGED, 1));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::LAYOUT_INVALIDATED, 1));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::WIN_IACCESSIBLE_STATE_CHANGED,
1));
}
TEST(AXEventGeneratorTest, MultiselectableStateChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kGrid;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddState(ax::mojom::State::kMultiselectable);
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::MULTISELECTABLE_STATE_CHANGED,
1));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::STATE_CHANGED, 1));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::WIN_IACCESSIBLE_STATE_CHANGED,
1));
}
TEST(AXEventGeneratorTest, RequiredStateChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kTextField;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddState(ax::mojom::State::kRequired);
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::REQUIRED_STATE_CHANGED, 1));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::STATE_CHANGED, 1));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::WIN_IACCESSIBLE_STATE_CHANGED,
1));
}
TEST(AXEventGeneratorTest, FlowToChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(6);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kGenericContainer;
initial_state.nodes[0].child_ids.assign({2, 3, 4, 5, 6});
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kGenericContainer;
initial_state.nodes[1].AddIntListAttribute(
ax::mojom::IntListAttribute::kFlowtoIds, {3, 4});
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kGenericContainer;
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kGenericContainer;
initial_state.nodes[4].id = 5;
initial_state.nodes[4].role = ax::mojom::Role::kGenericContainer;
initial_state.nodes[5].id = 6;
initial_state.nodes[5].role = ax::mojom::Role::kGenericContainer;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[1].AddIntListAttribute(ax::mojom::IntListAttribute::kFlowtoIds,
{4, 5, 6});
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::FLOW_FROM_CHANGED, 3));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::FLOW_FROM_CHANGED, 5));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::FLOW_FROM_CHANGED, 6));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::FLOW_TO_CHANGED, 2));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::RELATED_NODE_CHANGED, 2));
}
TEST(AXEventGeneratorTest, ControlsChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(2);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
std::vector<int> ids = {2};
update.nodes[0].AddIntListAttribute(ax::mojom::IntListAttribute::kControlsIds,
ids);
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::CONTROLS_CHANGED, 1));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::RELATED_NODE_CHANGED, 1));
}
TEST(AXEventGeneratorTest, AtomicChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddBoolAttribute(ax::mojom::BoolAttribute::kLiveAtomic, true);
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::ATOMIC_CHANGED, 1));
}
TEST(AXEventGeneratorTest, DropeffectChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddDropeffect(ax::mojom::Dropeffect::kCopy);
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::DROPEFFECT_CHANGED, 1));
}
TEST(AXEventGeneratorTest, GrabbedChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddBoolAttribute(ax::mojom::BoolAttribute::kGrabbed, true);
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::GRABBED_CHANGED, 1));
}
TEST(AXEventGeneratorTest, HasPopupChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].SetHasPopup(ax::mojom::HasPopup::kTrue);
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::HASPOPUP_CHANGED, 1));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::WIN_IACCESSIBLE_STATE_CHANGED,
1));
}
TEST(AXEventGeneratorTest, LiveRelevantChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddStringAttribute(ax::mojom::StringAttribute::kLiveRelevant,
"all");
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::LIVE_RELEVANT_CHANGED, 1));
}
TEST(AXEventGeneratorTest, MultilineStateChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddState(ax::mojom::State::kMultiline);
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::MULTILINE_STATE_CHANGED, 1));
EXPECT_TRUE(
HasEvent(event_generator, AXEventGenerator::Event::STATE_CHANGED, 1));
EXPECT_TRUE(HasEvent(event_generator,
AXEventGenerator::Event::WIN_IACCESSIBLE_STATE_CHANGED,
1));
}
} // namespace ui
| engine/third_party/accessibility/ax/ax_event_generator_unittest.cc/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_event_generator_unittest.cc",
"repo_id": "engine",
"token_count": 35148
} | 453 |
// 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_NODE_TEXT_STYLES_H_
#define UI_ACCESSIBILITY_AX_NODE_TEXT_STYLES_H_
#include <string>
#include "ax_base_export.h"
namespace ui {
// A compact representation of text styles on an AXNode. This data represents
// a snapshot at a given time and is not intended to be held for periods of
// time. For this reason, it is a move-only class, to encourage deliberate
// short-term usage.
struct AX_BASE_EXPORT AXNodeTextStyles {
AXNodeTextStyles();
// Move-only class, explicitly delete copy-construction and assignment
AXNodeTextStyles(const AXNodeTextStyles& other) = delete;
AXNodeTextStyles& operator=(const AXNodeTextStyles&) = delete;
// Move constructor and assignment
AXNodeTextStyles(AXNodeTextStyles&& other);
AXNodeTextStyles& operator=(AXNodeTextStyles&& other);
bool operator==(const AXNodeTextStyles& other) const;
bool operator!=(const AXNodeTextStyles& other) const;
bool IsUnset() const;
int32_t background_color;
int32_t color;
int32_t invalid_state;
int32_t overline_style;
int32_t strikethrough_style;
int32_t text_direction;
int32_t text_position;
int32_t text_style;
int32_t underline_style;
float font_size;
float font_weight;
std::string font_family;
};
} // namespace ui
#endif // UI_ACCESSIBILITY_AX_NODE_TEXT_STYLES_H_
| engine/third_party/accessibility/ax/ax_node_text_styles.h/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_node_text_styles.h",
"repo_id": "engine",
"token_count": 494
} | 454 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ACCESSIBILITY_AX_TREE_DATA_H_
#define UI_ACCESSIBILITY_AX_TREE_DATA_H_
#include <cstdint>
#include <map>
#include <string>
#include <vector>
#include "ax_enums.h"
#include "ax_export.h"
#include "ax_node.h"
#include "ax_tree_id_registry.h"
namespace ui {
// The data associated with an accessibility tree that's global to the
// tree and not associated with any particular node in the tree.
struct AX_EXPORT AXTreeData {
AXTreeData();
AXTreeData(const AXTreeData& other);
virtual ~AXTreeData();
// Return a string representation of this data, for debugging.
virtual std::string ToString() const;
// This is a simple serializable struct. All member variables should be
// public and copyable.
// The globally unique ID of this accessibility tree.
AXTreeID tree_id;
// The ID of the accessibility tree that this tree is contained in, if any.
AXTreeID parent_tree_id;
// The ID of the accessibility tree that has focus. This is typically set
// on the root frame in a frame tree.
AXTreeID focused_tree_id;
// Attributes specific to trees that are web frames.
std::string doctype;
bool loaded = false;
float loading_progress = 0.0f;
std::string mimetype;
std::string title;
std::string url;
// The node with keyboard focus within this tree, if any, or
// AXNode::kInvalidAXID if no node in this tree has focus.
AXNode::AXID focus_id = AXNode::kInvalidAXID;
// The current text selection within this tree, if any, expressed as the
// node ID and character offset of the anchor (selection start) and focus
// (selection end). If the offset could correspond to a position on two
// different lines, sel_upstream_affinity means the cursor is on the first
// line, otherwise it's on the second line.
// Most use cases will want to use ui::OwnerTree::GetUnignoredSelection.
bool sel_is_backward = false;
AXNode::AXID sel_anchor_object_id = AXNode::kInvalidAXID;
int32_t sel_anchor_offset = -1;
ax::mojom::TextAffinity sel_anchor_affinity;
AXNode::AXID sel_focus_object_id = AXNode::kInvalidAXID;
int32_t sel_focus_offset = -1;
ax::mojom::TextAffinity sel_focus_affinity;
// The node that's used as the root scroller. On some platforms
// like Android we need to ignore accessibility scroll offsets for
// that node and get them from the viewport instead.
AXNode::AXID root_scroller_id = AXNode::kInvalidAXID;
};
AX_EXPORT bool operator==(const AXTreeData& lhs, const AXTreeData& rhs);
AX_EXPORT bool operator!=(const AXTreeData& lhs, const AXTreeData& rhs);
} // namespace ui
#endif // UI_ACCESSIBILITY_AX_TREE_DATA_H_
| engine/third_party/accessibility/ax/ax_tree_data.h/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_tree_data.h",
"repo_id": "engine",
"token_count": 888
} | 455 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ax_platform_node.h"
#include "ax/ax_node_data.h"
#include "ax_build/build_config.h"
#include "ax_platform_node_delegate.h"
namespace ui {
std::vector<AXModeObserver*> AXPlatformNode::ax_mode_observers_;
std::function<AXPlatformNode::NativeWindowHandlerCallback>
AXPlatformNode::native_window_handler_;
// static
AXMode AXPlatformNode::ax_mode_;
// static
gfx::NativeViewAccessible AXPlatformNode::popup_focus_override_ = nullptr;
// static
AXPlatformNode* AXPlatformNode::FromNativeWindow(
gfx::NativeWindow native_window) {
if (native_window_handler_)
return native_window_handler_(native_window);
return nullptr;
}
void AXPlatformNode::RegisterNativeWindowHandler(
std::function<AXPlatformNode::NativeWindowHandlerCallback> handler) {
native_window_handler_ = handler;
}
AXPlatformNode::AXPlatformNode() {}
AXPlatformNode::~AXPlatformNode() {}
void AXPlatformNode::Destroy() {}
int32_t AXPlatformNode::GetUniqueId() const {
BASE_DCHECK(GetDelegate());
return GetDelegate() ? GetDelegate()->GetUniqueId().Get() : -1;
}
void AXPlatformNode::SetIsPrimaryWebContentsForWindow(bool is_primary) {
is_primary_web_contents_for_window_ = is_primary;
}
bool AXPlatformNode::IsPrimaryWebContentsForWindow() const {
return is_primary_web_contents_for_window_;
}
std::string AXPlatformNode::ToString() {
return GetDelegate() ? GetDelegate()->ToString() : "No delegate";
}
std::string AXPlatformNode::SubtreeToString() {
return GetDelegate() ? GetDelegate()->SubtreeToString() : "No delegate";
}
std::ostream& operator<<(std::ostream& stream, AXPlatformNode& node) {
return stream << node.ToString();
}
// static
void AXPlatformNode::AddAXModeObserver(AXModeObserver* observer) {
ax_mode_observers_.push_back(observer);
}
// static
void AXPlatformNode::RemoveAXModeObserver(AXModeObserver* observer) {
ax_mode_observers_.erase(std::find(ax_mode_observers_.begin(),
ax_mode_observers_.end(), observer));
}
// static
void AXPlatformNode::NotifyAddAXModeFlags(AXMode mode_flags) {
// Note: this is only called on Windows.
AXMode new_ax_mode(ax_mode_);
new_ax_mode |= mode_flags;
if (new_ax_mode == ax_mode_)
return; // No change.
ax_mode_ = new_ax_mode;
for (AXModeObserver* observer : ax_mode_observers_)
observer->OnAXModeAdded(mode_flags);
}
// static
void AXPlatformNode::SetPopupFocusOverride(
gfx::NativeViewAccessible popup_focus_override) {
popup_focus_override_ = popup_focus_override;
}
// static
gfx::NativeViewAccessible AXPlatformNode::GetPopupFocusOverride() {
return popup_focus_override_;
}
} // namespace ui
| engine/third_party/accessibility/ax/platform/ax_platform_node.cc/0 | {
"file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node.cc",
"repo_id": "engine",
"token_count": 971
} | 456 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ax/platform/ax_platform_node_win_unittest.h"
#include <UIAutomationClient.h>
#include <UIAutomationCoreApi.h>
#include <vector>
#include "ax/ax_action_data.h"
#include "ax/platform/ax_fragment_root_win.h"
#include "ax/platform/ax_platform_node_textprovider_win.h"
#include "ax/platform/ax_platform_node_textrangeprovider_win.h"
#include "ax/platform/test_ax_node_wrapper.h"
#include "base/win/scoped_bstr.h"
#include "base/win/scoped_safearray.h"
#include "flutter/fml/logging.h"
#include "flutter/fml/platform/win/wstring_conversion.h"
using Microsoft::WRL::ComPtr;
namespace ui {
// Helper macros for UIAutomation HRESULT expectations
#define EXPECT_UIA_INVALIDOPERATION(expr) \
EXPECT_EQ(static_cast<HRESULT>(UIA_E_INVALIDOPERATION), (expr))
#define EXPECT_INVALIDARG(expr) \
EXPECT_EQ(static_cast<HRESULT>(E_INVALIDARG), (expr))
class AXPlatformNodeTextProviderTest : public AXPlatformNodeWinTest {
public:
AXPlatformNodeTextProviderTest() = default;
~AXPlatformNodeTextProviderTest() override = default;
AXPlatformNodeTextProviderTest(const AXPlatformNodeTextProviderTest&) =
delete;
AXPlatformNodeTextProviderTest& operator=(
const AXPlatformNodeTextProviderTest&) = delete;
protected:
void SetOwner(AXPlatformNodeWin* owner,
ITextRangeProvider* destination_range) {
ComPtr<ITextRangeProvider> destination_provider = destination_range;
ComPtr<AXPlatformNodeTextRangeProviderWin> destination_provider_interal;
destination_provider->QueryInterface(
IID_PPV_ARGS(&destination_provider_interal));
destination_provider_interal->SetOwnerForTesting(owner);
}
AXPlatformNodeWin* GetOwner(
const AXPlatformNodeTextProviderWin* text_provider) {
return text_provider->owner_.Get();
}
const AXNodePosition::AXPositionInstance& GetStart(
const AXPlatformNodeTextRangeProviderWin* text_range) {
return text_range->start();
}
const AXNodePosition::AXPositionInstance& GetEnd(
const AXPlatformNodeTextRangeProviderWin* text_range) {
return text_range->end();
}
};
TEST_F(AXPlatformNodeTextProviderTest, CreateDegenerateRangeFromStart) {
AXNodeData text1_data;
text1_data.id = 3;
text1_data.role = ax::mojom::Role::kStaticText;
text1_data.SetName("some text");
AXNodeData text2_data;
text2_data.id = 4;
text2_data.role = ax::mojom::Role::kStaticText;
text2_data.SetName("more text");
AXNodeData link_data;
link_data.id = 2;
link_data.role = ax::mojom::Role::kLink;
link_data.child_ids = {3, 4};
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kStaticText;
root_data.SetName("Document");
root_data.child_ids = {2};
AXTreeUpdate update;
AXTreeData tree_data;
tree_data.tree_id = AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = root_data.id;
update.nodes = {root_data, link_data, text1_data, text2_data};
Init(update);
AXNode* root_node = GetRootAsAXNode();
AXNode* link_node = root_node->children()[0];
AXNode* text2_node = link_node->children()[1];
AXPlatformNodeWin* owner =
static_cast<AXPlatformNodeWin*>(AXPlatformNodeFromNode(root_node));
BASE_DCHECK(owner);
ComPtr<IRawElementProviderSimple> root_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(root_node);
ComPtr<IRawElementProviderSimple> link_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(link_node);
ComPtr<IRawElementProviderSimple> text2_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(text2_node);
ComPtr<AXPlatformNodeWin> root_platform_node;
EXPECT_HRESULT_SUCCEEDED(
root_node_raw->QueryInterface(IID_PPV_ARGS(&root_platform_node)));
ComPtr<AXPlatformNodeWin> link_platform_node;
EXPECT_HRESULT_SUCCEEDED(
link_node_raw->QueryInterface(IID_PPV_ARGS(&link_platform_node)));
ComPtr<AXPlatformNodeWin> text2_platform_node;
EXPECT_HRESULT_SUCCEEDED(
text2_node_raw->QueryInterface(IID_PPV_ARGS(&text2_platform_node)));
// Degenerate range created on root node should be:
// <>some textmore text
ComPtr<ITextRangeProvider> text_range_provider =
AXPlatformNodeTextProviderWin::CreateDegenerateRangeAtStart(
root_platform_node.Get());
SetOwner(owner, text_range_provider.Get());
base::win::ScopedBstr text_content;
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(-1, text_content.Receive()));
EXPECT_EQ(0, wcscmp(text_content.Get(), L""));
ComPtr<AXPlatformNodeTextRangeProviderWin> actual_range;
text_range_provider->QueryInterface(IID_PPV_ARGS(&actual_range));
AXNodePosition::AXPositionInstance expected_start, expected_end;
expected_start = root_platform_node->GetDelegate()->CreateTextPositionAt(0);
expected_end = expected_start->Clone();
EXPECT_EQ(*GetStart(actual_range.Get()), *expected_start);
EXPECT_EQ(*GetEnd(actual_range.Get()), *expected_end);
text_content.Release();
// Degenerate range created on link node should be:
// <>some textmore text
text_range_provider =
AXPlatformNodeTextProviderWin::CreateDegenerateRangeAtStart(
link_platform_node.Get());
SetOwner(owner, text_range_provider.Get());
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(-1, text_content.Receive()));
EXPECT_EQ(0, wcscmp(text_content.Get(), L""));
text_range_provider->QueryInterface(IID_PPV_ARGS(&actual_range));
EXPECT_EQ(*GetStart(actual_range.Get()), *expected_start);
EXPECT_EQ(*GetEnd(actual_range.Get()), *expected_end);
text_content.Release();
// Degenerate range created on more text node should be:
// some text<>more text
text_range_provider =
AXPlatformNodeTextProviderWin::CreateDegenerateRangeAtStart(
text2_platform_node.Get());
SetOwner(owner, text_range_provider.Get());
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(-1, text_content.Receive()));
EXPECT_EQ(0, wcscmp(text_content.Get(), L""));
text_range_provider->QueryInterface(IID_PPV_ARGS(&actual_range));
expected_start = text2_platform_node->GetDelegate()->CreateTextPositionAt(0);
expected_end = expected_start->Clone();
EXPECT_EQ(*GetStart(actual_range.Get()), *expected_start);
EXPECT_EQ(*GetEnd(actual_range.Get()), *expected_end);
text_content.Release();
}
TEST_F(AXPlatformNodeTextProviderTest, ITextProviderRangeFromChild) {
AXNodeData text_data;
text_data.id = 2;
text_data.role = ax::mojom::Role::kStaticText;
text_data.SetName("some text");
AXNodeData empty_text_data;
empty_text_data.id = 3;
empty_text_data.role = ax::mojom::Role::kStaticText;
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kStaticText;
root_data.SetName("Document");
root_data.child_ids.push_back(2);
root_data.child_ids.push_back(3);
AXTreeUpdate update;
AXTreeData tree_data;
tree_data.tree_id = AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = root_data.id;
update.nodes.push_back(root_data);
update.nodes.push_back(text_data);
update.nodes.push_back(empty_text_data);
Init(update);
AXNode* root_node = GetRootAsAXNode();
AXNode* text_node = root_node->children()[0];
AXNode* empty_text_node = root_node->children()[1];
AXPlatformNodeWin* owner =
static_cast<AXPlatformNodeWin*>(AXPlatformNodeFromNode(root_node));
BASE_DCHECK(owner);
ComPtr<IRawElementProviderSimple> root_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(root_node);
ComPtr<IRawElementProviderSimple> text_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(text_node);
ComPtr<IRawElementProviderSimple> empty_text_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(empty_text_node);
// Call RangeFromChild on the root with the text child passed in.
ComPtr<ITextProvider> text_provider;
EXPECT_HRESULT_SUCCEEDED(
root_node_raw->GetPatternProvider(UIA_TextPatternId, &text_provider));
ComPtr<ITextRangeProvider> text_range_provider;
EXPECT_HRESULT_SUCCEEDED(
text_provider->RangeFromChild(text_node_raw.Get(), &text_range_provider));
SetOwner(owner, text_range_provider.Get());
base::win::ScopedBstr text_content;
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(-1, text_content.Receive()));
EXPECT_EQ(0, wcscmp(text_content.Get(), L"some text"));
// Now test that the reverse relation doesn't return a valid
// ITextRangeProvider, and instead returns E_INVALIDARG.
EXPECT_HRESULT_SUCCEEDED(
text_node_raw->GetPatternProvider(UIA_TextPatternId, &text_provider));
EXPECT_INVALIDARG(
text_provider->RangeFromChild(root_node_raw.Get(), &text_range_provider));
// Now test that a child with no text returns a degenerate range.
EXPECT_HRESULT_SUCCEEDED(
root_node_raw->GetPatternProvider(UIA_TextPatternId, &text_provider));
EXPECT_HRESULT_SUCCEEDED(text_provider->RangeFromChild(
empty_text_node_raw.Get(), &text_range_provider));
SetOwner(owner, text_range_provider.Get());
base::win::ScopedBstr empty_text_content;
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(-1, empty_text_content.Receive()));
EXPECT_EQ(0, wcscmp(empty_text_content.Get(), L""));
// Test that passing in an object from a different instance of
// IRawElementProviderSimple than that of the valid text provider
// returns UIA_E_INVALIDOPERATION.
ComPtr<IRawElementProviderSimple> other_root_node_raw;
MockIRawElementProviderSimple::CreateMockIRawElementProviderSimple(
&other_root_node_raw);
EXPECT_HRESULT_SUCCEEDED(
root_node_raw->GetPatternProvider(UIA_TextPatternId, &text_provider));
EXPECT_UIA_INVALIDOPERATION(text_provider->RangeFromChild(
other_root_node_raw.Get(), &text_range_provider));
}
TEST_F(AXPlatformNodeTextProviderTest,
ITextProviderRangeFromChildMultipleChildren) {
const int ROOT_ID = 1;
const int DIALOG_ID = 2;
const int DIALOG_LABEL_ID = 3;
const int DIALOG_DESCRIPTION_ID = 4;
const int BUTTON_ID = 5;
const int BUTTON_IMG_ID = 6;
const int BUTTON_TEXT_ID = 7;
const int DIALOG_DETAIL_ID = 8;
AXNodeData root;
root.id = ROOT_ID;
root.role = ax::mojom::Role::kStaticText;
root.SetName("Document");
root.child_ids = {DIALOG_ID};
AXNodeData dialog;
dialog.id = DIALOG_ID;
dialog.role = ax::mojom::Role::kDialog;
dialog.child_ids = {DIALOG_LABEL_ID, DIALOG_DESCRIPTION_ID, BUTTON_ID,
DIALOG_DETAIL_ID};
AXNodeData dialog_label;
dialog_label.id = DIALOG_LABEL_ID;
dialog_label.role = ax::mojom::Role::kStaticText;
dialog_label.SetName("Dialog label.");
AXNodeData dialog_description;
dialog_description.id = DIALOG_DESCRIPTION_ID;
dialog_description.role = ax::mojom::Role::kStaticText;
dialog_description.SetName("Dialog description.");
AXNodeData button;
button.id = BUTTON_ID;
button.role = ax::mojom::Role::kButton;
button.child_ids = {BUTTON_IMG_ID, BUTTON_TEXT_ID};
AXNodeData button_img;
button_img.id = BUTTON_IMG_ID;
button_img.role = ax::mojom::Role::kImage;
AXNodeData button_text;
button_text.id = BUTTON_TEXT_ID;
button_text.role = ax::mojom::Role::kStaticText;
button_text.SetName("ok.");
AXNodeData dialog_detail;
dialog_detail.id = DIALOG_DETAIL_ID;
dialog_detail.role = ax::mojom::Role::kStaticText;
dialog_detail.SetName("Some more detail about dialog.");
AXTreeUpdate update;
AXTreeData tree_data;
tree_data.tree_id = AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = ROOT_ID;
update.nodes = {root, dialog, dialog_label, dialog_description,
button, button_img, button_text, dialog_detail};
Init(update);
AXNode* root_node = GetRootAsAXNode();
AXNode* dialog_node = root_node->children()[0];
AXPlatformNodeWin* owner =
static_cast<AXPlatformNodeWin*>(AXPlatformNodeFromNode(root_node));
BASE_DCHECK(owner);
ComPtr<IRawElementProviderSimple> root_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(root_node);
ComPtr<IRawElementProviderSimple> dialog_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(dialog_node);
// Call RangeFromChild on the root with the dialog child passed in.
ComPtr<ITextProvider> text_provider;
EXPECT_HRESULT_SUCCEEDED(
root_node_raw->GetPatternProvider(UIA_TextPatternId, &text_provider));
ComPtr<ITextRangeProvider> text_range_provider;
EXPECT_HRESULT_SUCCEEDED(text_provider->RangeFromChild(dialog_node_raw.Get(),
&text_range_provider));
SetOwner(owner, text_range_provider.Get());
base::win::ScopedBstr text_content;
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(-1, text_content.Receive()));
EXPECT_EQ(fml::WideStringToUtf16(text_content.Get()),
u"Dialog label.Dialog description." + kEmbeddedCharacterAsString +
u"ok.Some more detail " + u"about dialog.");
// Check the reverse relationship that GetEnclosingElement on the text range
// gives back the dialog.
ComPtr<IRawElementProviderSimple> enclosing_element;
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetEnclosingElement(&enclosing_element));
EXPECT_EQ(enclosing_element.Get(), dialog_node_raw.Get());
}
TEST_F(AXPlatformNodeTextProviderTest, NearestTextIndexToPoint) {
AXNodeData text_data;
text_data.id = 2;
text_data.role = ax::mojom::Role::kInlineTextBox;
text_data.SetName("text");
// spacing: "t-e-x---t-"
text_data.AddIntListAttribute(ax::mojom::IntListAttribute::kCharacterOffsets,
{2, 4, 8, 10});
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
root_data.relative_bounds.bounds = gfx::RectF(1, 1, 2, 2);
root_data.child_ids.push_back(2);
Init(root_data, text_data);
AXNode* root_node = GetRootAsAXNode();
AXNode* text_node = root_node->children()[0];
struct NearestTextIndexTestData {
AXNode* node;
struct point_offset_expected_index_pair {
int point_offset_x;
int expected_index;
};
std::vector<point_offset_expected_index_pair> test_data;
};
NearestTextIndexTestData nodes[] = {
{text_node,
{{0, 0}, {2, 0}, {3, 1}, {4, 1}, {5, 2}, {8, 2}, {9, 3}, {10, 3}}},
{root_node,
{{0, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}, {8, 0}, {9, 0}, {10, 0}}}};
for (auto data : nodes) {
if (!data.node->IsText() && !data.node->data().IsTextField()) {
continue;
}
ComPtr<IRawElementProviderSimple> element_provider =
QueryInterfaceFromNode<IRawElementProviderSimple>(data.node);
ComPtr<ITextProvider> text_provider;
EXPECT_HRESULT_SUCCEEDED(element_provider->GetPatternProvider(
UIA_TextPatternId, &text_provider));
// get internal implementation to access helper for testing
ComPtr<AXPlatformNodeTextProviderWin> platform_text_provider;
EXPECT_HRESULT_SUCCEEDED(
text_provider->QueryInterface(IID_PPV_ARGS(&platform_text_provider)));
ComPtr<AXPlatformNodeWin> platform_node;
EXPECT_HRESULT_SUCCEEDED(
element_provider->QueryInterface(IID_PPV_ARGS(&platform_node)));
for (auto pair : data.test_data) {
EXPECT_EQ(pair.expected_index, platform_node->NearestTextIndexToPoint(
gfx::Point(pair.point_offset_x, 0)));
}
}
}
TEST_F(AXPlatformNodeTextProviderTest, ITextProviderDocumentRange) {
AXNodeData text_data;
text_data.id = 2;
text_data.role = ax::mojom::Role::kStaticText;
text_data.SetName("some text");
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kStaticText;
root_data.SetName("Document");
root_data.child_ids.push_back(2);
Init(root_data, text_data);
ComPtr<IRawElementProviderSimple> root_node =
GetRootIRawElementProviderSimple();
ComPtr<ITextProvider> text_provider;
EXPECT_HRESULT_SUCCEEDED(
root_node->GetPatternProvider(UIA_TextPatternId, &text_provider));
ComPtr<ITextRangeProvider> text_range_provider;
EXPECT_HRESULT_SUCCEEDED(
text_provider->get_DocumentRange(&text_range_provider));
}
TEST_F(AXPlatformNodeTextProviderTest,
DISABLED_ITextProviderDocumentRangeTrailingIgnored) {
// ++1 root
// ++++2 kGenericContainer
// ++++++3 kStaticText "Hello"
// ++++4 kGenericContainer
// ++++++5 kGenericContainer
// ++++++++6 kStaticText "3.14"
// ++++7 kGenericContainer (ignored)
// ++++++8 kGenericContainer (ignored)
// ++++++++9 kStaticText "ignored"
AXNodeData root_1;
AXNodeData gc_2;
AXNodeData static_text_3;
AXNodeData gc_4;
AXNodeData gc_5;
AXNodeData static_text_6;
AXNodeData gc_7_ignored;
AXNodeData gc_8_ignored;
AXNodeData static_text_9_ignored;
root_1.id = 1;
gc_2.id = 2;
static_text_3.id = 3;
gc_4.id = 4;
gc_5.id = 5;
static_text_6.id = 6;
gc_7_ignored.id = 7;
gc_8_ignored.id = 8;
static_text_9_ignored.id = 9;
root_1.role = ax::mojom::Role::kRootWebArea;
root_1.child_ids = {gc_2.id, gc_4.id, gc_7_ignored.id};
root_1.SetName("Document");
gc_2.role = ax::mojom::Role::kGenericContainer;
gc_2.AddIntListAttribute(ax::mojom::IntListAttribute::kLabelledbyIds,
{static_text_3.id});
gc_2.child_ids = {static_text_3.id};
static_text_3.role = ax::mojom::Role::kStaticText;
static_text_3.SetName("Hello");
gc_4.role = ax::mojom::Role::kGenericContainer;
gc_4.AddIntListAttribute(ax::mojom::IntListAttribute::kLabelledbyIds,
{gc_5.id});
gc_4.child_ids = {gc_5.id};
gc_5.role = ax::mojom::Role::kGenericContainer;
gc_5.child_ids = {static_text_6.id};
static_text_6.role = ax::mojom::Role::kStaticText;
static_text_6.SetName("3.14");
gc_7_ignored.role = ax::mojom::Role::kGenericContainer;
gc_7_ignored.child_ids = {gc_8_ignored.id};
gc_7_ignored.AddState(ax::mojom::State::kIgnored);
gc_8_ignored.role = ax::mojom::Role::kGenericContainer;
gc_8_ignored.child_ids = {static_text_9_ignored.id};
gc_8_ignored.AddState(ax::mojom::State::kIgnored);
static_text_9_ignored.role = ax::mojom::Role::kStaticText;
static_text_9_ignored.SetName("ignored");
static_text_9_ignored.AddState(ax::mojom::State::kIgnored);
AXTreeUpdate update;
AXTreeData tree_data;
tree_data.tree_id = AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = root_1.id;
update.nodes = {root_1, gc_2, static_text_3,
gc_4, gc_5, static_text_6,
gc_7_ignored, gc_8_ignored, static_text_9_ignored};
Init(update);
ComPtr<IRawElementProviderSimple> root_node =
GetRootIRawElementProviderSimple();
ComPtr<ITextProvider> text_provider;
EXPECT_HRESULT_SUCCEEDED(
root_node->GetPatternProvider(UIA_TextPatternId, &text_provider));
ComPtr<ITextRangeProvider> text_range_provider;
EXPECT_HRESULT_SUCCEEDED(
text_provider->get_DocumentRange(&text_range_provider));
ComPtr<AXPlatformNodeTextRangeProviderWin> text_range;
text_range_provider->QueryInterface(IID_PPV_ARGS(&text_range));
ComPtr<ITextProvider> root_text_provider;
EXPECT_HRESULT_SUCCEEDED(
root_node->GetPatternProvider(UIA_TextPatternId, &root_text_provider));
ComPtr<AXPlatformNodeTextProviderWin> root_platform_node;
root_text_provider->QueryInterface(IID_PPV_ARGS(&root_platform_node));
AXPlatformNodeWin* owner = GetOwner(root_platform_node.Get());
AXNodePosition::AXPositionInstance expected_start =
owner->GetDelegate()->CreateTextPositionAt(0)->AsLeafTextPosition();
AXNodePosition::AXPositionInstance expected_end =
owner->GetDelegate()
->CreateTextPositionAt(0)
->CreatePositionAtEndOfAnchor();
expected_end = expected_end->AsLeafTextPosition();
EXPECT_EQ(*GetStart(text_range.Get()), *expected_start);
EXPECT_EQ(*GetEnd(text_range.Get()), *expected_end);
}
TEST_F(AXPlatformNodeTextProviderTest, ITextProviderDocumentRangeNested) {
AXNodeData text_data;
text_data.id = 3;
text_data.role = ax::mojom::Role::kStaticText;
text_data.SetName("some text");
AXNodeData paragraph_data;
paragraph_data.id = 2;
paragraph_data.role = ax::mojom::Role::kParagraph;
paragraph_data.child_ids.push_back(3);
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kStaticText;
root_data.SetName("Document");
root_data.child_ids.push_back(2);
Init(root_data, paragraph_data, text_data);
ComPtr<IRawElementProviderSimple> root_node =
GetRootIRawElementProviderSimple();
ComPtr<ITextProvider> text_provider;
EXPECT_HRESULT_SUCCEEDED(
root_node->GetPatternProvider(UIA_TextPatternId, &text_provider));
ComPtr<ITextRangeProvider> text_range_provider;
EXPECT_HRESULT_SUCCEEDED(
text_provider->get_DocumentRange(&text_range_provider));
}
TEST_F(AXPlatformNodeTextProviderTest, ITextProviderSupportedSelection) {
AXNodeData text_data;
text_data.id = 2;
text_data.role = ax::mojom::Role::kStaticText;
text_data.SetName("some text");
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kStaticText;
root_data.SetName("Document");
root_data.child_ids.push_back(2);
Init(root_data, text_data);
ComPtr<IRawElementProviderSimple> root_node =
GetRootIRawElementProviderSimple();
ComPtr<ITextProvider> text_provider;
EXPECT_HRESULT_SUCCEEDED(
root_node->GetPatternProvider(UIA_TextPatternId, &text_provider));
SupportedTextSelection text_selection_mode;
EXPECT_HRESULT_SUCCEEDED(
text_provider->get_SupportedTextSelection(&text_selection_mode));
EXPECT_EQ(text_selection_mode, SupportedTextSelection_Single);
}
TEST_F(AXPlatformNodeTextProviderTest, ITextProviderGetSelection) {
AXNodeData text_data;
text_data.id = 2;
text_data.role = ax::mojom::Role::kStaticText;
text_data.SetName("some text");
AXNodeData textbox_data;
textbox_data.id = 3;
textbox_data.role = ax::mojom::Role::kInlineTextBox;
textbox_data.SetName("textbox text");
textbox_data.AddState(ax::mojom::State::kEditable);
AXNodeData nonatomic_textfield_data;
nonatomic_textfield_data.id = 4;
nonatomic_textfield_data.role = ax::mojom::Role::kGroup;
nonatomic_textfield_data.child_ids = {5};
AXNodeData text_child_data;
text_child_data.id = 5;
text_child_data.role = ax::mojom::Role::kStaticText;
text_child_data.SetName("text");
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kStaticText;
root_data.SetName("Document");
root_data.child_ids = {2, 3, 4};
AXTreeUpdate update;
AXTreeData tree_data;
tree_data.tree_id = AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = root_data.id;
update.nodes = {root_data, text_data, textbox_data, nonatomic_textfield_data,
text_child_data};
Init(update);
ComPtr<IRawElementProviderSimple> root_node =
GetRootIRawElementProviderSimple();
ComPtr<ITextProvider> root_text_provider;
EXPECT_HRESULT_SUCCEEDED(
root_node->GetPatternProvider(UIA_TextPatternId, &root_text_provider));
base::win::ScopedSafearray selections;
root_text_provider->GetSelection(selections.Receive());
ASSERT_EQ(nullptr, selections.Get());
ComPtr<AXPlatformNodeTextProviderWin> root_platform_node;
root_text_provider->QueryInterface(IID_PPV_ARGS(&root_platform_node));
AXPlatformNodeWin* owner = GetOwner(root_platform_node.Get());
AXTreeData& selected_tree_data =
const_cast<AXTreeData&>(owner->GetDelegate()->GetTreeData());
selected_tree_data.sel_focus_object_id = 2;
selected_tree_data.sel_anchor_object_id = 2;
selected_tree_data.sel_anchor_offset = 0;
selected_tree_data.sel_focus_offset = 4;
root_text_provider->GetSelection(selections.Receive());
ASSERT_NE(nullptr, selections.Get());
LONG ubound;
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetUBound(selections.Get(), 1, &ubound));
EXPECT_EQ(0, ubound);
LONG lbound;
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetLBound(selections.Get(), 1, &lbound));
EXPECT_EQ(0, lbound);
LONG index = 0;
ComPtr<ITextRangeProvider> text_range_provider;
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetElement(
selections.Get(), &index, static_cast<void**>(&text_range_provider)));
SetOwner(owner, text_range_provider.Get());
base::win::ScopedBstr text_content;
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(-1, text_content.Receive()));
EXPECT_EQ(0, wcscmp(text_content.Get(), L"some"));
text_content.Reset();
selections.Reset();
text_range_provider.Reset();
// Verify that start and end are appropriately swapped when sel_anchor_offset
// is greater than sel_focus_offset
selected_tree_data.sel_focus_object_id = 2;
selected_tree_data.sel_anchor_object_id = 2;
selected_tree_data.sel_anchor_offset = 4;
selected_tree_data.sel_focus_offset = 0;
root_text_provider->GetSelection(selections.Receive());
ASSERT_NE(nullptr, selections.Get());
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetUBound(selections.Get(), 1, &ubound));
EXPECT_EQ(0, ubound);
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetLBound(selections.Get(), 1, &lbound));
EXPECT_EQ(0, lbound);
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetElement(
selections.Get(), &index, static_cast<void**>(&text_range_provider)));
SetOwner(owner, text_range_provider.Get());
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(-1, text_content.Receive()));
EXPECT_EQ(0, wcscmp(text_content.Get(), L"some"));
text_content.Reset();
selections.Reset();
text_range_provider.Reset();
// Verify that text ranges at an insertion point returns a degenerate (empty)
// text range via textbox with sel_anchor_offset equal to sel_focus_offset
selected_tree_data.sel_focus_object_id = 3;
selected_tree_data.sel_anchor_object_id = 3;
selected_tree_data.sel_anchor_offset = 1;
selected_tree_data.sel_focus_offset = 1;
AXNode* text_edit_node = GetRootAsAXNode()->children()[1];
ComPtr<IRawElementProviderSimple> text_edit_com =
QueryInterfaceFromNode<IRawElementProviderSimple>(text_edit_node);
ComPtr<ITextProvider> text_edit_provider;
EXPECT_HRESULT_SUCCEEDED(text_edit_com->GetPatternProvider(
UIA_TextPatternId, &text_edit_provider));
selections.Reset();
EXPECT_HRESULT_SUCCEEDED(
text_edit_provider->GetSelection(selections.Receive()));
EXPECT_NE(nullptr, selections.Get());
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetUBound(selections.Get(), 1, &ubound));
EXPECT_EQ(0, ubound);
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetLBound(selections.Get(), 1, &lbound));
EXPECT_EQ(0, lbound);
ComPtr<ITextRangeProvider> text_edit_range_provider;
EXPECT_HRESULT_SUCCEEDED(
SafeArrayGetElement(selections.Get(), &index,
static_cast<void**>(&text_edit_range_provider)));
SetOwner(owner, text_edit_range_provider.Get());
EXPECT_HRESULT_SUCCEEDED(
text_edit_range_provider->GetText(-1, text_content.Receive()));
EXPECT_EQ(0U, text_content.Length());
text_content.Reset();
selections.Reset();
text_edit_range_provider.Reset();
// Verify selections that span multiple nodes
selected_tree_data.sel_focus_object_id = 2;
selected_tree_data.sel_focus_offset = 0;
selected_tree_data.sel_anchor_object_id = 3;
selected_tree_data.sel_anchor_offset = 12;
root_text_provider->GetSelection(selections.Receive());
ASSERT_NE(nullptr, selections.Get());
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetUBound(selections.Get(), 1, &ubound));
EXPECT_EQ(0, ubound);
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetLBound(selections.Get(), 1, &lbound));
EXPECT_EQ(0, lbound);
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetElement(
selections.Get(), &index, static_cast<void**>(&text_range_provider)));
SetOwner(owner, text_range_provider.Get());
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(-1, text_content.Receive()));
EXPECT_EQ(0, wcscmp(text_content.Get(), L"some texttextbox text"));
text_content.Reset();
selections.Reset();
text_range_provider.Reset();
// Verify SAFEARRAY value for degenerate selection.
selected_tree_data.sel_focus_object_id = 2;
selected_tree_data.sel_anchor_object_id = 2;
selected_tree_data.sel_anchor_offset = 1;
selected_tree_data.sel_focus_offset = 1;
root_text_provider->GetSelection(selections.Receive());
ASSERT_NE(nullptr, selections.Get());
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetUBound(selections.Get(), 1, &ubound));
EXPECT_EQ(0, ubound);
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetLBound(selections.Get(), 1, &lbound));
EXPECT_EQ(0, lbound);
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetElement(
selections.Get(), &index, static_cast<void**>(&text_range_provider)));
SetOwner(owner, text_range_provider.Get());
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(-1, text_content.Receive()));
EXPECT_EQ(0, wcscmp(text_content.Get(), L""));
text_content.Reset();
selections.Reset();
text_range_provider.Reset();
// Removed testing logic for non-atomic text fields as we do not have this
// role.
// Now delete the tree (which will delete the associated elements) and verify
// that UIA_E_ELEMENTNOTAVAILABLE is returned when calling GetSelection on
// a dead element
DestroyTree();
EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE),
text_edit_provider->GetSelection(selections.Receive()));
}
TEST_F(AXPlatformNodeTextProviderTest, ITextProviderGetActiveComposition) {
AXNodeData text_data;
text_data.id = 2;
text_data.role = ax::mojom::Role::kStaticText;
text_data.SetName("some text");
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kStaticText;
root_data.SetName("Document");
root_data.child_ids.push_back(2);
AXTreeUpdate update;
AXTreeData tree_data;
tree_data.tree_id = AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = root_data.id;
update.nodes.push_back(root_data);
update.nodes.push_back(text_data);
Init(update);
ComPtr<IRawElementProviderSimple> root_node =
GetRootIRawElementProviderSimple();
ComPtr<ITextProvider> root_text_provider;
EXPECT_HRESULT_SUCCEEDED(
root_node->GetPatternProvider(UIA_TextPatternId, &root_text_provider));
ComPtr<ITextEditProvider> root_text_edit_provider;
EXPECT_HRESULT_SUCCEEDED(root_node->GetPatternProvider(
UIA_TextEditPatternId, &root_text_edit_provider));
ComPtr<ITextRangeProvider> text_range_provider;
root_text_edit_provider->GetActiveComposition(&text_range_provider);
ASSERT_EQ(nullptr, text_range_provider);
ComPtr<AXPlatformNodeTextProviderWin> root_platform_node;
root_text_provider->QueryInterface(IID_PPV_ARGS(&root_platform_node));
AXActionData action_data;
action_data.action = ax::mojom::Action::kFocus;
action_data.target_node_id = 1;
AXPlatformNodeWin* owner = GetOwner(root_platform_node.Get());
owner->GetDelegate()->AccessibilityPerformAction(action_data);
const std::u16string active_composition_text = u"a";
owner->OnActiveComposition(gfx::Range(0, 1), active_composition_text, false);
root_text_edit_provider->GetActiveComposition(&text_range_provider);
ASSERT_NE(nullptr, text_range_provider);
ComPtr<AXPlatformNodeTextRangeProviderWin> actual_range;
AXNodePosition::AXPositionInstance expected_start =
owner->GetDelegate()->CreateTextPositionAt(0);
AXNodePosition::AXPositionInstance expected_end =
owner->GetDelegate()->CreateTextPositionAt(1);
text_range_provider->QueryInterface(IID_PPV_ARGS(&actual_range));
EXPECT_EQ(*GetStart(actual_range.Get()), *expected_start);
EXPECT_EQ(*GetEnd(actual_range.Get()), *expected_end);
}
TEST_F(AXPlatformNodeTextProviderTest, ITextProviderGetConversionTarget) {
AXNodeData text_data;
text_data.id = 2;
text_data.role = ax::mojom::Role::kStaticText;
text_data.SetName("some text");
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kStaticText;
root_data.SetName("Document");
root_data.child_ids.push_back(2);
AXTreeUpdate update;
AXTreeData tree_data;
tree_data.tree_id = AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = root_data.id;
update.nodes.push_back(root_data);
update.nodes.push_back(text_data);
Init(update);
ComPtr<IRawElementProviderSimple> root_node =
GetRootIRawElementProviderSimple();
ComPtr<ITextProvider> root_text_provider;
EXPECT_HRESULT_SUCCEEDED(
root_node->GetPatternProvider(UIA_TextPatternId, &root_text_provider));
ComPtr<ITextEditProvider> root_text_edit_provider;
EXPECT_HRESULT_SUCCEEDED(root_node->GetPatternProvider(
UIA_TextEditPatternId, &root_text_edit_provider));
ComPtr<ITextRangeProvider> text_range_provider;
root_text_edit_provider->GetConversionTarget(&text_range_provider);
ASSERT_EQ(nullptr, text_range_provider);
ComPtr<AXPlatformNodeTextProviderWin> root_platform_node;
root_text_provider->QueryInterface(IID_PPV_ARGS(&root_platform_node));
AXActionData action_data;
action_data.action = ax::mojom::Action::kFocus;
action_data.target_node_id = 1;
AXPlatformNodeWin* owner = GetOwner(root_platform_node.Get());
owner->GetDelegate()->AccessibilityPerformAction(action_data);
const std::u16string active_composition_text = u"a";
owner->OnActiveComposition(gfx::Range(0, 1), active_composition_text, false);
root_text_edit_provider->GetConversionTarget(&text_range_provider);
ASSERT_NE(nullptr, text_range_provider);
ComPtr<AXPlatformNodeTextRangeProviderWin> actual_range;
AXNodePosition::AXPositionInstance expected_start =
owner->GetDelegate()->CreateTextPositionAt(0);
AXNodePosition::AXPositionInstance expected_end =
owner->GetDelegate()->CreateTextPositionAt(1);
text_range_provider->QueryInterface(IID_PPV_ARGS(&actual_range));
EXPECT_EQ(*GetStart(actual_range.Get()), *expected_start);
EXPECT_EQ(*GetEnd(actual_range.Get()), *expected_end);
}
} // namespace ui
| engine/third_party/accessibility/ax/platform/ax_platform_node_textprovider_win_unittest.cc/0 | {
"file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node_textprovider_win_unittest.cc",
"repo_id": "engine",
"token_count": 13169
} | 457 |
// 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.
#include "compute_attributes.h"
#include <cstddef>
#include "ax/ax_enums.h"
#include "ax/ax_node_data.h"
#include "ax_platform_node_delegate.h"
namespace ui {
namespace {
std::optional<int32_t> GetCellAttribute(
const ui::AXPlatformNodeDelegate* delegate,
ax::mojom::IntAttribute attribute) {
switch (attribute) {
case ax::mojom::IntAttribute::kAriaCellColumnIndex:
return delegate->GetTableCellAriaColIndex();
case ax::mojom::IntAttribute::kAriaCellRowIndex:
return delegate->GetTableCellAriaRowIndex();
case ax::mojom::IntAttribute::kTableCellColumnIndex:
return delegate->GetTableCellColIndex();
case ax::mojom::IntAttribute::kTableCellRowIndex:
return delegate->GetTableCellRowIndex();
case ax::mojom::IntAttribute::kTableCellColumnSpan:
return delegate->GetTableCellColSpan();
case ax::mojom::IntAttribute::kTableCellRowSpan:
return delegate->GetTableCellRowSpan();
default:
return std::nullopt;
}
}
std::optional<int32_t> GetRowAttribute(
const ui::AXPlatformNodeDelegate* delegate,
ax::mojom::IntAttribute attribute) {
if (attribute == ax::mojom::IntAttribute::kTableRowIndex) {
return delegate->GetTableRowRowIndex();
}
return std::nullopt;
}
std::optional<int32_t> GetTableAttribute(
const ui::AXPlatformNodeDelegate* delegate,
ax::mojom::IntAttribute attribute) {
switch (attribute) {
case ax::mojom::IntAttribute::kTableColumnCount:
return delegate->GetTableColCount();
case ax::mojom::IntAttribute::kTableRowCount:
return delegate->GetTableRowCount();
case ax::mojom::IntAttribute::kAriaColumnCount:
return delegate->GetTableAriaColCount();
case ax::mojom::IntAttribute::kAriaRowCount:
return delegate->GetTableAriaRowCount();
default:
return std::nullopt;
}
}
std::optional<int> GetOrderedSetItemAttribute(
const ui::AXPlatformNodeDelegate* delegate,
ax::mojom::IntAttribute attribute) {
switch (attribute) {
case ax::mojom::IntAttribute::kPosInSet:
return delegate->GetPosInSet();
case ax::mojom::IntAttribute::kSetSize:
return delegate->GetSetSize();
default:
return std::nullopt;
}
}
std::optional<int> GetOrderedSetAttribute(
const ui::AXPlatformNodeDelegate* delegate,
ax::mojom::IntAttribute attribute) {
switch (attribute) {
case ax::mojom::IntAttribute::kSetSize:
return delegate->GetSetSize();
default:
return std::nullopt;
}
}
std::optional<int32_t> GetFromData(const ui::AXPlatformNodeDelegate* delegate,
ax::mojom::IntAttribute attribute) {
int32_t value;
if (delegate->GetData().GetIntAttribute(attribute, &value)) {
return value;
}
return std::nullopt;
}
} // namespace
std::optional<int32_t> ComputeAttribute(
const ui::AXPlatformNodeDelegate* delegate,
ax::mojom::IntAttribute attribute) {
std::optional<int32_t> maybe_value = std::nullopt;
// Table-related nodes.
if (delegate->IsTableCellOrHeader())
maybe_value = GetCellAttribute(delegate, attribute);
else if (delegate->IsTableRow())
maybe_value = GetRowAttribute(delegate, attribute);
else if (delegate->IsTable())
maybe_value = GetTableAttribute(delegate, attribute);
// Ordered-set-related nodes.
else if (delegate->IsOrderedSetItem())
maybe_value = GetOrderedSetItemAttribute(delegate, attribute);
else if (delegate->IsOrderedSet())
maybe_value = GetOrderedSetAttribute(delegate, attribute);
if (!maybe_value.has_value()) {
return GetFromData(delegate, attribute);
}
return maybe_value;
}
} // namespace ui
| engine/third_party/accessibility/ax/platform/compute_attributes.cc/0 | {
"file_path": "engine/third_party/accessibility/ax/platform/compute_attributes.cc",
"repo_id": "engine",
"token_count": 1379
} | 458 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ACCESSIBILITY_BASE_COMPILER_SPECIFIC_H_
#define ACCESSIBILITY_BASE_COMPILER_SPECIFIC_H_
#if !defined(__GNUC__) && !defined(__clang__) && !defined(_MSC_VER)
#error Unsupported compiler.
#endif
// Annotate a variable indicating it's ok if the variable is not used.
// (Typically used to silence a compiler warning when the assignment
// is important for some other reason.)
// Use like:
// int x = ...;
// BASE_ALLOW_UNUSED_LOCAL(x);
#define BASE_ALLOW_UNUSED_LOCAL(x) false ? (void)x : (void)0
// Annotate a typedef or function indicating it's ok if it's not used.
// Use like:
// typedef Foo Bar ALLOW_UNUSED_TYPE;
#if defined(__GNUC__) || defined(__clang__)
#define BASE_ALLOW_UNUSED_TYPE __attribute__((unused))
#else
#define BASE_ALLOW_UNUSED_TYPE
#endif
#endif // ACCESSIBILITY_BASE_COMPILER_SPECIFIC_H_
// Macro for hinting that an expression is likely to be false.
#if !defined(BASE_UNLIKELY)
#if defined(COMPILER_GCC) || defined(__clang__)
#define BASE_UNLIKELY(x) __builtin_expect(!!(x), 0)
#else
#define BASE_UNLIKELY(x) (x)
#endif // defined(COMPILER_GCC)
#endif // !defined(BASE_UNLIKELY)
#if !defined(BASE_LIKELY)
#if defined(COMPILER_GCC) || defined(__clang__)
#define BASE_LIKELY(x) __builtin_expect(!!(x), 1)
#else
#define BASE_LIKELY(x) (x)
#endif // defined(COMPILER_GCC)
#endif // !defined(BASE_LIKELY)
// Macro for telling -Wimplicit-fallthrough that a fallthrough is intentional.
#if defined(__clang__)
#define BASE_FALLTHROUGH [[clang::fallthrough]]
#else
#define BASE_FALLTHROUGH
#endif
| engine/third_party/accessibility/base/compiler_specific.h/0 | {
"file_path": "engine/third_party/accessibility/base/compiler_specific.h",
"repo_id": "engine",
"token_count": 645
} | 459 |
// 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_CONVERSIONS_ARM_IMPL_H_
#define BASE_NUMERICS_SAFE_CONVERSIONS_ARM_IMPL_H_
#include <cassert>
#include <limits>
#include <type_traits>
#include "base/numerics/safe_conversions_impl.h"
namespace base {
namespace internal {
// Fast saturation to a destination type.
template <typename Dst, typename Src>
struct SaturateFastAsmOp {
static constexpr bool is_supported =
std::is_signed<Src>::value && std::is_integral<Dst>::value &&
std::is_integral<Src>::value &&
IntegerBitsPlusSign<Src>::value <= IntegerBitsPlusSign<int32_t>::value &&
IntegerBitsPlusSign<Dst>::value <= IntegerBitsPlusSign<int32_t>::value &&
!IsTypeInRangeForNumericType<Dst, Src>::value;
__attribute__((always_inline)) static Dst Do(Src value) {
int32_t src = value;
typename std::conditional<std::is_signed<Dst>::value, int32_t,
uint32_t>::type result;
if (std::is_signed<Dst>::value) {
asm("ssat %[dst], %[shift], %[src]"
: [dst] "=r"(result)
: [src] "r"(src), [shift] "n"(IntegerBitsPlusSign<Dst>::value <= 32
? IntegerBitsPlusSign<Dst>::value
: 32));
} else {
asm("usat %[dst], %[shift], %[src]"
: [dst] "=r"(result)
: [src] "r"(src), [shift] "n"(IntegerBitsPlusSign<Dst>::value < 32
? IntegerBitsPlusSign<Dst>::value
: 31));
}
return static_cast<Dst>(result);
}
};
} // namespace internal
} // namespace base
#endif // BASE_NUMERICS_SAFE_CONVERSIONS_ARM_IMPL_H_
| engine/third_party/accessibility/base/numerics/safe_conversions_arm_impl.h/0 | {
"file_path": "engine/third_party/accessibility/base/numerics/safe_conversions_arm_impl.h",
"repo_id": "engine",
"token_count": 886
} | 460 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/win/dispatch_stub.h"
namespace base {
namespace win {
namespace test {
IFACEMETHODIMP DispatchStub::GetTypeInfoCount(UINT*) {
return E_NOTIMPL;
}
IFACEMETHODIMP DispatchStub::GetTypeInfo(UINT, LCID, ITypeInfo**) {
return E_NOTIMPL;
}
IFACEMETHODIMP DispatchStub::GetIDsOfNames(REFIID,
LPOLESTR*,
UINT,
LCID,
DISPID*) {
return E_NOTIMPL;
}
IFACEMETHODIMP DispatchStub::Invoke(DISPID,
REFIID,
LCID,
WORD,
DISPPARAMS*,
VARIANT*,
EXCEPINFO*,
UINT*) {
return E_NOTIMPL;
}
} // namespace test
} // namespace win
} // namespace base
| engine/third_party/accessibility/base/win/dispatch_stub.cc/0 | {
"file_path": "engine/third_party/accessibility/base/win/dispatch_stub.cc",
"repo_id": "engine",
"token_count": 694
} | 461 |
// 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 BASE_WIN_VARIANT_UTIL_H_
#define BASE_WIN_VARIANT_UTIL_H_
#include "base/logging.h"
namespace base {
namespace win {
namespace internal {
// Returns true if a VARIANT of type |self| can be assigned to a
// variant of type |other|.
// Does not allow converting unsigned <-> signed or converting between
// different sized types, but does allow converting IDispatch* -> IUnknown*.
constexpr bool VarTypeIsConvertibleTo(VARTYPE self, VARTYPE other) {
// IDispatch inherits from IUnknown, so it's safe to
// upcast a VT_DISPATCH into an IUnknown*.
return (self == other) || (self == VT_DISPATCH && other == VT_UNKNOWN);
}
// VartypeToNativeType contains the underlying |Type| and offset to the
// VARIANT union member related to the |ElementVartype| for simple types.
template <VARTYPE ElementVartype>
struct VartypeToNativeType final {};
template <>
struct VartypeToNativeType<VT_BOOL> final {
using Type = VARIANT_BOOL;
static constexpr VARIANT_BOOL VARIANT::*kMemberOffset = &VARIANT::boolVal;
};
template <>
struct VartypeToNativeType<VT_I1> final {
using Type = int8_t;
static constexpr CHAR VARIANT::*kMemberOffset = &VARIANT::cVal;
};
template <>
struct VartypeToNativeType<VT_UI1> final {
using Type = uint8_t;
static constexpr BYTE VARIANT::*kMemberOffset = &VARIANT::bVal;
};
template <>
struct VartypeToNativeType<VT_I2> final {
using Type = int16_t;
static constexpr SHORT VARIANT::*kMemberOffset = &VARIANT::iVal;
};
template <>
struct VartypeToNativeType<VT_UI2> final {
using Type = uint16_t;
static constexpr USHORT VARIANT::*kMemberOffset = &VARIANT::uiVal;
};
template <>
struct VartypeToNativeType<VT_I4> final {
using Type = int32_t;
static constexpr LONG VARIANT::*kMemberOffset = &VARIANT::lVal;
};
template <>
struct VartypeToNativeType<VT_UI4> final {
using Type = uint32_t;
static constexpr ULONG VARIANT::*kMemberOffset = &VARIANT::ulVal;
};
template <>
struct VartypeToNativeType<VT_I8> final {
using Type = int64_t;
static constexpr LONGLONG VARIANT::*kMemberOffset = &VARIANT::llVal;
};
template <>
struct VartypeToNativeType<VT_UI8> final {
using Type = uint64_t;
static constexpr ULONGLONG VARIANT::*kMemberOffset = &VARIANT::ullVal;
};
template <>
struct VartypeToNativeType<VT_R4> final {
using Type = float;
static constexpr FLOAT VARIANT::*kMemberOffset = &VARIANT::fltVal;
};
template <>
struct VartypeToNativeType<VT_R8> final {
using Type = double;
static constexpr DOUBLE VARIANT::*kMemberOffset = &VARIANT::dblVal;
};
template <>
struct VartypeToNativeType<VT_DATE> final {
using Type = DATE;
static constexpr DATE VARIANT::*kMemberOffset = &VARIANT::date;
};
template <>
struct VartypeToNativeType<VT_BSTR> final {
using Type = BSTR;
static constexpr BSTR VARIANT::*kMemberOffset = &VARIANT::bstrVal;
};
template <>
struct VartypeToNativeType<VT_UNKNOWN> final {
using Type = IUnknown*;
static constexpr IUnknown* VARIANT::*kMemberOffset = &VARIANT::punkVal;
};
template <>
struct VartypeToNativeType<VT_DISPATCH> final {
using Type = IDispatch*;
static constexpr IDispatch* VARIANT::*kMemberOffset = &VARIANT::pdispVal;
};
// VariantUtil contains the underlying |Type| and helper methods
// related to the |ElementVartype| for simple types.
template <VARTYPE ElementVartype>
struct VariantUtil final {
using Type = typename VartypeToNativeType<ElementVartype>::Type;
static constexpr bool IsConvertibleTo(VARTYPE vartype) {
return VarTypeIsConvertibleTo(ElementVartype, vartype);
}
static constexpr bool IsConvertibleFrom(VARTYPE vartype) {
return VarTypeIsConvertibleTo(vartype, ElementVartype);
}
// Get the associated VARIANT union member value.
// Returns the value owned by the VARIANT without affecting the lifetime
// of managed contents.
// e.g. Does not affect IUnknown* reference counts or allocate a BSTR.
static Type RawGet(const VARIANT& var) {
BASE_DCHECK(IsConvertibleFrom(V_VT(&var)));
return var.*VartypeToNativeType<ElementVartype>::kMemberOffset;
}
// Set the associated VARIANT union member value.
// The caller is responsible for handling the lifetime of managed contents.
// e.g. Incrementing IUnknown* reference counts or allocating a BSTR.
static void RawSet(VARIANT* var, Type value) {
BASE_DCHECK(IsConvertibleTo(V_VT(var)));
var->*VartypeToNativeType<ElementVartype>::kMemberOffset = value;
}
};
} // namespace internal
} // namespace win
} // namespace base
#endif // BASE_WIN_VARIANT_UTIL_H_
| engine/third_party/accessibility/base/win/variant_util.h/0 | {
"file_path": "engine/third_party/accessibility/base/win/variant_util.h",
"repo_id": "engine",
"token_count": 1616
} | 462 |
// 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_POINT_F_H_
#define UI_GFX_GEOMETRY_POINT_F_H_
#include <iosfwd>
#include <string>
#include <tuple>
#include "gfx/gfx_export.h"
#include "point.h"
#include "vector2d_f.h"
namespace gfx {
// A floating version of gfx::Point.
class GFX_EXPORT PointF {
public:
constexpr PointF() : x_(0.f), y_(0.f) {}
constexpr PointF(float x, float y) : x_(x), y_(y) {}
constexpr explicit PointF(const Point& p)
: PointF(static_cast<float>(p.x()), static_cast<float>(p.y())) {}
constexpr float x() const { return x_; }
constexpr float y() const { return y_; }
void set_x(float x) { x_ = x; }
void set_y(float y) { y_ = y; }
void SetPoint(float x, float y) {
x_ = x;
y_ = y;
}
void Offset(float delta_x, float delta_y) {
x_ += delta_x;
y_ += delta_y;
}
void operator+=(const Vector2dF& vector) {
x_ += vector.x();
y_ += vector.y();
}
void operator-=(const Vector2dF& vector) {
x_ -= vector.x();
y_ -= vector.y();
}
void SetToMin(const PointF& other);
void SetToMax(const PointF& other);
bool IsOrigin() const { return x_ == 0 && y_ == 0; }
Vector2dF OffsetFromOrigin() const { return Vector2dF(x_, y_); }
// A point is less than another point if its y-value is closer
// to the origin. If the y-values are the same, then point with
// the x-value closer to the origin is considered less than the
// other.
// This comparison is required to use PointF in sets, or sorted
// vectors.
bool operator<(const PointF& rhs) const {
return std::tie(y_, x_) < std::tie(rhs.y_, rhs.x_);
}
void Scale(float scale) { Scale(scale, scale); }
void Scale(float x_scale, float y_scale) {
SetPoint(x() * x_scale, y() * y_scale);
}
// Returns a string representation of point.
std::string ToString() const;
private:
float x_;
float y_;
};
inline bool operator==(const PointF& lhs, const PointF& rhs) {
return lhs.x() == rhs.x() && lhs.y() == rhs.y();
}
inline bool operator!=(const PointF& lhs, const PointF& rhs) {
return !(lhs == rhs);
}
inline PointF operator+(const PointF& lhs, const Vector2dF& rhs) {
PointF result(lhs);
result += rhs;
return result;
}
inline PointF operator-(const PointF& lhs, const Vector2dF& rhs) {
PointF result(lhs);
result -= rhs;
return result;
}
inline Vector2dF operator-(const PointF& lhs, const PointF& rhs) {
return Vector2dF(lhs.x() - rhs.x(), lhs.y() - rhs.y());
}
inline PointF PointAtOffsetFromOrigin(const Vector2dF& offset_from_origin) {
return PointF(offset_from_origin.x(), offset_from_origin.y());
}
GFX_EXPORT PointF ScalePoint(const PointF& p, float x_scale, float y_scale);
inline PointF ScalePoint(const PointF& p, float scale) {
return ScalePoint(p, 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 PointF& point, ::std::ostream* os);
} // namespace gfx
#endif // UI_GFX_GEOMETRY_POINT_F_H_
| engine/third_party/accessibility/gfx/geometry/point_f.h/0 | {
"file_path": "engine/third_party/accessibility/gfx/geometry/point_f.h",
"repo_id": "engine",
"token_count": 1232
} | 463 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "vector2d.h"
#include <cmath>
#include "base/numerics/clamped_math.h"
#include "base/string_utils.h"
namespace gfx {
bool Vector2d::IsZero() const {
return x_ == 0 && y_ == 0;
}
void Vector2d::Add(const Vector2d& other) {
x_ = base::ClampAdd(other.x_, x_);
y_ = base::ClampAdd(other.y_, y_);
}
void Vector2d::Subtract(const Vector2d& other) {
x_ = base::ClampSub(x_, other.x_);
y_ = base::ClampSub(y_, other.y_);
}
int64_t Vector2d::LengthSquared() const {
return static_cast<int64_t>(x_) * x_ + static_cast<int64_t>(y_) * y_;
}
float Vector2d::Length() const {
return static_cast<float>(std::sqrt(static_cast<double>(LengthSquared())));
}
std::string Vector2d::ToString() const {
return base::StringPrintf("[%d %d]", x_, y_);
}
} // namespace gfx
| engine/third_party/accessibility/gfx/geometry/vector2d.cc/0 | {
"file_path": "engine/third_party/accessibility/gfx/geometry/vector2d.cc",
"repo_id": "engine",
"token_count": 381
} | 464 |
// 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_GFX_TEST_GFX_UTIL_H_
#define UI_GFX_TEST_GFX_UTIL_H_
#include <iosfwd>
#include <string>
#include "gtest/gtest.h"
namespace gfx {
class AxisTransform2d;
class BoxF;
class PointF;
class RectF;
class SizeF;
#define EXPECT_AXIS_TRANSFORM2D_EQ(a, b) \
EXPECT_PRED_FORMAT2(::gfx::AssertAxisTransform2dFloatEqual, a, b)
::testing::AssertionResult AssertAxisTransform2dFloatEqual(
const char* lhs_expr,
const char* rhs_expr,
const AxisTransform2d& lhs,
const AxisTransform2d& rhs);
#define EXPECT_BOXF_EQ(a, b) \
EXPECT_PRED_FORMAT2(::gfx::AssertBoxFloatEqual, a, b)
::testing::AssertionResult AssertBoxFloatEqual(const char* lhs_expr,
const char* rhs_expr,
const BoxF& lhs,
const BoxF& rhs);
#define EXPECT_POINTF_EQ(a, b) \
EXPECT_PRED_FORMAT2(::gfx::AssertPointFloatEqual, a, b)
::testing::AssertionResult AssertPointFloatEqual(const char* lhs_expr,
const char* rhs_expr,
const PointF& lhs,
const PointF& rhs);
#define EXPECT_RECTF_EQ(a, b) \
EXPECT_PRED_FORMAT2(::gfx::AssertRectFloatEqual, a, b)
::testing::AssertionResult AssertRectFloatEqual(const char* lhs_expr,
const char* rhs_expr,
const RectF& lhs,
const RectF& rhs);
#define EXPECT_SIZEF_EQ(a, b) \
EXPECT_PRED_FORMAT2(::gfx::AssertSizeFFloatEqual, a, b)
::testing::AssertionResult AssertSizeFFloatEqual(const char* lhs_expr,
const char* rhs_expr,
const SizeF& lhs,
const SizeF& rhs);
} // namespace gfx
#endif // UI_GFX_TEST_GFX_UTIL_H_
| engine/third_party/accessibility/gfx/test/gfx_util.h/0 | {
"file_path": "engine/third_party/accessibility/gfx/test/gfx_util.h",
"repo_id": "engine",
"token_count": 1247
} | 465 |
# This is the list of Fuchsia Authors.
# Names should be added to this file as one of
# Organization's name
# Individual's name <submission email address>
# Individual's name <submission email address> <email2> <emailN>
Google Inc.
The Chromium Authors
| engine/third_party/tonic/AUTHORS/0 | {
"file_path": "engine/third_party/tonic/AUTHORS",
"repo_id": "engine",
"token_count": 82
} | 466 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef LIB_TONIC_DART_CLASS_PROVIDER_H_
#define LIB_TONIC_DART_CLASS_PROVIDER_H_
#include "third_party/dart/runtime/include/dart_api.h"
#include "tonic/dart_persistent_value.h"
namespace tonic {
class DartState;
class DartClassProvider {
public:
DartClassProvider(DartState* dart_state, const char* library_name);
~DartClassProvider();
Dart_Handle GetClassByName(const char* class_name);
private:
DartPersistentValue library_;
TONIC_DISALLOW_COPY_AND_ASSIGN(DartClassProvider);
};
} // namespace tonic
#endif // LIB_TONIC_DART_CLASS_PROVIDER_H_
| engine/third_party/tonic/dart_class_provider.h/0 | {
"file_path": "engine/third_party/tonic/dart_class_provider.h",
"repo_id": "engine",
"token_count": 255
} | 467 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef LIB_TONIC_DART_WRAPPABLE_H_
#define LIB_TONIC_DART_WRAPPABLE_H_
#include "third_party/dart/runtime/include/dart_api.h"
#include "tonic/common/macros.h"
#include "tonic/converter/dart_converter.h"
#include "tonic/dart_state.h"
#include "tonic/dart_weak_persistent_value.h"
#include "tonic/dart_wrapper_info.h"
#include "tonic/logging/dart_error.h"
#include <type_traits>
namespace tonic {
// DartWrappable is a base class that you can inherit from in order to be
// exposed to Dart code as an interface.
class DartWrappable {
public:
enum DartNativeFields {
kPeerIndex, // Must be first to work with Dart_GetNativeReceiver.
kNumberOfNativeFields,
};
DartWrappable() : dart_wrapper_(DartWeakPersistentValue()) {}
// Subclasses that wish to expose a new interface must override this function
// and provide information about their wrapper. There is no need to call your
// base class's implementation of this function.
// Implement using IMPLEMENT_WRAPPERTYPEINFO macro
virtual const DartWrapperInfo& GetDartWrapperInfo() const = 0;
virtual void RetainDartWrappableReference() const = 0;
virtual void ReleaseDartWrappableReference() const = 0;
// Use this method sparingly. It follows a slower path using Dart_New.
// Prefer constructing the object in Dart code and using
// AssociateWithDartWrapper.
Dart_Handle CreateDartWrapper(DartState* dart_state);
void AssociateWithDartWrapper(Dart_Handle wrappable);
void ClearDartWrapper(); // Warning: Might delete this.
Dart_WeakPersistentHandle dart_wrapper() const {
return dart_wrapper_.value();
}
protected:
virtual ~DartWrappable();
static Dart_PersistentHandle GetTypeForWrapper(
tonic::DartState* dart_state,
const tonic::DartWrapperInfo& wrapper_info);
private:
static void FinalizeDartWrapper(void* isolate_callback_data, void* peer);
DartWeakPersistentValue dart_wrapper_;
TONIC_DISALLOW_COPY_AND_ASSIGN(DartWrappable);
};
#define DEFINE_WRAPPERTYPEINFO() \
public: \
const tonic::DartWrapperInfo& GetDartWrapperInfo() const override { \
return dart_wrapper_info_; \
} \
static Dart_PersistentHandle GetDartType(tonic::DartState* dart_state) { \
return GetTypeForWrapper(dart_state, dart_wrapper_info_); \
} \
\
private: \
static const tonic::DartWrapperInfo& dart_wrapper_info_
#define IMPLEMENT_WRAPPERTYPEINFO(LibraryName, ClassName) \
static const tonic::DartWrapperInfo \
kDartWrapperInfo_##LibraryName_##ClassName(#LibraryName, #ClassName); \
const tonic::DartWrapperInfo& ClassName::dart_wrapper_info_ = \
kDartWrapperInfo_##LibraryName_##ClassName;
struct DartConverterWrappable {
static DartWrappable* FromDart(Dart_Handle handle);
static DartWrappable* FromArguments(Dart_NativeArguments args,
int index,
Dart_Handle& exception);
};
template <typename T>
struct DartConverter<
T*,
typename std::enable_if<
std::is_convertible<T*, const DartWrappable*>::value>::type> {
using FfiType = DartWrappable*;
static constexpr const char* kFfiRepresentation = "Pointer";
static constexpr const char* kDartRepresentation = "Pointer";
static constexpr bool kAllowedInLeafCall = true;
static Dart_Handle ToDart(DartWrappable* val) {
if (!val) {
return Dart_Null();
}
if (Dart_WeakPersistentHandle wrapper = val->dart_wrapper()) {
auto strong_handle = Dart_HandleFromWeakPersistent(wrapper);
if (!Dart_IsNull(strong_handle)) {
return strong_handle;
}
// After the weak referenced object has been GCed, the handle points to
// Dart_Null(). Fall through create a new wrapper object.
}
return val->CreateDartWrapper(DartState::Current());
}
static void SetReturnValue(Dart_NativeArguments args,
DartWrappable* val,
bool auto_scope = true) {
if (!val) {
Dart_SetReturnValue(args, Dart_Null());
return;
} else if (Dart_WeakPersistentHandle wrapper = val->dart_wrapper()) {
auto strong_handle = Dart_HandleFromWeakPersistent(wrapper);
if (!Dart_IsNull(strong_handle)) {
Dart_SetReturnValue(args, strong_handle);
return;
}
// After the weak referenced object has been GCed, the handle points to
// Dart_Null(). Fall through create a new wrapper object.
}
Dart_SetReturnValue(args, val->CreateDartWrapper(DartState::Current()));
}
static T* FromDart(Dart_Handle handle) {
// TODO(abarth): We're missing a type check.
return static_cast<T*>(DartConverterWrappable::FromDart(handle));
}
static T* FromArguments(Dart_NativeArguments args,
int index,
Dart_Handle& exception,
bool auto_scope = true) {
// TODO(abarth): We're missing a type check.
return static_cast<T*>(
DartConverterWrappable::FromArguments(args, index, exception));
}
static T* FromFfi(FfiType val) { return static_cast<T*>(val); }
static FfiType ToFfi(T* val) { return val; }
static const char* GetFfiRepresentation() { return kFfiRepresentation; }
static const char* GetDartRepresentation() { return kDartRepresentation; }
static bool AllowedInLeafCall() { return kAllowedInLeafCall; }
};
////////////////////////////////////////////////////////////////////////////////
// Support for generic smart pointers that have a "get" method that returns a
// pointer to a type that is Dart convertible as well as a constructor that
// adopts a raw pointer to that type.
template <template <typename T> class PTR, typename T>
struct DartConverter<PTR<T>> {
using NativeType = PTR<T>;
using FfiType = Dart_Handle;
static constexpr const char* kFfiRepresentation = "Handle";
static constexpr const char* kDartRepresentation = "Object";
static constexpr bool kAllowedInLeafCall = false;
static Dart_Handle ToDart(const NativeType& val) {
return DartConverter<T*>::ToDart(val.get());
}
static NativeType FromDart(Dart_Handle handle) {
return NativeType(DartConverter<T*>::FromDart(handle));
}
static NativeType FromArguments(Dart_NativeArguments args,
int index,
Dart_Handle& exception,
bool auto_scope = true) {
return NativeType(
DartConverter<T*>::FromArguments(args, index, exception, auto_scope));
}
static void SetReturnValue(Dart_NativeArguments args,
const NativeType& val,
bool auto_scope = true) {
DartConverter<T*>::SetReturnValue(args, val.get());
}
static NativeType FromFfi(FfiType val) { return FromDart(val); }
static FfiType ToFfi(const NativeType& val) { return ToDart(val); }
static const char* GetFfiRepresentation() { return kFfiRepresentation; }
static const char* GetDartRepresentation() { return kDartRepresentation; }
static bool AllowedInLeafCall() { return kAllowedInLeafCall; }
};
template <typename T>
inline T* GetReceiver(Dart_NativeArguments args) {
intptr_t receiver;
Dart_Handle result = Dart_GetNativeReceiver(args, &receiver);
TONIC_DCHECK(!Dart_IsError(result));
if (!receiver)
Dart_ThrowException(ToDart("Object has been disposed."));
return static_cast<T*>(reinterpret_cast<DartWrappable*>(receiver));
}
} // namespace tonic
#endif // LIB_TONIC_DART_WRAPPABLE_H_
| engine/third_party/tonic/dart_wrappable.h/0 | {
"file_path": "engine/third_party/tonic/dart_wrappable.h",
"repo_id": "engine",
"token_count": 3363
} | 468 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FILESYSTEM_PORTABLE_UNISTD_H_
#define FILESYSTEM_PORTABLE_UNISTD_H_
#include "tonic/common/build_config.h"
#if defined(OS_WIN)
#include <direct.h>
#include <io.h>
#include <stdlib.h>
#define STDERR_FILENO _fileno(stderr)
#define PATH_MAX _MAX_PATH
#define S_ISDIR(m) (((m)&S_IFMT) == S_IFDIR)
#define S_ISREG(m) (((m)&S_IFMT) == S_IFREG)
#define R_OK 4
#define mkdir(path, mode) _mkdir(path)
#else
#include <unistd.h>
#endif
#endif // FILESYSTEM_PORTABLE_UNISTD_H_
| engine/third_party/tonic/filesystem/filesystem/portable_unistd.h/0 | {
"file_path": "engine/third_party/tonic/filesystem/filesystem/portable_unistd.h",
"repo_id": "engine",
"token_count": 271
} | 469 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef LIB_TONIC_SCOPES_DART_ISOLATE_SCOPE_H_
#define LIB_TONIC_SCOPES_DART_ISOLATE_SCOPE_H_
#include "third_party/dart/runtime/include/dart_api.h"
#include "tonic/common/macros.h"
namespace tonic {
// DartIsolateScope is a helper class for entering and exiting a given isolate.
class DartIsolateScope {
public:
explicit DartIsolateScope(Dart_Isolate isolate);
~DartIsolateScope();
private:
Dart_Isolate isolate_;
Dart_Isolate previous_;
TONIC_DISALLOW_COPY_AND_ASSIGN(DartIsolateScope);
};
} // namespace tonic
#endif // LIB_TONIC_SCOPES_DART_ISOLATE_SCOPE_H_
| engine/third_party/tonic/scopes/dart_isolate_scope.h/0 | {
"file_path": "engine/third_party/tonic/scopes/dart_isolate_scope.h",
"repo_id": "engine",
"token_count": 272
} | 470 |
/*
* Copyright 2019 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.
*/
#include "font_features.h"
#include <sstream>
namespace txt {
void FontFeatures::SetFeature(std::string tag, int value) {
feature_map_[tag] = value;
}
std::string FontFeatures::GetFeatureSettings() const {
if (feature_map_.empty())
return "";
std::ostringstream stream;
for (const auto& kv : feature_map_) {
if (stream.tellp()) {
stream << ',';
}
stream << kv.first << '=' << kv.second;
}
return stream.str();
}
const std::map<std::string, int>& FontFeatures::GetFontFeatures() const {
return feature_map_;
}
void FontVariations::SetAxisValue(std::string tag, float value) {
axis_map_[tag] = value;
}
const std::map<std::string, float>& FontVariations::GetAxisValues() const {
return axis_map_;
}
} // namespace txt
| engine/third_party/txt/src/txt/font_features.cc/0 | {
"file_path": "engine/third_party/txt/src/txt/font_features.cc",
"repo_id": "engine",
"token_count": 439
} | 471 |
// Copyright 2013 The Flutter 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 "txt/platform.h"
#if defined(SK_FONTMGR_FONTCONFIG_AVAILABLE)
#include "third_party/skia/include/ports/SkFontMgr_fontconfig.h"
#endif
#if defined(SK_FONTMGR_FREETYPE_DIRECTORY_AVAILABLE)
#include "include/ports/SkFontMgr_directory.h"
#endif
#if defined(SK_FONTMGR_FREETYPE_EMPTY_AVAILABLE)
#include "third_party/skia/include/ports/SkFontMgr_empty.h"
#endif
namespace txt {
std::vector<std::string> GetDefaultFontFamilies() {
return {"Ubuntu", "Cantarell", "DejaVu Sans", "Liberation Sans", "Arial"};
}
sk_sp<SkFontMgr> GetDefaultFontManager(uint32_t font_initialization_data) {
#if defined(SK_FONTMGR_FONTCONFIG_AVAILABLE)
static sk_sp<SkFontMgr> mgr = SkFontMgr_New_FontConfig(nullptr);
#elif defined(SK_FONTMGR_FREETYPE_DIRECTORY_AVAILABLE)
static sk_sp<SkFontMgr> mgr =
SkFontMgr_New_Custom_Directory("/usr/share/fonts/");
#elif defined(SK_FONTMGR_FREETYPE_EMPTY_AVAILABLE)
static sk_sp<SkFontMgr> mgr = SkFontMgr_New_Custom_Empty();
#else
static sk_sp<SkFontMgr> mgr = SkFontMgr::RefEmpty();
#endif
return mgr;
}
} // namespace txt
| engine/third_party/txt/src/txt/platform_linux.cc/0 | {
"file_path": "engine/third_party/txt/src/txt/platform_linux.cc",
"repo_id": "engine",
"token_count": 509
} | 472 |
# Web Locale Keymap
This package maps Web's KeyboardEvent to Flutter's logical keys. It only
includes "locale sensitive" keys, which are all the letters, regular digits, and
symbols. It works for all layouts shown in [Microsoft/VSCode](https://github.com/microsoft/vscode) repo.
The mapping data and test cases are generated by `gen_web_locale_keymap` package.
Do not edit them manually.
# Usage
1. Ensure that the key is a locale key.
2. Get the logical key from `getLogicalKey()`.
3. If the return value is null, then the key can not be mapped as a character
either. Mint the logical key value.
```dart
import 'package:web_locale_keymap/web_locale_keymap.dart' as locale_keymap;
final locale_keymap.LocaleKeymap mapping =
locale_keymap.LocaleKeymap.win(); // Or .darwin() or .linux()
/* ... */
int getLogicalKey(html.KeyboardEvent event) {
int? result = _convertToDeadKey(event)
?? _convertToUnprintableKey(event)
?? _convertToNumpadKey(event);
if (result != null) {
return result;
}
result = mapping.getLogicalKey(event.code, event.key, event.keyCode);
if (result != null) {
return result;
}
return _mintLogicalKey(event);
}
```
| engine/third_party/web_locale_keymap/README.md/0 | {
"file_path": "engine/third_party/web_locale_keymap/README.md",
"repo_id": "engine",
"token_count": 409
} | 473 |
#!/usr/bin/env python3
#
# Copyright 2019 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import datetime
import os
import sys
import json
THIS_DIR = os.path.abspath(os.path.dirname(__file__))
# The template for the POM file.
POM_FILE_CONTENT = '''<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>io.flutter</groupId>
<artifactId>{0}</artifactId>
<version>{1}</version>
<packaging>jar</packaging>
<dependencies>
{2}
</dependencies>
</project>
'''
POM_DEPENDENCY = '''
<dependency>
<groupId>{0}</groupId>
<artifactId>{1}</artifactId>
<version>{2}</version>
<scope>compile</scope>
</dependency>
'''
MAVEN_METADATA_CONTENT = '''
<metadata xmlns="http://maven.apache.org/METADATA/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/METADATA/1.1.0 http://maven.apache.org/xsd/metadata-1.1.0.xsd" modelVersion="1.1.0">
<groupId>io.flutter</groupId>
<artifactId>{0}</artifactId>
<version>{1}</version>
<versioning>
<versions>
<version>{1}</version>
</versions>
<snapshot>
<timestamp>{2}</timestamp>
<buildNumber>0</buildNumber>
</snapshot>
<snapshotVersions>
<snapshotVersion>
<extension>jar</extension>
<value>{1}</value>
</snapshotVersion>
<snapshotVersion>
<extension>pom</extension>
<value>{1}</value>
</snapshotVersion>
</snapshotVersions>
</versioning>
</metadata>
'''
def utf8(s):
return str(s, 'utf-8') if isinstance(s, (bytes, bytearray)) else s
def main():
with open(os.path.join(THIS_DIR, 'files.json')) as f:
dependencies = json.load(f)
parser = argparse.ArgumentParser(description='Generate the POM file for the engine artifacts')
parser.add_argument(
'--engine-artifact-id',
type=utf8,
required=True,
help='The artifact id. e.g. android_arm_release'
)
parser.add_argument('--engine-version', type=utf8, required=True, help='The engine commit hash')
parser.add_argument(
'--destination', type=utf8, required=True, help='The destination directory absolute path'
)
parser.add_argument(
'--include-embedding-dependencies',
type=bool,
help='Include the dependencies for the embedding'
)
args = parser.parse_args()
engine_artifact_id = args.engine_artifact_id
engine_version = args.engine_version
artifact_version = '1.0.0-' + engine_version
out_file_name = '%s.pom' % engine_artifact_id
pom_dependencies = ''
if args.include_embedding_dependencies:
for dependency in dependencies:
if not dependency['provides']:
# Don't include transitive dependencies since they aren't used by the embedding.
continue
group_id, artifact_id, version = dependency['maven_dependency'].split(':')
pom_dependencies += POM_DEPENDENCY.format(group_id, artifact_id, version)
# Write the POM file.
with open(os.path.join(args.destination, out_file_name), 'w') as f:
f.write(POM_FILE_CONTENT.format(engine_artifact_id, artifact_version, pom_dependencies))
# Write the Maven metadata file.
with open(os.path.join(args.destination, '%s.maven-metadata.xml' % engine_artifact_id), 'w') as f:
timestamp = datetime.datetime.utcnow().strftime("%Y%m%d.%H%M%S")
f.write(MAVEN_METADATA_CONTENT.format(engine_artifact_id, artifact_version, timestamp))
if __name__ == '__main__':
sys.exit(main())
| engine/tools/androidx/generate_pom_file.py/0 | {
"file_path": "engine/tools/androidx/generate_pom_file.py",
"repo_id": "engine",
"token_count": 1525
} | 474 |
package: flutter_internal/tools/arm-tools
description: Tools for analyzing shaders
install_mode: copy
data:
- dir: arm-tools
| engine/tools/cipd/malioc/cipd.yaml/0 | {
"file_path": "engine/tools/cipd/malioc/cipd.yaml",
"repo_id": "engine",
"token_count": 38
} | 475 |
#!/usr/bin/env python3
#
# 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.
"""
This script is based on chromium/chromium/main/tools/clang/scripts/update.py.
It is used on Windows platforms to copy the correct msdia*.dll to the
clang folder, as a "gclient hook".
"""
import os
import shutil
import stat
import sys
# Path constants. (All of these should be absolute paths.)
THIS_DIR = os.path.abspath(os.path.dirname(__file__))
LLVM_BUILD_DIR = os.path.abspath(
os.path.join(THIS_DIR, '..', '..', 'buildtools', 'windows-x64', 'clang')
)
def GetDiaDll():
"""Get the location of msdia*.dll for the platform."""
# Bump after VC updates.
DIA_DLL = {
'2013': 'msdia120.dll',
'2015': 'msdia140.dll',
'2017': 'msdia140.dll',
'2019': 'msdia140.dll',
'2022': 'msdia140.dll',
}
# Don't let vs_toolchain overwrite our environment.
environ_bak = os.environ
sys.path.append(os.path.join(THIS_DIR, '..', '..', 'build'))
import vs_toolchain
win_sdk_dir = vs_toolchain.SetEnvironmentAndGetSDKDir()
msvs_version = vs_toolchain.GetVisualStudioVersion()
if bool(int(os.environ.get('DEPOT_TOOLS_WIN_TOOLCHAIN', '1'))):
# Depot tools .zip layout:
# \- DIA SDK
# \- Windows Kits
# \- 10
# \- ... # Location of `DEPOT_TOOLS_WIN_TOOLCHAIN`
dia_path = os.path.join(win_sdk_dir, '..', '..', 'DIA SDK', 'bin', 'amd64')
else:
if 'GYP_MSVS_OVERRIDE_PATH' in os.environ:
vs_path = os.environ['GYP_MSVS_OVERRIDE_PATH']
else:
vs_path = vs_toolchain.DetectVisualStudioPath()
dia_path = os.path.join(vs_path, 'DIA SDK', 'bin', 'amd64')
os.environ = environ_bak
return os.path.join(dia_path, DIA_DLL[msvs_version])
def CopyFile(src, dst):
"""Copy a file from src to dst."""
print("Copying %s to %s" % (str(src), str(dst)))
shutil.copy(src, dst)
def CopyDiaDllTo(target_dir):
# This script always wants to use the 64-bit msdia*.dll.
dia_dll = GetDiaDll()
CopyFile(dia_dll, target_dir)
def main():
CopyDiaDllTo(os.path.join(LLVM_BUILD_DIR, 'bin'))
return 0
if __name__ == '__main__':
sys.exit(main())
| engine/tools/dia_dll.py/0 | {
"file_path": "engine/tools/dia_dll.py",
"repo_id": "engine",
"token_count": 920
} | 476 |
// Copyright 2013 The Flutter 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:ffi' as ffi show Abi;
import 'dart:io' as io show Directory, Platform, exitCode, stderr;
import 'package:engine_build_configs/engine_build_configs.dart';
import 'package:engine_repo_tools/engine_repo_tools.dart';
import 'package:path/path.dart' as p;
import 'package:platform/platform.dart';
import 'package:process_runner/process_runner.dart';
import 'src/commands/command_runner.dart';
import 'src/environment.dart';
import 'src/logger.dart';
void main(List<String> args) async {
// Find the engine repo.
final Engine engine;
try {
engine = Engine.findWithin(p.dirname(io.Platform.script.toFilePath()));
} catch (e) {
io.stderr.writeln(e);
io.exitCode = 1;
return;
}
// Find and parse the engine build configs.
final io.Directory buildConfigsDir = io.Directory(p.join(
engine.flutterDir.path,
'ci',
'builders',
));
final BuildConfigLoader loader = BuildConfigLoader(
buildConfigsDir: buildConfigsDir,
);
// Treat it as an error if no build configs were found. The caller likely
// expected to find some.
final Map<String, BuilderConfig> configs = loader.configs;
if (configs.isEmpty) {
io.stderr.writeln(
'Error: No build configs found under ${buildConfigsDir.path}',
);
io.exitCode = 1;
return;
}
if (loader.errors.isNotEmpty) {
loader.errors.forEach(io.stderr.writeln);
io.exitCode = 1;
}
final Environment environment = Environment(
abi: ffi.Abi.current(),
engine: engine,
platform: const LocalPlatform(),
processRunner: ProcessRunner(),
logger: Logger(),
);
// Use the Engine and BuildConfig collection to build the CommandRunner.
final ToolCommandRunner runner = ToolCommandRunner(
environment: environment,
configs: configs,
);
try {
io.exitCode = await runner.run(args);
} on FatalError catch (e, st) {
environment.logger.error('FatalError caught in main. Please file a bug\n'
'error: $e\n'
'stack: $st');
io.exitCode = 1;
}
return;
}
| engine/tools/engine_tool/lib/main.dart/0 | {
"file_path": "engine/tools/engine_tool/lib/main.dart",
"repo_id": "engine",
"token_count": 780
} | 477 |
// Copyright 2013 The Flutter 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';
import 'package:path/path.dart' as p;
import 'package:process_runner/process_runner.dart';
import 'environment.dart';
import 'json_utils.dart';
import 'worker_pool.dart';
/// Artifacts from an exited sub-process.
final class ProcessArtifacts {
/// Constructs an instance of ProcessArtifacts from raw values.
ProcessArtifacts(
this.cwd, this.commandLine, this.exitCode, this.stdout, this.stderr,
{this.pid});
/// Constructs an instance of ProcessArtifacts from serialized JSON text.
factory ProcessArtifacts.fromJson(String serialized) {
final Map<String, dynamic> artifact =
jsonDecode(serialized) as Map<String, dynamic>;
final List<String> errors = <String>[];
final Directory cwd = Directory(stringOfJson(artifact, 'cwd', errors)!);
final List<String> commandLine =
stringListOfJson(artifact, 'commandLine', errors)!;
final int exitCode = intOfJson(artifact, 'exitCode', errors)!;
final String stdout = stringOfJson(artifact, 'stdout', errors)!;
final String stderr = stringOfJson(artifact, 'stderr', errors)!;
return ProcessArtifacts(cwd, commandLine, exitCode, stdout, stderr);
}
/// Constructs an instance of ProcessArtifacts from a file containing JSON.
factory ProcessArtifacts.fromFile(File file) {
return ProcessArtifacts.fromJson(file.readAsStringSync());
}
/// Saves ProcessArtifacts into file.
void save(File file) {
final Map<String, Object> data = <String, Object>{};
if (pid != null) {
data['pid'] = pid!;
}
data['exitCode'] = exitCode;
data['stdout'] = stdout;
data['stderr'] = stderr;
data['cwd'] = cwd.absolute.path;
data['commandLine'] = commandLine;
file.writeAsStringSync(jsonEncodePretty(data));
}
/// Creates a temporary file and saves the artifacts into it.
/// Returns the File.
File saveTemp() {
final Directory systemTemp = Directory.systemTemp;
final String prefix = pid != null ? 'et$pid' : 'et';
final Directory artifacts = systemTemp.createTempSync(prefix);
final File resultFile =
File(p.join(artifacts.path, 'process_artifacts.json'));
save(resultFile);
return resultFile;
}
/// Current working directory of process when it was spawned.
final Directory cwd;
/// Full command line of process.
final List<String> commandLine;
/// Exit code.
final int exitCode;
/// Stdout (may be empty).
final String stdout;
/// Stdout (may be empty).
final String stderr;
/// Pid (when available).
final int? pid;
}
/// A WorkerTask that runs a process
class ProcessTask extends WorkerTask {
/// Construct a new process task with name, cwd, and command line.
ProcessTask(super.name, this._environment, this._cwd, this._commandLine);
final Environment _environment;
final Directory _cwd;
final List<String> _commandLine;
late ProcessArtifacts? _processArtifacts;
late String? _processArtifactsPath;
@override
Future<bool> run() async {
final ProcessRunnerResult result = await _environment.processRunner
.runProcess(_commandLine, failOk: true, workingDirectory: _cwd);
_processArtifacts = ProcessArtifacts(
_cwd, _commandLine, result.exitCode, result.stdout, result.stderr,
pid: result.pid);
_processArtifactsPath = _processArtifacts!.saveTemp().path;
return result.exitCode == 0;
}
/// Returns the ProcessArtifacts after run completes.
ProcessArtifacts get processArtifacts {
return _processArtifacts!;
}
/// Returns the path that the process artifacts were saved in.
String get processArtifactsPath {
return _processArtifactsPath!;
}
}
| engine/tools/engine_tool/lib/src/proc_utils.dart/0 | {
"file_path": "engine/tools/engine_tool/lib/src/proc_utils.dart",
"repo_id": "engine",
"token_count": 1255
} | 478 |
#!/usr/bin/env vpython3
import unittest
import build_fuchsia_artifacts
class BuildFuchsiaArtifactsTest(unittest.TestCase):
def test_read_fuchsia_target_api_level(self):
# It's expected to update this test each time the fuchsia_target_api_level
# in //flutter/build/config/fuchsia/gn_configs.gni is changed, so it won't
# accidentally publishing the artifacts with a wrong api level suffix.
self.assertEqual(build_fuchsia_artifacts.ReadTargetAPILevel(), '16')
if __name__ == '__main__':
unittest.main()
| engine/tools/fuchsia/build_fuchsia_artifacts_test.py/0 | {
"file_path": "engine/tools/fuchsia/build_fuchsia_artifacts_test.py",
"repo_id": "engine",
"token_count": 182
} | 479 |
#!/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.
'''Reads the contents of a kernel manifest generated by the build and
converts it to a format suitable for distribution_entries
'''
import argparse
import collections
import json
import os
import sys
Entry = collections.namedtuple('Entry', ['source', 'dest'])
def collect(path_prefix, lines):
'''Reads the kernel manifest and creates an array of Entry objects.
- lines: a list of lines from the manifest
'''
entries = []
for line in lines:
values = line.split("=", 1)
entries.append(Entry(source=path_prefix + values[1], dest=values[0]))
return entries
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'--path_prefix', help='Directory path containing the manifest entry sources', required=True
)
parser.add_argument('--input', help='Path to original manifest', required=True)
parser.add_argument('--output', help='Path to the updated json file', required=True)
args = parser.parse_args()
with open(args.input, 'r') as input_file:
contents = input_file.read().splitlines()
entries = collect(args.path_prefix, contents)
if entries is None:
return 1
with open(args.output, 'w') as output_file:
json.dump([e._asdict() for e in entries],
output_file,
indent=2,
sort_keys=True,
separators=(',', ': '))
return 0
if __name__ == '__main__':
sys.exit(main())
| engine/tools/fuchsia/dart/kernel/convert_manifest_to_json.py/0 | {
"file_path": "engine/tools/fuchsia/dart/kernel/convert_manifest_to_json.py",
"repo_id": "engine",
"token_count": 536
} | 480 |
# Copyright 2013 The Flutter 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/flutter/flutter_build_config.gni")
declare_args() {
if (flutter_runtime_mode == "release") {
# Product AOT
flutter_default_build_cfg = flutter_release_build_cfg
} else if (flutter_runtime_mode == "jit_release") {
# Product JIT
flutter_default_build_cfg = flutter_jit_release_build_cfg
} else if (flutter_runtime_mode == "debug") {
# Non-product JIT
flutter_default_build_cfg = flutter_debug_build_cfg
} else { # "profile"
# Non-product AOT
flutter_default_build_cfg = flutter_profile_build_cfg
}
}
| engine/tools/fuchsia/flutter/config.gni/0 | {
"file_path": "engine/tools/fuchsia/flutter/config.gni",
"repo_id": "engine",
"token_count": 264
} | 481 |
# Copyright 2013 The Flutter 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/dart_library.gni")
import("//flutter/tools/fuchsia/gn-sdk/src/fidl_library.gni")
template("_fuchsia_dart_library") {
assert(defined(invoker.meta), "The meta file content must be specified.")
meta = invoker.meta
assert(meta.type == "dart_library")
_output_name = meta.name
_sources = []
_deps = []
_dart_language_version = "2.12"
foreach(source, meta.sources) {
_sources += [ string_replace("$source", "${meta.root}/lib/", "") ]
}
foreach(dep, meta.deps) {
_deps += [ "../dart:$dep" ]
}
foreach(dep, meta.fidl_deps) {
_deps += [ "//flutter/tools/fuchsia/fidl:$dep" ]
}
# Compute the third_party deps. The Fuchsia SDK doesn't know where to resolve
# a third_party dep, and Flutter has third_party Dart libraries in more than
# one location (some downloaded directly, others as part of the Dart SDK or
# bundled as a Dart SDK third_party dep). Find a matching library. If a match
# is required by a build dependency, and a match is not found, you may need to
# add an entry for it in `flutter/DEPS`.
known_pkg_paths = [
"third_party/pkg",
"third_party/dart/pkg",
"third_party/dart/third_party/pkg",
]
args = [
"--ignore-missing",
"--root",
rebase_path("//"),
"--target",
rebase_path(target_name, "//"),
]
foreach(path, known_pkg_paths) {
args += [
"--local-path",
path,
]
}
foreach(third_party_dep, meta.third_party_deps) {
_deps += [ "//flutter/shell/platform/fuchsia/dart:" + third_party_dep.name ]
}
dart_library(target_name) {
package_root = "${fuchsia_sdk}/${meta.root}"
package_name = _output_name
language_version = _dart_language_version
sources = _sources
deps = _deps
}
}
template("sdk_targets") {
assert(defined(invoker.meta), "The meta.json file path must be specified.")
target_type = invoker.target_name
meta_json = read_file(invoker.meta, "json")
foreach(part, meta_json.parts) {
part_meta_json = {
}
part_meta = part.meta
part_meta_rebased = "$fuchsia_sdk/$part_meta"
if (part_meta != "version_history.json") {
part_meta_json = read_file(part_meta_rebased, "json")
subtarget_name = part_meta_json.name
# Check if the part is using `part.element_type` or `part.type`.
part_type = ""
if (defined(part.element_type)) {
part_type = part.element_type
} else if (defined(part.type)) {
part_type = part.type
}
if (part_type == target_type) {
if (target_type == "dart_library") {
_fuchsia_dart_library(subtarget_name) {
meta = part_meta_json
}
} else if (target_type == "fidl_library") {
fidl_library(subtarget_name) {
meta = part_meta_json
}
}
}
}
}
group(target_name) {
}
}
| engine/tools/fuchsia/sdk/sdk_targets.gni/0 | {
"file_path": "engine/tools/fuchsia/sdk/sdk_targets.gni",
"repo_id": "engine",
"token_count": 1255
} | 482 |
// Copyright 2014 The Flutter 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:http/http.dart' as http;
import 'package:meta/meta.dart' show immutable;
import 'package:path/path.dart' as path;
import 'common.dart';
import 'json_get.dart';
import 'layout_types.dart';
/// Signature for function that asynchonously returns a value.
typedef AsyncGetter<T> = Future<T> Function();
/// The filename of the local cache for the GraphQL response.
const String _githubCacheFileName = 'github-response.json';
/// The file of the remote repo to query.
const String _githubTargetFolder = 'src/vs/workbench/services/keybinding/browser/keyboardLayouts';
/// The full query string for GraphQL.
const String _githubQuery = '''
{
repository(owner: "microsoft", name: "vscode") {
defaultBranchRef {
target {
... on Commit {
history(first: 1) {
nodes {
oid
file(path: "$_githubTargetFolder") {
extension lineCount object {
... on Tree {
entries {
name object {
... on Blob {
text
}
}
}
}
}
}
}
}
}
}
}
}
}
''';
/// All goals in the form of KeyboardEvent.key.
final List<String> _kGoalKeys = kLayoutGoals.keys.toList();
/// A map from the key of `kLayoutGoals` (KeyboardEvent.key) to an
/// auto-incremental index.
final Map<String, int> _kGoalToIndex = Map<String, int>.fromEntries(
_kGoalKeys.asMap().entries.map(
(MapEntry<int, String> entry) => MapEntry<String, int>(entry.value, entry.key)),
);
/// Retrieve a string using the procedure defined by `ifNotExist` based on the
/// cache file at `cachePath`.
///
/// If `forceRefresh` is false, this function tries to read the cache file, calls
/// `ifNotExist` when necessary, and writes the result to the cache.
///
/// If `forceRefresh` is true, this function never read the cache file, always
/// calls `ifNotExist` when necessary, and still writes the result to the cache.
///
/// Exceptions from `ifNotExist` will be thrown, while exceptions related to
/// caching are only printed.
Future<String> _tryCached(String cachePath, bool forceRefresh, AsyncGetter<String> ifNotExist) async {
final File cacheFile = File(cachePath);
if (!forceRefresh && cacheFile.existsSync()) {
try {
final String result = cacheFile.readAsStringSync();
print('Using GitHub cache.');
return result;
} catch (exception) {
print('Error reading GitHub cache, rebuilding. Details: $exception');
}
}
final String result = await ifNotExist();
IOSink? sink;
try {
print('Requesting from GitHub...');
Directory(path.dirname(cachePath)).createSync(recursive: true);
sink = cacheFile.openWrite();
cacheFile.writeAsStringSync(result);
} catch (exception) {
print('Error writing GitHub cache. Details: $exception');
} finally {
sink?.close();
}
return result;
}
/// Make a GraphQL request, cache it, and return the result.
///
/// If `forceRefresh` is false, this function tries to read the cache file at
/// `cachePath`. Regardless of `forceRefresh`, the response is always recorded
/// in the cache file.
Future<Map<String, dynamic>> _fetchGithub(String githubToken, bool forceRefresh, String cachePath) async {
final String response = await _tryCached(cachePath, forceRefresh, () async {
final String condensedQuery = _githubQuery
.replaceAll(RegExp(r'\{ +'), '{')
.replaceAll(RegExp(r' +\}'), '}');
final http.Response response = await http.post(
Uri.parse('https://api.github.com/graphql'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'bearer $githubToken',
},
body: jsonEncode(<String, String>{
'query': condensedQuery,
}),
);
if (response.statusCode != 200) {
throw Exception('Request to GitHub failed with status code ${response.statusCode}: ${response.reasonPhrase}');
}
return response.body;
});
return jsonDecode(response) as Map<String, dynamic>;
}
@immutable
class _GitHubFile {
const _GitHubFile({required this.name, required this.content});
final String name;
final String content;
}
_GitHubFile _jsonGetGithubFile(JsonContext<JsonArray> files, int index) {
final JsonContext<JsonObject> file = jsonGetIndex<JsonObject>(files, index);
return _GitHubFile(
name: jsonGetKey<String>(file, 'name').current,
content: jsonGetPath<String>(file, 'object.text').current,
);
}
/// Parses a literal JavaScript string that represents a character, which might
/// have been escaped or empty.
String _parsePrintable(String rawString, int isDeadKey) {
// Parse a char represented in unicode hex, such as \u001b.
final RegExp hexParser = RegExp(r'^\\u([0-9a-fA-F]+)$');
if (isDeadKey != 0) {
return LayoutEntry.kDeadKey;
}
if (rawString.isEmpty) {
return '';
}
final RegExpMatch? hexMatch = hexParser.firstMatch(rawString);
if (hexMatch != null) {
final int codeUnit = int.parse(hexMatch.group(1)!, radix: 16);
return String.fromCharCode(codeUnit);
}
return const <String, String>{
r'\\': r'\',
r'\r': '\r',
r'\b': '\b',
r'\t': '\t',
r"\'": "'",
}[rawString] ?? rawString;
}
LayoutPlatform _platformFromGithubString(String origin) {
switch (origin) {
case 'win':
return LayoutPlatform.win;
case 'linux':
return LayoutPlatform.linux;
case 'darwin':
return LayoutPlatform.darwin;
default:
throw ArgumentError('Unexpected platform "$origin".');
}
}
/// Parses a single layout file.
Layout _parseLayoutFromGithubFile(_GitHubFile file) {
final Map<String, LayoutEntry> entries = <String, LayoutEntry>{};
// Parse a line that looks like the following, and get its key as well as
// the content within the square bracket.
//
// F19: [],
// KeyZ: ['y', 'Y', '', '', 0, 'VK_Y'],
final RegExp lineParser = RegExp(r'^[ \t]*(.+?): \[(.*)\],$');
// Parse each child of the content within the square bracket.
final RegExp listParser = RegExp(r"^'(.*?)', '(.*?)', '(.*?)', '(.*?)', (\d)(?:, '(.+)')?$");
file.content.split('\n').forEach((String line) {
final RegExpMatch? lineMatch = lineParser.firstMatch(line);
if (lineMatch == null) {
return;
}
// KeyboardKey.code, such as "KeyZ".
final String eventCode = lineMatch.group(1)!;
// Only record goals.
if (!_kGoalToIndex.containsKey(eventCode)) {
return;
}
// Comma-separated definition as a string, such as "'y', 'Y', '', '', 0, 'VK_Y'".
final String definition = lineMatch.group(2)!;
if (definition.isEmpty) {
return;
}
// Group 1-4 are single strings for an entry, such as "y", "", "\u001b".
// Group 5 is the dead mask.
final RegExpMatch? listMatch = listParser.firstMatch(definition);
assert(listMatch != null, 'Unable to match $definition');
final int deadMask = int.parse(listMatch!.group(5)!, radix: 10);
entries[eventCode] = LayoutEntry(
<String>[
_parsePrintable(listMatch.group(1)!, deadMask & 0x1),
_parsePrintable(listMatch.group(2)!, deadMask & 0x2),
_parsePrintable(listMatch.group(3)!, deadMask & 0x4),
_parsePrintable(listMatch.group(4)!, deadMask & 0x8),
],
);
});
for (final String goalKey in _kGoalKeys) {
entries.putIfAbsent(goalKey, () => LayoutEntry.empty);
}
// Parse the file name, which looks like "en-belgian.win.ts".
final RegExp fileNameParser = RegExp(r'^([^.]+)\.([^.]+)\.ts$');
late final Layout layout;
try {
final RegExpMatch? match = fileNameParser.firstMatch(file.name);
final String layoutName = match!.group(1)!;
final LayoutPlatform platform = _platformFromGithubString(match.group(2)!);
layout = Layout(layoutName, platform, entries);
} catch (exception) {
throw ArgumentError('Unrecognizable file name ${file.name}.');
}
return layout;
}
/// Sort layouts by language first, then by platform.
int _sortLayout(Layout a, Layout b) {
int result = a.language.compareTo(b.language);
if (result == 0) {
result = a.platform.index.compareTo(b.platform.index);
}
return result;
}
/// The overall results returned from the GitHub request.
class GithubResult {
/// Create a [GithubResult].
const GithubResult(this.layouts, this.url);
/// All layouts, sorted.
final List<Layout> layouts;
/// The URL that points to the source folder of the VSCode GitHub repo,
/// containing the correct commit hash.
final String url;
}
/// Fetch necessary information from the VSCode GitHub repo.
///
/// The GraphQL request is made using the token `githubToken` (which requires
/// no extra access). The response is cached in files under directory
/// `cacheRoot`.
///
/// If `force` is false, this function tries to read the cache. Regardless of
/// `force`, the response is always recorded in the cache.
Future<GithubResult> fetchFromGithub({
required String githubToken,
required bool force,
required String cacheRoot,
}) async {
// Fetch files from GitHub.
final Map<String, dynamic> githubBody = await _fetchGithub(
githubToken,
force,
path.join(cacheRoot, _githubCacheFileName),
);
// Parse the result from GitHub.
final JsonContext<JsonObject> commitJson = jsonGetPath<JsonObject>(
JsonContext.root(githubBody),
'data.repository.defaultBranchRef.target.history.nodes.0',
);
final String commitId = jsonGetKey<String>(commitJson, 'oid').current;
final JsonContext<JsonArray> fileListJson = jsonGetPath<JsonArray>(
commitJson,
'file.object.entries',
);
final Iterable<_GitHubFile> files = Iterable<_GitHubFile>.generate(
fileListJson.current.length,
(int index) => _jsonGetGithubFile(fileListJson, index),
).where(
// Exclude controlling files, which contain no layout information.
(_GitHubFile file) => !file.name.startsWith('layout.contribution.')
&& !file.name.startsWith('_.contribution'),
);
// Layouts must be sorted to ensure that the output file has a fixed order.
final List<Layout> layouts = files.map(_parseLayoutFromGithubFile)
.toList()
..sort(_sortLayout);
final String url = 'https://github.com/microsoft/vscode/tree/$commitId/$_githubTargetFolder';
return GithubResult(layouts, url);
//
}
| engine/tools/gen_web_locale_keymap/lib/github.dart/0 | {
"file_path": "engine/tools/gen_web_locale_keymap/lib/github.dart",
"repo_id": "engine",
"token_count": 3874
} | 483 |
# header_guard_check
A tool to check that C++ header guards are used consistently in the engine.
```shell
# Assuming you are in the `flutter` root of the engine repo.
dart ./tools/header_guard_check/bin/main.dart
```
The tool checks _all_ header files for the following pattern:
```h
// path/to/file.h
#ifndef PATH_TO_FILE_H_
#define PATH_TO_FILE_H_
...
#endif // PATH_TO_FILE_H_
```
If the header file does not follow this pattern, the tool will print an error
message and exit with a non-zero exit code. For more information about why we
use this pattern, see [the Google C++ style guide](https://google.github.io/styleguide/cppguide.html#The__define_Guard).
## Automatic fixes
The tool can automatically fix header files that do not follow the pattern:
```shell
dart ./tools/header_guard_check/bin/main.dart --fix
```
## Advanced usage
### Restricting the files to check
By default, the tool checks all header files in the engine. You can restrict the
files to check by passing a relative (to the `engine/src/flutter` root) paths to
include:
```shell
dart ./tools/header_guard_check/bin/main.dart --include impeller
```
| engine/tools/header_guard_check/README.md/0 | {
"file_path": "engine/tools/header_guard_check/README.md",
"repo_id": "engine",
"token_count": 352
} | 484 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Only look for copyrights and licenses at the top of the file.
// This can be increased as necessary, but the larger the value, the slower the
// script will be, so be judicious.
//
// FWIW, png.h's license statements end near the 7KB mark.
// third_party/boringssl/src/include/openssl/ssl.h has licenses for 7285 bytes
// third_party/boringssl/src/include/openssl/tls1.h has licenses for 7530 bytes
const int kMaxSize = 7530;
| engine/tools/licenses/lib/limits.dart/0 | {
"file_path": "engine/tools/licenses/lib/limits.dart",
"repo_id": "engine",
"token_count": 173
} | 485 |
include: ../../../analysis_options.yaml
linter:
rules:
public_member_api_docs: false
| engine/tools/pkg/engine_build_configs/analysis_options.yaml/0 | {
"file_path": "engine/tools/pkg/engine_build_configs/analysis_options.yaml",
"repo_id": "engine",
"token_count": 35
} | 486 |
// Copyright 2013 The Flutter 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_VULKAN_VULKAN_DEBUG_REPORT_H_
#define FLUTTER_VULKAN_VULKAN_DEBUG_REPORT_H_
#include "flutter/fml/macros.h"
#include "flutter/vulkan/procs/vulkan_handle.h"
#include "flutter/vulkan/procs/vulkan_interface.h"
#include "flutter/vulkan/procs/vulkan_proc_table.h"
namespace vulkan {
class VulkanDebugReport {
public:
static std::string DebugExtensionName();
VulkanDebugReport(const VulkanProcTable& vk,
const VulkanHandle<VkInstance>& application);
~VulkanDebugReport();
bool IsValid() const;
private:
const VulkanProcTable& vk_;
const VulkanHandle<VkInstance>& application_;
VulkanHandle<VkDebugReportCallbackEXT> handle_;
bool valid_;
FML_DISALLOW_COPY_AND_ASSIGN(VulkanDebugReport);
};
} // namespace vulkan
#endif // FLUTTER_VULKAN_VULKAN_DEBUG_REPORT_H_
| engine/vulkan/vulkan_debug_report.h/0 | {
"file_path": "engine/vulkan/vulkan_debug_report.h",
"repo_id": "engine",
"token_count": 368
} | 487 |
// Copyright 2013 The Flutter 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_VULKAN_VULKAN_SWAPCHAIN_H_
#define FLUTTER_VULKAN_VULKAN_SWAPCHAIN_H_
#include <memory>
#include <utility>
#include <vector>
#include "flutter/fml/compiler_specific.h"
#include "flutter/fml/macros.h"
#include "flutter/vulkan/procs/vulkan_handle.h"
#include "third_party/skia/include/core/SkSize.h"
#include "third_party/skia/include/core/SkSurface.h"
namespace vulkan {
class VulkanProcTable;
class VulkanDevice;
class VulkanSurface;
class VulkanBackbuffer;
class VulkanImage;
class VulkanSwapchain {
public:
VulkanSwapchain(const VulkanProcTable& vk,
const VulkanDevice& device,
const VulkanSurface& surface,
GrDirectContext* skia_context,
std::unique_ptr<VulkanSwapchain> old_swapchain,
uint32_t queue_family_index);
~VulkanSwapchain();
bool IsValid() const;
enum class AcquireStatus {
/// A valid SkSurface was acquired successfully from the swapchain.
Success,
/// The underlying surface of the swapchain was permanently lost. This is an
/// unrecoverable error. The entire surface must be recreated along with the
/// swapchain.
ErrorSurfaceLost,
/// The swapchain surface is out-of-date with the underlying surface. The
/// swapchain must be recreated.
ErrorSurfaceOutOfDate,
};
using AcquireResult = std::pair<AcquireStatus, sk_sp<SkSurface>>;
/// Acquire an SkSurface from the swapchain for the caller to render into for
/// later submission via |Submit|. There must not be consecutive calls to
/// |AcquireFrame| without and interleaving |Submit|.
AcquireResult AcquireSurface();
/// Submit a previously acquired. There must not be consecutive calls to
/// |Submit| without and interleaving |AcquireFrame|.
[[nodiscard]] bool Submit();
SkISize GetSize() const;
#if FML_OS_ANDROID
private:
const VulkanProcTable& vk;
const VulkanDevice& device_;
VkSurfaceCapabilitiesKHR capabilities_;
VkSurfaceFormatKHR surface_format_;
VulkanHandle<VkSwapchainKHR> swapchain_;
std::vector<std::unique_ptr<VulkanBackbuffer>> backbuffers_;
std::vector<std::unique_ptr<VulkanImage>> images_;
std::vector<sk_sp<SkSurface>> surfaces_;
VkPipelineStageFlagBits current_pipeline_stage_;
size_t current_backbuffer_index_;
size_t current_image_index_;
bool valid_;
std::vector<VkImage> GetImages() const;
bool CreateSwapchainImages(GrDirectContext* skia_context,
SkColorType color_type,
const sk_sp<SkColorSpace>& color_space,
VkImageUsageFlags usage_flags);
sk_sp<SkSurface> CreateSkiaSurface(GrDirectContext* skia_context,
VkImage image,
VkImageUsageFlags usage_flags,
const SkISize& size,
SkColorType color_type,
sk_sp<SkColorSpace> color_space) const;
VulkanBackbuffer* GetNextBackbuffer();
#endif // FML_OS_ANDROID
FML_DISALLOW_COPY_AND_ASSIGN(VulkanSwapchain);
};
} // namespace vulkan
#endif // FLUTTER_VULKAN_VULKAN_SWAPCHAIN_H_
| engine/vulkan/vulkan_swapchain.h/0 | {
"file_path": "engine/vulkan/vulkan_swapchain.h",
"repo_id": "engine",
"token_count": 1373
} | 488 |
This directory contains code for the web page that hosts Web Engine tests.
| engine/web_sdk/web_engine_tester/lib/static/README.md/0 | {
"file_path": "engine/web_sdk/web_engine_tester/lib/static/README.md",
"repo_id": "engine",
"token_count": 15
} | 489 |
<component name="CopyrightManager">
<settings default="chromium">
<module2copyright>
<element module="Project Files" copyright="chromium" />
</module2copyright>
<LanguageOptions name="JAVA">
<option name="fileTypeOverride" value="3" />
<option name="addBlankAfter" value="false" />
</LanguageOptions>
</settings>
</component> | flutter-intellij/.idea/copyright/profiles_settings.xml/0 | {
"file_path": "flutter-intellij/.idea/copyright/profiles_settings.xml",
"repo_id": "flutter-intellij",
"token_count": 124
} | 490 |
# Below is a list of people and organizations that have contributed
# to the Flutter project. Names should be added to the list like so:
#
# Name/Organization <email address>
Google Inc.
Brandon Donnelson <[email protected]>
Brian Egan <[email protected]>
Alexander Doroshko <[email protected]>
Alexander Zolotov <[email protected]>
QuangSon <[email protected]>
ChangJoo Park <[email protected]>
Amol Grover <[email protected]>
Jeremy Judeaux <[email protected]>
Letticia Nicoli <[email protected]>
Alex Li <[email protected]>
Marcus Tomlinson <[email protected]>
Juyeong Lee <[email protected]>
Hrishikesh Kadam <[email protected]>
Sander Kersten <[email protected]>
Pradumna Saraf <[email protected]>
Pedro Massango <[email protected]>
Wagner Silvestre <[email protected]>
Eli Albert <[email protected]>
Mohamed El Sayed <[email protected]>
Edwin Ludik <[email protected]>
| flutter-intellij/AUTHORS/0 | {
"file_path": "flutter-intellij/AUTHORS",
"repo_id": "flutter-intellij",
"token_count": 377
} | 491 |
#!/usr/bin/env bash
../third_party/gradlew $@
| flutter-intellij/flutter-gui-tests/gradlew/0 | {
"file_path": "flutter-intellij/flutter-gui-tests/gradlew",
"repo_id": "flutter-intellij",
"token_count": 20
} | 492 |
/*
* 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.
*/
import org.gradle.api.tasks.testing.logging.TestExceptionFormat
repositories {
mavenLocal()
maven {
url=uri("https://www.jetbrains.com/intellij-repository/snapshots/")
}
mavenCentral()
maven {
url=uri("https://oss.sonatype.org/content/repositories/snapshots/")
}
maven {
url=uri("https://www.jetbrains.com/intellij-repository/releases")
}
}
plugins {
id("java")
id("kotlin")
id("org.jetbrains.intellij")
}
val ide: String by project
val flutterPluginVersion: String by project
val javaVersion: String by project
val androidVersion: String by project
val dartVersion: String by project
val baseVersion: String by project
val smaliPlugin: String by project
val langPlugin: String by project
val ideVersion: String by project
group = "io.flutter"
version = flutterPluginVersion
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().all {
kotlinOptions {
jvmTarget = javaVersion
}
}
java {
sourceCompatibility = JavaVersion.toVersion(javaVersion)
targetCompatibility = JavaVersion.toVersion(javaVersion)
}
intellij {
// This adds nullability assertions, but also compiles forms.
instrumentCode.set(true)
updateSinceUntilBuild.set(false)
downloadSources.set(false)
version.set(ideVersion)
val pluginList = mutableListOf("java", "properties", "junit", "Kotlin", "Git4Idea",
"gradle", "Groovy", "yaml", "Dart:$dartVersion")
// If 2023.3+ and IDEA (not AS), then "org.jetbrains.android:$androidVersion", otherwise "org.jetbrains.android",
// see https://github.com/flutter/flutter-intellij/issues/7145
if(ide == "android-studio") {
pluginList.add("org.jetbrains.android");
} else if (ide == "ideaIC") {
pluginList.add("org.jetbrains.android:$androidVersion");
}
if (ide == "android-studio") {
pluginList.add(smaliPlugin)
}
pluginList.add(langPlugin)
plugins.set(pluginList)
if (ide == "android-studio") {
type.set("AI")
}
}
dependencies {
compileOnly("org.jetbrains:annotations:24.0.0")
testImplementation("org.jetbrains:annotations:24.0.0")
testImplementation("org.powermock:powermock-api-mockito2:2.0.9")
testImplementation("org.powermock:powermock-module-junit4:2.0.9")
testImplementation(mapOf("group" to "org.mockito", "name" to "mockito-core", "version" to "5.2.0"))
if (ide == "android-studio") {
testImplementation(project(":flutter-studio"))
testRuntimeOnly(fileTree(mapOf("dir" to "${project.rootDir}/artifacts/android-studio/plugins",
"include" to listOf("**/*.jar"),
"exclude" to listOf("**/kotlin-compiler.jar", "**/kotlin-plugin.jar", "**/kotlin-stdlib-jdk8.jar"))))
compileOnly(fileTree(mapOf("dir" to "${project.rootDir}/artifacts/android-studio/lib",
"include" to listOf("*.jar"),
"exclude" to listOf("**/annotations.jar"))))
testRuntimeOnly(fileTree(mapOf("dir" to "${project.rootDir}/artifacts/android-studio/lib",
"include" to listOf("*.jar"))))
compileOnly(fileTree(mapOf("dir" to "${project.rootDir}/artifacts/android-studio/plugins/git4idea/lib",
"include" to listOf("*.jar"))))
testImplementation(fileTree(mapOf("dir" to "${project.rootDir}/artifacts/android-studio/plugins/git4idea/lib",
"include" to listOf("*.jar"))))
} else {
compileOnly(fileTree(mapOf("dir" to "${project.rootDir}/artifacts/ideaIC/plugins/git4idea/lib",
"include" to listOf("*.jar"))))
compileOnly(fileTree(mapOf("dir" to "${project.rootDir}/artifacts/ideaIC/plugins/java/lib",
"include" to listOf("*.jar"))))
testImplementation(fileTree(mapOf("dir" to "${project.rootDir}/artifacts/ideaIC/plugins/git4idea/lib",
"include" to listOf("*.jar"))))
}
compileOnly("com.google.guava:guava:31.1-jre")
compileOnly("com.google.code.gson:gson:2.10.1")
testImplementation("com.google.guava:guava:31.1-jre")
testImplementation("com.google.code.gson:gson:2.10.1")
compileOnly(fileTree(mapOf("dir" to "${project.rootDir}/third_party/lib/jxbrowser",
"include" to listOf("*.jar"))))
testImplementation(fileTree(mapOf("dir" to "${project.rootDir}/third_party/lib/jxbrowser",
"include" to listOf("*.jar"))))
testImplementation("junit:junit:4.13.2")
}
sourceSets {
main {
java.srcDirs(listOf(
"src",
"third_party/vmServiceDrivers"
))
// Add kotlin.srcDirs if we start using Kotlin in the main plugin.
resources.srcDirs(listOf(
"src",
"resources"
))
}
test {
java.srcDirs(listOf(
"src",
"testSrc/unit",
"third_party/vmServiceDrivers"
))
resources.srcDirs(listOf(
"resources",
"testData",
"testSrc/unit"
))
}
}
tasks {
buildSearchableOptions {
enabled = false
}
instrumentCode {
compilerVersion.set("$baseVersion")
}
instrumentTestCode {
compilerVersion.set("$baseVersion")
}
test {
useJUnit()
testLogging {
showCauses = true
showStackTraces = true
showStandardStreams = true
exceptionFormat = TestExceptionFormat.FULL
events("skipped", "failed")
}
}
}
| flutter-intellij/flutter-idea/build.gradle.kts/0 | {
"file_path": "flutter-intellij/flutter-idea/build.gradle.kts",
"repo_id": "flutter-intellij",
"token_count": 2168
} | 493 |
/*
* 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.
*/
package io.flutter.actions;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.project.Project;
import io.flutter.pub.PubRoot;
import io.flutter.sdk.FlutterSdk;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class FlutterUpgradeAction extends FlutterSdkAction {
@Override
public void startCommand(@NotNull Project project, @NotNull FlutterSdk sdk, @Nullable PubRoot root, @NotNull DataContext context) {
sdk.flutterUpgrade().startInConsole(project);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/actions/FlutterUpgradeAction.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/FlutterUpgradeAction.java",
"repo_id": "flutter-intellij",
"token_count": 221
} | 494 |
/*
* 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.
*/
package io.flutter.actions;
import com.google.common.base.Joiner;
import com.intellij.execution.Executor;
import com.intellij.execution.ProgramRunnerUtil;
import com.intellij.execution.RunManagerEx;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.runners.ExecutionEnvironmentBuilder;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import io.flutter.FlutterBundle;
import io.flutter.FlutterInitializer;
import io.flutter.run.FlutterLaunchMode;
import io.flutter.run.LaunchState;
import io.flutter.run.SdkFields;
import io.flutter.run.SdkRunConfig;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
public abstract class RunFlutterAction extends AnAction {
private final @NotNull String myDetailedTextKey;
private final @NotNull FlutterLaunchMode myLaunchMode;
private final @NotNull String myExecutorId;
public RunFlutterAction(@NotNull String text,
@NotNull String detailedTextKey,
@NotNull String description,
@NotNull Icon icon,
@NotNull FlutterLaunchMode launchMode,
@NotNull String executorId) {
super(text, description, icon);
myDetailedTextKey = detailedTextKey;
myLaunchMode = launchMode;
myExecutorId = executorId;
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
// NOTE: When making changes here, consider making similar changes to ConnectAndroidDebuggerAction.
FlutterInitializer.sendAnalyticsAction(this);
final RunnerAndConfigurationSettings settings = getRunConfigSettings(e);
if (settings == null) {
return;
}
final RunConfiguration configuration = settings.getConfiguration();
if (!(configuration instanceof SdkRunConfig)) {
// Action is disabled; shouldn't happen.
return;
}
final SdkRunConfig sdkRunConfig = (SdkRunConfig)configuration.clone();
final SdkFields fields = sdkRunConfig.getFields();
final String additionalArgs = fields.getAdditionalArgs();
String flavorArg = null;
if (fields.getBuildFlavor() != null) {
flavorArg = "--flavor=" + fields.getBuildFlavor();
}
final List<String> args = new ArrayList<>();
if (additionalArgs != null) {
args.add(additionalArgs);
}
if (flavorArg != null) {
args.add(flavorArg);
}
if (!args.isEmpty()) {
fields.setAdditionalArgs(Joiner.on(" ").join(args));
}
final Executor executor = getExecutor(myExecutorId);
if (executor == null) {
return;
}
final ExecutionEnvironmentBuilder builder = ExecutionEnvironmentBuilder.create(executor, sdkRunConfig);
final ExecutionEnvironment env;
try {
env = builder.activeTarget().dataContext(e.getDataContext()).build();
}
catch (IllegalStateException ex) {
// We're seeing IllegalStateExceptions from here (#4067 - "Runner must be specified"), and are not sure of
// the reason why. This adds a bit more diagnostics to the exception to help us determine what's going on.
throw new IllegalStateException(
ex.getMessage() + " (" + myExecutorId + "/" + myLaunchMode + "/" + getClass().getSimpleName() + ")");
}
FlutterLaunchMode.addToEnvironment(env, myLaunchMode);
ProgramRunnerUtil.executeConfiguration(env, false, true);
}
@Override
public void update(@NotNull AnActionEvent e) {
// Text.
final String config = getSelectedRunConfig(e);
final String message =
config != null ? FlutterBundle.message(myDetailedTextKey, config) : FlutterBundle.message("app.profile.action.text");
e.getPresentation().setText(message);
// Enablement.
e.getPresentation().setEnabled(shouldEnable(e));
}
private static boolean shouldEnable(@Nullable AnActionEvent e) {
final RunnerAndConfigurationSettings settings = getRunConfigSettings(e);
final RunConfiguration config = settings == null ? null : settings.getConfiguration();
// TODO(pq): add support for Bazel.
return config instanceof SdkRunConfig && LaunchState.getRunningAppProcess((SdkRunConfig)config) == null;
}
@Nullable
protected static String getSelectedRunConfig(@Nullable AnActionEvent e) {
final RunnerAndConfigurationSettings settings = getRunConfigSettings(e);
if (settings != null) {
return settings.getConfiguration().getName();
}
return null;
}
@Nullable
public static RunnerAndConfigurationSettings getRunConfigSettings(@Nullable AnActionEvent event) {
if (event == null) {
return null;
}
final Project project = event.getProject();
if (project == null) {
return null;
}
return RunManagerEx.getInstanceEx(project).getSelectedConfiguration();
}
@Nullable
public static Executor getExecutor(@NotNull String executorId) {
for (Executor executor : Executor.EXECUTOR_EXTENSION_NAME.getExtensions()) {
if (executorId.equals(executor.getId())) {
return executor;
}
}
return null;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/actions/RunFlutterAction.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/RunFlutterAction.java",
"repo_id": "flutter-intellij",
"token_count": 1886
} | 495 |
/*
* 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.
*/
package io.flutter.bazel;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableSet;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.vfs.InvalidVirtualFileAccessException;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
/**
* The directory tree for a Bazel workspace.
* <p>
* <p>Bazel workspaces are identified by looking for a WORKSPACE file.
* <p>
* <p>Also includes the flutter.json config file, which is loaded at the same time.
*/
public class Workspace {
private static final String PLUGIN_CONFIG_PATH = "dart/config/ide/flutter.json";
// TODO(jacobr): find a way to load the bazel uri scheme rather than hard coding it
// as this scheme may change in the future.
public static final String BAZEL_URI_SCHEME = "google3://";
@NotNull private final VirtualFile root;
@Nullable private final PluginConfig config;
@Nullable private final String daemonScript;
@Nullable private final String devToolsScript;
@Nullable private final String doctorScript;
@Nullable private final String testScript;
@Nullable private final String runScript;
@Nullable private final String syncScript;
@Nullable private final String toolsScript;
@Nullable private final String sdkHome;
@Nullable private final String requiredIJPluginID;
@Nullable private final String requiredIJPluginMessage;
@Nullable private final String configWarningPrefix;
@Nullable private final String updatedIosRunMessage;
private Workspace(@NotNull VirtualFile root,
@Nullable PluginConfig config,
@Nullable String daemonScript,
@Nullable String devToolsScript,
@Nullable String doctorScript,
@Nullable String testScript,
@Nullable String runScript,
@Nullable String syncScript,
@Nullable String toolsScript,
@Nullable String sdkHome,
@Nullable String requiredIJPluginID,
@Nullable String requiredIJPluginMessage,
@Nullable String configWarningPrefix,
@Nullable String updatedIosRunMessage) {
this.root = root;
this.config = config;
this.daemonScript = daemonScript;
this.devToolsScript = devToolsScript;
this.doctorScript = doctorScript;
this.testScript = testScript;
this.runScript = runScript;
this.syncScript = syncScript;
this.toolsScript = toolsScript;
this.sdkHome = sdkHome;
this.requiredIJPluginID = requiredIJPluginID;
this.requiredIJPluginMessage = requiredIJPluginMessage;
this.configWarningPrefix = configWarningPrefix;
this.updatedIosRunMessage = updatedIosRunMessage;
}
/**
* Returns the path to each content root within the module that is below the workspace root.
* <p>
* <p>Each path will be relative to the workspace root directory.
*/
@NotNull
public ImmutableSet<String> getContentPaths(@NotNull final Module module) {
// Find all the content roots within this workspace.
final VirtualFile[] contentRoots = ModuleRootManager.getInstance(module).getContentRoots();
final ImmutableSet.Builder<String> result = ImmutableSet.builder();
for (VirtualFile root : contentRoots) {
final String path = getRelativePath(root);
if (path != null) {
result.add(path);
}
}
return result.build();
}
/**
* Returns a VirtualFile's path relative to the workspace's root directory.
* <p>
* <p>Returns null for the workspace root or anything outside the workspace.
*/
@Nullable
public String getRelativePath(@Nullable VirtualFile file) {
final List<String> path = new ArrayList<>();
while (file != null) {
if (file.equals(root)) {
if (path.isEmpty()) {
return null; // This is the root.
}
Collections.reverse(path);
return Joiner.on('/').join(path);
}
path.add(file.getName());
file = file.getParent();
}
return null;
}
/**
* Returns the directory containing the WORKSPACE file.
*/
@NotNull
public VirtualFile getRoot() {
return root;
}
/**
* Returns the script that starts 'flutter daemon', or null if not configured.
*/
@Nullable
public String getDaemonScript() {
return daemonScript;
}
/**
* Returns the script that starts DevTools, or null if not configured.
*/
@Nullable
public String getDevToolsScript() {
return devToolsScript;
}
/**
* Returns the script that starts 'flutter doctor', or null if not configured.
*/
@Nullable
public String getDoctorScript() {
return doctorScript;
}
/**
* Returns the script that starts 'flutter test', or null if not configured.
*/
@Nullable
public String getTestScript() {
return testScript;
}
/**
* Returns the script that starts 'flutter run', or null if not configured.
*/
@Nullable
public String getRunScript() {
return runScript;
}
/**
* Returns the script that starts 'flutter sync', or null if not configured.
*/
@Nullable
public String getSyncScript() {
return syncScript;
}
/**
* Returns the generic script for running flutter actions, or null if not configured.
*/
@Nullable
public String getToolsScript() {
return toolsScript;
}
/**
* Returns the directory that contains the flutter SDK commands, or null if not configured.
*/
@Nullable
public String getSdkHome() {
return sdkHome;
}
/**
* Returns the required IJ plugin ID, or null if not configured.
*/
@Nullable
public String getRequiredIJPluginID() {
return requiredIJPluginID;
}
/**
* Returns the required IJ plugin message, if the plugin id is not installed, or null if not configured.
*/
@Nullable
public String getRequiredIJPluginMessage() {
return requiredIJPluginMessage;
}
/**
* Returns the prefix associated with configuration warnings.
*/
@Nullable
public String getConfigWarningPrefix() {
return configWarningPrefix;
}
/**
* Returns the message notifying users that running iOS apps has improved.
*/
@Nullable
public String getUpdatedIosRunMessage() {
return updatedIosRunMessage;
}
/**
* Returns true if the plugin config was loaded.
*/
public boolean hasPluginConfig() {
return config != null;
}
/**
* Returns relative paths to the files within the workspace that it depends on.
* <p>
* <p>When they change, the Workspace should be reloaded.
*/
@NotNull
public Set<String> getDependencies() {
return ImmutableSet.of("WORKSPACE", PLUGIN_CONFIG_PATH);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Workspace)) return false;
final Workspace other = (Workspace)obj;
return Objects.equal(root, other.root) && Objects.equal(config, other.config);
}
@Override
public int hashCode() {
return Objects.hashCode(root, config);
}
/**
* Loads the Bazel workspace from the filesystem.
* <p>
* <p>Also loads flutter.plugin if present.
* <p>
* <p>(Note that we might not load all the way from disk due to the VirtualFileSystem's caching.)
* <p> Never call this method directly. Instead use WorkespaceCache.getInstance().
* </p>
*
* @return the Workspace, or null if there is none.
*/
@Nullable
static Workspace loadUncached(@NotNull Project project) {
if (project.isDisposed()) {
return null;
}
final VirtualFile workspaceFile = findWorkspaceFile(project);
if (workspaceFile == null) return null;
final VirtualFile root = workspaceFile.getParent();
final String readonlyPath = "../READONLY/" + root.getName();
final VirtualFile readonlyRoot = root.findFileByRelativePath(readonlyPath);
VirtualFile configFile = root.findFileByRelativePath(PLUGIN_CONFIG_PATH);
if (configFile == null && readonlyRoot != null) {
configFile = readonlyRoot.findFileByRelativePath(PLUGIN_CONFIG_PATH);
}
if (configFile == null) return null;
final PluginConfig config = PluginConfig.load(configFile);
final String daemonScript = config == null ? null : getScriptFromPath(root, readonlyPath, config.getDaemonScript());
final String devToolsScript = config == null ? null : getScriptFromPath(root, readonlyPath, config.getDevToolsScript());
final String doctorScript = config == null ? null : getScriptFromPath(root, readonlyPath, config.getDoctorScript());
final String testScript = config == null ? null : getScriptFromPath(root, readonlyPath, config.getTestScript());
final String runScript = config == null ? null : getScriptFromPath(root, readonlyPath, config.getRunScript());
final String syncScript = config == null ? null : getScriptFromPath(root, readonlyPath, config.getSyncScript());
final String toolsScript = config == null ? null : getScriptFromPath(root, readonlyPath, config.getToolsScript());
final String sdkHome = config == null ? null : getScriptFromPath(root, readonlyPath, config.getSdkHome());
final String requiredIJPluginID = config == null ? null : config.getRequiredIJPluginID();
final String requiredIJPluginMessage = config == null ? null : config.getRequiredIJPluginMessage();
final String configWarningPrefix = config == null ? null : config.getConfigWarningPrefix();
final String updatedIosRunMessage = config == null ? null : config.getUpdatedIosRunMessage();
return new Workspace(root, config, daemonScript, devToolsScript, doctorScript, testScript, runScript, syncScript, toolsScript, sdkHome, requiredIJPluginID, requiredIJPluginMessage, configWarningPrefix, updatedIosRunMessage);
}
@VisibleForTesting
public static Workspace forTest(VirtualFile workspaceRoot, PluginConfig pluginConfig) {
return new Workspace(
workspaceRoot,
pluginConfig,
pluginConfig.getDaemonScript(),
pluginConfig.getDevToolsScript(),
pluginConfig.getDoctorScript(),
pluginConfig.getTestScript(),
pluginConfig.getRunScript(),
pluginConfig.getSyncScript(),
pluginConfig.getToolsScript(),
pluginConfig.getSdkHome(),
pluginConfig.getRequiredIJPluginID(),
pluginConfig.getRequiredIJPluginMessage(),
pluginConfig.getConfigWarningPrefix(),
pluginConfig.getUpdatedIosRunMessage());
}
/**
* Attempts to find a script inside of the workspace.
*
* @param root the workspace root.
* @param readonlyPath the relative path to the readonly contents of the workspace.
* @param relativeScriptPath the relative path to the desired script inside of the workspace.
* @return the script's path relative to the workspace, or null if it was not found.
*/
private static String getScriptFromPath(@NotNull VirtualFile root, @NotNull String readonlyPath, @Nullable String relativeScriptPath) {
if (relativeScriptPath == null) {
return null;
}
final String readonlyScriptPath = readonlyPath + "/" + relativeScriptPath;
if (root.findFileByRelativePath(relativeScriptPath) != null) {
return relativeScriptPath;
}
if (root.findFileByRelativePath(readonlyScriptPath) != null) {
return readonlyScriptPath;
}
return null;
}
/**
* Returns the Bazel WORKSPACE file for a Project, or null if not using Bazel.
* <p>
* At least one content root must be within the workspace, and the project cannot have
* content roots in more than one workspace.
*/
@Nullable
private static VirtualFile findWorkspaceFile(@NotNull Project p) {
final Computable<VirtualFile> readAction = () -> {
final Map<String, VirtualFile> candidates = new HashMap<>();
for (VirtualFile contentRoot : ProjectRootManager.getInstance(p).getContentRoots()) {
final VirtualFile wf = findContainingWorkspaceFile(contentRoot);
if (wf != null) {
candidates.put(wf.getPath(), wf);
}
}
if (candidates.size() == 1) {
return candidates.values().iterator().next();
}
// not found
return null;
};
return ApplicationManager.getApplication().runReadAction(readAction);
}
/**
* Returns the closest WORKSPACE file within or above the given directory, or null if not found.
*/
@Nullable
private static VirtualFile findContainingWorkspaceFile(@NotNull VirtualFile dir) {
while (dir != null) {
try {
final VirtualFile child = dir.findChild("WORKSPACE");
if (child != null && child.exists() && !child.isDirectory()) {
return child;
}
dir = dir.getParent();
} catch (InvalidVirtualFileAccessException ex) {
// The VFS is out of sync.
return null;
}
}
// not found
return null;
}
private static final Logger LOG = Logger.getInstance(Workspace.class);
public String convertPath(String path) {
if (path.startsWith(Workspace.BAZEL_URI_SCHEME)) {
return getRoot().getPath() + path.substring(Workspace.BAZEL_URI_SCHEME.length());
}
return path;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/bazel/Workspace.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/bazel/Workspace.java",
"repo_id": "flutter-intellij",
"token_count": 4584
} | 496 |
/*
* 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.
*/
package io.flutter.editor;
import com.google.common.collect.Lists;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.fileEditor.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.jetbrains.lang.dart.analyzer.DartAnalysisServerService;
import io.flutter.FlutterUtils;
import io.flutter.dart.FlutterDartAnalysisServer;
import io.flutter.dart.FlutterOutlineListener;
import org.dartlang.analysis.server.protocol.FlutterOutline;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
/**
* Service that watches for {@link FlutterOutline}s for all active editors containing Dart files.
*
* <p>
* This service works by listening to the {@link Project}'s MessageBus for {@link FileEditor}s that are
* added or removed. Using the set of currently active {@link EditorEx} editor windows, this service
* then subscribes to the {@link FlutterDartAnalysisServer} for updates to the {@link FlutterOutline} of each file.
*
* <p>
* This class provides a {@link Listener} that notifies consumers when
* <ul>
* <li>The collection of currently active editors has changed</li>
* <li>Each outline for a currently active editor has updated.</li>
* </ul>
*/
public class ActiveEditorsOutlineService implements Disposable {
@NotNull private final Project project;
/**
* Outlines for the currently visible files.
*/
@NotNull private final Map<String, FlutterOutline> pathToOutline = new HashMap<>();
/**
* Outline listeners for the currently visible files.
*/
@NotNull private final Map<String, FlutterOutlineListener> outlineListeners = new HashMap<>();
/**
* List of listeners.
*/
@NotNull private final Set<Listener> listeners = new HashSet<>();
@NotNull
public static ActiveEditorsOutlineService getInstance(@NotNull final Project project) {
return Objects.requireNonNull(project.getService(ActiveEditorsOutlineService.class));
}
public ActiveEditorsOutlineService(@NotNull Project project) {
this.project = project;
updateActiveEditors();
// See comment in WidgetIndentsHighlightingPassFactory for choice of disposable here.
project.getMessageBus().connect(getAnalysisServer())
.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerListener() {
public void selectionChanged(@NotNull FileEditorManagerEvent event) {
updateActiveEditors();
}
});
}
@NotNull
private FlutterDartAnalysisServer getAnalysisServer() {
return FlutterDartAnalysisServer.getInstance(project);
}
/**
* Gets all of the {@link EditorEx} editors open to Dart files.
*/
public List<EditorEx> getActiveDartEditors() {
if (project.isDisposed()) {
return Collections.emptyList();
}
final FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
if (fileEditorManager == null) {
// TODO(jacobr): why do we sometimes hit this edge case?
return Collections.emptyList();
}
final FileEditor[] editors = fileEditorManager.getSelectedEditors();
final List<EditorEx> dartEditors = new ArrayList<>();
for (FileEditor fileEditor : editors) {
if (!(fileEditor instanceof TextEditor)) continue;
final TextEditor textEditor = (TextEditor)fileEditor;
final Editor editor = textEditor.getEditor();
if (editor instanceof EditorEx && !editor.isDisposed() && FlutterUtils.isDartFile(((EditorEx)editor).getVirtualFile())) {
dartEditors.add((EditorEx)editor);
}
}
return dartEditors;
}
private void updateActiveEditors() {
if (project.isDisposed()) {
return;
}
final FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
if (fileEditorManager == null) {
// TODO(jacobr): why do we sometimes hit this edge case?
return;
}
final VirtualFile[] files = fileEditorManager.getSelectedFiles();
final Set<String> newPaths = new HashSet<>();
for (VirtualFile file : files) {
if (FlutterUtils.isDartFile(file) && file.isInLocalFileSystem()) {
newPaths.add(file.getPath());
}
}
// Remove obsolete outline listeners.
final List<String> obsoletePaths = new ArrayList<>();
FlutterDartAnalysisServer analysisServer = getAnalysisServer();
synchronized (outlineListeners) {
for (final String path : outlineListeners.keySet()) {
if (!newPaths.contains(path)) {
obsoletePaths.add(path);
}
}
for (final String path : obsoletePaths) {
final FlutterOutlineListener listener = outlineListeners.remove(path);
if (listener != null) {
getAnalysisServer().removeOutlineListener(path, listener);
}
}
// Register new outline listeners.
for (final String path : newPaths) {
if (outlineListeners.containsKey(path)) {
continue;
}
final FlutterOutlineListener listener = new OutlineListener(path);
outlineListeners.put(path, listener);
getAnalysisServer().addOutlineListener(FileUtil.toSystemDependentName(path), listener);
}
}
synchronized (pathToOutline) {
for (final String path : obsoletePaths) {
// Clear the current outline as it may become out of date before the file is visible again.
pathToOutline.remove(path);
}
}
}
private void notifyOutlineUpdated(String path) {
final ArrayList<Listener> listenerList;
synchronized (listeners) {
listenerList = Lists.newArrayList(listeners);
}
for (Listener listener : listenerList) {
listener.onOutlineChanged(path, getOutline(path));
}
}
public void addListener(@NotNull Listener listener) {
synchronized (listeners) {
listeners.add(listener);
}
}
public void removeListener(@NotNull Listener listener) {
synchronized (listeners) {
listeners.remove(listener);
}
}
/**
* Gets the most up-to-date {@link FlutterOutline} for the file at {@param path}.
* <p>
* To get an outline that is guaranteed in-sync with the file it outlines, see {@link #getIfUpdated}.
*/
@Nullable
public FlutterOutline getOutline(@Nullable String path) {
return pathToOutline.get(path);
}
/**
* Gets the {@link FlutterOutline} for {@param file} if and only if the outline is up to date with the file.
*
* <p>
* Returns null if the file is out of date.
*/
@Nullable
public FlutterOutline getIfUpdated(@NotNull PsiFile file) {
final FlutterOutline outline = getOutline(file.getVirtualFile().getPath());
if (outline == null || isOutdated(outline, file)) {
return null;
}
else {
return outline;
}
}
/**
* Checks that the {@param outline} matches the current version of {@param file}.
*
* <p>
* An outline and file match if they have the same length.
*/
private boolean isOutdated(@NotNull FlutterOutline outline, @NotNull PsiFile file) {
final DartAnalysisServerService das = DartAnalysisServerService.getInstance(file.getProject());
return file.getTextLength() != outline.getLength()
&& file.getTextLength() != das.getConvertedOffset(file.getVirtualFile(), outline.getLength());
}
@Override
public void dispose() {
FlutterDartAnalysisServer analysisServer = getAnalysisServer();
synchronized (outlineListeners) {
final Iterator<Map.Entry<String, FlutterOutlineListener>> iterator = outlineListeners.entrySet().iterator();
while (iterator.hasNext()) {
final Map.Entry<String, FlutterOutlineListener> entry = iterator.next();
final String path = entry.getKey();
final FlutterOutlineListener listener = entry.getValue();
iterator.remove();
if (listener != null) {
getAnalysisServer().removeOutlineListener(path, listener);
}
}
outlineListeners.clear();
}
synchronized (pathToOutline) {
pathToOutline.clear();
}
synchronized (listeners) {
listeners.clear();
}
}
/**
* Listener for changes to the active editors or open outlines.
*/
public interface Listener {
/**
* Called on a change in the {@link FlutterOutline} of file at {@param filePath}.
*/
void onOutlineChanged(@NotNull String filePath, @Nullable FlutterOutline outline);
}
/**
* Listener called by the {@link FlutterDartAnalysisServer} when an open file's outline changes.
*
* <p>
* This class caches the updated outline inside {@link ActiveEditorsOutlineService#pathToOutline} for the file.
*/
private class OutlineListener implements FlutterOutlineListener {
private final String path;
OutlineListener(String path) {
this.path = path;
}
@Override
public void outlineUpdated(@NotNull String systemDependentPath,
@NotNull FlutterOutline outline,
@Nullable String instrumentedCode) {
// Avoid using the path return by the FlutterOutline service as it will
// be system dependent causing bugs on windows.
synchronized (outlineListeners) {
if (!outlineListeners.containsKey(path)) {
// The outline listener subscription was already cancelled.
return;
}
}
synchronized (pathToOutline) {
pathToOutline.put(path, outline);
notifyOutlineUpdated(path);
}
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/editor/ActiveEditorsOutlineService.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/ActiveEditorsOutlineService.java",
"repo_id": "flutter-intellij",
"token_count": 3395
} | 497 |
/*
* 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.
*/
package io.flutter.editor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.IconLoader;
import io.flutter.FlutterUtils;
import javax.swing.*;
import java.io.IOException;
import java.util.Properties;
public class FlutterMaterialIcons {
private static final Logger LOG = Logger.getInstance(FlutterMaterialIcons.class);
private static final Properties icons;
static {
icons = new Properties();
try {
icons.load(FlutterMaterialIcons.class.getResourceAsStream("/flutter/icons/material.properties"));
}
catch (IOException e) {
FlutterUtils.warn(LOG, e);
}
}
public static Icon getIconForHex(String hexValue) {
final String iconName = icons.getProperty(hexValue + ".codepoint");
return getIcon(iconName);
}
public static Icon getIconForName(String name) {
return getIcon(name);
}
private static Icon getIcon(String name) {
if (name == null) {
return null;
}
final String path = icons.getProperty(name);
if (path == null) {
return null;
}
return IconLoader.findIcon("/flutter/icons/" + path, FlutterMaterialIcons.class);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/editor/FlutterMaterialIcons.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/FlutterMaterialIcons.java",
"repo_id": "flutter-intellij",
"token_count": 452
} | 498 |
/*
* 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.
*/
package io.flutter.editor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.util.TextRange;
import org.dartlang.analysis.server.protocol.FlutterOutline;
import org.dartlang.analysis.server.protocol.FlutterOutlineAttribute;
import org.dartlang.analysis.server.protocol.Location;
import java.util.ArrayList;
/**
* Analog to the IndentGuideDescriptor class from the regular FilteredIndentsHighlightingPass.
* <p>
* The core difference relative to IndentGuideDescriptor is this descriptor
* tracks a list of child nodes to visualize the tree structure of a build
* method. WidgetIndentsHighlightingPass will use this information to draw horizontal
* lines to show part-child relationships.
* <p>
* Widget indent guides depend on the analysis service as the source of truth,
* so more information has to be still accurate even after the document is
* edited as there will be a slight delay before new analysis data is available.
*/
public class WidgetIndentGuideDescriptor {
public static class WidgetPropertyDescriptor {
private RangeMarker marker;
private final FlutterOutlineAttribute attribute;
WidgetPropertyDescriptor(FlutterOutlineAttribute attribute) {
this.attribute = attribute;
}
public String getName() {
return attribute.getName();
}
public FlutterOutlineAttribute getAttribute() {
return attribute;
}
public int getEndOffset() {
if (marker == null) {
final Location location = attribute.getValueLocation();
final int startOffset = location.getOffset();
final int endOffset = startOffset + location.getLength();
return endOffset;
}
return marker.getEndOffset();
}
public void track(Document document) {
if (marker != null) {
// TODO(jacobr): it does indicate a bit of a logic bug if we are calling this method twice.
assert (marker.getDocument() == document);
return;
}
// Create a range marker that goes from the start of the indent for the line
// to the column of the actual entity.
final int docLength = document.getTextLength();
final Location location = attribute.getValueLocation();
final int startOffset = Math.min(location.getOffset(), docLength);
final int endOffset = Math.min(startOffset + location.getLength(), docLength);
marker = document.createRangeMarker(startOffset, endOffset);
}
public void dispose() {
if (marker != null) {
marker.dispose();
}
}
}
public final WidgetIndentGuideDescriptor parent;
public final ArrayList<OutlineLocation> childLines;
public final OutlineLocation widget;
public final int indentLevel;
public final int startLine;
public final int endLine;
public final FlutterOutline outlineNode;
public WidgetIndentGuideDescriptor(
WidgetIndentGuideDescriptor parent,
int indentLevel,
int startLine,
int endLine,
ArrayList<OutlineLocation> childLines,
OutlineLocation widget,
FlutterOutline outlineNode
) {
this.parent = parent;
this.childLines = childLines;
this.widget = widget;
this.indentLevel = indentLevel;
this.startLine = startLine;
this.endLine = endLine;
this.outlineNode = outlineNode;
}
void dispose() {
if (widget != null) {
widget.dispose();
}
if (childLines == null) return;
for (OutlineLocation childLine : childLines) {
childLine.dispose();
}
childLines.clear();
}
/**
* This method must be called to opt the indent guide into tracking
* location changes due to document edits.
* <p>
* If trackLocations is called on a descriptor, you must later call dispose
* to stop listening for changes to the document once the descriptor is
* obsolete.
*/
boolean tracked = false;
public void trackLocations(Document document) {
if (tracked) return;
tracked = true;
if (widget != null) {
widget.track(document);
}
if (childLines == null) return;
for (OutlineLocation childLine : childLines) {
childLine.track(document);
}
}
public TextRange getMarker() {
return widget.getFullRange();
}
@Override
public int hashCode() {
int result = indentLevel;
result = 31 * result + startLine;
result = 31 * result + endLine;
if (childLines != null) {
for (OutlineLocation location : childLines) {
result = 31 * result + location.hashCode();
}
}
if (widget != null) {
result = 31 * result + widget.hashCode();
}
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final WidgetIndentGuideDescriptor that = (WidgetIndentGuideDescriptor)o;
if (endLine != that.endLine) return false;
if (indentLevel != that.indentLevel) return false;
if (startLine != that.startLine) return false;
if (childLines == null || that.childLines == null) {
return childLines == that.childLines;
}
if (childLines.size() != that.childLines.size()) {
return false;
}
for (int i = 0; i < childLines.size(); ++i) {
if (!childLines.get(i).equals(that.childLines.get(i))) {
return false;
}
}
return true;
}
public int compareTo(WidgetIndentGuideDescriptor that) {
int answer = endLine - that.endLine;
if (answer != 0) {
return answer;
}
answer = indentLevel - that.indentLevel;
if (answer != 0) {
return answer;
}
answer = startLine - that.startLine;
if (answer != 0) {
return answer;
}
if (childLines == that.childLines) {
return 0;
}
if (childLines == null || that.childLines == null) {
return childLines == null ? -1 : 1;
}
answer = childLines.size() - that.childLines.size();
if (answer != 0) {
return answer;
}
for (int i = 0; i < childLines.size(); ++i) {
answer = childLines.get(i).compareTo(that.childLines.get(i));
if (answer != 0) {
return answer;
}
}
return 0;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/editor/WidgetIndentGuideDescriptor.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/WidgetIndentGuideDescriptor.java",
"repo_id": "flutter-intellij",
"token_count": 2236
} | 499 |
/*
* 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.
*/
package io.flutter.inspector;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.util.ArrayList;
/**
* Represents a path in a DiagnosticsNode tree used to quickly display a path
* in the DiagnosticsNode tree in response to a change in the selected object
* on the device.
*/
public class DiagnosticsPathNode {
private final InspectorService.ObjectGroup inspectorService;
private final JsonObject json;
public DiagnosticsPathNode(JsonObject json, InspectorService.ObjectGroup inspectorService) {
this.inspectorService = inspectorService;
this.json = json;
}
public DiagnosticsNode getNode() {
// We are lazy about getting the diagnosticNode instanceRef so that no additional round trips using the observatory protocol
// are yet triggered for the typical case where properties of a node are not inspected.
return new DiagnosticsNode(json.getAsJsonObject("node"), inspectorService, false, null);
}
public ArrayList<DiagnosticsNode> getChildren() {
final ArrayList<DiagnosticsNode> children = new ArrayList<>();
final JsonElement childrenElement = json.get("children");
if (childrenElement.isJsonNull()) {
return children;
}
final JsonArray childrenJson = childrenElement.getAsJsonArray();
for (int i = 0; i < childrenJson.size(); ++i) {
children.add(new DiagnosticsNode(childrenJson.get(i).getAsJsonObject(), inspectorService, false, null));
}
return children;
}
/**
* Returns the index of the child that continues the path if any.
*/
public int getChildIndex() {
final JsonElement childIndex = json.get("childIndex");
if (childIndex.isJsonNull()) {
return -1;
}
return childIndex.getAsInt();
}
}
| flutter-intellij/flutter-idea/src/io/flutter/inspector/DiagnosticsPathNode.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/inspector/DiagnosticsPathNode.java",
"repo_id": "flutter-intellij",
"token_count": 592
} | 500 |
/*
* 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.
*/
package io.flutter.inspector;
import com.intellij.xdebugger.XSourcePosition;
import com.intellij.xdebugger.frame.XNavigatable;
import com.intellij.xdebugger.frame.XValue;
public class JumpToTypeSourceAction extends JumpToSourceActionBase {
public JumpToTypeSourceAction() {
super("jumpToTypeSource");
}
@Override
protected void startComputingSourcePosition(XValue value, XNavigatable navigatable) {
value.computeTypeSourcePosition(navigatable);
}
@Override
protected XSourcePosition getSourcePosition(DiagnosticsNode node) {
return null;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/inspector/JumpToTypeSourceAction.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/inspector/JumpToTypeSourceAction.java",
"repo_id": "flutter-intellij",
"token_count": 227
} | 501 |
/*
* 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.
*/
package io.flutter.module;
import com.intellij.icons.AllIcons;
import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.TextComponentAccessor;
import com.intellij.openapi.ui.ValidationInfo;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.ui.ComboboxWithBrowseButton;
import com.intellij.ui.DocumentAdapter;
import com.intellij.ui.components.JBLabel;
import com.intellij.xml.util.XmlStringUtil;
import io.flutter.FlutterBundle;
import io.flutter.module.settings.SettingsHelpForm;
import io.flutter.sdk.FlutterSdk;
import io.flutter.sdk.FlutterSdkUtil;
import javax.swing.ComboBoxEditor;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.event.DocumentEvent;
import javax.swing.text.JTextComponent;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class FlutterGeneratorPeer {
private final WizardContext myContext;
private JPanel myMainPanel;
private ComboboxWithBrowseButton mySdkPathComboWithBrowse;
private JBLabel myVersionContent;
private JLabel errorIcon;
private JTextPane errorText;
private JScrollPane errorPane;
private SettingsHelpForm myHelpForm;
public FlutterGeneratorPeer(WizardContext context) {
myContext = context;
errorIcon.setText("");
errorIcon.setIcon(AllIcons.Actions.Lightning);
Messages.installHyperlinkSupport(errorText);
// Hide pending real content.
myVersionContent.setVisible(false);
// TODO(messick) Remove this field.
myHelpForm.getComponent().setVisible(false);
init();
}
private void init() {
mySdkPathComboWithBrowse.getComboBox().setEditable(true);
FlutterSdkUtil.addKnownSDKPathsToCombo(mySdkPathComboWithBrowse.getComboBox());
mySdkPathComboWithBrowse.addBrowseFolderListener(FlutterBundle.message("flutter.sdk.browse.path.label"), null, null,
FileChooserDescriptorFactory.createSingleFolderDescriptor(),
TextComponentAccessor.STRING_COMBOBOX_WHOLE_TEXT);
mySdkPathComboWithBrowse.getComboBox().addActionListener(e -> fillSdkCache());
fillSdkCache();
final JTextComponent editorComponent = (JTextComponent)getSdkEditor().getEditorComponent();
editorComponent.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(@NotNull DocumentEvent e) {
validate();
}
});
errorIcon.setVisible(false);
errorPane.setVisible(false);
}
private void fillSdkCache() {
ApplicationManager.getApplication().executeOnPooledThread(() -> {
String path = (String)mySdkPathComboWithBrowse.getComboBox().getSelectedItem();
if (path != null) {
FlutterSdk sdk = FlutterSdk.forPath(path);
if (sdk != null) {
sdk.queryConfiguredPlatforms(false);
sdk.queryFlutterChannel(false);
}
}
});
}
@SuppressWarnings("EmptyMethod")
void apply() {
}
@NotNull
public JComponent getComponent() {
return myMainPanel;
}
private void createUIComponents() {
mySdkPathComboWithBrowse = new ComboboxWithBrowseButton(new ComboBox<>());
}
// TODO Link this to actual validation.
public boolean validate() {
final ValidationInfo info = validateSdk();
if (info != null) {
errorText.setText(XmlStringUtil.wrapInHtml(info.message));
}
errorIcon.setVisible(info != null);
errorPane.setVisible(info != null);
return info == null;
}
@Nullable
private ValidationInfo validateSdk() {
final String sdkPath = getSdkComboPath();
if (StringUtils.isEmpty(sdkPath)) {
return new ValidationInfo("A Flutter SDK must be specified for project creation.", mySdkPathComboWithBrowse);
}
final String message = FlutterSdkUtil.getErrorMessageIfWrongSdkRootPath(sdkPath);
if (message != null) {
return new ValidationInfo(message, mySdkPathComboWithBrowse);
}
return null;
}
@NotNull
public String getSdkComboPath() {
return FileUtilRt.toSystemIndependentName(getSdkEditor().getItem().toString().trim());
}
@NotNull
public ComboBoxEditor getSdkEditor() {
return mySdkPathComboWithBrowse.getComboBox().getEditor();
}
public SettingsHelpForm getHelpForm() {
return myHelpForm;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/module/FlutterGeneratorPeer.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/module/FlutterGeneratorPeer.java",
"repo_id": "flutter-intellij",
"token_count": 1806
} | 502 |
/*
* 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.
*/
package io.flutter.perf;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.fileEditor.TextEditor;
import io.flutter.run.daemon.FlutterApp;
import org.jetbrains.annotations.NotNull;
/**
* View model for displaying perf stats for a TextEditor.
* <p>
* This model tracks the state defining how perf stats should be displayed in
* the text editor along with the actual perf stats accessible via the
* getStats method.
*/
public interface EditorPerfModel extends PerfModel, Disposable {
@NotNull
FilePerfInfo getStats();
@NotNull
TextEditor getTextEditor();
FlutterApp getApp();
boolean getAlwaysShowLineMarkers();
void setAlwaysShowLineMarkersOverride(boolean show);
void setPerfInfo(@NotNull FilePerfInfo stats);
}
| flutter-intellij/flutter-idea/src/io/flutter/perf/EditorPerfModel.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/perf/EditorPerfModel.java",
"repo_id": "flutter-intellij",
"token_count": 271
} | 503 |
/*
* 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.
*/
package io.flutter.perf;
/**
* Class for accumulating sliding window performance stats optimized for fast
* performance and stable memory usage.
*/
class SlidingWindowStats {
// This lets as track a bit over 3 seconds at 60fps.
// TODO(jacobr): consider a longer sliding window length
// if we care about replaying historic stats for a longer
// period of time.
static final int _windowLength = 200 * 2;
/// Array of timestamp followed by count.
final int[] _window;
int _next = 0;
int _start = 0;
int _total = 0;
int _totalSinceNavigation = 0;
SlidingWindowStats() {
_window = new int[_windowLength];
}
int getTotal() {
return _total;
}
int getTotalSinceNavigation() {
return _totalSinceNavigation;
}
void clear() {
_next = 0;
_start = 0;
_total = 0;
_totalSinceNavigation = 0;
}
void onNavigation() {
_totalSinceNavigation = 0;
}
int getTotalWithinWindow(int windowStart) {
if (_next == _start) {
return 0;
}
final int end = _start >= 0 ? _start : _next;
int i = _next;
int count = 0;
while (true) {
i -= 2;
if (i < 0) {
i += _windowLength;
}
if (_window[i] < windowStart) {
break;
}
count += _window[i + 1];
if (i == end) {
break;
}
}
return count;
}
void add(int count, int timeStamp) {
_total += count;
_totalSinceNavigation += count;
if (_start != _next) {
int last = _next - 2;
if (last < 0) {
last += _windowLength;
}
final int lastTimeStamp = _window[last];
if (lastTimeStamp == timeStamp) {
_window[last + 1] += count;
return;
}
// The sliding window assumes timestamps must be given in increasing
// order.
assert (lastTimeStamp < timeStamp);
}
_window[_next] = timeStamp;
_window[_next + 1] = count;
_next += 2;
if (_next == _windowLength) {
_next = 0;
}
if (_start == _next) {
// The entire sliding window is now full so no need
// to track an explicit start.
_start = -1;
}
}
public int getPeakWithinWindow(int windowStart) {
if (_next == _start) {
return 0;
}
final int end = _start >= 0 ? _start : _next;
int i = _next;
int peakValue = 0;
while (true) {
i -= 2;
if (i < 0) {
i += _windowLength;
}
if (_window[i] < windowStart) {
break;
}
peakValue = Math.max(peakValue, _window[i + 1]);
if (i == end) {
break;
}
}
return peakValue;
}
public int getValue(PerfMetric metric, int currentTime) {
switch (metric) {
case total:
return getTotal();
case pastSecond:
return getTotalWithinWindow(currentTime - 999);
case lastFrame:
return getPeakWithinWindow(currentTime);
case peakRecent:
return getPeakWithinWindow(currentTime - 499);
case totalSinceEnteringCurrentScreen:
return getTotalSinceNavigation();
default:
return 0;
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/perf/SlidingWindowStats.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/perf/SlidingWindowStats.java",
"repo_id": "flutter-intellij",
"token_count": 1341
} | 504 |
/*
* 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.
*/
package io.flutter.preview;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.LayeredIcon;
import com.intellij.ui.SimpleTextAttributes;
import com.jetbrains.lang.dart.DartComponentType;
import com.jetbrains.lang.dart.util.DartPresentableUtil;
import org.dartlang.analysis.server.protocol.Element;
import org.dartlang.analysis.server.protocol.ElementKind;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import static com.intellij.icons.AllIcons.Nodes.Class;
import static com.intellij.icons.AllIcons.Nodes.Enum;
import static com.intellij.icons.AllIcons.Nodes.*;
import static com.intellij.icons.AllIcons.RunConfigurations.Junit;
/**
* Most of the class is copied from Dart Plugin.
* https://github.com/JetBrains/intellij-plugins/blob/master/Dart/src/com/jetbrains/lang/dart/ide/structure/DartStructureViewElement.java
*/
public class DartElementPresentationUtil {
private static final LayeredIcon STATIC_FINAL_FIELD_ICON = new LayeredIcon(Field, StaticMark, FinalMark);
private static final LayeredIcon FINAL_FIELD_ICON = new LayeredIcon(Field, FinalMark);
private static final LayeredIcon STATIC_FIELD_ICON = new LayeredIcon(Field, StaticMark);
private static final LayeredIcon STATIC_METHOD_ICON = new LayeredIcon(Method, StaticMark);
private static final LayeredIcon TOP_LEVEL_FUNCTION_ICON = new LayeredIcon(Function, StaticMark);
private static final LayeredIcon TOP_LEVEL_VAR_ICON = new LayeredIcon(Variable, StaticMark);
private static final LayeredIcon CONSTRUCTOR_INVOCATION_ICON = new LayeredIcon(Class, TabPin);
private static final LayeredIcon FUNCTION_INVOCATION_ICON = new LayeredIcon(Method, TabPin);
private static final LayeredIcon TOP_LEVEL_CONST_ICON = new LayeredIcon(Variable, StaticMark, FinalMark);
@Nullable
public static Icon getIcon(@NotNull Element element) {
final boolean finalOrConst = element.isConst() || element.isFinal();
switch (element.getKind()) {
case ElementKind.CLASS:
return element.isAbstract() ? AbstractClass : Class;
case ElementKind.EXTENSION:
return Include;
case ElementKind.MIXIN:
return AbstractClass;
case ElementKind.CONSTRUCTOR:
return Method;
case ElementKind.CONSTRUCTOR_INVOCATION:
return CONSTRUCTOR_INVOCATION_ICON;
case ElementKind.ENUM:
return Enum;
case ElementKind.ENUM_CONSTANT:
return STATIC_FINAL_FIELD_ICON;
case ElementKind.FIELD:
if (finalOrConst && element.isTopLevelOrStatic()) return STATIC_FINAL_FIELD_ICON;
if (finalOrConst) return FINAL_FIELD_ICON;
if (element.isTopLevelOrStatic()) return STATIC_FIELD_ICON;
return Field;
case ElementKind.FUNCTION:
return element.isTopLevelOrStatic() ? TOP_LEVEL_FUNCTION_ICON : Lambda;
case ElementKind.FUNCTION_INVOCATION:
return FUNCTION_INVOCATION_ICON;
case ElementKind.FUNCTION_TYPE_ALIAS:
return DartComponentType.TYPEDEF.getIcon();
case ElementKind.GETTER:
return element.isTopLevelOrStatic() ? PropertyReadStatic : PropertyRead;
case ElementKind.METHOD:
if (element.isAbstract()) return AbstractMethod;
return element.isTopLevelOrStatic() ? STATIC_METHOD_ICON : Method;
case ElementKind.SETTER:
return element.isTopLevelOrStatic() ? PropertyWriteStatic : PropertyWrite;
case ElementKind.TOP_LEVEL_VARIABLE:
return finalOrConst ? TOP_LEVEL_CONST_ICON : TOP_LEVEL_VAR_ICON;
case ElementKind.UNIT_TEST_GROUP:
return TestSourceFolder;
case ElementKind.UNIT_TEST_TEST:
return Junit;
case ElementKind.CLASS_TYPE_ALIAS:
case ElementKind.COMPILATION_UNIT:
case ElementKind.FILE:
case ElementKind.LABEL:
case ElementKind.LIBRARY:
case ElementKind.LOCAL_VARIABLE:
case ElementKind.PARAMETER:
case ElementKind.PREFIX:
case ElementKind.TYPE_PARAMETER:
case ElementKind.UNKNOWN:
default:
return null; // unexpected
}
}
public static void renderElement(@NotNull Element element, @NotNull OutlineTreeCellRenderer renderer, boolean nameInBold) {
final SimpleTextAttributes attributes =
nameInBold ? SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES : SimpleTextAttributes.REGULAR_ATTRIBUTES;
renderer.appendSearch(element.getName(), attributes);
if (!StringUtil.isEmpty(element.getTypeParameters())) {
renderer.appendSearch(element.getTypeParameters(), attributes);
}
if (!StringUtil.isEmpty(element.getParameters())) {
renderer.appendSearch(element.getParameters(), attributes);
}
if (!StringUtil.isEmpty(element.getReturnType())) {
renderer.append(" ");
renderer.append(DartPresentableUtil.RIGHT_ARROW);
renderer.append(" ");
renderer.appendSearch(element.getReturnType(), SimpleTextAttributes.REGULAR_ATTRIBUTES);
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/preview/DartElementPresentationUtil.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/preview/DartElementPresentationUtil.java",
"repo_id": "flutter-intellij",
"token_count": 1869
} | 505 |
/*
* 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.
*/
package io.flutter.refactoring;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.jetbrains.lang.dart.ide.refactoring.ServerRefactoring;
import org.dartlang.analysis.server.protocol.ExtractWidgetOptions;
import org.dartlang.analysis.server.protocol.RefactoringFeedback;
import org.dartlang.analysis.server.protocol.RefactoringKind;
import org.dartlang.analysis.server.protocol.RefactoringOptions;
import org.jetbrains.annotations.NotNull;
/**
* LTK wrapper around Analysis Server 'Extract Widget' refactoring.
*/
public class ExtractWidgetRefactoring extends ServerRefactoring {
private final ExtractWidgetOptions options = new ExtractWidgetOptions("NewWidget");
public ExtractWidgetRefactoring(@NotNull final Project project,
@NotNull final VirtualFile file,
final int offset,
final int length) {
super(project, "Extract Widget", RefactoringKind.EXTRACT_WIDGET, file, offset, length);
}
@Override
protected RefactoringOptions getOptions() {
return options;
}
@Override
protected void setFeedback(@NotNull RefactoringFeedback feedback) {
}
public void setName(@NotNull String name) {
options.setName(name);
}
public void sendOptions() {
setOptions(true, null);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/refactoring/ExtractWidgetRefactoring.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/refactoring/ExtractWidgetRefactoring.java",
"repo_id": "flutter-intellij",
"token_count": 536
} | 506 |
/*
* 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.
*/
package io.flutter.run;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.util.PsiTreeUtil;
import com.jetbrains.lang.dart.DartFileType;
import com.jetbrains.lang.dart.psi.DartFile;
import com.jetbrains.lang.dart.psi.DartImportStatement;
import com.jetbrains.lang.dart.util.DartResolveUtil;
import io.flutter.FlutterBundle;
import io.flutter.bazel.Workspace;
import io.flutter.bazel.WorkspaceCache;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.stream.Stream;
/**
* The location of a Dart file containing a main() method for launching a Flutter app.
* <p>
* It has been checked for errors, but the check might not have succeeded.
*/
public class MainFile {
@NotNull
private final VirtualFile file;
@NotNull
private final VirtualFile appDir;
private final boolean flutterImports;
private MainFile(@NotNull VirtualFile file, @NotNull VirtualFile appDir, boolean flutterImports) {
this.file = file;
this.appDir = appDir;
this.flutterImports = flutterImports;
}
/**
* Returns the Dart file containing main.
*/
@NotNull
public VirtualFile getFile() {
return file;
}
/**
* Returns the closest ancestor directory containing a pubspec.yaml, BUILD, or packages meta-data file.
*/
@NotNull
public VirtualFile getAppDir() {
return appDir;
}
/**
* Returns true if the file has any direct flutter imports.
*/
public boolean hasFlutterImports() {
return flutterImports;
}
/**
* Verifies that the given path points to an entrypoint file within a Flutter app.
* <p>
* If there is an error, {@link Result#canLaunch} will return false and the error is available via {@link Result#getError}
*/
@NotNull
public static MainFile.Result verify(@Nullable String path, Project project) {
if (!ApplicationManager.getApplication().isReadAccessAllowed()) {
throw new IllegalStateException("need read access");
}
if (StringUtil.isEmptyOrSpaces(path)) {
return error(FlutterBundle.message("entrypoint.not.set"));
}
final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(path);
if (file == null) {
return error(FlutterBundle.message("entrypoint.not.found", FileUtil.toSystemDependentName(path)));
}
if (file.getFileType() != DartFileType.INSTANCE) {
return error(FlutterBundle.message("entrypoint.not.dart"));
}
final PsiFile psi = PsiManager.getInstance(project).findFile(file);
if (!(psi instanceof DartFile)) {
return error(FlutterBundle.message("entrypoint.not.dart"));
}
final DartFile dart = (DartFile)psi;
if (DartResolveUtil.getMainFunction(dart) == null) {
return error(FlutterBundle.message("main.not.in.entrypoint"));
}
if (!inProject(file, project)) {
return error(FlutterBundle.message("entrypoint.not.in.project"));
}
final VirtualFile dir = findAppDir(file, project);
if (dir == null) {
return error(FlutterBundle.message("entrypoint.not.in.app.dir"));
}
final boolean hasFlutterImports = findImportUrls(dart).anyMatch((url) -> url.startsWith("package:flutter/"));
return new MainFile.Result(new MainFile(file, dir, hasFlutterImports), null);
}
@Nullable
private static VirtualFile findAppDir(@Nullable VirtualFile file, @NotNull Project project) {
if (WorkspaceCache.getInstance(project).isBazel()) {
final Workspace workspace = WorkspaceCache.getInstance(project).get();
assert(workspace != null);
return workspace.getRoot();
}
for (VirtualFile candidate = file; inProject(candidate, project); candidate = candidate.getParent()) {
if (isAppDir(candidate, project)) return candidate;
}
return null;
}
private static boolean isAppDir(@NotNull VirtualFile dir, @NotNull Project project) {
assert(!WorkspaceCache.getInstance(project).isBazel());
return dir.isDirectory() && (
dir.findChild("pubspec.yaml") != null ||
dir.findChild(".dart_tool") != null ||
dir.findChild(".packages") != null
);
}
private static boolean inProject(@Nullable VirtualFile file, @NotNull Project project) {
return file != null && ProjectRootManager.getInstance(project).getFileIndex().isInContent(file);
}
/**
* Returns the import URL's in a Dart file.
*/
@NotNull
private static Stream<String> findImportUrls(@NotNull DartFile file) {
final DartImportStatement[] imports = PsiTreeUtil.getChildrenOfType(file, DartImportStatement.class);
if (imports == null) return Stream.empty();
return Arrays.stream(imports).map(DartImportStatement::getUriString);
}
private static MainFile.Result error(@NotNull String message) {
return new MainFile.Result(null, message);
}
/**
* The result of {@link #verify}; either a MainFile or an error.
*/
public static class Result {
@Nullable
private final MainFile file;
@Nullable
private final String error;
private Result(@Nullable MainFile file, @Nullable String error) {
assert (file == null || error == null);
assert (file != null || error != null);
this.file = file;
this.error = error;
}
/**
* Returns true if the Flutter app can be launched.
* <p>
* If false, the error can be found by calling {@link #getError}.
*/
public boolean canLaunch() {
return error == null;
}
/**
* Returns the error message to display if this file is not launchable.
*/
@NotNull
public String getError() {
if (error == null) {
throw new IllegalStateException("called getError when there is no error");
}
return error;
}
/**
* Unwraps the MainFile. Valid only if there's not an error.
*/
public MainFile get() {
if (file == null) {
throw new IllegalStateException("called getLaunchable when there is an error: " + error);
}
return file;
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/run/MainFile.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/MainFile.java",
"repo_id": "flutter-intellij",
"token_count": 2271
} | 507 |
/*
* 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.
*/
package io.flutter.run.bazelTest;
import com.google.common.annotations.VisibleForTesting;
import com.intellij.psi.PsiElement;
import com.jetbrains.lang.dart.psi.DartFile;
import io.flutter.FlutterUtils;
import io.flutter.bazel.WorkspaceCache;
import io.flutter.run.common.CommonTestConfigUtils;
import io.flutter.run.common.TestType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class BazelTestConfigUtils extends CommonTestConfigUtils {
@VisibleForTesting
BazelTestConfigUtils() {
}
private static BazelTestConfigUtils instance;
public static BazelTestConfigUtils getInstance() {
if (instance == null) {
instance = new BazelTestConfigUtils();
}
return instance;
}
private boolean isBazelFlutterCode(@Nullable DartFile file) {
return file != null && WorkspaceCache.getInstance(file.getProject()).isBazel();
}
@Nullable
@Override
public TestType asTestCall(@NotNull PsiElement element) {
if (!isBazelFlutterCode(FlutterUtils.getDartFile(element))) return null;
return super.asTestCall(element);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/run/bazelTest/BazelTestConfigUtils.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/bazelTest/BazelTestConfigUtils.java",
"repo_id": "flutter-intellij",
"token_count": 422
} | 508 |
/*
* Copyright 2021 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.
*/
package io.flutter.run.coverage;
import com.intellij.coverage.CoverageDataManager;
import com.intellij.coverage.CoverageRunner;
import com.intellij.execution.configurations.RunConfigurationBase;
import com.intellij.execution.configurations.coverage.CoverageEnabledConfiguration;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ModalityUiUtil;
import io.flutter.pub.PubRoot;
import io.flutter.run.test.TestConfig;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class FlutterCoverageEnabledConfiguration extends CoverageEnabledConfiguration {
private static final Logger LOG = Logger.getInstance(FlutterCoverageEnabledConfiguration.class.getName());
public FlutterCoverageEnabledConfiguration(@NotNull RunConfigurationBase<?> configuration) {
super(configuration);
super.setCoverageRunner(CoverageRunner.getInstance(FlutterCoverageRunner.class));
createCoverageFile();
ModalityUiUtil.invokeLaterIfNeeded(
ModalityState.any(),
() -> setCurrentCoverageSuite(CoverageDataManager.getInstance(configuration.getProject()).addCoverageSuite(this)));
}
@Override
protected String createCoverageFile() {
if (myCoverageFilePath == null) {
if (!(getConfiguration() instanceof TestConfig)) {
return "";
}
VirtualFile file = ((TestConfig)getConfiguration()).getFields().getFileOrDir();
final VirtualFile root = PubRoot.forFile(file).getRoot();
myCoverageFilePath = root.getPath() + "/coverage/lcov.info";
}
return myCoverageFilePath;
}
@Override
public void setCoverageRunner(@Nullable final CoverageRunner coverageRunner) {
// Save and restore myCoverageFilePath because the super method clears it.
final String path = myCoverageFilePath;
super.setCoverageRunner(coverageRunner);
myCoverageFilePath = path;
}
@Override
public void coverageRunnerExtensionRemoved(@NotNull CoverageRunner runner) {
final String path = myCoverageFilePath;
super.coverageRunnerExtensionRemoved(runner);
myCoverageFilePath = path;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/run/coverage/FlutterCoverageEnabledConfiguration.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/coverage/FlutterCoverageEnabledConfiguration.java",
"repo_id": "flutter-intellij",
"token_count": 744
} | 509 |
/*
* 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.
*/
package io.flutter.run.test;
import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.execution.actions.ConfigurationFromContext;
import com.intellij.execution.actions.RunConfigurationProducer;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.jetbrains.lang.dart.psi.DartFile;
import io.flutter.FlutterUtils;
import io.flutter.dart.DartPlugin;
import io.flutter.pub.PubRoot;
import io.flutter.run.FlutterRunConfigurationProducer;
import io.flutter.sdk.FlutterSdk;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Determines when we can run a test using "flutter test".
*/
public class FlutterTestConfigProducer extends RunConfigurationProducer<TestConfig> {
private final TestConfigUtils testConfigUtils = TestConfigUtils.getInstance();
protected FlutterTestConfigProducer() {
super(FlutterTestConfigType.getInstance());
}
private static boolean isFlutterContext(@NotNull ConfigurationContext context) {
final PsiElement location = context.getPsiLocation();
return location != null && FlutterUtils.isInFlutterProject(context.getProject(), location);
}
/**
* If the current file looks like a Flutter test, initializes the run config to run it.
* <p>
* Returns true if successfully set up.
*/
@Override
protected boolean setupConfigurationFromContext(@NotNull TestConfig config,
@NotNull ConfigurationContext context,
@NotNull Ref<PsiElement> sourceElement) {
if (!isFlutterContext(context)) return false;
final PsiElement elt = context.getPsiLocation();
if (elt instanceof PsiDirectory) {
return setupForDirectory(config, (PsiDirectory)elt);
}
final DartFile file = FlutterRunConfigurationProducer.getDartFile(context);
if (file == null) {
return false;
}
if (supportsFiltering(config.getSdk())) {
final String testName = testConfigUtils.findTestName(elt);
if (testName != null && elt != null) {
final boolean hasVariant = "testWidgets".equals(elt.getText());
return setupForSingleTest(config, context, file, testName, hasVariant);
}
}
return setupForDartFile(config, context, file);
}
private boolean supportsFiltering(@Nullable FlutterSdk sdk) {
return sdk != null && sdk.getVersion().flutterTestSupportsFiltering();
}
private boolean setupForSingleTest(TestConfig config, ConfigurationContext context, DartFile file, String testName, boolean hasVariant) {
final VirtualFile testFile = verifyFlutterTestFile(config, context, file);
if (testFile == null) return false;
config.setFields(TestFields.forTestName(testName, testFile.getPath()).useRegexp(hasVariant));
config.setGeneratedName();
return true;
}
private boolean setupForDartFile(TestConfig config, ConfigurationContext context, DartFile file) {
final VirtualFile testFile = verifyFlutterTestFile(config, context, file);
if (testFile == null) return false;
config.setFields(TestFields.forFile(testFile.getPath()));
config.setGeneratedName();
return true;
}
private VirtualFile verifyFlutterTestFile(TestConfig config, ConfigurationContext context, DartFile file) {
final VirtualFile candidate = FlutterRunConfigurationProducer.getFlutterEntryFile(context, false, false);
if (candidate == null) return null;
return FlutterUtils.isInTestDir(file) ? candidate : null;
}
private boolean setupForDirectory(TestConfig config, PsiDirectory dir) {
final PubRoot root = PubRoot.forDescendant(dir.getVirtualFile(), dir.getProject());
if (root == null) return false;
if (!root.hasTests(dir.getVirtualFile())) return false;
config.setFields(TestFields.forDir(dir.getVirtualFile().getPath()));
config.setGeneratedName();
return true;
}
/**
* Returns true if a run config was already created for this file. If so we will reuse it.
*/
@Override
public boolean isConfigurationFromContext(TestConfig config, @NotNull ConfigurationContext context) {
final VirtualFile fileOrDir = config.getFields().getFileOrDir();
if (fileOrDir == null) return false;
final PsiElement target = context.getPsiLocation();
if (target instanceof PsiDirectory) {
return ((PsiDirectory)target).getVirtualFile().equals(fileOrDir);
}
if (!FlutterRunConfigurationProducer.hasDartFile(context, fileOrDir.getPath())) return false;
final String testName = testConfigUtils.findTestName(context.getPsiLocation());
if (config.getFields().getScope() == TestFields.Scope.NAME) {
return testName != null && testName.equals(config.getFields().getTestName());
}
else {
return testName == null;
}
}
@Override
public boolean shouldReplace(@NotNull ConfigurationFromContext self, @NotNull ConfigurationFromContext other) {
return DartPlugin.isDartTestConfiguration(other.getConfigurationType());
}
}
| flutter-intellij/flutter-idea/src/io/flutter/run/test/FlutterTestConfigProducer.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/test/FlutterTestConfigProducer.java",
"repo_id": "flutter-intellij",
"token_count": 1742
} | 510 |
/*
* 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.
*/
package io.flutter.samples;
import com.intellij.ide.BrowserUtil;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.ui.EditorNotificationPanel;
import com.intellij.ui.HyperlinkLabel;
import icons.FlutterIcons;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.util.List;
public class FlutterSampleActionsPanel extends EditorNotificationPanel {
FlutterSampleActionsPanel(@NotNull List<FlutterSample> samples) {
super(EditorColors.GUTTER_BACKGROUND);
icon(FlutterIcons.Flutter);
text("View hosted code sample");
for (int i = 0; i < samples.size(); i++) {
if (i != 0) {
myLinksPanel.add(new JSeparator(SwingConstants.VERTICAL));
}
final FlutterSample sample = samples.get(i);
final HyperlinkLabel label = createActionLabel(sample.getClassName(), () -> browseTo(sample));
label.setToolTipText(sample.getHostedDocsUrl());
}
}
private void browseTo(FlutterSample sample) {
BrowserUtil.browse(sample.getHostedDocsUrl());
}
}
| flutter-intellij/flutter-idea/src/io/flutter/samples/FlutterSampleActionsPanel.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/samples/FlutterSampleActionsPanel.java",
"repo_id": "flutter-intellij",
"token_count": 422
} | 511 |
/*
* 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.
*/
package io.flutter.sdk;
import com.intellij.ide.ui.search.SearchableOptionContributor;
import com.intellij.ide.ui.search.SearchableOptionProcessor;
import io.flutter.FlutterBundle;
import io.flutter.FlutterConstants;
import org.jetbrains.annotations.NotNull;
// Note: update this file when updating FlutterSettingsConfigurable.
public class FlutterSearchableOptionContributor extends SearchableOptionContributor {
@Override
public void processOptions(@NotNull SearchableOptionProcessor processor) {
// Keep these in the same order as FlutterBundle.properties
add(processor, FlutterBundle.message("settings.try.out.features.still.under.development"));
add(processor, FlutterBundle.message("settings.enable.android.gradle.sync"));
// For some reason the word "report" is ignored by the search feature, but the other words work.
add(processor, FlutterBundle.message("settings.report.google.analytics"));
add(processor, FlutterBundle.message("settings.enable.hot.ui"));
add(processor, FlutterBundle.message("settings.enable.verbose.logging"));
add(processor, FlutterBundle.message("settings.format.code.on.save"));
add(processor, FlutterBundle.message("settings.organize.imports.on.save"));
add(processor, FlutterBundle.message("settings.flutter.version"));
add(processor, FlutterBundle.message("settings.open.inspector.on.launch"));
add(processor, FlutterBundle.message("settings.hot.reload.on.save"));
add(processor, FlutterBundle.message("settings.enable.bazel.hot.restart"));
add(processor, FlutterBundle.message("settings.allow.tests.in.sources"));
add(processor, FlutterBundle.message("settings.allow.tests.tooltip"));
add(processor, FlutterBundle.message("settings.font.packages"));
add(processor, FlutterBundle.message("settings.show.all.configs"));
add(processor, FlutterBundle.message("settings.show.all.configs.tooltip"));
add(processor, FlutterBundle.message("settings.enable.androi.gradle.sync.tooltip"));
add(processor, FlutterBundle.message("settings.experiments"));
add(processor, FlutterBundle.message("settings.editor"));
add(processor, FlutterBundle.message("settings.show.build.guides"));
add(processor, FlutterBundle.message("settings.show.build.guides.tooltip"));
add(processor, FlutterBundle.message("settings.format.code.tooltip"));
add(processor, FlutterBundle.message("settings.organize.imports.tooltip"));
add(processor, FlutterBundle.message("settings.show.closing.labels"));
add(processor, FlutterBundle.message("settings.sdk.copy.content"));
add(processor, FlutterBundle.message("settings.report.analytics.tooltip"));
add(processor, FlutterBundle.message("settings.enable.verbose.logging.tooltip"));
}
private static void add(@NotNull SearchableOptionProcessor processor, @NotNull String key) {
processor.addOptions(key, null, key, FlutterConstants.FLUTTER_SETTINGS_PAGE_ID,
FlutterSettingsConfigurable.FLUTTER_SETTINGS_PAGE_NAME, true);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/sdk/FlutterSearchableOptionContributor.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/sdk/FlutterSearchableOptionContributor.java",
"repo_id": "flutter-intellij",
"token_count": 1047
} | 512 |
/*
* 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.
*/
package io.flutter.utils;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.ProcessCanceledException;
import javax.swing.*;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
public class AsyncUtils {
/**
* Helper to get the value of a future on the UI thread.
* <p>
* The action will never be called if the future is cancelled.
*/
public static <T> void whenCompleteUiThread(CompletableFuture<T> future, BiConsumer<? super T, ? super Throwable> action) {
future.whenCompleteAsync(
(T value, Throwable throwable) -> {
// Exceptions due to the Future being cancelled need to be treated
// differently as they indicate that no work should be done rather
// than that an error occurred.
// By convention we cancel Futures when the value to be computed
// would be obsolete. For example, the Future may be for a value from
// a previous Dart isolate or the user has already navigated somewhere
// else.
if (throwable instanceof CancellationException) {
return;
}
invokeLater(() -> action.accept(value, throwable));
}
);
}
public static void invokeLater(Runnable runnable) {
final Application app = ApplicationManager.getApplication();
if (app == null || app.isUnitTestMode()) {
// This case existing to support unit testing.
SwingUtilities.invokeLater(runnable);
}
else {
app.invokeLater(runnable);
}
}
public static void invokeAndWait(Runnable runnable) throws ProcessCanceledException {
final Application app = ApplicationManager.getApplication();
if (app == null || app.isUnitTestMode()) {
try {
// This case existing to support unit testing.
SwingUtilities.invokeAndWait(runnable);
}
catch (InterruptedException | InvocationTargetException e) {
throw new ProcessCanceledException(e);
}
}
else {
app.invokeAndWait(runnable);
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/utils/AsyncUtils.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/AsyncUtils.java",
"repo_id": "flutter-intellij",
"token_count": 802
} | 513 |
/*
* 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.
*/
package io.flutter.utils;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableSet;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Disposer;
import com.intellij.util.concurrency.AppExecutorUtil;
import io.flutter.FlutterUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.Closeable;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
/**
* A thread-safe variable that can be updated by submitting a callback to run in the background.
*
* <p>When the callback is finished (and there is no newer task that makes it obsolete),
* its value will be published and subscribers will be notified.
*
* <p>It's guaranteed that a Refreshable's visible state won't change while an event handler
* is running on the Swing dispatch thread.
*/
public class Refreshable<T> implements Closeable {
private final Schedule schedule = new Schedule();
private final Publisher publisher;
/**
* Holds a future that completes when the background task exits.
*
* <p>Null when idle.
*/
private final AtomicReference<Future> backgroundTask = new AtomicReference<>();
/**
* Subscribers to be notified after a value is published.
*
* <p>Access should be synchronized on the field.
*/
private final Set<Runnable> subscribers = new LinkedHashSet<>();
/**
* The representation of this Refreshable in IntelliJ's dispose tree.
*
* <p>(Private so that nobody can add children.)
*/
private final Disposable disposeNode;
public Refreshable() {
this(null);
}
/**
* Creates a refreshable variable that reports when it stops using a value that it created.
*
* @param unpublish will be called when the value is no longer in use. Can be called even though
* the value was never published. It will run on the Swing dispatch thread.
*/
public Refreshable(Consumer<T> unpublish) {
this.publisher = new Publisher(unpublish);
this.disposeNode = this::close;
}
/**
* Returns the most recently published value, without waiting for any updates.
*
* <p>Returns null if the cache is uninitialized.
*
* <p>Calling getNow() twice during the same Swing event handler will return the same result.
*/
public @Nullable
T getNow() {
return publisher.get();
}
/**
* Returns whether the Refreshable is busy, idle, or closed.
*/
public State getState() {
return publisher.state.get();
}
/**
* Waits for the background task to finish or the Refreshable to be closed, then returns the current value.
*
* <p>If {@link #refresh} is never called then this will block forever waiting
* for the variable to be initialized.
*
* @throws IllegalStateException if called on the Swing dispatch thread.
*/
public @Nullable
T getWhenReady() {
if (SwingUtilities.isEventDispatchThread()) {
throw new IllegalStateException("getWhenReady shouldn't be called from Swing dispatch thread");
}
publisher.waitForFirstValue();
final Future refreshDone = backgroundTask.get();
if (refreshDone == null) {
return getNow(); // No background task; currently idle.
}
try {
refreshDone.get();
}
catch (Exception e) {
FlutterUtils.warn(LOG, "Unexpected exception waiting for refresh task to finish", e);
}
return getNow();
}
/**
* Runs a callback whenever the Refreshable's value or state changes.
*
* <p>The callback will be run on the Swing dispatch thread.
*/
public void subscribe(@NotNull Runnable callback) {
synchronized (subscribers) {
if (publisher.isClosing()) {
throw new IllegalStateException("Can't subscribe to closed Refreshable");
}
subscribers.add(callback);
}
}
/**
* Stops notifications to a callback that was passed to {@link ::subscribe}.
*/
public void unsubscribe(@NotNull Runnable callback) {
synchronized (subscribers) {
subscribers.remove(callback);
}
}
/**
* Creates and publishes a new value in the background.
*
* <p>(Convenience method for when a {@link Request} isn't needed.)
*/
public void refresh(@NotNull Callable<T> callback) {
refresh((x) -> callback.call());
}
/**
* Creates and publishes a new value in the background.
*
* <p>If an exception is thrown, no new value will be published, but
* a message will be logged.
*/
public void refresh(@NotNull Callback<T> callback) {
if (publisher.isClosing()) {
FlutterUtils.warn(LOG, "attempted to update closed Refreshable");
return;
}
schedule.reschedule(new Request<>(this, callback));
// Start up the background task if it's not running.
final FutureTask next = new FutureTask<>(this::runInBackground, null);
if (backgroundTask.compareAndSet(null, next)) {
// Wait until after event handler currently running, in case it calls refresh again.
SwingUtilities.invokeLater(() -> AppExecutorUtil.getAppExecutorService().submit(next));
}
}
/**
* Asynchronously shuts down the Refreshable.
*
* <p>Sets the published value to null and cancels any background tasks.
*
* <p>Also sets the state to CLOSED and notifies subscribers. Removes subscribers after delivering the last event.
*/
public void close() {
if (!publisher.close()) {
return; // already closed.
}
// Cancel any running create task.
schedule.reschedule(null);
// Remove from dispose tree. Calls close() again, harmlessly.
Disposer.dispose(disposeNode);
}
/**
* Automatically unsubscribes and unpublishes when a parent object is disposed.
*
* <p>Only one parent can be registered at a time. Auto-unsubscribe
* will stop working for any object previously passed to this
* method.
*/
public void setDisposeParent(Disposable parent) {
Disposer.register(parent, disposeNode);
}
/**
* Runs requests until there are no more requests. Publishes the last successful response.
*/
private void runInBackground() {
try {
publisher.setState(State.BUSY);
for (Request<T> request = schedule.next(); request != null; request = schedule.next()) {
// Do the work.
try {
final T value = request.callback.call(request);
publisher.reschedule(value);
}
catch (CancellationException e) {
// This is normal.
}
catch (Exception e) {
if (!Objects.equal(e.getMessage(), "expected failure in test")) {
FlutterUtils.warn(LOG, "Callback threw an exception while updating a Refreshable", e);
}
}
finally {
schedule.done(request);
}
try {
// Wait for an opportunity to publish.
SwingUtilities.invokeAndWait(() -> {
// If the schedule changed in the meantime, skip publishing the value.
if (!schedule.hasNext()) {
if (publisher.publish()) {
publisher.fireEvent();
}
}
});
}
catch (Exception e) {
FlutterUtils.warn(LOG, "Unable to publish a value while updating a Refreshable", e);
}
}
}
finally {
publisher.setState(State.IDLE);
backgroundTask.set(null); // Allow restart on exit.
}
}
private static final Logger LOG = Logger.getInstance(Refreshable.class);
/**
* A value indicating whether the Refreshable is being updated or not.
*/
public enum State {BUSY, IDLE, CLOSED}
/**
* A function that produces the next value of a Refreshable.
*/
public interface Callback<T> {
/**
* Calculates the new value.
*
* <p>If no update is needed, it should either return the previous value or
* throw {@link CancellationException} to avoid publishing a new value.
* (Any other exception will have the same effect, but a warning will be logged.)
*/
T call(Request req) throws Exception;
}
/**
* A scheduled or running refresh request.
*/
public static class Request<T> {
private final Refreshable<T> target;
private final Callback<T> callback;
Request(Refreshable<T> target, Callback<T> callback) {
this.target = target;
this.callback = callback;
}
/**
* Returns true if the value is no longer needed, because another request
* is ready to run.
*
* <p>When the request is cancelled, the caller can either return the previous
* value or throw {@link CancellationException} to avoid publishing a new
* value.
*/
public boolean isCancelled() {
return target.schedule.isCancelled(this);
}
/**
* The value returned by the most recent successful request.
* (It might not be published yet.)
*/
public T getPrevious() {
return target.publisher.getPrevious();
}
}
/**
* Manages the schedule for creating new values on the background thread.
*/
private class Schedule {
/**
* The next request to run.
*
* <p>Null when there's nothing more to do.
*/
private @Nullable Request<T> scheduled;
/**
* The currently running create callback.
*
* <p>Null when nothing is currently running.
*/
private @Nullable Request<T> running;
/**
* If not null, the create callback has been cancelled.
*/
private @Nullable Request<T> cancelled;
/**
* Replaces currently scheduled tasks with a new task.
*/
synchronized void reschedule(@Nullable Request<T> request) {
scheduled = request;
cancelled = running;
}
/**
* Checks if there is any work scheduled.
*/
synchronized boolean hasNext() {
return scheduled != null;
}
/**
* Returns the next task to run, or null if nothing is scheduled.
*/
synchronized @Nullable
Request<T> next() {
assert (running == null);
running = scheduled;
scheduled = null;
return running;
}
/**
* Indicates that we finished creating a value.
*/
synchronized void done(@NotNull Request<T> request) {
assert (running != null);
running = null;
cancelled = null;
}
synchronized boolean isCancelled(Request<T> callback) {
return callback == cancelled;
}
}
/**
* Manages the schedule for publishing and unpublishing values.
*/
private class Publisher {
private final @NotNull Consumer<T> unpublishCallback;
private @Nullable T scheduled;
private @Nullable T published;
private final AtomicReference<State> state = new AtomicReference<>(State.IDLE);
/**
* Completes when the first value is published or the Refreshable is closed.
*/
private final FutureTask initialized = new FutureTask<>(() -> null);
private boolean needToPublish;
private boolean closing;
Publisher(@Nullable Consumer<T> unpublish) {
if (unpublish == null) {
unpublish = (x) -> {
};
}
this.unpublishCallback = unpublish;
}
/**
* Schedules a value to be published later, provided that it's not a duplicate.
*/
synchronized void reschedule(@Nullable T toPublish) {
if (scheduled != null && Objects.equal(toPublish, scheduled)) {
return; // Duplicate already scheduled. Nothing to do.
}
final T discarded = unschedule();
if (discarded != null) {
SwingUtilities.invokeLater(() -> unpublish(discarded));
}
// Don't publish a duplicate. (Don't unpublish a duplicate either.)
if (initialized.isDone() && Objects.equal(toPublish, published)) {
needToPublish = false;
return;
}
if (closing) {
// Don't publish anything else since we're closing.
// Discard new value instead of publishing it.
if (toPublish != null) {
SwingUtilities.invokeLater(() -> unpublish(toPublish));
}
return;
}
scheduled = toPublish;
needToPublish = true;
}
/**
* Remove any previously scheduled value, returning it.
*/
private synchronized T unschedule() {
final T old = scheduled;
scheduled = null;
needToPublish = false;
return old;
}
/**
* Returns the value that was scheduled most recently.
*/
private synchronized T getPrevious() {
if (needToPublish) {
return scheduled;
}
else {
return published;
}
}
boolean close() {
final T wasScheduled;
synchronized (this) {
if (closing) return false;
wasScheduled = unschedule();
closing = true;
}
Runnable callback = () -> {
unpublish(wasScheduled);
final T wasPublished;
synchronized (this) {
wasPublished = published;
published = null;
}
unpublish(wasPublished);
setState(State.CLOSED);
// Free subscribers. (Avoid memory leaks.)
synchronized (subscribers) {
subscribers.clear();
}
// unblock getWhenReady() if no value was ever published.
initialized.run();
};
Application application = ApplicationManager.getApplication();
if (application != null && !application.isUnitTestMode()) {
application.invokeAndWait(callback);
}
else {
SwingUtilities.invokeLater(callback);
}
return true;
}
/**
* Returns true if the value was published.
*/
boolean publish() {
assert (SwingUtilities.isEventDispatchThread());
final T discarded;
synchronized (this) {
if (!needToPublish) return false;
discarded = published;
published = unschedule();
needToPublish = false;
initialized.run();
}
if (discarded != null) {
unpublish(discarded);
}
return true;
}
void unpublish(@Nullable T discarded) {
assert (SwingUtilities.isEventDispatchThread());
if (discarded == null) return;
try {
unpublishCallback.accept(discarded);
}
catch (Exception e) {
FlutterUtils.warn(LOG, "An unpublish callback threw an exception while updating a Refreshable", e);
}
}
void setState(State newState) {
if (SwingUtilities.isEventDispatchThread()) {
doSetState(newState);
return;
}
try {
SwingUtilities.invokeAndWait(() -> doSetState(newState));
}
catch (Exception e) {
FlutterUtils.warn(LOG, "Unable to change state of Refreshable", e);
}
}
private void doSetState(State newState) {
final State oldState = state.getAndSet(newState);
if (oldState == newState) return; // debounce
fireEvent();
}
private void fireEvent() {
assert SwingUtilities.isEventDispatchThread();
for (Runnable sub : getSubscribers()) {
try {
sub.run();
}
catch (Exception e) {
if (!Objects.equal(e.getMessage(), "expected failure in test")) {
FlutterUtils.warn(LOG, "A subscriber to a Refreshable threw an exception", e);
}
}
}
}
private Set<Runnable> getSubscribers() {
synchronized (subscribers) {
return ImmutableSet.copyOf(subscribers);
}
}
void waitForFirstValue() {
try {
initialized.get();
}
catch (Exception e) {
FlutterUtils.warn(LOG, "Unexpected exception waiting for Refreshable to initialize", e);
}
}
synchronized T get() {
return published;
}
synchronized boolean isClosing() {
return closing;
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/utils/Refreshable.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/Refreshable.java",
"repo_id": "flutter-intellij",
"token_count": 5950
} | 514 |
/*
* 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.
*/
package io.flutter.utils.math;
/**
* Defines a [Quaternion] (a four-dimensional vector) for efficient rotation
* calculations.
* <p>
* This code is ported from the Quaternion class in the Dart vector_math
* package. The Class is ported as is without concern for making the code
* consistent with Java api conventions to keep the code consistent with
* the Dart code to simplify using Transform Matrixes returned by Flutter.
* <p>
* Quaternion are better for interpolating between rotations and avoid the
* [gimbal lock](http://de.wikipedia.org/wiki/Gimbal_Lock) problem compared to
* euler rotations.
*/
@SuppressWarnings({"Duplicates", "UnnecessaryLocalVariable"})
class Quaternion {
final double[] _qStorage;
private Quaternion() {
_qStorage = new double[4];
}
public Quaternion(Quaternion other) {
_qStorage = other._qStorage.clone();
}
/**
* Constructs a quaternion using the raw values [x], [y], [z], and [w].
*/
public Quaternion(double x, double y, double z, double w) {
_qStorage = new double[4];
setValues(x, y, z, w);
}
/**
* Constructs a quaternion with given double[] as [storage].
*/
public Quaternion(double[] _qStorage) {
this._qStorage = _qStorage;
}
/**
* Constructs a quaternion from a rotation of [angle] around [axis].
*/
public static Quaternion axisAngle(Vector3 axis, double angle) {
final Quaternion ret = new Quaternion();
ret.setAxisAngle(axis, angle);
return ret;
}
/**
* Constructs a quaternion to be the rotation that rotates vector [a] to [b].
*/
public static Quaternion fromTwoVectors(Vector3 a, Vector3 b) {
final Quaternion ret = new Quaternion();
ret.setFromTwoVectors(a, b);
return ret;
}
/**
* Constructs a quaternion as a copy of [original].
*/
public static Quaternion copy(Quaternion original) {
final Quaternion ret = new Quaternion();
ret.setFrom(original);
return ret;
}
/**
* Constructs a quaternion set to the identity quaternion.
*/
public static Quaternion identity() {
final Quaternion ret = new Quaternion();
ret._qStorage[3] = 1.0;
return ret;
}
/**
* Constructs a quaternion from time derivative of [q] with angular
* velocity [omega].
*/
public static Quaternion dq(Quaternion q, Vector3 omega) {
final Quaternion ret = new Quaternion();
ret.setDQ(q, omega);
return ret;
}
/**
* Access the internal [storage] of the quaternions components.
*/
public double[] getStorage() {
return _qStorage;
}
/**
* Access the [x] component of the quaternion.
*/
public double getX() {
return _qStorage[0];
}
public void setX(double x) {
_qStorage[0] = x;
}
/**
* Access the [y] component of the quaternion.
*/
public double getY() {
return _qStorage[1];
}
public void setY(double y) {
_qStorage[1] = y;
}
/**
* Access the [z] component of the quaternion.
*/
public double getZ() {
return _qStorage[2];
}
public void setZ(double z) {
_qStorage[2] = z;
}
/**
* Access the [w] component of the quaternion.
*/
public double getW() {
return _qStorage[3];
}
public void setW(double w) {
_qStorage[3] = w;
}
/**
* Constructs a quaternion from [yaw], [pitch] and [roll].
*/
public Quaternion euler(double yaw, double pitch, double roll) {
final Quaternion ret = new Quaternion();
ret.setEuler(yaw, pitch, roll);
return ret;
}
/**
* Returns a new copy of [this].
*/
@SuppressWarnings("MethodDoesntCallSuperMethod")
@Override
public Quaternion clone() {
return new Quaternion(this);
}
/**
* Copy [source] into [this].
*/
public void setFrom(Quaternion source) {
final double[] sourceStorage = source._qStorage;
_qStorage[0] = sourceStorage[0];
_qStorage[1] = sourceStorage[1];
_qStorage[2] = sourceStorage[2];
_qStorage[3] = sourceStorage[3];
}
/**
* Set the quaternion to the raw values [x], [y], [z], and [w].
*/
public void setValues(double x, double y, double z, double w) {
_qStorage[0] = x;
_qStorage[1] = y;
_qStorage[2] = z;
_qStorage[3] = w;
}
/**
* Set the quaternion with rotation of [radians] around [axis].
*/
public void setAxisAngle(Vector3 axis, double radians) {
final double len = axis.getLength();
if (len == 0.0) {
return;
}
final double halfSin = Math.sin(radians * 0.5) / len;
final double[] axisStorage = axis.getStorage();
_qStorage[0] = axisStorage[0] * halfSin;
_qStorage[1] = axisStorage[1] * halfSin;
_qStorage[2] = axisStorage[2] * halfSin;
_qStorage[3] = Math.cos(radians * 0.5);
}
public void setFromTwoVectors(Vector3 a, Vector3 b) {
final Vector3 v1 = a.normalized();
final Vector3 v2 = b.normalized();
final double c = v1.dot(v2);
double angle = Math.acos(c);
Vector3 axis = v1.cross(v2);
if (Math.abs(1.0 + c) < 0.0005) {
// c \approx -1 indicates 180 degree rotation
angle = Math.PI;
// a and b are parallel in opposite directions. We need any
// vector as our rotation axis that is perpendicular.
// Find one by taking the cross product of v1 with an appropriate unit axis
if (v1.getX() > v1.getY() && v1.getX() > v1.getZ()) {
// v1 points in a dominantly x direction, so don't cross with that axis
axis = v1.cross(new Vector3(0.0, 1.0, 0.0));
}
else {
// Predominantly points in some other direction, so x-axis should be safe
axis = v1.cross(new Vector3(1.0, 0.0, 0.0));
}
}
else if (Math.abs(1.0 - c) < 0.0005) {
// c \approx 1 is 0-degree rotation, axis is arbitrary
angle = 0.0;
axis = new Vector3(1.0, 0.0, 0.0);
}
setAxisAngle(axis.normalized(), angle);
}
/**
* Set the quaternion to the time derivative of [q] with angular velocity
* [omega].
*/
public void setDQ(Quaternion q, Vector3 omega) {
final double[] qStorage = q._qStorage;
final double[] omegaStorage = omega.getStorage();
final double qx = qStorage[0];
final double qy = qStorage[1];
final double qz = qStorage[2];
final double qw = qStorage[3];
final double ox = omegaStorage[0];
final double oy = omegaStorage[1];
final double oz = omegaStorage[2];
final double _x = ox * qw + oy * qz - oz * qy;
final double _y = oy * qw + oz * qx - ox * qz;
final double _z = oz * qw + ox * qy - oy * qx;
final double _w = -ox * qx - oy * qy - oz * qz;
_qStorage[0] = _x * 0.5;
_qStorage[1] = _y * 0.5;
_qStorage[2] = _z * 0.5;
_qStorage[3] = _w * 0.5;
}
/**
* Set quaternion with rotation of [yaw], [pitch] and [roll].
*/
public void setEuler(double yaw, double pitch, double roll) {
final double halfYaw = yaw * 0.5;
final double halfPitch = pitch * 0.5;
final double halfRoll = roll * 0.5;
final double cosYaw = Math.cos(halfYaw);
final double sinYaw = Math.sin(halfYaw);
final double cosPitch = Math.cos(halfPitch);
final double sinPitch = Math.sin(halfPitch);
final double cosRoll = Math.cos(halfRoll);
final double sinRoll = Math.sin(halfRoll);
_qStorage[0] = cosRoll * sinPitch * cosYaw + sinRoll * cosPitch * sinYaw;
_qStorage[1] = cosRoll * cosPitch * sinYaw - sinRoll * sinPitch * cosYaw;
_qStorage[2] = sinRoll * cosPitch * cosYaw - cosRoll * sinPitch * sinYaw;
_qStorage[3] = cosRoll * cosPitch * cosYaw + sinRoll * sinPitch * sinYaw;
}
/**
* Normalize [this].
*/
public double normalize() {
final double l = getLength();
if (l == 0.0) {
return 0.0;
}
final double d = 1.0 / l;
_qStorage[0] *= d;
_qStorage[1] *= d;
_qStorage[2] *= d;
_qStorage[3] *= d;
return l;
}
/**
* Conjugate [this].
*/
public void conjugate() {
_qStorage[2] = -_qStorage[2];
_qStorage[1] = -_qStorage[1];
_qStorage[0] = -_qStorage[0];
}
/**
* Invert [this].
*/
public void inverse() {
final double l = 1.0 / getLength2();
_qStorage[3] = _qStorage[3] * l;
_qStorage[2] = -_qStorage[2] * l;
_qStorage[1] = -_qStorage[1] * l;
_qStorage[0] = -_qStorage[0] * l;
}
/**
* Normalized copy of [this].
*/
public Quaternion normalized() {
final Quaternion ret = clone();
ret.normalize();
return ret;
}
/**
* Conjugated copy of [this].
*/
public Quaternion conjugated() {
final Quaternion ret = clone();
ret.conjugate();
return ret;
}
/**
* Inverted copy of [this].
*/
public Quaternion inverted() {
final Quaternion ret = clone();
ret.inverse();
return ret;
}
/**
* [radians] of rotation around the [axis] of the rotation.
*/
public double getRadians() {
return 2.0 * Math.acos(_qStorage[3]);
}
/**
* [axis] of rotation.
*/
public Vector3 getAxis() {
final double den = 1.0 - (_qStorage[3] * _qStorage[3]);
if (den < 0.0005) {
// 0-angle rotation, so axis does not matter
return new Vector3();
}
final double scale = 1.0 / Math.sqrt(den);
return new Vector3(
_qStorage[0] * scale, _qStorage[1] * scale, _qStorage[2] * scale);
}
/**
* Length squared.
*/
public double getLength2() {
final double x = _qStorage[0];
final double y = _qStorage[1];
final double z = _qStorage[2];
final double w = _qStorage[3];
return (x * x) + (y * y) + (z * z) + (w * w);
}
/**
* Length.
*/
public double getLength() {
return Math.sqrt(getLength2());
}
/**
* Returns a copy of [v] rotated by quaternion.
*/
public Vector3 rotated(Vector3 v) {
final Vector3 out = v.clone();
rotate(out);
return out;
}
/**
* Rotates [v] by [this].
*/
public Vector3 rotate(Vector3 v) {
// conjugate(this) * [v,0] * this
final double _w = _qStorage[3];
final double _z = _qStorage[2];
final double _y = _qStorage[1];
final double _x = _qStorage[0];
final double tiw = _w;
final double tiz = -_z;
final double tiy = -_y;
final double tix = -_x;
final double tx = tiw * v.getX() + tix * 0.0 + tiy * v.getZ() - tiz * v.getY();
final double ty = tiw * v.getY() + tiy * 0.0 + tiz * v.getX() - tix * v.getZ();
final double tz = tiw * v.getZ() + tiz * 0.0 + tix * v.getY() - tiy * v.getX();
final double tw = tiw * 0.0 - tix * v.getX() - tiy * v.getY() - tiz * v.getZ();
final double result_x = tw * _x + tx * _w + ty * _z - tz * _y;
final double result_y = tw * _y + ty * _w + tz * _x - tx * _z;
final double result_z = tw * _z + tz * _w + tx * _y - ty * _x;
final double[] vStorage = v.getStorage();
vStorage[2] = result_z;
vStorage[1] = result_y;
vStorage[0] = result_x;
return v;
}
/**
* Add [arg] to [this].
*/
public void add(Quaternion arg) {
final double[] argStorage = arg._qStorage;
_qStorage[0] = _qStorage[0] + argStorage[0];
_qStorage[1] = _qStorage[1] + argStorage[1];
_qStorage[2] = _qStorage[2] + argStorage[2];
_qStorage[3] = _qStorage[3] + argStorage[3];
}
/**
* Subtracts [arg] from [this].
*/
public void sub(Quaternion arg) {
final double[] argStorage = arg._qStorage;
_qStorage[0] = _qStorage[0] - argStorage[0];
_qStorage[1] = _qStorage[1] - argStorage[1];
_qStorage[2] = _qStorage[2] - argStorage[2];
_qStorage[3] = _qStorage[3] - argStorage[3];
}
/**
* Scales [this] by [scale].
*/
public void scale(double scale) {
_qStorage[3] = _qStorage[3] * scale;
_qStorage[2] = _qStorage[2] * scale;
_qStorage[1] = _qStorage[1] * scale;
_qStorage[0] = _qStorage[0] * scale;
}
/**
* Scaled copy of [this].
*/
public Quaternion scaled(double scale) {
final Quaternion ret = clone();
ret.scale(scale);
return ret;
}
/**
* [this] rotated by [other].
*/
public Quaternion operatorMultiply(Quaternion other) {
final double _w = _qStorage[3];
final double _z = _qStorage[2];
final double _y = _qStorage[1];
final double _x = _qStorage[0];
final double[] otherStorage = other._qStorage;
final double ow = otherStorage[3];
final double oz = otherStorage[2];
final double oy = otherStorage[1];
final double ox = otherStorage[0];
return new Quaternion(
_w * ox + _x * ow + _y * oz - _z * oy,
_w * oy + _y * ow + _z * ox - _x * oz,
_w * oz + _z * ow + _x * oy - _y * ox,
_w * ow - _x * ox - _y * oy - _z * oz);
}
/**
* Returns copy of [this] + [other].
*/
public Quaternion operatorAdd(Quaternion other) {
final Quaternion ret = clone();
ret.add(other);
return ret;
}
/**
* Returns copy of [this] - [other].
*/
public Quaternion operatorSub(Quaternion other) {
final Quaternion ret = clone();
ret.sub(other);
return ret;
}
/**
* Returns negated copy of [this].
*/
public Quaternion operatorConjugated() {
final Quaternion ret = clone();
ret.conjugated();
return ret;
}
/**
* Printable string.
*/
@Override()
public String toString() {
return "" + _qStorage[0] + ", " + _qStorage[1] + ", " + _qStorage[2] + " @ " + _qStorage[3];
}
/**
* Relative error between [this] and [correct].
*/
public double relativeError(Quaternion correct) {
final Quaternion diff = correct.operatorSub(this);
final double norm_diff = diff.getLength();
final double correct_norm = correct.getLength();
return norm_diff / correct_norm;
}
/**
* Absolute error between [this] and [correct].
*/
public double absoluteError(Quaternion correct) {
final double this_norm = getLength();
final double correct_norm = correct.getLength();
final double norm_diff = Math.abs(this_norm - correct_norm);
return norm_diff;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/utils/math/Quaternion.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/math/Quaternion.java",
"repo_id": "flutter-intellij",
"token_count": 5619
} | 515 |
/*
* 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.
*/
package io.flutter.view;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.util.messages.MessageBus;
import com.intellij.util.messages.Topic;
import io.flutter.run.daemon.FlutterApp;
import io.flutter.vmService.VMServiceManager;
import org.dartlang.vm.service.VmService;
import org.jetbrains.annotations.NotNull;
/**
* Coordinates communication on the message bus.
*/
public class FlutterViewMessages {
public static final Topic<FlutterDebugNotifier> FLUTTER_DEBUG_TOPIC = Topic.create("flutter.debugActive", FlutterDebugNotifier.class);
public interface FlutterDebugNotifier {
void debugActive(FlutterDebugEvent event);
}
public static class FlutterDebugEvent {
public final @NotNull FlutterApp app;
public final @NotNull VmService vmService;
FlutterDebugEvent(@NotNull FlutterApp app,
@NotNull VmService vmService) {
this.app = app;
this.vmService = vmService;
}
}
public static void sendDebugActive(@NotNull Project project,
@NotNull FlutterApp app,
@NotNull VmService vmService) {
final MessageBus bus = project.getMessageBus();
final FlutterDebugNotifier publisher = bus.syncPublisher(FLUTTER_DEBUG_TOPIC);
assert (app.getFlutterDebugProcess() != null);
final VMServiceManager vmServiceManager = new VMServiceManager(app, vmService);
Disposer.register(app.getFlutterDebugProcess().getVmServiceWrapper(), vmServiceManager);
app.setVmServices(vmService, vmServiceManager);
publisher.debugActive(new FlutterDebugEvent(app, vmService));
}
}
| flutter-intellij/flutter-idea/src/io/flutter/view/FlutterViewMessages.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/view/FlutterViewMessages.java",
"repo_id": "flutter-intellij",
"token_count": 656
} | 516 |
package io.flutter.vmService;
import com.intellij.openapi.project.Project;
import com.intellij.xdebugger.XDebugSession;
import com.intellij.xdebugger.XDebuggerManager;
import com.intellij.xdebugger.breakpoints.XBreakpoint;
import com.intellij.xdebugger.breakpoints.XBreakpointHandler;
import com.intellij.xdebugger.breakpoints.XBreakpointManager;
import com.intellij.xdebugger.breakpoints.XBreakpointType;
import com.jetbrains.lang.dart.ide.runner.DartExceptionBreakpointProperties;
import com.jetbrains.lang.dart.ide.runner.DartExceptionBreakpointType;
import org.dartlang.vm.service.element.ExceptionPauseMode;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Set;
public class DartExceptionBreakpointHandler extends XBreakpointHandler<XBreakpoint<DartExceptionBreakpointProperties>> {
private final DartVmServiceDebugProcess myDebugProcess;
public DartExceptionBreakpointHandler(@NotNull final DartVmServiceDebugProcess debugProcess) {
super(DartExceptionBreakpointType.class);
myDebugProcess = debugProcess;
}
@NotNull
public static XBreakpoint<DartExceptionBreakpointProperties> getDefaultExceptionBreakpoint(@NotNull final Project project) {
final XBreakpointManager bpManager = XDebuggerManager.getInstance(project).getBreakpointManager();
final DartExceptionBreakpointType bpType = XBreakpointType.EXTENSION_POINT_NAME.findExtension(DartExceptionBreakpointType.class);
assert(bpType != null);
@NotNull Set<XBreakpoint<DartExceptionBreakpointProperties>> bps = bpManager.getDefaultBreakpoints(bpType);
assert (bps.size() == 1);
final XBreakpoint<DartExceptionBreakpointProperties> breakpoint = new ArrayList<>(bps).get(0);
assert breakpoint != null;
return breakpoint;
}
@NotNull
public static ExceptionPauseMode getBreakOnExceptionMode(@NotNull XDebugSession session,
@Nullable final XBreakpoint<DartExceptionBreakpointProperties> bp) {
if (session.areBreakpointsMuted()) {
return ExceptionPauseMode.None;
}
if (bp == null) return ExceptionPauseMode.Unhandled; // Default to breaking on unhandled exceptions.
if (!bp.isEnabled()) return ExceptionPauseMode.None;
return bp.getProperties().isBreakOnAllExceptions() ? ExceptionPauseMode.All : ExceptionPauseMode.Unhandled;
}
@Override
public void registerBreakpoint(@NotNull final XBreakpoint<DartExceptionBreakpointProperties> breakpoint) {
final VmServiceWrapper vmServiceWrapper = myDebugProcess.getVmServiceWrapper();
if (vmServiceWrapper != null) {
vmServiceWrapper.setExceptionPauseMode(getBreakOnExceptionMode(myDebugProcess.getSession(), breakpoint));
}
}
@Override
public void unregisterBreakpoint(@NotNull final XBreakpoint<DartExceptionBreakpointProperties> breakpoint, final boolean temporary) {
registerBreakpoint(breakpoint);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/vmService/DartExceptionBreakpointHandler.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/vmService/DartExceptionBreakpointHandler.java",
"repo_id": "flutter-intellij",
"token_count": 945
} | 517 |
package io.flutter.vmService.frame;
import com.google.gson.JsonElement;
import com.intellij.icons.AllIcons;
import com.intellij.util.SmartList;
import com.intellij.xdebugger.frame.*;
import io.flutter.vmService.DartVmServiceDebugProcess;
import org.dartlang.vm.service.consumer.GetObjectConsumer;
import org.dartlang.vm.service.element.*;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.util.concurrent.atomic.AtomicInteger;
// similar to com.intellij.debugger.engine.JavaStaticGroup
class DartStaticFieldsGroup extends XValueGroup {
@NotNull private final DartVmServiceDebugProcess myDebugProcess;
@NotNull private final String myIsolateId;
@NotNull private final String myClassName;
@NotNull private final SmartList<FieldRef> myFieldRefs;
public DartStaticFieldsGroup(@NotNull final DartVmServiceDebugProcess debugProcess,
@NotNull final String isolateId,
@NotNull final String className,
@NotNull final SmartList<FieldRef> fieldsRefs) {
super("static");
myDebugProcess = debugProcess;
myIsolateId = isolateId;
myClassName = className;
myFieldRefs = fieldsRefs;
}
@NotNull
@Override
public String getSeparator() {
return "";
}
@Override
public String getComment() {
return " members of " + myClassName;
}
@Override
public Icon getIcon() {
return AllIcons.Nodes.Static;
}
@Override
public void computeChildren(@NotNull final XCompositeNode node) {
final AtomicInteger counter = new AtomicInteger(myFieldRefs.size());
final XValueChildrenList list = new XValueChildrenList(myFieldRefs.size());
for (final FieldRef fieldRef : myFieldRefs) {
myDebugProcess.getVmServiceWrapper().getObject(myIsolateId, fieldRef.getId(), new GetObjectConsumer() {
@Override
public void received(Obj field) {
final InstanceRef instanceRef = ((Field)field).getStaticValue();
// static field may be not initialized yet, in this case this instanceRef is in fact a Sentinel
if (instanceRef != null && "@Instance".equals(instanceRef.getType())) {
list.add(new DartVmServiceValue(myDebugProcess, myIsolateId, ((Field)field).getName(), instanceRef, null, fieldRef, false));
}
else if (instanceRef != null && "Sentinel".equals(instanceRef.getType())) {
list.add(new XNamedValue(((Field)field).getName()) {
@Override
public void computeSourcePosition(@NotNull XNavigatable navigatable) {
DartVmServiceValue.doComputeSourcePosition(myDebugProcess, navigatable, myIsolateId, fieldRef);
}
@Override
public void computePresentation(@NotNull XValueNode node, @NotNull XValuePlace place) {
final JsonElement valueAsString = instanceRef.getJson().get("valueAsString");
final String value = valueAsString == null ? "not initialized" : valueAsString.getAsString();
node.setPresentation(AllIcons.Nodes.Field, null, value, false);
}
});
}
if (counter.decrementAndGet() == 0) {
if (list.size() == 0) {
node.setErrorMessage("Static fields not initialized yet");
}
else {
node.addChildren(list, true);
}
}
}
@Override
public void received(Sentinel sentinel) {
node.setErrorMessage(sentinel.getValueAsString());
}
@Override
public void onError(RPCError error) {
node.setErrorMessage(error.getMessage());
}
});
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/vmService/frame/DartStaticFieldsGroup.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/vmService/frame/DartStaticFieldsGroup.java",
"repo_id": "flutter-intellij",
"token_count": 1503
} | 518 |
/*
* Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
* for details. 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 has been automatically generated. Please do not edit it manually.
* To regenerate the file, use the script "pkg/analysis_server/tool/spec/generate_files".
*/
package org.dartlang.analysis.server.protocol;
import com.google.common.collect.Lists;
import com.google.dart.server.utilities.general.ObjectUtilities;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* A value of a property of a Flutter widget.
*
* @coverage dart.server.generated.types
*/
@SuppressWarnings("unused")
public class FlutterWidgetPropertyValue {
public static final FlutterWidgetPropertyValue[] EMPTY_ARRAY = new FlutterWidgetPropertyValue[0];
public static final List<FlutterWidgetPropertyValue> EMPTY_LIST = Lists.newArrayList();
private final Boolean boolValue;
private final Double doubleValue;
private final Integer intValue;
private final String stringValue;
private final FlutterWidgetPropertyValueEnumItem enumValue;
/**
* A free-form expression, which will be used as the value as is.
*/
private final String expression;
/**
* Constructor for {@link FlutterWidgetPropertyValue}.
*/
public FlutterWidgetPropertyValue(Boolean boolValue,
Double doubleValue,
Integer intValue,
String stringValue,
FlutterWidgetPropertyValueEnumItem enumValue,
String expression) {
this.boolValue = boolValue;
this.doubleValue = doubleValue;
this.intValue = intValue;
this.stringValue = stringValue;
this.enumValue = enumValue;
this.expression = expression;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof FlutterWidgetPropertyValue) {
FlutterWidgetPropertyValue other = (FlutterWidgetPropertyValue)obj;
return
ObjectUtilities.equals(other.boolValue, boolValue) &&
ObjectUtilities.equals(other.doubleValue, doubleValue) &&
ObjectUtilities.equals(other.intValue, intValue) &&
ObjectUtilities.equals(other.stringValue, stringValue) &&
ObjectUtilities.equals(other.enumValue, enumValue) &&
ObjectUtilities.equals(other.expression, expression);
}
return false;
}
public static FlutterWidgetPropertyValue fromJson(JsonObject jsonObject) {
Boolean boolValue = jsonObject.get("boolValue") == null ? null : jsonObject.get("boolValue").getAsBoolean();
Double doubleValue = jsonObject.get("doubleValue") == null ? null : jsonObject.get("doubleValue").getAsDouble();
Integer intValue = jsonObject.get("intValue") == null ? null : jsonObject.get("intValue").getAsInt();
String stringValue = jsonObject.get("stringValue") == null ? null : jsonObject.get("stringValue").getAsString();
FlutterWidgetPropertyValueEnumItem enumValue = jsonObject.get("enumValue") == null
? null
: FlutterWidgetPropertyValueEnumItem
.fromJson(jsonObject.get("enumValue").getAsJsonObject());
String expression = jsonObject.get("expression") == null ? null : jsonObject.get("expression").getAsString();
return new FlutterWidgetPropertyValue(boolValue, doubleValue, intValue, stringValue, enumValue, expression);
}
public static List<FlutterWidgetPropertyValue> fromJsonArray(JsonArray jsonArray) {
if (jsonArray == null) {
return EMPTY_LIST;
}
ArrayList<FlutterWidgetPropertyValue> list = new ArrayList<FlutterWidgetPropertyValue>(jsonArray.size());
Iterator<JsonElement> iterator = jsonArray.iterator();
while (iterator.hasNext()) {
list.add(fromJson(iterator.next().getAsJsonObject()));
}
return list;
}
public Boolean getBoolValue() {
return boolValue;
}
public Double getDoubleValue() {
return doubleValue;
}
public FlutterWidgetPropertyValueEnumItem getEnumValue() {
return enumValue;
}
/**
* A free-form expression, which will be used as the value as is.
*/
public String getExpression() {
return expression;
}
public Integer getIntValue() {
return intValue;
}
public String getStringValue() {
return stringValue;
}
@Override
public int hashCode() {
HashCodeBuilder builder = new HashCodeBuilder();
builder.append(boolValue);
builder.append(doubleValue);
builder.append(intValue);
builder.append(stringValue);
builder.append(enumValue);
builder.append(expression);
return builder.toHashCode();
}
public JsonObject toJson() {
JsonObject jsonObject = new JsonObject();
if (boolValue != null) {
jsonObject.addProperty("boolValue", boolValue);
}
if (doubleValue != null) {
jsonObject.addProperty("doubleValue", doubleValue);
}
if (intValue != null) {
jsonObject.addProperty("intValue", intValue);
}
if (stringValue != null) {
jsonObject.addProperty("stringValue", stringValue);
}
if (enumValue != null) {
jsonObject.add("enumValue", enumValue.toJson());
}
if (expression != null) {
jsonObject.addProperty("expression", expression);
}
return jsonObject;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("[");
builder.append("boolValue=");
builder.append(boolValue).append(", ");
builder.append("doubleValue=");
builder.append(doubleValue).append(", ");
builder.append("intValue=");
builder.append(intValue).append(", ");
builder.append("stringValue=");
builder.append(stringValue).append(", ");
builder.append("enumValue=");
builder.append(enumValue).append(", ");
builder.append("expression=");
builder.append(expression);
builder.append("]");
return builder.toString();
}
}
| flutter-intellij/flutter-idea/src/org/dartlang/analysis/server/protocol/FlutterWidgetPropertyValue.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/org/dartlang/analysis/server/protocol/FlutterWidgetPropertyValue.java",
"repo_id": "flutter-intellij",
"token_count": 2254
} | 519 |
/*
* 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.
*/
package io.flutter.bazel;
import com.intellij.openapi.roots.ModuleRootModificationUtil;
import com.intellij.openapi.vfs.VirtualFile;
import io.flutter.testing.ProjectFixture;
import io.flutter.testing.TestDir;
import io.flutter.testing.Testing;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.*;
public class WorkspaceTest {
@Rule
public final ProjectFixture fixture = Testing.makeEmptyModule();
@Rule
public final TestDir tmp = new TestDir();
@Test @Ignore
public void doesNotLoadWorkspaceWithoutConfigFile() throws Exception {
final VirtualFile expectedRoot = tmp.ensureDir("abc");
tmp.writeFile("abc/WORKSPACE", "");
tmp.ensureDir("abc/dart");
final VirtualFile contentRoot = tmp.ensureDir("abc/dart/something");
ModuleRootModificationUtil.addContentRoot(fixture.getModule(), contentRoot.getPath());
final Workspace w = Workspace.loadUncached(fixture.getProject());
assertNull(w);
}
@Test @Ignore
public void canLoadWorkspaceWithConfigFile() throws Exception {
final VirtualFile expectedRoot = tmp.ensureDir("abc");
tmp.writeFile("abc/WORKSPACE", "");
tmp.ensureDir("abc/dart");
final VirtualFile contentRoot = tmp.ensureDir("abc/dart/something");
ModuleRootModificationUtil.addContentRoot(fixture.getModule(), contentRoot.getPath());
tmp.ensureDir("abc/dart/config/ide");
tmp.writeFile("abc/dart/config/ide/flutter.json",
"{\"daemonScript\": \"something_daemon.sh\"," +
"\"doctorScript\": \"something_doctor.sh\"}");
tmp.writeFile("abc/something_daemon.sh", "");
tmp.writeFile("abc/something_doctor.sh", "");
final Workspace w = Workspace.loadUncached(fixture.getProject());
assertNotNull("expected a workspace", w);
assertEquals(expectedRoot, w.getRoot());
assertEquals("something_daemon.sh", w.getDaemonScript());
assertEquals("something_doctor.sh", w.getDoctorScript());
}
@Test @Ignore
public void canLoadWorkspaceWithConfigFileAndScriptInReadonly() throws Exception {
final VirtualFile expectedRoot = tmp.ensureDir("abc");
tmp.writeFile("abc/WORKSPACE", "");
tmp.ensureDir("abc/dart");
final VirtualFile contentRoot = tmp.ensureDir("abc/dart/something");
ModuleRootModificationUtil.addContentRoot(fixture.getModule(), contentRoot.getPath());
tmp.ensureDir("READONLY/abc/dart/config/ide");
tmp.writeFile("READONLY/abc/dart/config/ide/flutter.json",
"{\"daemonScript\": \"scripts/flutter_daemon.sh\"," +
"\"doctorScript\": \"scripts/flutter_doctor.sh\"}");
tmp.ensureDir("READONLY/abc/scripts");
tmp.writeFile("READONLY/abc/scripts/flutter_daemon.sh", "");
tmp.writeFile("READONLY/abc/scripts/flutter_doctor.sh", "");
final Workspace w = Workspace.loadUncached(fixture.getProject());
assertNotNull("expected a workspace", w);
assertEquals(expectedRoot, w.getRoot());
assertEquals("../READONLY/abc/scripts/flutter_daemon.sh", w.getDaemonScript());
assertEquals("../READONLY/abc/scripts/flutter_doctor.sh", w.getDoctorScript());
}
}
| flutter-intellij/flutter-idea/testSrc/unit/io/flutter/bazel/WorkspaceTest.java/0 | {
"file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/bazel/WorkspaceTest.java",
"repo_id": "flutter-intellij",
"token_count": 1178
} | 520 |
{
"type": "Event",
"kind": "Logging",
"isolate": {
"type": "@Isolate",
"id": "isolates/1562506484553303",
"name": "main",
"number": "1562506484553303"
},
"timestamp": 1562616987335,
"logRecord": {
"type": "LogRecord",
"sequenceNumber": 3,
"time": 1562616987335,
"level": 0,
"loggerName": {
"type": "@Instance",
"_vmType": "String",
"class": {
"type": "@Class",
"fixedId": true,
"id": "classes/76",
"name": "_OneByteString",
"_vmName": "_OneByteString@0150898"
},
"kind": "String",
"id": "objects/14",
"length": 6,
"valueAsString": "my.log"
},
"message": {
"type": "@Instance",
"_vmType": "String",
"class": {
"type": "@Class",
"fixedId": true,
"id": "classes/76",
"name": "_OneByteString",
"_vmName": "_OneByteString@0150898"
},
"kind": "String",
"id": "objects/15",
"length": 11,
"valueAsString": "hello world"
},
"zone": {
"type": "@Instance",
"class": {
"type": "@Class",
"fixedId": true,
"id": "classes/141",
"name": "Null"
},
"kind": "Null",
"fixedId": true,
"id": "objects/null",
"valueAsString": "null"
},
"error": {
"type": "@Instance",
"class": {
"type": "@Class",
"fixedId": true,
"id": "classes/141",
"name": "Null"
},
"kind": "Null",
"fixedId": true,
"id": "objects/null",
"valueAsString": "null"
},
"stackTrace": {
"type": "@Instance",
"class": {
"type": "@Class",
"fixedId": true,
"id": "classes/141",
"name": "Null"
},
"kind": "Null",
"fixedId": true,
"id": "objects/null",
"valueAsString": "null"
}
}
}
| flutter-intellij/flutter-idea/testSrc/unit/io/flutter/logging/console_log_1.json/0 | {
"file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/logging/console_log_1.json",
"repo_id": "flutter-intellij",
"token_count": 989
} | 521 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.