text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:developer' as developer;
import 'dart:js_interop';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import 'package:web_test_fonts/web_test_fonts.dart';
/// The mode the app is running in.
/// Keep these in sync with the same constants on the framework-side under foundation/constants.dart.
const bool kReleaseMode =
bool.fromEnvironment('dart.vm.product');
/// A constant that is true if the application was compiled in profile mode.
const bool kProfileMode =
bool.fromEnvironment('dart.vm.profile');
/// A constant that is true if the application was compiled in debug mode.
const bool kDebugMode = !kReleaseMode && !kProfileMode;
/// Returns mode of the app is running in as a string.
String get buildMode => kReleaseMode
? 'release'
: kProfileMode
? 'profile'
: 'debug';
/// A benchmark metric that includes frame-related computations prior to
/// submitting layer and picture operations to the underlying renderer, such as
/// HTML and CanvasKit. During this phase we compute transforms, clips, and
/// other information needed for rendering.
const String kProfilePrerollFrame = 'preroll_frame';
/// A benchmark metric that includes submitting layer and picture information
/// to the renderer.
const String kProfileApplyFrame = 'apply_frame';
final List<ui.VoidCallback> _hotRestartListeners = <ui.VoidCallback>[];
/// Requests that [listener] is called just before hot restarting the app.
void registerHotRestartListener(ui.VoidCallback listener) {
_hotRestartListeners.add(listener);
}
/// Pretends that hot restart is about to happen.
///
/// Useful in tests to check that the engine performs appropriate clean-ups,
/// such as removing static DOM listeners, prior to allowing the Dart runtime
/// to re-initialize the program.
void debugEmulateHotRestart() {
// While hot restart listeners are executing, more listeners may be added. To
// avoid concurrent modification, the listeners are copies and emptied. If new
// listeners are added in the process, the loop will pick them up.
while (_hotRestartListeners.isNotEmpty) {
final List<ui.VoidCallback> copyOfListeners = _hotRestartListeners.toList();
_hotRestartListeners.clear();
for (final ui.VoidCallback listener in copyOfListeners) {
listener();
}
}
}
/// How far along the initialization process the engine is currently is.
///
/// The initialization process starts with [none] and proceeds in increasing
/// `index` number until [initialized].
enum DebugEngineInitializationState {
/// Initialization hasn't started yet.
uninitialized,
/// The engine is initializing its non-UI services.
initializingServices,
/// The engine has initialized its non-UI services, but hasn't started
/// initializing the UI.
initializedServices,
/// The engine started attaching UI surfaces to the web page.
initializingUi,
/// The engine has fully completed initialization.
///
/// At this point the framework can start using the engine for I/O, rendering,
/// etc.
///
/// This is the final state of the engine.
initialized,
}
/// The current initialization state of the engine.
///
/// See [DebugEngineInitializationState] for possible states.
DebugEngineInitializationState get initializationState => _initializationState;
DebugEngineInitializationState _initializationState = DebugEngineInitializationState.uninitialized;
/// Resets the state back to [DebugEngineInitializationState.uninitialized].
///
/// This is for testing only.
void debugResetEngineInitializationState() {
_initializationState = DebugEngineInitializationState.uninitialized;
}
/// Initializes non-UI engine services.
///
/// Does not put any UI onto the page. It is therefore safe to call this
/// function while the page is showing non-Flutter UI, such as a loading
/// indicator, a splash screen, or in an add-to-app scenario where the host page
/// is written using a different web framework.
///
/// See also:
///
/// * [initializeEngineUi], which is typically called after this function, and
/// puts UI elements on the page.
Future<void> initializeEngineServices({
ui_web.AssetManager? assetManager,
JsFlutterConfiguration? jsConfiguration
}) async {
if (_initializationState != DebugEngineInitializationState.uninitialized) {
assert(() {
throw StateError(
'Invalid engine initialization state. `initializeEngineServices` was '
'called, but the engine has already started initialization and is '
'currently in state "$_initializationState".'
);
}());
return;
}
_initializationState = DebugEngineInitializationState.initializingServices;
// Store `jsConfiguration` so user settings are available to the engine.
configuration.setUserConfiguration(jsConfiguration);
// Called by the Web runtime just before hot restarting the app.
//
// This extension cleans up resources that are registered with browser's
// global singletons that Dart compiler is unable to clean-up automatically.
//
// This extension does not need to clean-up Dart statics. Those are cleaned
// up by the compiler.
developer.registerExtension('ext.flutter.disassemble', (_, __) {
for (final ui.VoidCallback listener in _hotRestartListeners) {
listener();
}
return Future<developer.ServiceExtensionResponse>.value(
developer.ServiceExtensionResponse.result('OK'));
});
if (Profiler.isBenchmarkMode) {
Profiler.ensureInitialized();
}
bool waitingForAnimation = false;
scheduleFrameCallback = () {
// We're asked to schedule a frame and call `frameHandler` when the frame
// fires.
if (!waitingForAnimation) {
waitingForAnimation = true;
domWindow.requestAnimationFrame((JSNumber highResTime) {
FrameTimingRecorder.recordCurrentFrameVsync();
// In Flutter terminology "building a frame" consists of "beginning
// frame" and "drawing frame".
//
// We do not call `recordBuildFinish` from here because
// part of the rasterization process, particularly in the HTML
// renderer, takes place in the `SceneBuilder.build()`.
FrameTimingRecorder.recordCurrentFrameBuildStart();
// Reset immediately, because `frameHandler` can schedule more frames.
waitingForAnimation = false;
// We have to convert high-resolution time to `int` so we can construct
// a `Duration` out of it. However, high-res time is supplied in
// milliseconds as a double value, with sub-millisecond information
// hidden in the fraction. So we first multiply it by 1000 to uncover
// microsecond precision, and only then convert to `int`.
final int highResTimeMicroseconds =
(1000 * highResTime.toDartDouble).toInt();
if (EnginePlatformDispatcher.instance.onBeginFrame != null) {
EnginePlatformDispatcher.instance.invokeOnBeginFrame(
Duration(microseconds: highResTimeMicroseconds));
}
if (EnginePlatformDispatcher.instance.onDrawFrame != null) {
// TODO(yjbanov): technically Flutter flushes microtasks between
// onBeginFrame and onDrawFrame. We don't, which hasn't
// been an issue yet, but eventually we'll have to
// implement it properly. (Also see the to-do in
// `EnginePlatformDispatcher.scheduleWarmUpFrame`).
EnginePlatformDispatcher.instance.invokeOnDrawFrame();
}
});
}
};
assetManager ??= ui_web.AssetManager(assetBase: configuration.assetBase);
_setAssetManager(assetManager);
Future<void> initializeRendererCallback () async => renderer.initialize();
await Future.wait<void>(<Future<void>>[initializeRendererCallback(), _downloadAssetFonts()]);
_initializationState = DebugEngineInitializationState.initializedServices;
}
/// Initializes the UI surfaces for the Flutter framework to render to.
///
/// Must be called after [initializeEngineServices].
///
/// This function will start altering the HTML structure of the page. If used
/// in an add-to-app scenario, the host page is expected to prepare for Flutter
/// UI appearing on screen prior to calling this function.
Future<void> initializeEngineUi() async {
if (_initializationState != DebugEngineInitializationState.initializedServices) {
assert(() {
throw StateError(
'Invalid engine initialization state. `initializeEngineUi` was '
'called while the engine initialization state was '
'"$_initializationState". `initializeEngineUi` can only be called '
'when the engine is in state '
'"${DebugEngineInitializationState.initializedServices}".'
);
}());
return;
}
_initializationState = DebugEngineInitializationState.initializingUi;
RawKeyboard.initialize(onMacOs: operatingSystem == OperatingSystem.macOs);
KeyboardBinding.initInstance();
if (!configuration.multiViewEnabled) {
final EngineFlutterWindow implicitView =
ensureImplicitViewInitialized(hostElement: configuration.hostElement);
if (renderer is HtmlRenderer) {
ensureResourceManagerInitialized(implicitView);
}
}
_initializationState = DebugEngineInitializationState.initialized;
}
ui_web.AssetManager get engineAssetManager => _debugAssetManager ?? _assetManager!;
ui_web.AssetManager? _assetManager;
ui_web.AssetManager? _debugAssetManager;
set debugOnlyAssetManager(ui_web.AssetManager? manager) => _debugAssetManager = manager;
void _setAssetManager(ui_web.AssetManager assetManager) {
if (assetManager == _assetManager) {
return;
}
_assetManager = assetManager;
}
Future<void> _downloadAssetFonts() async {
renderer.fontCollection.clear();
if (ui_web.debugEmulateFlutterTesterEnvironment) {
// Load the embedded test font before loading fonts from the assets so that
// the embedded test font is the default (first) font.
await renderer.fontCollection.loadFontFromList(
EmbeddedTestFont.flutterTest.data,
fontFamily: EmbeddedTestFont.flutterTest.fontFamily
);
}
if (_debugAssetManager != null || _assetManager != null) {
await renderer.fontCollection.loadAssetFonts(await fetchFontManifest(ui_web.assetManager));
}
}
/// Whether to disable the font fallback system.
///
/// We need to disable font fallbacks for some framework tests because
/// Flutter error messages may contain an arrow symbol which is not
/// covered by ASCII fonts. This causes us to try to download the
/// Noto Sans Symbols font, which kicks off a `Timer` which doesn't
/// complete before the Widget tree is disposed (this is by design).
bool get debugDisableFontFallbacks => _debugDisableFontFallbacks;
set debugDisableFontFallbacks(bool value) {
_debugDisableFontFallbacks = value;
}
bool _debugDisableFontFallbacks = false;
| engine/lib/web_ui/lib/src/engine/initialization.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/initialization.dart",
"repo_id": "engine",
"token_count": 3334
} | 251 |
// Copyright 2013 The Flutter 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:js_interop';
import 'dart:typed_data';
import 'package:meta/meta.dart';
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import '../engine.dart';
/// Requests that the browser schedule a frame.
///
/// This may be overridden in tests, for example, to pump fake frames.
ui.VoidCallback? scheduleFrameCallback;
/// Signature of functions added as a listener to high contrast changes
typedef HighContrastListener = void Function(bool enabled);
typedef _KeyDataResponseCallback = void Function(bool handled);
const StandardMethodCodec standardCodec = StandardMethodCodec();
const JSONMethodCodec jsonCodec = JSONMethodCodec();
/// Determines if high contrast is enabled using media query 'forced-colors: active' for Windows
class HighContrastSupport {
static HighContrastSupport instance = HighContrastSupport();
static const String _highContrastMediaQueryString = '(forced-colors: active)';
final List<HighContrastListener> _listeners = <HighContrastListener>[];
/// Reference to css media query that indicates whether high contrast is on.
final DomMediaQueryList _highContrastMediaQuery =
domWindow.matchMedia(_highContrastMediaQueryString);
late final DomEventListener _onHighContrastChangeListener =
createDomEventListener(_onHighContrastChange);
bool get isHighContrastEnabled => _highContrastMediaQuery.matches;
/// Adds function to the list of listeners on high contrast changes
void addListener(HighContrastListener listener) {
if (_listeners.isEmpty) {
_highContrastMediaQuery.addListener(_onHighContrastChangeListener);
}
_listeners.add(listener);
}
/// Removes function from the list of listeners on high contrast changes
void removeListener(HighContrastListener listener) {
_listeners.remove(listener);
if (_listeners.isEmpty) {
_highContrastMediaQuery.removeListener(_onHighContrastChangeListener);
}
}
JSVoid _onHighContrastChange(DomEvent event) {
final DomMediaQueryListEvent mqEvent = event as DomMediaQueryListEvent;
final bool isHighContrastEnabled = mqEvent.matches!;
for (final HighContrastListener listener in _listeners) {
listener(isHighContrastEnabled);
}
}
}
/// Platform event dispatcher.
///
/// This is the central entry point for platform messages and configuration
/// events from the platform.
class EnginePlatformDispatcher extends ui.PlatformDispatcher {
/// Private constructor, since only dart:ui is supposed to create one of
/// these.
EnginePlatformDispatcher() {
_addBrightnessMediaQueryListener();
HighContrastSupport.instance.addListener(_updateHighContrast);
_addFontSizeObserver();
_addLocaleChangedListener();
registerHotRestartListener(dispose);
AppLifecycleState.instance.addListener(_setAppLifecycleState);
_viewFocusBinding.init();
domDocument.body?.prepend(accessibilityPlaceholder);
_onViewDisposedListener = viewManager.onViewDisposed.listen((_) {
// Send a metrics changed event to the framework when a view is disposed.
// View creation/resize is handled by the `_didResize` handler in the
// EngineFlutterView itself.
invokeOnMetricsChanged();
});
}
late StreamSubscription<int> _onViewDisposedListener;
/// The [EnginePlatformDispatcher] singleton.
static EnginePlatformDispatcher get instance => _instance;
static final EnginePlatformDispatcher _instance = EnginePlatformDispatcher();
@visibleForTesting
final DomElement accessibilityPlaceholder = EngineSemantics
.instance
.semanticsHelper
.prepareAccessibilityPlaceholder();
PlatformConfiguration configuration = PlatformConfiguration(
locales: parseBrowserLanguages(),
textScaleFactor: findBrowserTextScaleFactor(),
accessibilityFeatures: computeAccessibilityFeatures(),
);
/// Compute accessibility features based on the current value of high contrast flag
static EngineAccessibilityFeatures computeAccessibilityFeatures() {
final EngineAccessibilityFeaturesBuilder builder =
EngineAccessibilityFeaturesBuilder(0);
if (HighContrastSupport.instance.isHighContrastEnabled) {
builder.highContrast = true;
}
return builder.build();
}
void dispose() {
_removeBrightnessMediaQueryListener();
_disconnectFontSizeObserver();
_removeLocaleChangedListener();
HighContrastSupport.instance.removeListener(_updateHighContrast);
AppLifecycleState.instance.removeListener(_setAppLifecycleState);
_viewFocusBinding.dispose();
accessibilityPlaceholder.remove();
_onViewDisposedListener.cancel();
viewManager.dispose();
}
/// Receives all events related to platform configuration changes.
@override
ui.VoidCallback? get onPlatformConfigurationChanged =>
_onPlatformConfigurationChanged;
ui.VoidCallback? _onPlatformConfigurationChanged;
Zone? _onPlatformConfigurationChangedZone;
@override
set onPlatformConfigurationChanged(ui.VoidCallback? callback) {
_onPlatformConfigurationChanged = callback;
_onPlatformConfigurationChangedZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnPlatformConfigurationChanged() {
invoke(
_onPlatformConfigurationChanged, _onPlatformConfigurationChangedZone);
}
@override
Iterable<EngineFlutterDisplay> displays = <EngineFlutterDisplay>[
EngineFlutterDisplay.instance,
];
late final FlutterViewManager viewManager = FlutterViewManager(this);
/// The current list of windows.
@override
Iterable<EngineFlutterView> get views => viewManager.views;
/// Returns the [EngineFlutterView] with the provided ID if one exists, or null
/// otherwise.
@override
EngineFlutterView? view({required int id}) => viewManager[id];
/// The [FlutterView] provided by the engine if the platform is unable to
/// create windows, or, for backwards compatibility.
///
/// If the platform provides an implicit view, it can be used to bootstrap
/// the framework. This is common for platforms designed for single-view
/// applications like mobile devices with a single display.
///
/// Applications and libraries must not rely on this property being set
/// as it may be null depending on the engine's configuration. Instead,
/// consider using [View.of] to lookup the [FlutterView] the current
/// [BuildContext] is drawing into.
///
/// While the properties on the referenced [FlutterView] may change,
/// the reference itself is guaranteed to never change over the lifetime
/// of the application: if this property is null at startup, it will remain
/// so throughout the entire lifetime of the application. If it points to a
/// specific [FlutterView], it will continue to point to the same view until
/// the application is shut down (although the engine may replace or remove
/// the underlying backing surface of the view at its discretion).
///
/// See also:
///
/// * [View.of], for accessing the current view.
/// * [PlatformDisptacher.views] for a list of all [FlutterView]s provided
/// by the platform.
@override
EngineFlutterWindow? get implicitView =>
viewManager[kImplicitViewId] as EngineFlutterWindow?;
/// A callback that is invoked whenever the platform's [devicePixelRatio],
/// [physicalSize], [padding], [viewInsets], or [systemGestureInsets]
/// values change, for example when the device is rotated or when the
/// application is resized (e.g. when showing applications side-by-side
/// on Android).
///
/// The engine invokes this callback in the same zone in which the callback
/// was set.
///
/// The framework registers with this callback and updates the layout
/// appropriately.
///
/// See also:
///
/// * [WidgetsBindingObserver], for a mechanism at the widgets layer to
/// register for notifications when this is called.
/// * [MediaQuery.of], a simpler mechanism for the same.
@override
ui.VoidCallback? get onMetricsChanged => _onMetricsChanged;
ui.VoidCallback? _onMetricsChanged;
Zone? _onMetricsChangedZone;
@override
set onMetricsChanged(ui.VoidCallback? callback) {
_onMetricsChanged = callback;
_onMetricsChangedZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnMetricsChanged() {
if (_onMetricsChanged != null) {
invoke(_onMetricsChanged, _onMetricsChangedZone);
}
}
late final ViewFocusBinding _viewFocusBinding =
ViewFocusBinding(viewManager, invokeOnViewFocusChange);
@override
ui.ViewFocusChangeCallback? get onViewFocusChange => _onViewFocusChange;
ui.ViewFocusChangeCallback? _onViewFocusChange;
Zone? _onViewFocusChangeZone;
@override
set onViewFocusChange(ui.ViewFocusChangeCallback? callback) {
_onViewFocusChange = callback;
_onViewFocusChangeZone = Zone.current;
}
// Engine code should use this method instead of the callback directly.
// Otherwise zones won't work properly.
void invokeOnViewFocusChange(ui.ViewFocusEvent viewFocusEvent) {
invoke1<ui.ViewFocusEvent>(
_onViewFocusChange,
_onViewFocusChangeZone,
viewFocusEvent,
);
}
@override
void requestViewFocusChange({
required int viewId,
required ui.ViewFocusState state,
required ui.ViewFocusDirection direction,
}) {
_viewFocusBinding.changeViewFocus(viewId, state);
}
/// A set of views which have rendered in the current `onBeginFrame` or
/// `onDrawFrame` scope.
Set<ui.FlutterView>? _viewsRenderedInCurrentFrame;
/// A callback invoked when any window begins a frame.
///
/// A callback that is invoked to notify the application that it is an
/// appropriate time to provide a scene using the [SceneBuilder] API and the
/// [PlatformWindow.render] method.
/// When possible, this is driven by the hardware VSync signal of the attached
/// screen with the highest VSync rate. This is only called if
/// [PlatformWindow.scheduleFrame] has been called since the last time this
/// callback was invoked.
@override
ui.FrameCallback? get onBeginFrame => _onBeginFrame;
ui.FrameCallback? _onBeginFrame;
Zone? _onBeginFrameZone;
@override
set onBeginFrame(ui.FrameCallback? callback) {
_onBeginFrame = callback;
_onBeginFrameZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnBeginFrame(Duration duration) {
_viewsRenderedInCurrentFrame = <ui.FlutterView>{};
invoke1<Duration>(_onBeginFrame, _onBeginFrameZone, duration);
_viewsRenderedInCurrentFrame = null;
}
/// A callback that is invoked for each frame after [onBeginFrame] has
/// completed and after the microtask queue has been drained.
///
/// This can be used to implement a second phase of frame rendering that
/// happens after any deferred work queued by the [onBeginFrame] phase.
@override
ui.VoidCallback? get onDrawFrame => _onDrawFrame;
ui.VoidCallback? _onDrawFrame;
Zone? _onDrawFrameZone;
@override
set onDrawFrame(ui.VoidCallback? callback) {
_onDrawFrame = callback;
_onDrawFrameZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnDrawFrame() {
_viewsRenderedInCurrentFrame = <ui.FlutterView>{};
invoke(_onDrawFrame, _onDrawFrameZone);
_viewsRenderedInCurrentFrame = null;
}
/// A callback that is invoked when pointer data is available.
///
/// The framework invokes this callback in the same zone in which the
/// callback was set.
///
/// See also:
///
/// * [GestureBinding], the Flutter framework class which manages pointer
/// events.
@override
ui.PointerDataPacketCallback? get onPointerDataPacket => _onPointerDataPacket;
ui.PointerDataPacketCallback? _onPointerDataPacket;
Zone? _onPointerDataPacketZone;
@override
set onPointerDataPacket(ui.PointerDataPacketCallback? callback) {
_onPointerDataPacket = callback;
_onPointerDataPacketZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnPointerDataPacket(ui.PointerDataPacket dataPacket) {
invoke1<ui.PointerDataPacket>(
_onPointerDataPacket, _onPointerDataPacketZone, dataPacket);
}
/// A callback that is invoked when key data is available.
///
/// The framework invokes this callback in the same zone in which the
/// callback was set.
///
/// See also:
///
/// * [GestureBinding], the Flutter framework class which manages pointer
/// events.
@override
ui.KeyDataCallback? get onKeyData => _onKeyData;
ui.KeyDataCallback? _onKeyData;
Zone? _onKeyDataZone;
@override
set onKeyData(ui.KeyDataCallback? callback) {
_onKeyData = callback;
_onKeyDataZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnKeyData(ui.KeyData data, _KeyDataResponseCallback callback) {
final ui.KeyDataCallback? onKeyData = _onKeyData;
if (onKeyData != null) {
invoke(
() => callback(onKeyData(data)),
_onKeyDataZone,
);
} else {
callback(false);
}
}
/// A callback that is invoked to report the [FrameTiming] of recently
/// rasterized frames.
///
/// It's preferred to use [SchedulerBinding.addTimingsCallback] than to use
/// [PlatformDispatcher.onReportTimings] directly because
/// [SchedulerBinding.addTimingsCallback] allows multiple callbacks.
///
/// This can be used to see if the application has missed frames (through
/// [FrameTiming.buildDuration] and [FrameTiming.rasterDuration]), or high
/// latencies (through [FrameTiming.totalSpan]).
///
/// Unlike [Timeline], the timing information here is available in the release
/// mode (additional to the profile and the debug mode). Hence this can be
/// used to monitor the application's performance in the wild.
///
/// {@macro dart.ui.TimingsCallback.list}
///
/// If this is null, no additional work will be done. If this is not null,
/// Flutter spends less than 0.1ms every 1 second to report the timings
/// (measured on iPhone6S). The 0.1ms is about 0.6% of 16ms (frame budget for
/// 60fps), or 0.01% CPU usage per second.
@override
ui.TimingsCallback? get onReportTimings => _onReportTimings;
ui.TimingsCallback? _onReportTimings;
Zone? _onReportTimingsZone;
@override
set onReportTimings(ui.TimingsCallback? callback) {
_onReportTimings = callback;
_onReportTimingsZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnReportTimings(List<ui.FrameTiming> timings) {
invoke1<List<ui.FrameTiming>>(
_onReportTimings, _onReportTimingsZone, timings);
}
@override
void sendPlatformMessage(
String name,
ByteData? data,
ui.PlatformMessageResponseCallback? callback,
) {
_sendPlatformMessage(
name, data, _zonedPlatformMessageResponseCallback(callback));
}
@override
void sendPortPlatformMessage(
String name,
ByteData? data,
int identifier,
Object port,
) {
throw Exception("Isolates aren't supported in web.");
}
@override
void registerBackgroundIsolate(ui.RootIsolateToken token) {
throw Exception("Isolates aren't supported in web.");
}
// TODO(ianh): Deprecate onPlatformMessage once the framework is moved over
// to using channel buffers exclusively.
@override
ui.PlatformMessageCallback? get onPlatformMessage => _onPlatformMessage;
ui.PlatformMessageCallback? _onPlatformMessage;
Zone? _onPlatformMessageZone;
@override
set onPlatformMessage(ui.PlatformMessageCallback? callback) {
_onPlatformMessage = callback;
_onPlatformMessageZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnPlatformMessage(
String name,
ByteData? data,
ui.PlatformMessageResponseCallback callback,
) {
if (name == ui.ChannelBuffers.kControlChannelName) {
// TODO(ianh): move this logic into ChannelBuffers once we remove onPlatformMessage
try {
ui.channelBuffers.handleMessage(data!);
} finally {
callback(null);
}
} else if (_onPlatformMessage != null) {
invoke3<String, ByteData?, ui.PlatformMessageResponseCallback>(
_onPlatformMessage,
_onPlatformMessageZone,
name,
data,
callback,
);
} else {
ui.channelBuffers.push(name, data, callback);
}
}
/// Wraps the given [callback] in another callback that ensures that the
/// original callback is called in the zone it was registered in.
static ui.PlatformMessageResponseCallback?
_zonedPlatformMessageResponseCallback(
ui.PlatformMessageResponseCallback? callback) {
if (callback == null) {
return null;
}
// Store the zone in which the callback is being registered.
final Zone registrationZone = Zone.current;
return (ByteData? data) {
registrationZone.runUnaryGuarded(callback, data);
};
}
void _sendPlatformMessage(
String name,
ByteData? data,
ui.PlatformMessageResponseCallback? callback,
) {
// In widget tests we want to bypass processing of platform messages.
bool returnImmediately = false;
assert(() {
if (ui_web.debugEmulateFlutterTesterEnvironment) {
returnImmediately = true;
}
return true;
}());
if (returnImmediately) {
return;
}
if (debugPrintPlatformMessages) {
print('Sent platform message on channel: "$name"');
}
bool allowDebugEcho = false;
assert(() {
allowDebugEcho = true;
return true;
}());
if (allowDebugEcho && name == 'flutter/debug-echo') {
// Echoes back the data unchanged. Used for testing purposes.
replyToPlatformMessage(callback, data);
return;
}
switch (name) {
/// This should be in sync with shell/common/shell.cc
case 'flutter/skia':
final MethodCall decoded = jsonCodec.decodeMethodCall(data);
switch (decoded.method) {
case 'Skia.setResourceCacheMaxBytes':
if (renderer is CanvasKitRenderer) {
assert(
decoded.arguments is int,
'Argument to Skia.setResourceCacheMaxBytes must be an int, but was ${decoded.arguments.runtimeType}',
);
final int cacheSizeInBytes = decoded.arguments as int;
CanvasKitRenderer.instance.resourceCacheMaxBytes =
cacheSizeInBytes;
}
// Also respond in HTML mode. Otherwise, apps would have to detect
// CanvasKit vs HTML before invoking this method.
replyToPlatformMessage(
callback, jsonCodec.encodeSuccessEnvelope(<bool>[true]));
}
return;
case 'flutter/assets':
final String url = utf8.decode(data!.buffer.asUint8List());
_handleFlutterAssetsMessage(url, callback);
return;
case 'flutter/platform':
final MethodCall decoded = jsonCodec.decodeMethodCall(data);
switch (decoded.method) {
case 'SystemNavigator.pop':
// TODO(a-wallen): As multi-window support expands, the pop call
// will need to include the view ID. Right now only one view is
// supported.
//
// TODO(mdebbar): What should we do in multi-view mode?
// https://github.com/flutter/flutter/issues/139174
if (implicitView != null) {
implicitView!.browserHistory.exit().then((_) {
replyToPlatformMessage(
callback,
jsonCodec.encodeSuccessEnvelope(true),
);
});
} else {
replyToPlatformMessage(
callback,
jsonCodec.encodeSuccessEnvelope(true),
);
}
return;
case 'HapticFeedback.vibrate':
final String? type = decoded.arguments as String?;
vibrate(_getHapticFeedbackDuration(type));
replyToPlatformMessage(
callback, jsonCodec.encodeSuccessEnvelope(true));
return;
case 'SystemChrome.setApplicationSwitcherDescription':
final Map<String, Object?> arguments =
decoded.arguments as Map<String, Object?>;
final String label = arguments['label'] as String? ?? '';
// TODO(web): Stop setting the color from here, https://github.com/flutter/flutter/issues/123365
final int primaryColor =
arguments['primaryColor'] as int? ?? 0xFF000000;
domDocument.title = label;
setThemeColor(ui.Color(primaryColor));
replyToPlatformMessage(
callback, jsonCodec.encodeSuccessEnvelope(true));
return;
case 'SystemChrome.setSystemUIOverlayStyle':
final Map<String, Object?> arguments =
decoded.arguments as Map<String, Object?>;
final int? statusBarColor = arguments['statusBarColor'] as int?;
setThemeColor(
statusBarColor == null ? null : ui.Color(statusBarColor));
replyToPlatformMessage(
callback, jsonCodec.encodeSuccessEnvelope(true));
return;
case 'SystemChrome.setPreferredOrientations':
final List<dynamic> arguments = decoded.arguments as List<dynamic>;
ScreenOrientation.instance
.setPreferredOrientation(arguments)
.then((bool success) {
replyToPlatformMessage(
callback, jsonCodec.encodeSuccessEnvelope(success));
});
return;
case 'SystemSound.play':
// There are no default system sounds on web.
replyToPlatformMessage(
callback, jsonCodec.encodeSuccessEnvelope(true));
return;
case 'Clipboard.setData':
ClipboardMessageHandler().setDataMethodCall(decoded, callback);
return;
case 'Clipboard.getData':
ClipboardMessageHandler().getDataMethodCall(callback);
return;
case 'Clipboard.hasStrings':
ClipboardMessageHandler().hasStringsMethodCall(callback);
return;
}
// Dispatched by the bindings to delay service worker initialization.
case 'flutter/service_worker':
domWindow.dispatchEvent(createDomEvent('Event', 'flutter-first-frame'));
return;
case 'flutter/textinput':
textEditing.channel.handleTextInput(data, callback);
return;
case 'flutter/contextmenu':
final MethodCall decoded = jsonCodec.decodeMethodCall(data);
switch (decoded.method) {
case 'enableContextMenu':
implicitView!.contextMenu.enable();
replyToPlatformMessage(
callback, jsonCodec.encodeSuccessEnvelope(true));
return;
case 'disableContextMenu':
implicitView!.contextMenu.disable();
replyToPlatformMessage(
callback, jsonCodec.encodeSuccessEnvelope(true));
return;
}
return;
case 'flutter/mousecursor':
final MethodCall decoded = standardCodec.decodeMethodCall(data);
final Map<dynamic, dynamic> arguments =
decoded.arguments as Map<dynamic, dynamic>;
switch (decoded.method) {
case 'activateSystemCursor':
// TODO(mdebbar): Once the framework starts sending us a viewId, we
// should use it to grab the correct view.
// https://github.com/flutter/flutter/issues/140226
views.firstOrNull?.mouseCursor
.activateSystemCursor(arguments.tryString('kind'));
}
return;
case 'flutter/web_test_e2e':
replyToPlatformMessage(
callback,
jsonCodec.encodeSuccessEnvelope(
_handleWebTestEnd2EndMessage(jsonCodec, data)));
return;
case PlatformViewMessageHandler.channelName:
// `arguments` can be a Map<String, Object> for `create`,
// but an `int` for `dispose`, hence why `dynamic` everywhere.
final MethodCall(:String method, :dynamic arguments) =
standardCodec.decodeMethodCall(data);
PlatformViewMessageHandler.instance
.handlePlatformViewCall(method, arguments, callback!);
return;
case 'flutter/accessibility':
// In widget tests we want to bypass processing of platform messages.
const StandardMessageCodec codec = StandardMessageCodec();
// TODO(yjbanov): Dispatch the announcement to the correct view?
// https://github.com/flutter/flutter/issues/137445
implicitView?.accessibilityAnnouncements.handleMessage(codec, data);
replyToPlatformMessage(callback, codec.encodeMessage(true));
return;
case 'flutter/navigation':
// TODO(a-wallen): As multi-window support expands, the navigation call
// will need to include the view ID. Right now only one view is
// supported.
//
// TODO(mdebbar): What should we do in multi-view mode?
// https://github.com/flutter/flutter/issues/139174
if (implicitView != null) {
implicitView!.handleNavigationMessage(data).then((bool handled) {
if (handled) {
replyToPlatformMessage(
callback,
jsonCodec.encodeSuccessEnvelope(true),
);
} else {
callback?.call(null);
}
});
} else {
callback?.call(null);
}
// As soon as Flutter starts taking control of the app navigation, we
// should reset _defaultRouteName to "/" so it doesn't have any
// further effect after this point.
_defaultRouteName = '/';
return;
}
if (pluginMessageCallHandler != null) {
pluginMessageCallHandler!(name, data, callback);
return;
}
// Passing [null] to [callback] indicates that the platform message isn't
// implemented. Look at [MethodChannel.invokeMethod] to see how [null] is
// handled.
replyToPlatformMessage(callback, null);
}
Future<void> _handleFlutterAssetsMessage(
String url, ui.PlatformMessageResponseCallback? callback) async {
try {
final HttpFetchResponse response =
await ui_web.assetManager.loadAsset(url) as HttpFetchResponse;
final ByteBuffer assetData = await response.asByteBuffer();
replyToPlatformMessage(callback, assetData.asByteData());
} catch (error) {
printWarning('Error while trying to load an asset: $error');
replyToPlatformMessage(callback, null);
}
}
int _getHapticFeedbackDuration(String? type) {
const int vibrateLongPress = 50;
const int vibrateLightImpact = 10;
const int vibrateMediumImpact = 20;
const int vibrateHeavyImpact = 30;
const int vibrateSelectionClick = 10;
switch (type) {
case 'HapticFeedbackType.lightImpact':
return vibrateLightImpact;
case 'HapticFeedbackType.mediumImpact':
return vibrateMediumImpact;
case 'HapticFeedbackType.heavyImpact':
return vibrateHeavyImpact;
case 'HapticFeedbackType.selectionClick':
return vibrateSelectionClick;
default:
return vibrateLongPress;
}
}
/// Requests that, at the next appropriate opportunity, the [onBeginFrame]
/// and [onDrawFrame] callbacks be invoked.
///
/// See also:
///
/// * [SchedulerBinding], the Flutter framework class which manages the
/// scheduling of frames.
@override
void scheduleFrame() {
if (scheduleFrameCallback == null) {
throw Exception('scheduleFrameCallback must be initialized first.');
}
scheduleFrameCallback!();
}
@override
void scheduleWarmUpFrame({required ui.VoidCallback beginFrame, required ui.VoidCallback drawFrame}) {
Timer.run(beginFrame);
// We use timers here to ensure that microtasks flush in between.
//
// TODO(dkwingsmt): This logic was moved from the framework and is different
// from how Web renders a regular frame, which doesn't flush microtasks
// between the callbacks at all (see `initializeEngineServices`). We might
// want to change this. See the to-do in `initializeEngineServices` and
// https://github.com/flutter/engine/pull/50570#discussion_r1496671676
Timer.run(drawFrame);
}
/// Updates the application's rendering on the GPU with the newly provided
/// [Scene]. This function must be called within the scope of the
/// [onBeginFrame] or [onDrawFrame] callbacks being invoked. If this function
/// is called a second time during a single [onBeginFrame]/[onDrawFrame]
/// callback sequence or called outside the scope of those callbacks, the call
/// will be ignored.
///
/// To record graphical operations, first create a [PictureRecorder], then
/// construct a [Canvas], passing that [PictureRecorder] to its constructor.
/// After issuing all the graphical operations, call the
/// [PictureRecorder.endRecording] function on the [PictureRecorder] to obtain
/// the final [Picture] that represents the issued graphical operations.
///
/// Next, create a [SceneBuilder], and add the [Picture] to it using
/// [SceneBuilder.addPicture]. With the [SceneBuilder.build] method you can
/// then obtain a [Scene] object, which you can display to the user via this
/// [render] function.
///
/// See also:
///
/// * [SchedulerBinding], the Flutter framework class which manages the
/// scheduling of frames.
/// * [RendererBinding], the Flutter framework class which manages layout and
/// painting.
Future<void> render(ui.Scene scene, [ui.FlutterView? view]) async {
final EngineFlutterView? target = (view ?? implicitView) as EngineFlutterView?;
assert(target != null, 'Calling render without a FlutterView');
if (target == null) {
// If there is no view to render into, then this is a no-op.
return;
}
// Only render in an `onDrawFrame` or `onBeginFrame` scope. This is checked
// by checking if the `_viewsRenderedInCurrentFrame` is non-null and this
// view hasn't been rendered already in this scope.
final bool shouldRender =
_viewsRenderedInCurrentFrame?.add(target) ?? false;
// TODO(harryterkelsen): HTML renderer needs to violate the render rule in
// order to perform golden tests in Flutter framework because on the HTML
// renderer, golden tests render to DOM and then take a browser screenshot,
// https://github.com/flutter/flutter/issues/137073.
if (shouldRender || renderer.rendererTag == 'html') {
await renderer.renderScene(scene, target);
}
}
/// Additional accessibility features that may be enabled by the platform.
@override
ui.AccessibilityFeatures get accessibilityFeatures =>
configuration.accessibilityFeatures;
/// A callback that is invoked when the value of [accessibilityFeatures] changes.
///
/// The framework invokes this callback in the same zone in which the
/// callback was set.
@override
ui.VoidCallback? get onAccessibilityFeaturesChanged =>
_onAccessibilityFeaturesChanged;
ui.VoidCallback? _onAccessibilityFeaturesChanged;
Zone? _onAccessibilityFeaturesChangedZone;
@override
set onAccessibilityFeaturesChanged(ui.VoidCallback? callback) {
_onAccessibilityFeaturesChanged = callback;
_onAccessibilityFeaturesChangedZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnAccessibilityFeaturesChanged() {
invoke(
_onAccessibilityFeaturesChanged, _onAccessibilityFeaturesChangedZone);
}
/// Change the retained semantics data about this window.
///
/// If [semanticsEnabled] is true, the user has requested that this function
/// be called whenever the semantic content of this window changes.
///
/// In either case, this function disposes the given update, which means the
/// semantics update cannot be used further.
@override
@Deprecated('''
In a multi-view world, the platform dispatcher can no longer provide apis
to update semantics since each view will host its own semantics tree.
Semantics updates must be passed to an individual [FlutterView]. To update
semantics, use PlatformDispatcher.instance.views to get a [FlutterView] and
call `updateSemantics`.
''')
void updateSemantics(ui.SemanticsUpdate update) {
implicitView?.semantics.updateSemantics(update);
}
/// This is equivalent to `locales.first`, except that it will provide an
/// undefined (using the language tag "und") non-null locale if the [locales]
/// list has not been set or is empty.
///
/// We use the first locale in the [locales] list instead of the browser's
/// built-in `navigator.language` because browsers do not agree on the
/// implementation.
///
/// See also:
///
/// * https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/languages,
/// which explains browser quirks in the implementation notes.
@override
ui.Locale get locale =>
locales.isEmpty ? const ui.Locale.fromSubtags() : locales.first;
/// The full system-reported supported locales of the device.
///
/// This establishes the language and formatting conventions that application
/// should, if possible, use to render their user interface.
///
/// The list is ordered in order of priority, with lower-indexed locales being
/// preferred over higher-indexed ones. The first element is the primary [locale].
///
/// The [onLocaleChanged] callback is called whenever this value changes.
///
/// See also:
///
/// * [WidgetsBindingObserver], for a mechanism at the widgets layer to
/// observe when this value changes.
@override
List<ui.Locale> get locales => configuration.locales;
// A subscription to the 'languagechange' event of 'window'.
DomSubscription? _onLocaleChangedSubscription;
/// Configures the [_onLocaleChangedSubscription].
void _addLocaleChangedListener() {
if (_onLocaleChangedSubscription != null) {
return;
}
updateLocales(); // First time, for good measure.
_onLocaleChangedSubscription =
DomSubscription(domWindow, 'languagechange', (DomEvent _) {
// Update internal config, then propagate the changes.
updateLocales();
invokeOnLocaleChanged();
});
}
/// Removes the [_onLocaleChangedSubscription].
void _removeLocaleChangedListener() {
_onLocaleChangedSubscription?.cancel();
_onLocaleChangedSubscription = null;
}
/// Performs the platform-native locale resolution.
///
/// Each platform may return different results.
///
/// If the platform fails to resolve a locale, then this will return null.
///
/// This method returns synchronously and is a direct call to
/// platform specific APIs without invoking method channels.
@override
ui.Locale? computePlatformResolvedLocale(List<ui.Locale> supportedLocales) {
// TODO(garyq): Implement on web.
return null;
}
/// A callback that is invoked whenever [locale] changes value.
///
/// The framework invokes this callback in the same zone in which the
/// callback was set.
///
/// See also:
///
/// * [WidgetsBindingObserver], for a mechanism at the widgets layer to
/// observe when this callback is invoked.
@override
ui.VoidCallback? get onLocaleChanged => _onLocaleChanged;
ui.VoidCallback? _onLocaleChanged;
Zone? _onLocaleChangedZone;
@override
set onLocaleChanged(ui.VoidCallback? callback) {
_onLocaleChanged = callback;
_onLocaleChangedZone = Zone.current;
}
/// The locale used when we fail to get the list from the browser.
static const ui.Locale _defaultLocale = ui.Locale('en', 'US');
/// Sets locales to an empty list.
///
/// The empty list is not a valid value for locales. This is only used for
/// testing locale update logic.
void debugResetLocales() {
configuration = configuration.copyWith(locales: const <ui.Locale>[]);
}
// Called by `_onLocaleChangedSubscription` when browser languages change.
void updateLocales() {
configuration = configuration.copyWith(locales: parseBrowserLanguages());
}
static List<ui.Locale> parseBrowserLanguages() {
// TODO(yjbanov): find a solution for IE
final List<String>? languages = domWindow.navigator.languages;
if (languages == null || languages.isEmpty) {
// To make it easier for the app code, let's not leave the locales list
// empty. This way there's fewer corner cases for apps to handle.
return const <ui.Locale>[_defaultLocale];
}
final List<ui.Locale> locales = <ui.Locale>[];
for (final String language in languages) {
final List<String> parts = language.split('-');
if (parts.length > 1) {
locales.add(ui.Locale(parts.first, parts.last));
} else {
locales.add(ui.Locale(language));
}
}
assert(locales.isNotEmpty);
return locales;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnLocaleChanged() {
invoke(_onLocaleChanged, _onLocaleChangedZone);
}
/// The system-reported text scale.
///
/// This establishes the text scaling factor to use when rendering text,
/// according to the user's platform preferences.
///
/// The [onTextScaleFactorChanged] callback is called whenever this value
/// changes.
///
/// See also:
///
/// * [WidgetsBindingObserver], for a mechanism at the widgets layer to
/// observe when this value changes.
@override
double get textScaleFactor => configuration.textScaleFactor;
/// The setting indicating whether time should always be shown in the 24-hour
/// format.
///
/// This option is used by [showTimePicker].
@override
bool get alwaysUse24HourFormat => configuration.alwaysUse24HourFormat;
/// Updates [textScaleFactor] and invokes [onTextScaleFactorChanged] and
/// [onPlatformConfigurationChanged] callbacks if [textScaleFactor] changed.
void _updateTextScaleFactor(double value) {
if (configuration.textScaleFactor != value) {
configuration = configuration.copyWith(textScaleFactor: value);
invokeOnPlatformConfigurationChanged();
invokeOnTextScaleFactorChanged();
}
}
/// Watches for font-size changes in the browser's <html> element to
/// recalculate [textScaleFactor].
///
/// Updates [textScaleFactor] with the new value.
DomMutationObserver? _fontSizeObserver;
/// Set the callback function for updating [textScaleFactor] based on
/// font-size changes in the browser's <html> element.
void _addFontSizeObserver() {
const String styleAttribute = 'style';
_fontSizeObserver = createDomMutationObserver(
(JSArray<JSAny?> mutations, DomMutationObserver _) {
for (final JSAny? mutation in mutations.toDart) {
final DomMutationRecord record = mutation! as DomMutationRecord;
if (record.type == 'attributes' &&
record.attributeName == styleAttribute) {
final double newTextScaleFactor = findBrowserTextScaleFactor();
_updateTextScaleFactor(newTextScaleFactor);
}
}
});
_fontSizeObserver!.observe(
domDocument.documentElement!,
attributes: true,
attributeFilter: <String>[styleAttribute],
);
}
/// Remove the observer for font-size changes in the browser's <html> element.
void _disconnectFontSizeObserver() {
_fontSizeObserver?.disconnect();
_fontSizeObserver = null;
}
void _setAppLifecycleState(ui.AppLifecycleState state) {
invokeOnPlatformMessage(
'flutter/lifecycle',
const StringCodec().encodeMessage(state.toString()),
(_) {},
);
}
/// A callback that is invoked whenever [textScaleFactor] changes value.
///
/// The framework invokes this callback in the same zone in which the
/// callback was set.
///
/// See also:
///
/// * [WidgetsBindingObserver], for a mechanism at the widgets layer to
/// observe when this callback is invoked.
@override
ui.VoidCallback? get onTextScaleFactorChanged => _onTextScaleFactorChanged;
ui.VoidCallback? _onTextScaleFactorChanged;
Zone? _onTextScaleFactorChangedZone;
@override
set onTextScaleFactorChanged(ui.VoidCallback? callback) {
_onTextScaleFactorChanged = callback;
_onTextScaleFactorChangedZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnTextScaleFactorChanged() {
invoke(_onTextScaleFactorChanged, _onTextScaleFactorChangedZone);
}
void updateSemanticsEnabled(bool semanticsEnabled) {
if (semanticsEnabled != this.semanticsEnabled) {
configuration =
configuration.copyWith(semanticsEnabled: semanticsEnabled);
if (_onSemanticsEnabledChanged != null) {
invokeOnSemanticsEnabledChanged();
}
}
}
/// The setting indicating the current brightness mode of the host platform.
/// If the platform has no preference, [platformBrightness] defaults to [Brightness.light].
@override
ui.Brightness get platformBrightness => configuration.platformBrightness;
/// Updates [_platformBrightness] and invokes [onPlatformBrightnessChanged]
/// callback if [_platformBrightness] changed.
void _updatePlatformBrightness(ui.Brightness value) {
if (configuration.platformBrightness != value) {
configuration = configuration.copyWith(platformBrightness: value);
invokeOnPlatformConfigurationChanged();
invokeOnPlatformBrightnessChanged();
}
}
/// The setting indicating the current system font of the host platform.
@override
String? get systemFontFamily => configuration.systemFontFamily;
/// Updates [_highContrast] and invokes [onHighContrastModeChanged]
/// callback if [_highContrast] changed.
void _updateHighContrast(bool value) {
if (configuration.accessibilityFeatures.highContrast != value) {
final EngineAccessibilityFeatures original =
configuration.accessibilityFeatures as EngineAccessibilityFeatures;
configuration = configuration.copyWith(
accessibilityFeatures: original.copyWith(highContrast: value));
invokeOnPlatformConfigurationChanged();
}
}
/// Reference to css media query that indicates the user theme preference on the web.
final DomMediaQueryList _brightnessMediaQuery =
domWindow.matchMedia('(prefers-color-scheme: dark)');
/// A callback that is invoked whenever [_brightnessMediaQuery] changes value.
///
/// Updates the [_platformBrightness] with the new user preference.
DomEventListener? _brightnessMediaQueryListener;
/// Set the callback function for listening changes in [_brightnessMediaQuery] value.
void _addBrightnessMediaQueryListener() {
_updatePlatformBrightness(_brightnessMediaQuery.matches
? ui.Brightness.dark
: ui.Brightness.light);
_brightnessMediaQueryListener = createDomEventListener((DomEvent event) {
final DomMediaQueryListEvent mqEvent = event as DomMediaQueryListEvent;
_updatePlatformBrightness(
mqEvent.matches! ? ui.Brightness.dark : ui.Brightness.light);
});
_brightnessMediaQuery.addListener(_brightnessMediaQueryListener);
}
/// Remove the callback function for listening changes in [_brightnessMediaQuery] value.
void _removeBrightnessMediaQueryListener() {
_brightnessMediaQuery.removeListener(_brightnessMediaQueryListener);
_brightnessMediaQueryListener = null;
}
/// A callback that is invoked whenever [platformBrightness] changes value.
///
/// The framework invokes this callback in the same zone in which the
/// callback was set.
///
/// See also:
///
/// * [WidgetsBindingObserver], for a mechanism at the widgets layer to
/// observe when this callback is invoked.
@override
ui.VoidCallback? get onPlatformBrightnessChanged =>
_onPlatformBrightnessChanged;
ui.VoidCallback? _onPlatformBrightnessChanged;
Zone? _onPlatformBrightnessChangedZone;
@override
set onPlatformBrightnessChanged(ui.VoidCallback? callback) {
_onPlatformBrightnessChanged = callback;
_onPlatformBrightnessChangedZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnPlatformBrightnessChanged() {
invoke(_onPlatformBrightnessChanged, _onPlatformBrightnessChangedZone);
}
/// A callback that is invoked whenever [systemFontFamily] changes value.
///
/// The framework invokes this callback in the same zone in which the
/// callback was set.
///
/// See also:
///
/// * [WidgetsBindingObserver], for a mechanism at the widgets layer to
/// observe when this callback is invoked.
@override
ui.VoidCallback? get onSystemFontFamilyChanged => _onSystemFontFamilyChanged;
ui.VoidCallback? _onSystemFontFamilyChanged;
Zone? _onSystemFontFamilyChangedZone;
@override
set onSystemFontFamilyChanged(ui.VoidCallback? callback) {
_onSystemFontFamilyChanged = callback;
_onSystemFontFamilyChangedZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnSystemFontFamilyChanged() {
invoke(_onSystemFontFamilyChanged, _onSystemFontFamilyChangedZone);
}
/// Whether the user has requested that [updateSemantics] be called when
/// the semantic contents of window changes.
///
/// The [onSemanticsEnabledChanged] callback is called whenever this value
/// changes.
@override
bool get semanticsEnabled => configuration.semanticsEnabled;
/// A callback that is invoked when the value of [semanticsEnabled] changes.
///
/// The framework invokes this callback in the same zone in which the
/// callback was set.
@override
ui.VoidCallback? get onSemanticsEnabledChanged => _onSemanticsEnabledChanged;
ui.VoidCallback? _onSemanticsEnabledChanged;
Zone? _onSemanticsEnabledChangedZone;
@override
set onSemanticsEnabledChanged(ui.VoidCallback? callback) {
_onSemanticsEnabledChanged = callback;
_onSemanticsEnabledChangedZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnSemanticsEnabledChanged() {
invoke(_onSemanticsEnabledChanged, _onSemanticsEnabledChangedZone);
}
/// A callback that is invoked whenever the user requests an action to be
/// performed on a semantics node.
///
/// This callback is used when the user expresses the action they wish to
/// perform based on the semantics node supplied by updateSemantics.
///
/// The framework invokes this callback in the same zone in which the
/// callback was set.
@override
ui.SemanticsActionEventCallback? get onSemanticsActionEvent =>
_onSemanticsActionEvent;
ui.SemanticsActionEventCallback? _onSemanticsActionEvent;
Zone _onSemanticsActionEventZone = Zone.root;
@override
set onSemanticsActionEvent(ui.SemanticsActionEventCallback? callback) {
_onSemanticsActionEvent = callback;
_onSemanticsActionEventZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnSemanticsAction(
int nodeId, ui.SemanticsAction action, ByteData? args) {
invoke1<ui.SemanticsActionEvent>(
_onSemanticsActionEvent,
_onSemanticsActionEventZone,
ui.SemanticsActionEvent(
type: action,
nodeId: nodeId,
viewId: 0, // TODO(goderbauer): Wire up the real view ID.
arguments: args,
),
);
}
// TODO(dnfield): make this work on web.
// https://github.com/flutter/flutter/issues/100277
ui.ErrorCallback? _onError;
// ignore: unused_field
late Zone _onErrorZone;
@override
ui.ErrorCallback? get onError => _onError;
@override
set onError(ui.ErrorCallback? callback) {
_onError = callback;
_onErrorZone = Zone.current;
}
/// The route or path that the embedder requested when the application was
/// launched.
///
/// This will be the string "`/`" if no particular route was requested.
///
/// ## Android
///
/// On Android, calling
/// [`FlutterView.setInitialRoute`](/javadoc/io/flutter/view/FlutterView.html#setInitialRoute-java.lang.String-)
/// will set this value. The value must be set sufficiently early, i.e. before
/// the [runApp] call is executed in Dart, for this to have any effect on the
/// framework. The `createFlutterView` method in your `FlutterActivity`
/// subclass is a suitable time to set the value. The application's
/// `AndroidManifest.xml` file must also be updated to have a suitable
/// [`<intent-filter>`](https://developer.android.com/guide/topics/manifest/intent-filter-element.html).
///
/// ## iOS
///
/// On iOS, calling
/// [`FlutterViewController.setInitialRoute`](/ios-embedder/interface_flutter_view_controller.html#a7f269c2da73312f856d42611cc12a33f)
/// will set this value. The value must be set sufficiently early, i.e. before
/// the [runApp] call is executed in Dart, for this to have any effect on the
/// framework. The `application:didFinishLaunchingWithOptions:` method is a
/// suitable time to set this value.
///
/// See also:
///
/// * [Navigator], a widget that handles routing.
/// * [SystemChannels.navigation], which handles subsequent navigation
/// requests from the embedder.
@override
String get defaultRouteName {
// TODO(mdebbar): What should we do in multi-view mode?
// https://github.com/flutter/flutter/issues/139174
return _defaultRouteName ??=
implicitView?.browserHistory.currentPath ?? '/';
}
/// Lazily initialized when the `defaultRouteName` getter is invoked.
///
/// The reason for the lazy initialization is to give enough time for the app
/// to set [locationStrategy] in `lib/initialization.dart`.
String? _defaultRouteName;
/// In Flutter, platform messages are exchanged between threads so the
/// messages and responses have to be exchanged asynchronously. We simulate
/// that by adding a zero-length delay to the reply.
void replyToPlatformMessage(
ui.PlatformMessageResponseCallback? callback,
ByteData? data,
) {
Future<void>.delayed(Duration.zero).then((_) {
if (callback != null) {
callback(data);
}
});
}
@override
ui.FrameData get frameData => const ui.FrameData.webOnly();
@override
double scaleFontSize(double unscaledFontSize) =>
unscaledFontSize * textScaleFactor;
}
bool _handleWebTestEnd2EndMessage(MethodCodec codec, ByteData? data) {
final MethodCall decoded = codec.decodeMethodCall(data);
final double ratio = double.parse(decoded.arguments as String);
switch (decoded.method) {
case 'setDevicePixelRatio':
EngineFlutterDisplay.instance.debugOverrideDevicePixelRatio(ratio);
EnginePlatformDispatcher.instance.onMetricsChanged!();
return true;
}
return false;
}
/// Invokes [callback] inside the given [zone].
void invoke(void Function()? callback, Zone? zone) {
if (callback == null) {
return;
}
assert(zone != null);
if (identical(zone, Zone.current)) {
callback();
} else {
zone!.runGuarded(callback);
}
}
/// Invokes [callback] inside the given [zone] passing it [arg].
void invoke1<A>(void Function(A a)? callback, Zone? zone, A arg) {
if (callback == null) {
return;
}
assert(zone != null);
if (identical(zone, Zone.current)) {
callback(arg);
} else {
zone!.runUnaryGuarded<A>(callback, arg);
}
}
/// Invokes [callback] inside the given [zone] passing it [arg1] and [arg2].
void invoke2<A1, A2>(
void Function(A1 a1, A2 a2)? callback, Zone? zone, A1 arg1, A2 arg2) {
if (callback == null) {
return;
}
assert(zone != null);
if (identical(zone, Zone.current)) {
callback(arg1, arg2);
} else {
zone!.runGuarded(() {
callback(arg1, arg2);
});
}
}
/// Invokes [callback] inside the given [zone] passing it [arg1], [arg2], and [arg3].
void invoke3<A1, A2, A3>(void Function(A1 a1, A2 a2, A3 a3)? callback,
Zone? zone, A1 arg1, A2 arg2, A3 arg3) {
if (callback == null) {
return;
}
assert(zone != null);
if (identical(zone, Zone.current)) {
callback(arg1, arg2, arg3);
} else {
zone!.runGuarded(() {
callback(arg1, arg2, arg3);
});
}
}
const double _defaultRootFontSize = 16.0;
/// Finds the text scale factor of the browser by looking at the computed style
/// of the browser's <html> element.
double findBrowserTextScaleFactor() {
final num fontSize =
parseFontSize(domDocument.documentElement!) ?? _defaultRootFontSize;
return fontSize / _defaultRootFontSize;
}
class ViewConfiguration {
const ViewConfiguration({
this.view,
this.devicePixelRatio = 1.0,
this.visible = false,
this.viewInsets = ui.ViewPadding.zero as ViewPadding,
this.viewPadding = ui.ViewPadding.zero as ViewPadding,
this.systemGestureInsets = ui.ViewPadding.zero as ViewPadding,
this.padding = ui.ViewPadding.zero as ViewPadding,
this.gestureSettings = const ui.GestureSettings(),
this.displayFeatures = const <ui.DisplayFeature>[],
});
ViewConfiguration copyWith({
EngineFlutterView? view,
double? devicePixelRatio,
bool? visible,
ViewPadding? viewInsets,
ViewPadding? viewPadding,
ViewPadding? systemGestureInsets,
ViewPadding? padding,
ui.GestureSettings? gestureSettings,
List<ui.DisplayFeature>? displayFeatures,
}) {
return ViewConfiguration(
view: view ?? this.view,
devicePixelRatio: devicePixelRatio ?? this.devicePixelRatio,
visible: visible ?? this.visible,
viewInsets: viewInsets ?? this.viewInsets,
viewPadding: viewPadding ?? this.viewPadding,
systemGestureInsets: systemGestureInsets ?? this.systemGestureInsets,
padding: padding ?? this.padding,
gestureSettings: gestureSettings ?? this.gestureSettings,
displayFeatures: displayFeatures ?? this.displayFeatures,
);
}
final EngineFlutterView? view;
final double devicePixelRatio;
final bool visible;
final ViewPadding viewInsets;
final ViewPadding viewPadding;
final ViewPadding systemGestureInsets;
final ViewPadding padding;
final ui.GestureSettings gestureSettings;
final List<ui.DisplayFeature> displayFeatures;
@override
String toString() {
return '$runtimeType[view: $view]';
}
}
class PlatformConfiguration {
const PlatformConfiguration({
this.accessibilityFeatures = const EngineAccessibilityFeatures(0),
this.alwaysUse24HourFormat = false,
this.semanticsEnabled = false,
this.platformBrightness = ui.Brightness.light,
this.textScaleFactor = 1.0,
this.locales = const <ui.Locale>[],
this.defaultRouteName = '/',
this.systemFontFamily,
});
PlatformConfiguration copyWith({
ui.AccessibilityFeatures? accessibilityFeatures,
bool? alwaysUse24HourFormat,
bool? semanticsEnabled,
ui.Brightness? platformBrightness,
double? textScaleFactor,
List<ui.Locale>? locales,
String? defaultRouteName,
String? systemFontFamily,
}) {
return PlatformConfiguration(
accessibilityFeatures:
accessibilityFeatures ?? this.accessibilityFeatures,
alwaysUse24HourFormat:
alwaysUse24HourFormat ?? this.alwaysUse24HourFormat,
semanticsEnabled: semanticsEnabled ?? this.semanticsEnabled,
platformBrightness: platformBrightness ?? this.platformBrightness,
textScaleFactor: textScaleFactor ?? this.textScaleFactor,
locales: locales ?? this.locales,
defaultRouteName: defaultRouteName ?? this.defaultRouteName,
systemFontFamily: systemFontFamily ?? this.systemFontFamily,
);
}
final ui.AccessibilityFeatures accessibilityFeatures;
final bool alwaysUse24HourFormat;
final bool semanticsEnabled;
final ui.Brightness platformBrightness;
final double textScaleFactor;
final List<ui.Locale> locales;
final String defaultRouteName;
final String? systemFontFamily;
}
| engine/lib/web_ui/lib/src/engine/platform_dispatcher.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/platform_dispatcher.dart",
"repo_id": "engine",
"token_count": 18961
} | 252 |
// Copyright 2013 The Flutter 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:typed_data';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
// This file implements a SceneBuilder and Scene that works with any renderer
// implementation that provides:
// * A `ui.Canvas` that conforms to `SceneCanvas`
// * A `ui.Picture` that conforms to `ScenePicture`
// * A `ui.ImageFilter` that conforms to `SceneImageFilter`
//
// These contain a few augmentations to the normal `dart:ui` API that provide
// additional sizing information that the scene builder uses to determine how
// these object might occlude one another.
class EngineScene implements ui.Scene {
EngineScene(this.rootLayer);
final EngineRootLayer rootLayer;
// We keep a refcount here because this can be asynchronously rendered, so we
// don't necessarily want to dispose immediately when the user calls dispose.
// Instead, we need to stay alive until we're done rendering.
int _refCount = 1;
void beginRender() {
assert(_refCount > 0);
_refCount++;
}
void endRender() {
_refCount--;
_disposeIfNeeded();
}
@override
void dispose() {
_refCount--;
_disposeIfNeeded();
}
void _disposeIfNeeded() {
assert(_refCount >= 0);
if (_refCount == 0) {
rootLayer.dispose();
}
}
@override
Future<ui.Image> toImage(int width, int height) async {
return toImageSync(width, height);
}
@override
ui.Image toImageSync(int width, int height) {
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Rect canvasRect = ui.Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble());
final ui.Canvas canvas = ui.Canvas(recorder, canvasRect);
// Only rasterizes the picture slices.
for (final PictureSlice slice in rootLayer.slices.whereType<PictureSlice>()) {
canvas.drawPicture(slice.picture);
}
return recorder.endRecording().toImageSync(width, height);
}
}
class EngineSceneBuilder implements ui.SceneBuilder {
LayerBuilder currentBuilder = LayerBuilder.rootLayer();
@override
void addPerformanceOverlay(int enabledOptions, ui.Rect bounds) {
// We don't plan to implement this on the web.
throw UnimplementedError();
}
@override
void addPicture(
ui.Offset offset,
ui.Picture picture, {
bool isComplexHint = false,
bool willChangeHint = false
}) {
currentBuilder.addPicture(
offset,
picture,
isComplexHint:
isComplexHint,
willChangeHint: willChangeHint
);
}
@override
void addPlatformView(
int viewId, {
ui.Offset offset = ui.Offset.zero,
double width = 0.0,
double height = 0.0
}) {
currentBuilder.addPlatformView(
viewId,
offset: offset,
width: width,
height: height
);
}
@override
void addRetained(ui.EngineLayer retainedLayer) {
currentBuilder.mergeLayer(retainedLayer as PictureEngineLayer);
}
@override
void addTexture(
int textureId, {
ui.Offset offset = ui.Offset.zero,
double width = 0.0,
double height = 0.0,
bool freeze = false,
ui.FilterQuality filterQuality = ui.FilterQuality.low
}) {
// addTexture is not implemented on web.
}
@override
ui.BackdropFilterEngineLayer pushBackdropFilter(
ui.ImageFilter filter, {
ui.BlendMode blendMode = ui.BlendMode.srcOver,
ui.BackdropFilterEngineLayer? oldLayer
}) => pushLayer<BackdropFilterLayer>(
BackdropFilterLayer(),
BackdropFilterOperation(filter, blendMode),
);
@override
ui.ClipPathEngineLayer pushClipPath(
ui.Path path, {
ui.Clip clipBehavior = ui.Clip.antiAlias,
ui.ClipPathEngineLayer? oldLayer
}) => pushLayer<ClipPathLayer>(
ClipPathLayer(),
ClipPathOperation(path, clipBehavior),
);
@override
ui.ClipRRectEngineLayer pushClipRRect(
ui.RRect rrect, {
required ui.Clip clipBehavior,
ui.ClipRRectEngineLayer? oldLayer
}) => pushLayer<ClipRRectLayer>(
ClipRRectLayer(),
ClipRRectOperation(rrect, clipBehavior)
);
@override
ui.ClipRectEngineLayer pushClipRect(
ui.Rect rect, {
ui.Clip clipBehavior = ui.Clip.antiAlias,
ui.ClipRectEngineLayer? oldLayer
}) {
return pushLayer<ClipRectLayer>(
ClipRectLayer(),
ClipRectOperation(rect, clipBehavior)
);
}
@override
ui.ColorFilterEngineLayer pushColorFilter(
ui.ColorFilter filter, {
ui.ColorFilterEngineLayer? oldLayer
}) => pushLayer<ColorFilterLayer>(
ColorFilterLayer(),
ColorFilterOperation(filter),
);
@override
ui.ImageFilterEngineLayer pushImageFilter(
ui.ImageFilter filter, {
ui.Offset offset = ui.Offset.zero,
ui.ImageFilterEngineLayer? oldLayer
}) => pushLayer<ImageFilterLayer>(
ImageFilterLayer(),
ImageFilterOperation(filter, offset),
);
@override
ui.OffsetEngineLayer pushOffset(
double dx,
double dy, {
ui.OffsetEngineLayer? oldLayer
}) => pushLayer<OffsetLayer>(
OffsetLayer(),
OffsetOperation(dx, dy)
);
@override
ui.OpacityEngineLayer pushOpacity(int alpha, {
ui.Offset offset = ui.Offset.zero,
ui.OpacityEngineLayer? oldLayer
}) => pushLayer<OpacityLayer>(
OpacityLayer(),
OpacityOperation(alpha, offset),
);
@override
ui.ShaderMaskEngineLayer pushShaderMask(
ui.Shader shader,
ui.Rect maskRect,
ui.BlendMode blendMode, {
ui.ShaderMaskEngineLayer? oldLayer,
ui.FilterQuality filterQuality = ui.FilterQuality.low
}) => pushLayer<ShaderMaskLayer>(
ShaderMaskLayer(),
ShaderMaskOperation(shader, maskRect, blendMode)
);
@override
ui.TransformEngineLayer pushTransform(
Float64List matrix4, {
ui.TransformEngineLayer? oldLayer
}) => pushLayer<TransformLayer>(
TransformLayer(),
TransformOperation(matrix4),
);
@override
void setCheckerboardOffscreenLayers(bool checkerboard) {
// Not implemented on web
}
@override
void setCheckerboardRasterCacheImages(bool checkerboard) {
// Not implemented on web
}
@override
void setProperties(
double width,
double height,
double insetTop,
double insetRight,
double insetBottom,
double insetLeft,
bool focusable
) {
// Not implemented on web
}
@override
void setRasterizerTracingThreshold(int frameInterval) {
// Not implemented on web
}
@override
ui.Scene build() {
while (currentBuilder.parent != null) {
pop();
}
final PictureEngineLayer rootLayer = currentBuilder.build();
return EngineScene(rootLayer as EngineRootLayer);
}
@override
void pop() {
final PictureEngineLayer layer = currentBuilder.build();
final LayerBuilder? parentBuilder = currentBuilder.parent;
if (parentBuilder == null) {
throw StateError('Popped too many times.');
}
currentBuilder = parentBuilder;
currentBuilder.mergeLayer(layer);
}
T pushLayer<T extends PictureEngineLayer>(T layer, LayerOperation operation) {
currentBuilder = LayerBuilder.childLayer(
parent: currentBuilder,
layer: layer,
operation: operation
);
return layer;
}
}
| engine/lib/web_ui/lib/src/engine/scene_builder.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/scene_builder.dart",
"repo_id": "engine",
"token_count": 2637
} | 253 |
// Copyright 2013 The Flutter 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:meta/meta.dart';
import '../browser_detection.dart';
import '../dom.dart';
import 'semantics.dart';
/// The maximum [semanticsActivationAttempts] before we give up waiting for
/// the user to enable semantics.
///
/// This number is arbitrary and can be adjusted if it doesn't work well.
const int kMaxSemanticsActivationAttempts = 20;
/// After an event related to semantics activation has been received, we consume
/// the consecutive events on the engine. Do not send them to the framework.
/// For example when a 'mousedown' targeting a placeholder received following
/// 'mouseup' is also not sent to the framework.
/// Otherwise these events can cause unintended gestures on the framework side.
const Duration _periodToConsumeEvents = Duration(milliseconds: 300);
/// The message in the label for the placeholder element used to enable
/// accessibility.
///
/// This uses US English as the default message. Set this value prior to
/// calling `runApp` to translate to another language.
String placeholderMessage = 'Enable accessibility';
/// A helper for [EngineSemanticsOwner].
///
/// [SemanticsHelper] prepares and placeholder to enable semantics.
///
/// It decides if an event is purely semantics enabling related or a regular
/// event which should be forwarded to the framework.
///
/// It does this by using a [SemanticsEnabler]. The [SemanticsEnabler]
/// implementation is chosen using form factor type.
///
/// See [DesktopSemanticsEnabler], [MobileSemanticsEnabler].
class SemanticsHelper {
SemanticsEnabler _semanticsEnabler =
isDesktop ? DesktopSemanticsEnabler() : MobileSemanticsEnabler();
@visibleForTesting
set semanticsEnabler(SemanticsEnabler semanticsEnabler) {
_semanticsEnabler = semanticsEnabler;
}
bool shouldEnableSemantics(DomEvent event) {
return _semanticsEnabler.shouldEnableSemantics(event);
}
DomElement prepareAccessibilityPlaceholder() {
return _semanticsEnabler.prepareAccessibilityPlaceholder();
}
/// Stops waiting for the user to enable semantics and removes the
/// placeholder.
///
/// This is used when semantics is enabled programmatically and therefore the
/// placehodler is no longer needed.
void dispose() {
_semanticsEnabler.dispose();
}
}
@visibleForTesting
abstract class SemanticsEnabler {
/// Whether to enable semantics.
///
/// Semantics should be enabled if the web engine is no longer waiting for
/// extra signals from the user events. See [isWaitingToEnableSemantics].
///
/// Or if the received [DomEvent] is suitable/enough for enabling the
/// semantics. See [tryEnableSemantics].
bool shouldEnableSemantics(DomEvent event) {
if (!isWaitingToEnableSemantics) {
// Forward to framework as normal.
return true;
} else {
return tryEnableSemantics(event);
}
}
/// Attempts to activate semantics.
///
/// Returns true if the `event` is not related to semantics activation and
/// should be forwarded to the framework.
bool tryEnableSemantics(DomEvent event);
/// Creates the placeholder for accessibility.
///
/// Puts it inside the glasspane.
///
/// On focus the element announces that accessibility can be enabled by
/// tapping/clicking. (Announcement depends on the assistive technology)
DomElement prepareAccessibilityPlaceholder();
/// Whether platform is still considering enabling semantics.
///
/// At this stage a relevant set of events are always assessed to see if
/// they activate the semantics.
///
/// If not they are sent to framework as normal events.
bool get isWaitingToEnableSemantics;
/// Stops waiting for the user to enable semantics and removes the placeholder.
void dispose();
}
/// The desktop semantics enabler uses a simpler strategy compared to mobile.
///
/// A placeholder element is created completely outside the view and is not
/// reachable via touch or mouse. Assistive technology can still find it either
/// using keyboard shortcuts or via next/previous touch gesture (for touch
/// screens). This simplification removes the need for pointer event
/// disambiguation or timers. The placeholder simply waits for a click event
/// and enables semantics.
@visibleForTesting
class DesktopSemanticsEnabler extends SemanticsEnabler {
/// A temporary placeholder used to capture a request to activate semantics.
DomElement? _semanticsPlaceholder;
/// Whether we are waiting for the user to enable semantics.
@override
bool get isWaitingToEnableSemantics => _semanticsPlaceholder != null;
@override
bool tryEnableSemantics(DomEvent event) {
// Semantics may be enabled programmatically. If there's a race between that
// and the DOM event, we may end up here while there's no longer a placeholder
// to work with.
if (!isWaitingToEnableSemantics) {
return true;
}
if (EngineSemantics.instance.semanticsEnabled) {
// Semantics already enabled, forward to framework as normal.
return true;
}
// In touch screen laptops, the touch is received as a mouse click
const Set<String> kInterestingEventTypes = <String>{
'click',
'keyup',
'keydown',
'mouseup',
'mousedown',
'pointerdown',
'pointerup',
};
if (!kInterestingEventTypes.contains(event.type)) {
// The event is not relevant, forward to framework as normal.
return true;
}
// Check for the event target.
final bool enableConditionPassed = event.target == _semanticsPlaceholder;
if (!enableConditionPassed) {
// This was not a semantics activating event; forward as normal.
return true;
}
EngineSemantics.instance.semanticsEnabled = true;
dispose();
return false;
}
@override
DomElement prepareAccessibilityPlaceholder() {
final DomElement placeholder =
_semanticsPlaceholder = createDomElement('flt-semantics-placeholder');
// Only listen to "click" because other kinds of events are reported via
// PointerBinding.
placeholder.addEventListener('click', createDomEventListener((DomEvent event) {
tryEnableSemantics(event);
}), true);
// Adding roles to semantics placeholder. 'aria-live' will make sure that
// the content is announced to the assistive technology user as soon as the
// page receives focus. 'tabindex' makes sure the button is the first
// target of tab. 'aria-label' is used to define the placeholder message
// to the assistive technology user.
placeholder
..setAttribute('role', 'button')
..setAttribute('aria-live', 'polite')
..setAttribute('tabindex', '0')
..setAttribute('aria-label', placeholderMessage);
// The placeholder sits just outside the window so only AT can reach it.
placeholder.style
..position = 'absolute'
..left = '-1px'
..top = '-1px'
..width = '1px'
..height = '1px';
return placeholder;
}
@override
void dispose() {
_semanticsPlaceholder?.remove();
_semanticsPlaceholder = null;
}
}
@visibleForTesting
class MobileSemanticsEnabler extends SemanticsEnabler {
/// We do not immediately enable semantics when the user requests it, but
/// instead wait for a short period of time before doing it. This is because
/// the request comes as an event targeted on the [_semanticsPlaceholder].
/// This event, depending on the browser, comes as a burst of events.
/// For example, Safari on IOS sends "touchstart", "touchend", and "click".
/// So during a short time period we consume all events and prevent forwarding
/// to the framework. Otherwise, the events will be interpreted twice, once as
/// a request to activate semantics, and a second time by Flutter's gesture
/// recognizers.
@visibleForTesting
Timer? semanticsActivationTimer;
/// A temporary placeholder used to capture a request to activate semantics.
DomElement? _semanticsPlaceholder;
/// The number of events we processed that could potentially activate
/// semantics.
int semanticsActivationAttempts = 0;
/// Instructs [_tryEnableSemantics] to remove [_semanticsPlaceholder].
///
/// For Blink browser engine the placeholder is removed upon any next event.
///
/// For Webkit browser engine the placeholder is removed upon the next
/// "touchend" event. This is to prevent Safari from swallowing the event
/// that happens on an element that's being removed. Blink doesn't have
/// this issue.
bool _schedulePlaceholderRemoval = false;
/// Whether we are waiting for the user to enable semantics.
@override
bool get isWaitingToEnableSemantics => _semanticsPlaceholder != null;
@override
bool tryEnableSemantics(DomEvent event) {
// Semantics may be enabled programmatically. If there's a race between that
// and the DOM event, we may end up here while there's no longer a placeholder
// to work with.
if (!isWaitingToEnableSemantics) {
return true;
}
if (_schedulePlaceholderRemoval) {
// The event type can also be click for VoiceOver.
final bool removeNow = browserEngine != BrowserEngine.webkit ||
event.type == 'touchend' ||
event.type == 'pointerup' ||
event.type == 'click';
if (removeNow) {
dispose();
}
return true;
}
if (EngineSemantics.instance.semanticsEnabled) {
// Semantics already enabled, forward to framework as normal.
return true;
}
semanticsActivationAttempts += 1;
if (semanticsActivationAttempts >= kMaxSemanticsActivationAttempts) {
// We have received multiple user events, none of which resulted in
// semantics activation. This is a signal that the user is not interested
// in semantics, and so we will stop waiting for it.
_schedulePlaceholderRemoval = true;
return true;
}
// ios-safari browsers which starts sending `pointer` events instead of
// `touch` events. (Tested with 12.1 which uses touch events vs 13.5
// which uses pointer events.)
const Set<String> kInterestingEventTypes = <String>{
'click',
'touchstart',
'touchend',
'pointerdown',
'pointermove',
'pointerup',
};
if (!kInterestingEventTypes.contains(event.type)) {
// The event is not relevant, forward to framework as normal.
return true;
}
if (semanticsActivationTimer != null) {
// We are in a waiting period to activate a timer. While the timer is
// active we should consume events pertaining to semantics activation.
// Otherwise the event will also be interpreted by the framework and
// potentially result in activating a gesture in the app.
return false;
}
// Look at where exactly (within 1 pixel) the event landed. If it landed
// exactly in the middle of the placeholder we interpret it as a signal
// to enable accessibility. This is because when VoiceOver and TalkBack
// generate a tap it lands it in the middle of the focused element. This
// method is a bit flawed in that a user's finger could theoretically land
// in the middle of the element too. However, the chance of that happening
// is very small. Even low-end phones typically have >2 million pixels
// (e.g. Moto G4). It is very unlikely that a user will land their finger
// exactly in the middle. In the worst case an unlucky user would
// accidentally enable accessibility and the app will be slightly slower
// than normal, but the app will continue functioning as normal. Our
// semantics tree is designed to not interfere with Flutter's gesture
// detection.
bool enableConditionPassed = false;
late final DomPoint activationPoint;
switch (event.type) {
case 'click':
final DomMouseEvent click = event as DomMouseEvent;
activationPoint = click.offset;
case 'touchstart':
case 'touchend':
final DomTouchEvent touchEvent = event as DomTouchEvent;
activationPoint = touchEvent.changedTouches.first.client;
case 'pointerdown':
case 'pointerup':
final DomPointerEvent touch = event as DomPointerEvent;
activationPoint = touch.client;
default:
// The event is not relevant, forward to framework as normal.
return true;
}
final DomRect activatingElementRect =
_semanticsPlaceholder!.getBoundingClientRect();
final double midX = activatingElementRect.left +
(activatingElementRect.right - activatingElementRect.left) / 2;
final double midY = activatingElementRect.top +
(activatingElementRect.bottom - activatingElementRect.top) / 2;
final double deltaX = activationPoint.x.toDouble() - midX;
final double deltaY = activationPoint.y.toDouble() - midY;
final double deltaSquared = deltaX * deltaX + deltaY * deltaY;
if (deltaSquared < 1.0) {
enableConditionPassed = true;
}
if (enableConditionPassed) {
assert(semanticsActivationTimer == null);
_schedulePlaceholderRemoval = true;
semanticsActivationTimer = Timer(_periodToConsumeEvents, () {
dispose();
EngineSemantics.instance.semanticsEnabled = true;
});
return false;
}
// This was not a semantics activating event; forward as normal.
return true;
}
@override
DomElement prepareAccessibilityPlaceholder() {
final DomElement placeholder =
_semanticsPlaceholder = createDomElement('flt-semantics-placeholder');
// Only listen to "click" because other kinds of events are reported via
// PointerBinding.
placeholder.addEventListener('click', createDomEventListener((DomEvent event) {
tryEnableSemantics(event);
}), true);
placeholder
..setAttribute('role', 'button')
..setAttribute('aria-label', placeholderMessage);
placeholder.style
..position = 'absolute'
..left = '0'
..top = '0'
..right = '0'
..bottom = '0';
return placeholder;
}
@override
void dispose() {
_semanticsPlaceholder?.remove();
_semanticsPlaceholder = null;
semanticsActivationTimer = null;
}
}
| engine/lib/web_ui/lib/src/engine/semantics/semantics_helper.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/semantics/semantics_helper.dart",
"repo_id": "engine",
"token_count": 4327
} | 254 |
// Copyright 2013 The Flutter 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';
import 'dart:js_interop';
import 'dart:typed_data';
import 'package:ui/src/engine.dart';
import 'package:ui/src/engine/skwasm/skwasm_impl.dart';
import 'package:ui/ui.dart' as ui;
class SkwasmImage extends SkwasmObjectWrapper<RawImage> implements ui.Image {
SkwasmImage(ImageHandle handle) : super(handle, _registry)
{
ui.Image.onCreate?.call(this);
}
factory SkwasmImage.fromPixels(
Uint8List pixels,
int width,
int height,
ui.PixelFormat format, {
int? rowBytes,
}) {
final SkDataHandle dataHandle = skDataCreate(pixels.length);
final Pointer<Uint8> dataPointer = skDataGetPointer(dataHandle).cast<Uint8>();
for (int i = 0; i < pixels.length; i++) {
dataPointer[i] = pixels[i];
}
final ImageHandle imageHandle = imageCreateFromPixels(
dataHandle,
width,
height,
format.index,
rowBytes ?? 4 * width,
);
skDataDispose(dataHandle);
return SkwasmImage(imageHandle);
}
static final SkwasmFinalizationRegistry<RawImage> _registry =
SkwasmFinalizationRegistry<RawImage>(imageDispose);
@override
void dispose() {
super.dispose();
ui.Image.onDispose?.call(this);
}
@override
int get width => imageGetWidth(handle);
@override
int get height => imageGetHeight(handle);
@override
Future<ByteData?> toByteData(
{ui.ImageByteFormat format = ui.ImageByteFormat.rawRgba}) async {
if (format == ui.ImageByteFormat.png) {
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Canvas canvas = ui.Canvas(recorder);
canvas.drawImage(this, ui.Offset.zero, ui.Paint());
final DomImageBitmap bitmap =
(await (renderer as SkwasmRenderer).surface.renderPictures(
<SkwasmPicture>[recorder.endRecording() as SkwasmPicture],
)).imageBitmaps.single;
final DomOffscreenCanvas offscreenCanvas =
createDomOffscreenCanvas(bitmap.width.toDartInt, bitmap.height.toDartInt);
final DomCanvasRenderingContextBitmapRenderer context =
offscreenCanvas.getContext('bitmaprenderer')! as DomCanvasRenderingContextBitmapRenderer;
context.transferFromImageBitmap(bitmap);
final DomBlob blob = await offscreenCanvas.convertToBlob();
final JSArrayBuffer arrayBuffer = (await blob.arrayBuffer().toDart)! as JSArrayBuffer;
// Zero out the contents of the canvas so that resources can be reclaimed
// by the browser.
context.transferFromImageBitmap(null);
return ByteData.view(arrayBuffer.toDart);
} else {
return (renderer as SkwasmRenderer).surface.rasterizeImage(this, format);
}
}
@override
ui.ColorSpace get colorSpace => ui.ColorSpace.sRGB;
@override
SkwasmImage clone() {
imageRef(handle);
return SkwasmImage(handle);
}
@override
bool isCloneOf(ui.Image other) => other is SkwasmImage && handle == other.handle;
@override
List<StackTrace>? debugGetOpenHandleStackTraces() => null;
@override
String toString() => '[$width\u00D7$height]';
}
| engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/image.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/image.dart",
"repo_id": "engine",
"token_count": 1217
} | 255 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@DefaultAsset('skwasm')
library skwasm_impl;
import 'dart:ffi';
import 'package:ui/src/engine/skwasm/skwasm_impl.dart';
final class RawPictureRecorder extends Opaque {}
typedef PictureRecorderHandle = Pointer<RawPictureRecorder>;
final class RawPicture extends Opaque {}
typedef PictureHandle = Pointer<RawPicture>;
@Native<PictureRecorderHandle Function()>(
symbol: 'pictureRecorder_create',
isLeaf: true)
external PictureRecorderHandle pictureRecorderCreate();
@Native<Void Function(PictureRecorderHandle)>(
symbol: 'pictureRecorder_dispose',
isLeaf: true)
external void pictureRecorderDispose(PictureRecorderHandle picture);
@Native<CanvasHandle Function(PictureRecorderHandle, RawRect)>(
symbol: 'pictureRecorder_beginRecording',
isLeaf: true)
external CanvasHandle pictureRecorderBeginRecording(
PictureRecorderHandle picture, RawRect cullRect);
@Native<PictureHandle Function(PictureRecorderHandle)>(
symbol: 'pictureRecorder_endRecording',
isLeaf: true)
external PictureHandle pictureRecorderEndRecording(PictureRecorderHandle picture);
@Native<Void Function(PictureHandle)>(
symbol: 'picture_dispose',
isLeaf: true)
external void pictureDispose(PictureHandle handle);
@Native<Uint32 Function(PictureHandle)>(
symbol: 'picture_approximateBytesUsed',
isLeaf: true)
external int pictureApproximateBytesUsed(PictureHandle handle);
@Native<Void Function(PictureHandle, RawRect)>(
symbol: 'picture_getCullRect',
isLeaf: true)
external void pictureGetCullRect(PictureHandle handle, RawRect outRect);
| engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_picture.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_picture.dart",
"repo_id": "engine",
"token_count": 505
} | 256 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: avoid_unused_constructor_parameters
import 'dart:ffi';
import 'dart:typed_data';
import 'package:ui/src/engine/skwasm/skwasm_impl.dart';
import 'package:ui/ui.dart' as ui;
class SkwasmVertices extends SkwasmObjectWrapper<RawVertices> implements ui.Vertices {
factory SkwasmVertices(
ui.VertexMode mode,
List<ui.Offset> positions, {
List<ui.Offset>? textureCoordinates,
List<ui.Color>? colors,
List<int>? indices,
}) => withStackScope((StackScope scope) {
final RawPointArray rawPositions = scope.convertPointArrayToNative(positions);
final RawPointArray rawTextureCoordinates = textureCoordinates != null
? scope.convertPointArrayToNative(textureCoordinates)
: nullptr;
final RawColorArray rawColors = colors != null
? scope.convertColorArrayToNative(colors)
: nullptr;
final Pointer<Uint16> rawIndices = indices != null
? scope.convertIntsToUint16Native(indices)
: nullptr;
final int indexCount = indices != null ? indices.length : 0;
return SkwasmVertices._(verticesCreate(
mode.index,
positions.length,
rawPositions,
rawTextureCoordinates,
rawColors,
indexCount,
rawIndices,
));
});
factory SkwasmVertices.raw(
ui.VertexMode mode,
Float32List positions, {
Float32List? textureCoordinates,
Int32List? colors,
Uint16List? indices,
}) => withStackScope((StackScope scope) {
final RawPointArray rawPositions = scope.convertDoublesToNative(positions);
final RawPointArray rawTextureCoordinates = textureCoordinates != null
? scope.convertDoublesToNative(textureCoordinates)
: nullptr;
final RawColorArray rawColors = colors != null
? scope.convertIntsToUint32Native(colors)
: nullptr;
final Pointer<Uint16> rawIndices = indices != null
? scope.convertIntsToUint16Native(indices)
: nullptr;
final int indexCount = indices != null ? indices.length : 0;
return SkwasmVertices._(verticesCreate(
mode.index,
positions.length ~/ 2,
rawPositions,
rawTextureCoordinates,
rawColors,
indexCount,
rawIndices,
));
});
SkwasmVertices._(VerticesHandle handle) : super(handle, _registry);
static final SkwasmFinalizationRegistry<RawVertices> _registry =
SkwasmFinalizationRegistry<RawVertices>(verticesDispose);
}
| engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/vertices.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/vertices.dart",
"repo_id": "engine",
"token_count": 955
} | 257 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import '../browser_detection.dart';
import '../dom.dart';
import '../util.dart';
import '../view_embedder/style_manager.dart';
import 'measurement.dart';
import 'paragraph.dart';
String buildCssFontString({
required ui.FontStyle? fontStyle,
required ui.FontWeight? fontWeight,
required double? fontSize,
required String fontFamily,
}) {
final String cssFontStyle = fontStyle?.toCssString() ?? StyleManager.defaultFontStyle;
final String cssFontWeight = fontWeight?.toCssString() ?? StyleManager.defaultFontWeight;
final int cssFontSize = (fontSize ?? StyleManager.defaultFontSize).floor();
final String cssFontFamily = canonicalizeFontFamily(fontFamily)!;
return '$cssFontStyle $cssFontWeight ${cssFontSize}px $cssFontFamily';
}
/// Contains all styles that have an effect on the height of text.
///
/// This is useful as a cache key for [TextHeightRuler].
class TextHeightStyle {
TextHeightStyle({
required this.fontFamily,
required this.fontSize,
required this.height,
required this.fontFeatures,
required this.fontVariations,
});
final String fontFamily;
final double fontSize;
final double? height;
final List<ui.FontFeature>? fontFeatures;
final List<ui.FontVariation>? fontVariations;
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is TextHeightStyle && other.hashCode == hashCode;
}
@override
late final int hashCode = Object.hash(
fontFamily,
fontSize,
height,
fontFeatures == null ? null : Object.hashAll(fontFeatures!),
fontVariations == null ? null : Object.hashAll(fontVariations!),
);
}
/// Provides text dimensions found on [_element]. The idea behind this class is
/// to allow the [ParagraphRuler] to mutate multiple dom elements and allow
/// consumers to lazily read the measurements.
///
/// The [ParagraphRuler] would have multiple instances of [TextDimensions] with
/// different backing elements for different types of measurements. When a
/// measurement is needed, the [ParagraphRuler] would mutate all the backing
/// elements at once. The consumer of the ruler can later read those
/// measurements.
///
/// The rationale behind this is to minimize browser reflows by batching dom
/// writes first, then performing all the reads.
class TextDimensions {
TextDimensions(this._element);
final DomElement _element;
DomRect? _cachedBoundingClientRect;
void _invalidateBoundsCache() {
_cachedBoundingClientRect = null;
}
/// Sets text of contents to a single space character to measure empty text.
void updateTextToSpace() {
_invalidateBoundsCache();
_element.text = ' ';
}
void applyHeightStyle(TextHeightStyle textHeightStyle) {
final String fontFamily = textHeightStyle.fontFamily;
final double fontSize = textHeightStyle.fontSize;
final DomCSSStyleDeclaration style = _element.style;
style
..fontSize = '${fontSize.floor()}px'
..fontFamily = canonicalizeFontFamily(fontFamily)!;
final double? height = textHeightStyle.height;
// Workaround the rounding introduced by https://github.com/flutter/flutter/issues/122066
// in tests.
final double? effectiveLineHeight = height ?? (fontFamily == 'FlutterTest' ? 1.0 : null);
if (effectiveLineHeight != null) {
style.lineHeight = effectiveLineHeight.toString();
}
_invalidateBoundsCache();
}
/// Appends element and probe to hostElement that is set up for a specific
/// TextStyle.
void appendToHost(DomHTMLElement hostElement) {
hostElement.append(_element);
_invalidateBoundsCache();
}
DomRect _readAndCacheMetrics() =>
_cachedBoundingClientRect ??= _element.getBoundingClientRect();
/// The height of the paragraph being measured.
double get height {
double cachedHeight = _readAndCacheMetrics().height;
if (browserEngine == BrowserEngine.firefox &&
// In the flutter tester environment, we use a predictable-size for font
// measurement tests.
!ui_web.debugEmulateFlutterTesterEnvironment) {
// See subpixel rounding bug :
// https://bugzilla.mozilla.org/show_bug.cgi?id=442139
// This causes bottom of letters such as 'y' to be cutoff and
// incorrect rendering of double underlines.
cachedHeight += 1.0;
}
return cachedHeight;
}
}
/// Performs height measurement for the given [textHeightStyle].
///
/// The two results of this ruler's measurement are:
///
/// 1. [alphabeticBaseline].
/// 2. [height].
class TextHeightRuler {
TextHeightRuler(this.textHeightStyle, this.rulerHost);
final TextHeightStyle textHeightStyle;
final RulerHost rulerHost;
// Elements used to measure the line-height metric.
late final DomHTMLElement _probe = _createProbe();
late final DomHTMLElement _host = _createHost();
final TextDimensions _dimensions = TextDimensions(domDocument.createElement('flt-paragraph'));
/// The alphabetic baseline for this ruler's [textHeightStyle].
late final double alphabeticBaseline = _probe.getBoundingClientRect().bottom;
/// The height for this ruler's [textHeightStyle].
late final double height = _dimensions.height;
/// Disposes of this ruler and detaches it from the DOM tree.
void dispose() {
_host.remove();
}
DomHTMLElement _createHost() {
final DomHTMLDivElement host = createDomHTMLDivElement();
host.style
..visibility = 'hidden'
..position = 'absolute'
..top = '0'
..left = '0'
..display = 'flex'
..flexDirection = 'row'
..alignItems = 'baseline'
..margin = '0'
..border = '0'
..padding = '0';
assert(() {
host.setAttribute('data-ruler', 'line-height');
return true;
}());
_dimensions.applyHeightStyle(textHeightStyle);
// Force single-line (even if wider than screen) and preserve whitespaces.
_dimensions._element.style.whiteSpace = 'pre';
// To measure line-height, all we need is a whitespace.
_dimensions.updateTextToSpace();
_dimensions.appendToHost(host);
rulerHost.addElement(host);
return host;
}
DomHTMLElement _createProbe() {
final DomHTMLElement probe = createDomHTMLDivElement();
_host.append(probe);
return probe;
}
}
| engine/lib/web_ui/lib/src/engine/text/ruler.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/text/ruler.dart",
"repo_id": "engine",
"token_count": 2080
} | 258 |
// Copyright 2013 The Flutter 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:ui/src/engine/browser_detection.dart';
import 'package:ui/src/engine/display.dart';
import 'package:ui/src/engine/dom.dart';
import 'package:ui/src/engine/window.dart';
import 'package:ui/ui.dart' as ui show Size;
import 'dimensions_provider.dart';
/// This class provides the real-time dimensions of a "full page" viewport.
///
/// All the measurements returned from this class are potentially *expensive*,
/// and should be cached as needed. Every call to every method on this class
/// WILL perform actual DOM measurements.
class FullPageDimensionsProvider extends DimensionsProvider {
/// Constructs a global [FullPageDimensionsProvider].
///
/// Doesn't need any parameters, because all the measurements come from the
/// globally available [DomVisualViewport].
FullPageDimensionsProvider() {
// Determine what 'resize' event we'll be listening to.
// This is needed for older browsers (Firefox < 91, Safari < 13)
// TODO(dit): Clean this up, https://github.com/flutter/flutter/issues/117105
final DomEventTarget resizeEventTarget =
domWindow.visualViewport ?? domWindow;
// Subscribe to the 'resize' event, and convert it to a ui.Size stream.
_domResizeSubscription = DomSubscription(
resizeEventTarget,
'resize',
_onVisualViewportResize,
);
}
late DomSubscription _domResizeSubscription;
final StreamController<ui.Size?> _onResizeStreamController =
StreamController<ui.Size?>.broadcast();
void _onVisualViewportResize(DomEvent event) {
// `event` doesn't contain any size information (as opposed to the custom
// element resize observer). If it did, we could broadcast the physical
// dimensions here and never have to re-measure the app, until the next
// resize event triggers.
// Would it be too costly to broadcast the computed physical size from here,
// and then never re-measure the app?
// Related: https://github.com/flutter/flutter/issues/117036
_onResizeStreamController.add(null);
}
@override
void close() {
super.close();
_domResizeSubscription.cancel();
// ignore:unawaited_futures
_onResizeStreamController.close();
}
@override
Stream<ui.Size?> get onResize => _onResizeStreamController.stream;
@override
ui.Size computePhysicalSize() {
late double windowInnerWidth;
late double windowInnerHeight;
final DomVisualViewport? viewport = domWindow.visualViewport;
final double devicePixelRatio = EngineFlutterDisplay.instance.devicePixelRatio;
if (viewport != null) {
if (operatingSystem == OperatingSystem.iOs) {
/// Chrome on iOS reports incorrect viewport.height when app
/// starts in portrait orientation and the phone is rotated to
/// landscape.
///
/// We instead use documentElement clientWidth/Height to read
/// accurate physical size. VisualViewport api is only used during
/// text editing to make sure inset is correctly reported to
/// framework.
final double docWidth = domDocument.documentElement!.clientWidth;
final double docHeight = domDocument.documentElement!.clientHeight;
windowInnerWidth = docWidth * devicePixelRatio;
windowInnerHeight = docHeight * devicePixelRatio;
} else {
windowInnerWidth = viewport.width! * devicePixelRatio;
windowInnerHeight = viewport.height! * devicePixelRatio;
}
} else {
windowInnerWidth = domWindow.innerWidth! * devicePixelRatio;
windowInnerHeight = domWindow.innerHeight! * devicePixelRatio;
}
return ui.Size(
windowInnerWidth,
windowInnerHeight,
);
}
@override
ViewPadding computeKeyboardInsets(
double physicalHeight,
bool isEditingOnMobile,
) {
final double devicePixelRatio = EngineFlutterDisplay.instance.devicePixelRatio;
final DomVisualViewport? viewport = domWindow.visualViewport;
late double windowInnerHeight;
if (viewport != null) {
if (operatingSystem == OperatingSystem.iOs && !isEditingOnMobile) {
windowInnerHeight =
domDocument.documentElement!.clientHeight * devicePixelRatio;
} else {
windowInnerHeight = viewport.height! * devicePixelRatio;
}
} else {
windowInnerHeight = domWindow.innerHeight! * devicePixelRatio;
}
final double bottomPadding = physicalHeight - windowInnerHeight;
return ViewPadding(bottom: bottomPadding, left: 0, right: 0, top: 0);
}
}
| engine/lib/web_ui/lib/src/engine/view_embedder/dimensions_provider/full_page_dimensions_provider.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/view_embedder/dimensions_provider/full_page_dimensions_provider.dart",
"repo_id": "engine",
"token_count": 1541
} | 259 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:ui/src/engine.dart';
/// Signature of the callback that receives a benchmark [value] labeled by
/// [name].
typedef BenchmarkValueCallback = void Function(String name, double value);
/// A callback for receiving benchmark values.
///
/// Each benchmark value is labeled by a `name` and has a double `value`.
set benchmarkValueCallback(BenchmarkValueCallback? callback) {
engineBenchmarkValueCallback = callback;
}
| engine/lib/web_ui/lib/ui_web/src/ui_web/benchmarks.dart/0 | {
"file_path": "engine/lib/web_ui/lib/ui_web/src/ui_web/benchmarks.dart",
"repo_id": "engine",
"token_count": 152
} | 260 |
// Copyright 2013 The Flutter 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 "export.h"
#include "helpers.h"
#include "third_party/skia/include/core/SkColorFilter.h"
#include "third_party/skia/include/core/SkMaskFilter.h"
#include "third_party/skia/include/effects/SkImageFilters.h"
using namespace Skwasm;
SKWASM_EXPORT SkImageFilter* imageFilter_createBlur(SkScalar sigmaX,
SkScalar sigmaY,
SkTileMode tileMode) {
return SkImageFilters::Blur(sigmaX, sigmaY, tileMode, nullptr).release();
}
SKWASM_EXPORT SkImageFilter* imageFilter_createDilate(SkScalar radiusX,
SkScalar radiusY) {
return SkImageFilters::Dilate(radiusX, radiusY, nullptr).release();
}
SKWASM_EXPORT SkImageFilter* imageFilter_createErode(SkScalar radiusX,
SkScalar radiusY) {
return SkImageFilters::Erode(radiusX, radiusY, nullptr).release();
}
SKWASM_EXPORT SkImageFilter* imageFilter_createMatrix(SkScalar* matrix33,
FilterQuality quality) {
return SkImageFilters::MatrixTransform(createMatrix(matrix33),
samplingOptionsForQuality(quality),
nullptr)
.release();
}
SKWASM_EXPORT SkImageFilter* imageFilter_createFromColorFilter(
SkColorFilter* filter) {
return SkImageFilters::ColorFilter(sk_ref_sp<SkColorFilter>(filter), nullptr)
.release();
}
SKWASM_EXPORT SkImageFilter* imageFilter_compose(SkImageFilter* outer,
SkImageFilter* inner) {
return SkImageFilters::Compose(sk_ref_sp<SkImageFilter>(outer),
sk_ref_sp<SkImageFilter>(inner))
.release();
}
SKWASM_EXPORT void imageFilter_dispose(SkImageFilter* filter) {
filter->unref();
}
SKWASM_EXPORT void imageFilter_getFilterBounds(SkImageFilter* filter,
SkIRect* inOutBounds) {
SkIRect outputRect =
filter->filterBounds(*inOutBounds, SkMatrix(),
SkImageFilter::MapDirection::kForward_MapDirection);
*inOutBounds = outputRect;
}
SKWASM_EXPORT SkColorFilter* colorFilter_createMode(SkColor color,
SkBlendMode mode) {
return SkColorFilters::Blend(color, mode).release();
}
SKWASM_EXPORT SkColorFilter* colorFilter_createMatrix(
float* matrixData // 20 values
) {
return SkColorFilters::Matrix(matrixData).release();
}
SKWASM_EXPORT SkColorFilter* colorFilter_createSRGBToLinearGamma() {
return SkColorFilters::SRGBToLinearGamma().release();
}
SKWASM_EXPORT SkColorFilter* colorFilter_createLinearToSRGBGamma() {
return SkColorFilters::LinearToSRGBGamma().release();
}
SKWASM_EXPORT SkColorFilter* colorFilter_compose(SkColorFilter* outer,
SkColorFilter* inner) {
return SkColorFilters::Compose(sk_ref_sp<SkColorFilter>(outer),
sk_ref_sp<SkColorFilter>(inner))
.release();
}
SKWASM_EXPORT void colorFilter_dispose(SkColorFilter* filter) {
filter->unref();
}
SKWASM_EXPORT SkMaskFilter* maskFilter_createBlur(SkBlurStyle blurStyle,
SkScalar sigma) {
return SkMaskFilter::MakeBlur(blurStyle, sigma).release();
}
SKWASM_EXPORT void maskFilter_dispose(SkMaskFilter* filter) {
filter->unref();
}
| engine/lib/web_ui/skwasm/filters.cpp/0 | {
"file_path": "engine/lib/web_ui/skwasm/filters.cpp",
"repo_id": "engine",
"token_count": 1745
} | 261 |
// Copyright 2013 The Flutter 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 "../export.h"
#include "../wrappers.h"
#include "third_party/skia/modules/skparagraph/include/Paragraph.h"
using namespace skia::textlayout;
using namespace Skwasm;
SKWASM_EXPORT ParagraphStyle* paragraphStyle_create() {
auto style = new ParagraphStyle();
// This is the default behavior in Flutter
style->setReplaceTabCharacters(true);
// Default text style has a black color
TextStyle textStyle;
textStyle.setColor(SK_ColorBLACK);
style->setTextStyle(textStyle);
return style;
}
SKWASM_EXPORT void paragraphStyle_dispose(ParagraphStyle* style) {
delete style;
}
SKWASM_EXPORT void paragraphStyle_setTextAlign(ParagraphStyle* style,
TextAlign align) {
style->setTextAlign(align);
}
SKWASM_EXPORT void paragraphStyle_setTextDirection(ParagraphStyle* style,
TextDirection direction) {
style->setTextDirection(direction);
}
SKWASM_EXPORT void paragraphStyle_setMaxLines(ParagraphStyle* style,
size_t maxLines) {
style->setMaxLines(maxLines);
}
SKWASM_EXPORT void paragraphStyle_setHeight(ParagraphStyle* style,
SkScalar height) {
style->setHeight(height);
}
SKWASM_EXPORT void paragraphStyle_setTextHeightBehavior(
ParagraphStyle* style,
bool applyHeightToFirstAscent,
bool applyHeightToLastDescent) {
TextHeightBehavior behavior;
if (!applyHeightToFirstAscent && !applyHeightToLastDescent) {
behavior = kDisableAll;
} else if (!applyHeightToLastDescent) {
behavior = kDisableLastDescent;
} else if (!applyHeightToFirstAscent) {
behavior = kDisableFirstAscent;
} else {
behavior = kAll;
}
style->setTextHeightBehavior(behavior);
}
SKWASM_EXPORT void paragraphStyle_setEllipsis(ParagraphStyle* style,
SkString* ellipsis) {
style->setEllipsis(*ellipsis);
}
SKWASM_EXPORT void paragraphStyle_setStrutStyle(ParagraphStyle* style,
StrutStyle* strutStyle) {
style->setStrutStyle(*strutStyle);
}
SKWASM_EXPORT void paragraphStyle_setTextStyle(ParagraphStyle* style,
TextStyle* textStyle) {
style->setTextStyle(*textStyle);
}
SKWASM_EXPORT void paragraphStyle_setApplyRoundingHack(ParagraphStyle* style,
bool applyRoundingHack) {
style->setApplyRoundingHack(applyRoundingHack);
}
| engine/lib/web_ui/skwasm/text/paragraph_style.cpp/0 | {
"file_path": "engine/lib/web_ui/skwasm/text/paragraph_style.cpp",
"repo_id": "engine",
"token_count": 1150
} | 262 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import 'common.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
const ui.Rect kDefaultRegion = ui.Rect.fromLTRB(0, 0, 500, 250);
void testMain() {
ui_web.debugEmulateFlutterTesterEnvironment = true;
group('flutter_tester emulation', () {
setUpCanvasKitTest(withImplicitView: true);
test('defaults to FlutterTest font family',
() async {
final CkPictureRecorder recorder = CkPictureRecorder();
final CkCanvas canvas = recorder.beginRecording(kDefaultRegion);
canvas.translate(10, 10);
void drawTextWithOutline(String text, {
String? paragraphFontFamily,
String? textFontFamily,
List<String>? textFontFallbacks,
String? strutStyleFontFamily,
List<String>? strutStyleFontFallbacks,
double? strutStyleFontSize,
}) {
final CkStrutStyle? strutStyle;
if (strutStyleFontFamily != null || strutStyleFontFallbacks != null || strutStyleFontSize != null) {
strutStyle = CkStrutStyle(
fontFamily: strutStyleFontFamily,
fontFamilyFallback: strutStyleFontFallbacks,
fontSize: strutStyleFontSize,
);
} else {
strutStyle = null;
}
final CkParagraphBuilder builder = CkParagraphBuilder(CkParagraphStyle(
fontFamily: paragraphFontFamily,
strutStyle: strutStyle,
));
final bool needsTextStyle = textFontFamily != null || textFontFallbacks != null;
if (needsTextStyle) {
builder.pushStyle(CkTextStyle(
fontFamily: textFontFamily,
fontFamilyFallback: textFontFallbacks,
));
}
builder.addText(text);
if (needsTextStyle) {
builder.pop();
}
final CkParagraph paragraph = builder.build();
paragraph.layout(const ui.ParagraphConstraints(width: 10000));
canvas.drawParagraph(paragraph, ui.Offset.zero);
canvas.drawRect(
ui.Rect.fromLTWH(-4, -4, paragraph.maxIntrinsicWidth + 8, paragraph.height + 8),
CkPaint()
..style = ui.PaintingStyle.stroke
..strokeWidth = 1,
);
canvas.translate(
0,
paragraph.height + 16,
);
}
drawTextWithOutline('default');
drawTextWithOutline(
'roboto paragraph',
paragraphFontFamily: 'Roboto',
);
drawTextWithOutline(
'roboto text',
textFontFamily: 'Roboto',
);
drawTextWithOutline(
'roboto text fallback',
textFontFallbacks: <String>['Roboto'],
);
drawTextWithOutline(
'roboto strut style',
strutStyleFontFamily: 'Roboto',
strutStyleFontSize: 40,
);
drawTextWithOutline(
'roboto strut style fallback',
strutStyleFontFallbacks: <String>['Roboto'],
strutStyleFontSize: 40,
);
await matchPictureGolden(
'canvaskit_defaults_to_ahem.png',
recorder.endRecording(),
region: kDefaultRegion,
);
});
// TODO(yjbanov): https://github.com/flutter/flutter/issues/71520
}, skip: isSafari || isFirefox);
}
| engine/lib/web_ui/test/canvaskit/flutter_tester_emulation_golden_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/canvaskit/flutter_tester_emulation_golden_test.dart",
"repo_id": "engine",
"token_count": 1532
} | 263 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:typed_data';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'common.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
group('PlatformDispatcher', () {
setUpCanvasKitTest();
test('responds to flutter/skia Skia.setResourceCacheMaxBytes', () async {
const MethodCodec codec = JSONMethodCodec();
final Completer<ByteData?> completer = Completer<ByteData?>();
ui.PlatformDispatcher.instance.sendPlatformMessage(
'flutter/skia',
codec.encodeMethodCall(const MethodCall(
'Skia.setResourceCacheMaxBytes',
512 * 1000 * 1000,
)),
completer.complete,
);
final ByteData? response = await completer.future;
expect(response, isNotNull);
expect(
codec.decodeEnvelope(response!),
<bool>[true],
);
});
});
}
| engine/lib/web_ui/test/canvaskit/platform_dispatcher_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/canvaskit/platform_dispatcher_test.dart",
"repo_id": "engine",
"token_count": 458
} | 264 |
// Copyright 2013 The Flutter 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:typed_data';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart';
/// Contains method name that was called on [MockEngineCanvas] and arguments
/// that were passed.
class MockCanvasCall {
MockCanvasCall._({
required this.methodName,
this.arguments,
});
final String methodName;
final dynamic arguments;
@override
String toString() {
return '$MockCanvasCall($methodName, $arguments)';
}
}
/// A fake implementation of [EngineCanvas] that logs calls to its methods but
/// doesn't actually paint anything.
///
/// Useful for testing interactions between upper layers of the system with
/// canvases.
class MockEngineCanvas implements EngineCanvas {
final List<MockCanvasCall> methodCallLog = <MockCanvasCall>[];
@override
DomElement get rootElement => _rootElement;
final DomElement _rootElement = createDomHTMLDivElement();
void _called(String methodName, {dynamic arguments}) {
methodCallLog.add(MockCanvasCall._(
methodName: methodName,
arguments: arguments,
));
}
@override
void dispose() {
_called('dispose');
}
@override
void clear() {
_called('clear');
}
@override
void save() {
_called('save');
}
@override
void restore() {
_called('restore');
}
@override
void translate(double dx, double dy) {
_called('translate', arguments: <String, double>{
'dx': dx,
'dy': dy,
});
}
@override
void scale(double sx, double sy) {
_called('scale', arguments: <String, double>{
'sx': sx,
'sy': sy,
});
}
@override
void rotate(double radians) {
_called('rotate', arguments: radians);
}
@override
void skew(double sx, double sy) {
_called('skew', arguments: <String, double>{
'sx': sx,
'sy': sy,
});
}
@override
void transform(Float32List matrix4) {
_called('transform', arguments: matrix4);
}
@override
void clipRect(Rect rect, ClipOp op) {
_called('clipRect', arguments: rect);
}
@override
void clipRRect(RRect rrect) {
_called('clipRRect', arguments: rrect);
}
@override
void clipPath(Path path) {
_called('clipPath', arguments: path);
}
@override
void drawColor(Color color, BlendMode blendMode) {
_called('drawColor', arguments: <String, dynamic>{
'color': color,
'blendMode': blendMode,
});
}
@override
void drawLine(Offset p1, Offset p2, SurfacePaintData paint) {
_called('drawLine', arguments: <String, dynamic>{
'p1': p1,
'p2': p2,
'paint': paint,
});
}
@override
void drawPaint(SurfacePaintData paint) {
_called('drawPaint', arguments: paint);
}
@override
void drawRect(Rect rect, SurfacePaintData paint) {
_called('drawRect', arguments: <String, dynamic>{
'rect': rect,
'paint': paint,
});
}
@override
void drawRRect(RRect rrect, SurfacePaintData paint) {
_called('drawRRect', arguments: <String, dynamic>{
'rrect': rrect,
'paint': paint,
});
}
@override
void drawDRRect(RRect outer, RRect inner, SurfacePaintData paint) {
_called('drawDRRect', arguments: <String, dynamic>{
'outer': outer,
'inner': inner,
'paint': paint,
});
}
@override
void drawOval(Rect rect, SurfacePaintData paint) {
_called('drawOval', arguments: <String, dynamic>{
'rect': rect,
'paint': paint,
});
}
@override
void drawCircle(Offset c, double radius, SurfacePaintData paint) {
_called('drawCircle', arguments: <String, dynamic>{
'c': c,
'radius': radius,
'paint': paint,
});
}
@override
void drawPath(Path path, SurfacePaintData paint) {
_called('drawPath', arguments: <String, dynamic>{
'path': path,
'paint': paint,
});
}
@override
void drawShadow(
Path path, Color color, double elevation, bool transparentOccluder) {
_called('drawShadow', arguments: <String, dynamic>{
'path': path,
'color': color,
'elevation': elevation,
'transparentOccluder': transparentOccluder,
});
}
@override
void drawImage(Image image, Offset p, SurfacePaintData paint) {
_called('drawImage', arguments: <String, dynamic>{
'image': image,
'p': p,
'paint': paint,
});
}
@override
void drawImageRect(Image image, Rect src, Rect dst, SurfacePaintData paint) {
_called('drawImageRect', arguments: <String, dynamic>{
'image': image,
'src': src,
'dst': dst,
'paint': paint,
});
}
@override
void drawParagraph(Paragraph paragraph, Offset offset) {
_called('drawParagraph', arguments: <String, dynamic>{
'paragraph': paragraph,
'offset': offset,
});
}
@override
void drawVertices(
Vertices vertices, BlendMode blendMode, SurfacePaintData paint) {
_called('drawVertices', arguments: <String, dynamic>{
'vertices': vertices,
'blendMode': blendMode,
'paint': paint,
});
}
@override
void drawPoints(PointMode pointMode, Float32List points, SurfacePaintData paint) {
_called('drawPoints', arguments: <String, dynamic>{
'pointMode': pointMode,
'points': points,
'paint': paint,
});
}
@override
void endOfPaint() {
_called('endOfPaint', arguments: <String, dynamic>{});
}
}
| engine/lib/web_ui/test/common/mock_engine_canvas.dart/0 | {
"file_path": "engine/lib/web_ui/test/common/mock_engine_canvas.dart",
"repo_id": "engine",
"token_count": 2097
} | 265 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This is testing some of the named constants.
// ignore_for_file: use_named_constants
import 'dart:math' as math show sqrt;
import 'dart:math' show pi;
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/ui.dart';
import '../common/matchers.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
test('Offset.direction', () {
expect(const Offset(0.0, 0.0).direction, 0.0);
expect(const Offset(0.0, 1.0).direction, pi / 2.0);
expect(const Offset(0.0, -1.0).direction, -pi / 2.0);
expect(const Offset(1.0, 0.0).direction, 0.0);
expect(const Offset(1.0, 1.0).direction, pi / 4.0);
expect(const Offset(1.0, -1.0).direction, -pi / 4.0);
expect(const Offset(-1.0, 0.0).direction, pi);
expect(const Offset(-1.0, 1.0).direction, pi * 3.0 / 4.0);
expect(const Offset(-1.0, -1.0).direction, -pi * 3.0 / 4.0);
});
test('Offset.fromDirection', () {
expect(Offset.fromDirection(0.0, 0.0), const Offset(0.0, 0.0));
// aah, floating point math. i love you so.
expect(Offset.fromDirection(pi / 2.0), within(from: const Offset(0.0, 1.0)));
expect(Offset.fromDirection(-pi / 2.0), within(from: const Offset(0.0, -1.0)));
expect(Offset.fromDirection(0.0), const Offset(1.0, 0.0));
expect(
Offset.fromDirection(pi / 4.0),
within(from: Offset(1.0 / math.sqrt(2.0), 1.0 / math.sqrt(2.0))),
);
expect(
Offset.fromDirection(-pi / 4.0),
within(from: Offset(1.0 / math.sqrt(2.0), -1.0 / math.sqrt(2.0))),
);
expect(Offset.fromDirection(pi), within(from: const Offset(-1.0, 0.0)));
expect(
Offset.fromDirection(pi * 3.0 / 4.0),
within(from: Offset(-1.0 / math.sqrt(2.0), 1.0 / math.sqrt(2.0))),
);
expect(
Offset.fromDirection(-pi * 3.0 / 4.0),
within(from: Offset(-1.0 / math.sqrt(2.0), -1.0 / math.sqrt(2.0))),
);
expect(Offset.fromDirection(0.0, 2.0), const Offset(2.0, 0.0));
expect(
Offset.fromDirection(pi / 6, 2.0),
within(from: Offset(math.sqrt(3.0), 1.0)),
);
});
test('Size.aspectRatio', () {
expect(const Size(0.0, 0.0).aspectRatio, 0.0);
expect(const Size(-0.0, 0.0).aspectRatio, 0.0);
expect(const Size(0.0, -0.0).aspectRatio, 0.0);
expect(const Size(-0.0, -0.0).aspectRatio, 0.0);
expect(const Size(0.0, 1.0).aspectRatio, 0.0);
expect(const Size(0.0, -1.0).aspectRatio, -0.0);
expect(const Size(1.0, 0.0).aspectRatio, double.infinity);
expect(const Size(1.0, 1.0).aspectRatio, 1.0);
expect(const Size(1.0, -1.0).aspectRatio, -1.0);
expect(const Size(-1.0, 0.0).aspectRatio, -double.infinity);
expect(const Size(-1.0, 1.0).aspectRatio, -1.0);
expect(const Size(-1.0, -1.0).aspectRatio, 1.0);
expect(const Size(3.0, 4.0).aspectRatio, 3.0 / 4.0);
});
test('Radius.clamp() operates as expected', () {
final RRect rrectMin = RRect.fromLTRBR(1, 3, 5, 7,
const Radius.circular(-100).clamp(minimum: Radius.zero));
expect(rrectMin.left, 1);
expect(rrectMin.top, 3);
expect(rrectMin.right, 5);
expect(rrectMin.bottom, 7);
expect(rrectMin.trRadius, equals(const Radius.circular(0)));
expect(rrectMin.blRadius, equals(const Radius.circular(0)));
final RRect rrectMax = RRect.fromLTRBR(1, 3, 5, 7,
const Radius.circular(100).clamp(maximum: const Radius.circular(10)));
expect(rrectMax.left, 1);
expect(rrectMax.top, 3);
expect(rrectMax.right, 5);
expect(rrectMax.bottom, 7);
expect(rrectMax.trRadius, equals(const Radius.circular(10)));
expect(rrectMax.blRadius, equals(const Radius.circular(10)));
final RRect rrectMix = RRect.fromLTRBR(1, 3, 5, 7,
const Radius.elliptical(-100, 100).clamp(minimum: Radius.zero, maximum: const Radius.circular(10)));
expect(rrectMix.left, 1);
expect(rrectMix.top, 3);
expect(rrectMix.right, 5);
expect(rrectMix.bottom, 7);
expect(rrectMix.trRadius, equals(const Radius.elliptical(0, 10)));
expect(rrectMix.blRadius, equals(const Radius.elliptical(0, 10)));
final RRect rrectMix1 = RRect.fromLTRBR(1, 3, 5, 7,
const Radius.elliptical(100, -100).clamp(minimum: Radius.zero, maximum: const Radius.circular(10)));
expect(rrectMix1.left, 1);
expect(rrectMix1.top, 3);
expect(rrectMix1.right, 5);
expect(rrectMix1.bottom, 7);
expect(rrectMix1.trRadius, equals(const Radius.elliptical(10, 0)));
expect(rrectMix1.blRadius, equals(const Radius.elliptical(10, 0)));
});
test('Radius.clampValues() operates as expected', () {
final RRect rrectMin = RRect.fromLTRBR(1, 3, 5, 7,
const Radius.circular(-100).clampValues(minimumX: 0, minimumY: 0));
expect(rrectMin.left, 1);
expect(rrectMin.top, 3);
expect(rrectMin.right, 5);
expect(rrectMin.bottom, 7);
expect(rrectMin.trRadius, equals(const Radius.circular(0)));
expect(rrectMin.blRadius, equals(const Radius.circular(0)));
final RRect rrectMax = RRect.fromLTRBR(1, 3, 5, 7,
const Radius.circular(100).clampValues(maximumX: 10, maximumY: 20));
expect(rrectMax.left, 1);
expect(rrectMax.top, 3);
expect(rrectMax.right, 5);
expect(rrectMax.bottom, 7);
expect(rrectMax.trRadius, equals(const Radius.elliptical(10, 20)));
expect(rrectMax.blRadius, equals(const Radius.elliptical(10, 20)));
final RRect rrectMix = RRect.fromLTRBR(1, 3, 5, 7,
const Radius.elliptical(-100, 100).clampValues(minimumX: 5, minimumY: 6, maximumX: 10, maximumY: 20));
expect(rrectMix.left, 1);
expect(rrectMix.top, 3);
expect(rrectMix.right, 5);
expect(rrectMix.bottom, 7);
expect(rrectMix.trRadius, equals(const Radius.elliptical(5, 20)));
expect(rrectMix.blRadius, equals(const Radius.elliptical(5, 20)));
final RRect rrectMix2 = RRect.fromLTRBR(1, 3, 5, 7,
const Radius.elliptical(100, -100).clampValues(minimumX: 5, minimumY: 6, maximumX: 10, maximumY: 20));
expect(rrectMix2.left, 1);
expect(rrectMix2.top, 3);
expect(rrectMix2.right, 5);
expect(rrectMix2.bottom, 7);
expect(rrectMix2.trRadius, equals(const Radius.elliptical(10, 6)));
expect(rrectMix2.blRadius, equals(const Radius.elliptical(10, 6)));
});
test('RRect asserts when corner radii are negative', () {
bool assertsEnabled = false;
assert(() {
assertsEnabled = true;
return true;
}());
if (!assertsEnabled) {
return;
}
expect(() {
RRect.fromRectAndCorners(
const Rect.fromLTRB(10.0, 20.0, 30.0, 40.0),
topLeft: const Radius.circular(-1),
);
}, throwsA(isA<AssertionError>()));
expect(() {
RRect.fromRectAndCorners(
const Rect.fromLTRB(10.0, 20.0, 30.0, 40.0),
topRight: const Radius.circular(-2),
);
}, throwsA(isA<AssertionError>()));
expect(() {
RRect.fromRectAndCorners(
const Rect.fromLTRB(10.0, 20.0, 30.0, 40.0),
bottomLeft: const Radius.circular(-3),
);
}, throwsA(isA<AssertionError>()));
expect(() {
RRect.fromRectAndCorners(
const Rect.fromLTRB(10.0, 20.0, 30.0, 40.0),
bottomRight: const Radius.circular(-4),
);
}, throwsA(isA<AssertionError>()));
});
test('RRect.inflate clamps when deflating past zero', () {
RRect rrect = RRect.fromRectAndCorners(
const Rect.fromLTRB(10.0, 20.0, 30.0, 40.0),
topLeft: const Radius.circular(1),
topRight: const Radius.circular(2),
bottomLeft: const Radius.circular(3),
bottomRight: const Radius.circular(4),
).inflate(-1);
expect(rrect.tlRadiusX, 0);
expect(rrect.tlRadiusY, 0);
expect(rrect.trRadiusX, 1);
expect(rrect.trRadiusY, 1);
expect(rrect.blRadiusX, 2);
expect(rrect.blRadiusY, 2);
expect(rrect.brRadiusX, 3);
expect(rrect.brRadiusY, 3);
rrect = rrect.inflate(-1);
expect(rrect.tlRadiusX, 0);
expect(rrect.tlRadiusY, 0);
expect(rrect.trRadiusX, 0);
expect(rrect.trRadiusY, 0);
expect(rrect.blRadiusX, 1);
expect(rrect.blRadiusY, 1);
expect(rrect.brRadiusX, 2);
expect(rrect.brRadiusY, 2);
rrect = rrect.inflate(-1);
expect(rrect.tlRadiusX, 0);
expect(rrect.tlRadiusY, 0);
expect(rrect.trRadiusX, 0);
expect(rrect.trRadiusY, 0);
expect(rrect.blRadiusX, 0);
expect(rrect.blRadiusY, 0);
expect(rrect.brRadiusX, 1);
expect(rrect.brRadiusY, 1);
rrect = rrect.inflate(-1);
expect(rrect.tlRadiusX, 0);
expect(rrect.tlRadiusY, 0);
expect(rrect.trRadiusX, 0);
expect(rrect.trRadiusY, 0);
expect(rrect.blRadiusX, 0);
expect(rrect.blRadiusY, 0);
expect(rrect.brRadiusX, 0);
expect(rrect.brRadiusY, 0);
});
test('RRect.deflate clamps when deflating past zero', () {
RRect rrect = RRect.fromRectAndCorners(
const Rect.fromLTRB(10.0, 20.0, 30.0, 40.0),
topLeft: const Radius.circular(1),
topRight: const Radius.circular(2),
bottomLeft: const Radius.circular(3),
bottomRight: const Radius.circular(4),
).deflate(1);
expect(rrect.tlRadiusX, 0);
expect(rrect.tlRadiusY, 0);
expect(rrect.trRadiusX, 1);
expect(rrect.trRadiusY, 1);
expect(rrect.blRadiusX, 2);
expect(rrect.blRadiusY, 2);
expect(rrect.brRadiusX, 3);
expect(rrect.brRadiusY, 3);
rrect = rrect.deflate(1);
expect(rrect.tlRadiusX, 0);
expect(rrect.tlRadiusY, 0);
expect(rrect.trRadiusX, 0);
expect(rrect.trRadiusY, 0);
expect(rrect.blRadiusX, 1);
expect(rrect.blRadiusY, 1);
expect(rrect.brRadiusX, 2);
expect(rrect.brRadiusY, 2);
rrect = rrect.deflate(1);
expect(rrect.tlRadiusX, 0);
expect(rrect.tlRadiusY, 0);
expect(rrect.trRadiusX, 0);
expect(rrect.trRadiusY, 0);
expect(rrect.blRadiusX, 0);
expect(rrect.blRadiusY, 0);
expect(rrect.brRadiusX, 1);
expect(rrect.brRadiusY, 1);
rrect = rrect.deflate(1);
expect(rrect.tlRadiusX, 0);
expect(rrect.tlRadiusY, 0);
expect(rrect.trRadiusX, 0);
expect(rrect.trRadiusY, 0);
expect(rrect.blRadiusX, 0);
expect(rrect.blRadiusY, 0);
expect(rrect.brRadiusX, 0);
expect(rrect.brRadiusY, 0);
});
}
| engine/lib/web_ui/test/engine/geometry_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/geometry_test.dart",
"repo_id": "engine",
"token_count": 4686
} | 266 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:typed_data';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import '../common/test_initialization.dart';
const MethodCodec codec = JSONMethodCodec();
EngineFlutterWindow get implicitView =>
EnginePlatformDispatcher.instance.implicitView!;
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
group('without implicit view', () {
test('Handles navigation gracefully when no implicit view exists', () async {
expect(EnginePlatformDispatcher.instance.implicitView, isNull);
final Completer<ByteData?> completer = Completer<ByteData?>();
ui.PlatformDispatcher.instance.sendPlatformMessage(
'flutter/navigation',
codec.encodeMethodCall(const MethodCall(
'routeUpdated',
<String, dynamic>{'routeName': '/foo'},
)),
(ByteData? response) => completer.complete(response),
);
final ByteData? response = await completer.future;
expect(response, isNull);
});
});
group('with implicit view', () {
late TestUrlStrategy strategy;
setUpAll(() async {
await bootstrapAndRunApp(withImplicitView: true);
});
setUp(() async {
strategy = TestUrlStrategy();
await implicitView.debugInitializeHistory(strategy, useSingle: true);
});
tearDown(() async {
await implicitView.resetHistory();
});
test('Tracks pushed, replaced and popped routes', () async {
final Completer<void> completer = Completer<void>();
ui.PlatformDispatcher.instance.sendPlatformMessage(
'flutter/navigation',
codec.encodeMethodCall(const MethodCall(
'routeUpdated',
<String, dynamic>{'routeName': '/foo'},
)),
(_) => completer.complete(),
);
await completer.future;
expect(strategy.getPath(), '/foo');
});
});
}
| engine/lib/web_ui/test/engine/navigation_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/navigation_test.dart",
"repo_id": "engine",
"token_count": 794
} | 267 |
// Copyright 2013 The Flutter 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:js_interop';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart';
import '../common/test_initialization.dart';
import 'scene_builder_utils.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
class StubPictureRenderer implements PictureRenderer {
final DomCanvasElement scratchCanvasElement =
createDomCanvasElement(width: 500, height: 500);
@override
Future<RenderResult> renderPictures(List<ScenePicture> pictures) async {
renderedPictures.addAll(pictures);
final List<DomImageBitmap> bitmaps = await Future.wait(pictures.map((ScenePicture picture) {
final ui.Rect cullRect = picture.cullRect;
final Future<DomImageBitmap> bitmap = createImageBitmap(scratchCanvasElement as JSObject, (
x: 0,
y: 0,
width: cullRect.width.toInt(),
height: cullRect.height.toInt(),
));
return bitmap;
}));
return (
imageBitmaps: bitmaps,
rasterStartMicros: 0,
rasterEndMicros: 0,
);
}
@override
ScenePicture clipPicture(ScenePicture picture, ui.Rect clip) {
clipRequests[picture] = clip;
return picture;
}
List<ScenePicture> renderedPictures = <ScenePicture>[];
Map<ScenePicture, ui.Rect> clipRequests = <ScenePicture, ui.Rect>{};
}
class StubFlutterView implements ui.FlutterView {
@override
double get devicePixelRatio => throw UnimplementedError();
@override
ui.Display get display => throw UnimplementedError();
@override
List<ui.DisplayFeature> get displayFeatures => throw UnimplementedError();
@override
ui.GestureSettings get gestureSettings => throw UnimplementedError();
@override
ui.ViewPadding get padding => throw UnimplementedError();
@override
ui.ViewConstraints get physicalConstraints => throw UnimplementedError();
@override
ui.Size get physicalSize => const ui.Size(1000, 1000);
@override
ui.PlatformDispatcher get platformDispatcher => throw UnimplementedError();
@override
void render(ui.Scene scene, {ui.Size? size}) {
}
@override
ui.ViewPadding get systemGestureInsets => throw UnimplementedError();
@override
void updateSemantics(ui.SemanticsUpdate update) {
}
@override
int get viewId => throw UnimplementedError();
@override
ui.ViewPadding get viewInsets => throw UnimplementedError();
@override
ui.ViewPadding get viewPadding => throw UnimplementedError();
}
void testMain() {
late EngineSceneView sceneView;
late StubPictureRenderer stubPictureRenderer;
setUpAll(() async {
await bootstrapAndRunApp(withImplicitView: true);
});
setUp(() {
stubPictureRenderer = StubPictureRenderer();
sceneView = EngineSceneView(stubPictureRenderer, StubFlutterView());
});
test('SceneView places canvas according to device-pixel ratio', () async {
debugOverrideDevicePixelRatio(2.0);
final StubPicture picture = StubPicture(const ui.Rect.fromLTWH(
50,
80,
100,
120,
));
final EngineRootLayer rootLayer = EngineRootLayer();
rootLayer.slices.add(PictureSlice(picture));
final EngineScene scene = EngineScene(rootLayer);
await sceneView.renderScene(scene, null);
final DomElement sceneElement = sceneView.sceneElement;
final List<DomElement> children = sceneElement.children.toList();
expect(children.length, 1);
final DomElement containerElement = children.first;
expect(
containerElement.tagName, equalsIgnoringCase('flt-canvas-container'));
final List<DomElement> containerChildren =
containerElement.children.toList();
expect(containerChildren.length, 1);
final DomElement canvasElement = containerChildren.first;
final DomCSSStyleDeclaration style = canvasElement.style;
expect(style.left, '25px');
expect(style.top, '40px');
expect(style.width, '50px');
expect(style.height, '60px');
debugOverrideDevicePixelRatio(null);
});
test('SceneView places platform view according to device-pixel ratio',
() async {
debugOverrideDevicePixelRatio(2.0);
final PlatformView platformView = PlatformView(
1,
const ui.Size(100, 120),
const PlatformViewStyling(
position: PlatformViewPosition.offset(ui.Offset(50, 80)),
));
final EngineRootLayer rootLayer = EngineRootLayer();
rootLayer.slices.add(PlatformViewSlice(<PlatformView>[platformView], null));
final EngineScene scene = EngineScene(rootLayer);
await sceneView.renderScene(scene, null);
final DomElement sceneElement = sceneView.sceneElement;
final List<DomElement> children = sceneElement.children.toList();
expect(children.length, 1);
final DomElement containerElement = children.first;
expect(
containerElement.tagName, equalsIgnoringCase('flt-platform-view-slot'));
final DomCSSStyleDeclaration style = containerElement.style;
expect(style.left, '25px');
expect(style.top, '40px');
expect(style.width, '50px');
expect(style.height, '60px');
debugOverrideDevicePixelRatio(null);
});
test(
'SceneView always renders most recent picture and skips intermediate pictures',
() async {
final List<StubPicture> pictures = <StubPicture>[];
final List<Future<void>> renderFutures = <Future<void>>[];
for (int i = 1; i < 20; i++) {
final StubPicture picture = StubPicture(const ui.Rect.fromLTWH(
50,
80,
100,
120,
));
pictures.add(picture);
final EngineRootLayer rootLayer = EngineRootLayer();
rootLayer.slices.add(PictureSlice(picture));
final EngineScene scene = EngineScene(rootLayer);
renderFutures.add(sceneView.renderScene(scene, null));
}
await Future.wait(renderFutures);
// Should just render the first and last pictures and skip the one inbetween.
expect(stubPictureRenderer.renderedPictures.length, 2);
expect(stubPictureRenderer.renderedPictures.first, pictures.first);
expect(stubPictureRenderer.renderedPictures.last, pictures.last);
});
test('SceneView clips pictures that are outside the window screen', () async {
final StubPicture picture = StubPicture(const ui.Rect.fromLTWH(
-50,
-50,
100,
120,
));
final EngineRootLayer rootLayer = EngineRootLayer();
rootLayer.slices.add(PictureSlice(picture));
final EngineScene scene = EngineScene(rootLayer);
await sceneView.renderScene(scene, null);
expect(stubPictureRenderer.renderedPictures.length, 1);
expect(stubPictureRenderer.clipRequests.containsKey(picture), true);
});
}
| engine/lib/web_ui/test/engine/scene_view_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/scene_view_test.dart",
"repo_id": "engine",
"token_count": 2418
} | 268 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@TestOn('chrome || firefox')
library;
import 'dart:async';
import 'dart:js_interop';
import 'dart:js_util' as js_util;
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import '../../common/matchers.dart';
import '../../common/rendering.dart';
import '../../common/test_initialization.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
setUpAll(() async {
await bootstrapAndRunApp(withImplicitView: true);
setUpRenderingForTests();
});
group('SceneBuilder', () {
test('pushOffset implements surface lifecycle', () {
testLayerLifeCycle((ui.SceneBuilder sceneBuilder, ui.EngineLayer? oldLayer) {
return sceneBuilder.pushOffset(10, 20, oldLayer: oldLayer as ui.OffsetEngineLayer?);
}, () {
return '''<s><flt-offset></flt-offset></s>''';
});
});
test('pushTransform implements surface lifecycle', () {
testLayerLifeCycle((ui.SceneBuilder sceneBuilder, ui.EngineLayer? oldLayer) {
return sceneBuilder.pushTransform(
(Matrix4.identity()..scale(EngineFlutterDisplay.instance.browserDevicePixelRatio)).toFloat64());
}, () {
return '''<s><flt-transform></flt-transform></s>''';
});
});
test('pushClipRect implements surface lifecycle', () {
testLayerLifeCycle((ui.SceneBuilder sceneBuilder, ui.EngineLayer? oldLayer) {
return sceneBuilder.pushClipRect(const ui.Rect.fromLTRB(10, 20, 30, 40),
oldLayer: oldLayer as ui.ClipRectEngineLayer?);
}, () {
return '''
<s>
<clip><clip-i></clip-i></clip>
</s>
''';
});
});
test('pushClipRRect implements surface lifecycle', () {
testLayerLifeCycle((ui.SceneBuilder sceneBuilder, ui.EngineLayer? oldLayer) {
return sceneBuilder.pushClipRRect(
ui.RRect.fromLTRBR(10, 20, 30, 40, const ui.Radius.circular(3)),
oldLayer: oldLayer as ui.ClipRRectEngineLayer?,
clipBehavior: ui.Clip.none);
}, () {
return '''
<s>
<rclip><clip-i></clip-i></rclip>
</s>
''';
});
});
test('pushClipPath implements surface lifecycle', () {
testLayerLifeCycle((ui.SceneBuilder sceneBuilder, ui.EngineLayer? oldLayer) {
final ui.Path path = ui.Path()..addRect(const ui.Rect.fromLTRB(10, 20, 30, 40));
return sceneBuilder.pushClipPath(path, oldLayer: oldLayer as ui.ClipPathEngineLayer?);
}, () {
return '''
<s>
<flt-clippath>
<svg><defs><clipPath><path></path></clipPath></defs></svg>
</flt-clippath>
</s>
''';
});
});
test('pushOpacity implements surface lifecycle', () {
testLayerLifeCycle((ui.SceneBuilder sceneBuilder, ui.EngineLayer? oldLayer) {
return sceneBuilder.pushOpacity(10, oldLayer: oldLayer as ui.OpacityEngineLayer?);
}, () {
return '''<s><o></o></s>''';
});
});
test('pushBackdropFilter implements surface lifecycle', () {
testLayerLifeCycle((ui.SceneBuilder sceneBuilder, ui.EngineLayer? oldLayer) {
return sceneBuilder.pushBackdropFilter(
ui.ImageFilter.blur(sigmaX: 1.0, sigmaY: 1.0),
oldLayer: oldLayer as ui.BackdropFilterEngineLayer?,
);
}, () {
return '<s><flt-backdrop>'
'<flt-backdrop-filter></flt-backdrop-filter>'
'<flt-backdrop-interior></flt-backdrop-interior>'
'</flt-backdrop></s>';
});
});
});
group('parent child lifecycle', () {
test(
'build, retain, update, and applyPaint are called the right number of times',
() {
final PersistedScene scene1 = PersistedScene(null);
final PersistedClipRect clip1 =
PersistedClipRect(null, const ui.Rect.fromLTRB(10, 10, 20, 20),
ui.Clip.antiAlias);
final PersistedOpacity opacity = PersistedOpacity(null, 100, ui.Offset.zero);
final MockPersistedPicture picture = MockPersistedPicture();
scene1.appendChild(clip1);
clip1.appendChild(opacity);
opacity.appendChild(picture);
expect(picture.retainCount, 0);
expect(picture.buildCount, 0);
expect(picture.updateCount, 0);
expect(picture.applyPaintCount, 0);
scene1.preroll(PrerollSurfaceContext());
scene1.build();
commitScene(scene1);
expect(picture.retainCount, 0);
expect(picture.buildCount, 1);
expect(picture.updateCount, 0);
expect(picture.applyPaintCount, 1);
// The second scene graph retains the opacity, but not the clip. However,
// because the clip didn't change no repaints should happen.
final PersistedScene scene2 = PersistedScene(scene1);
final PersistedClipRect clip2 =
PersistedClipRect(clip1, const ui.Rect.fromLTRB(10, 10, 20, 20),
ui.Clip.antiAlias);
clip1.state = PersistedSurfaceState.pendingUpdate;
scene2.appendChild(clip2);
opacity.state = PersistedSurfaceState.pendingRetention;
clip2.appendChild(opacity);
scene2.preroll(PrerollSurfaceContext());
scene2.update(scene1);
commitScene(scene2);
expect(picture.retainCount, 1);
expect(picture.buildCount, 1);
expect(picture.updateCount, 0);
expect(picture.applyPaintCount, 1);
// The third scene graph retains the opacity, and produces a new clip.
// This should cause the picture to repaint despite being retained.
final PersistedScene scene3 = PersistedScene(scene2);
final PersistedClipRect clip3 =
PersistedClipRect(clip2, const ui.Rect.fromLTRB(10, 10, 50, 50),
ui.Clip.antiAlias);
clip2.state = PersistedSurfaceState.pendingUpdate;
scene3.appendChild(clip3);
opacity.state = PersistedSurfaceState.pendingRetention;
clip3.appendChild(opacity);
scene3.preroll(PrerollSurfaceContext());
scene3.update(scene2);
commitScene(scene3);
expect(picture.retainCount, 2);
expect(picture.buildCount, 1);
expect(picture.updateCount, 0);
expect(picture.applyPaintCount, 2);
}, // TODO(yjbanov): https://github.com/flutter/flutter/issues/46638
skip: browserEngine == BrowserEngine.firefox);
});
group('Compositing order', () {
// Regression test for https://github.com/flutter/flutter/issues/55058
//
// When BitmapCanvas uses multiple elements to paint, the very first
// canvas needs to have a -1 zIndex so it can preserve compositing order.
test('Canvas element should retain -1 zIndex after update', () async {
final SurfaceSceneBuilder builder = SurfaceSceneBuilder();
final ui.Picture picture1 = _drawPicture();
final ui.ClipRectEngineLayer oldLayer = builder.pushClipRect(
const ui.Rect.fromLTRB(10, 10, 300, 300),
);
builder.addPicture(ui.Offset.zero, picture1);
builder.pop();
final DomElement content = builder.build().webOnlyRootElement!;
expect(content.querySelector('canvas')!.style.zIndex, '-1');
// Force update to scene which will utilize reuse code path.
final SurfaceSceneBuilder builder2 = SurfaceSceneBuilder();
builder2.pushClipRect(
const ui.Rect.fromLTRB(5, 10, 300, 300),
oldLayer: oldLayer
);
final ui.Picture picture2 = _drawPicture();
builder2.addPicture(ui.Offset.zero, picture2);
builder2.pop();
final DomElement contentAfterReuse = builder2.build().webOnlyRootElement!;
expect(contentAfterReuse.querySelector('canvas')!.style.zIndex, '-1');
});
test('Multiple canvas elements should retain zIndex after update', () async {
final SurfaceSceneBuilder builder = SurfaceSceneBuilder();
final ui.Picture picture1 = _drawPathImagePath();
final ui.ClipRectEngineLayer oldLayer = builder.pushClipRect(
const ui.Rect.fromLTRB(10, 10, 300, 300),
);
builder.addPicture(ui.Offset.zero, picture1);
builder.pop();
final DomElement content = builder.build().webOnlyRootElement!;
domDocument.body!.append(content);
expect(content.querySelector('canvas')!.style.zIndex, '-1');
// Force update to scene which will utilize reuse code path.
final SurfaceSceneBuilder builder2 = SurfaceSceneBuilder();
builder2.pushClipRect(
const ui.Rect.fromLTRB(5, 10, 300, 300),
oldLayer: oldLayer
);
final ui.Picture picture2 = _drawPathImagePath();
builder2.addPicture(ui.Offset.zero, picture2);
builder2.pop();
final DomElement contentAfterReuse = builder2.build().webOnlyRootElement!;
final List<DomCanvasElement> list =
contentAfterReuse.querySelectorAll('canvas').cast<DomCanvasElement>().toList();
expect(list[0].style.zIndex, '-1');
expect(list[1].style.zIndex, '');
});
});
/// Verify elementCache is passed during update to reuse existing
/// image elements.
test('Should retain same image element', () async {
final SurfaceSceneBuilder builder = SurfaceSceneBuilder();
final ui.Picture picture1 = _drawPathImagePath();
final ui.ClipRectEngineLayer oldLayer = builder.pushClipRect(
const ui.Rect.fromLTRB(10, 10, 300, 300),
);
builder.addPicture(ui.Offset.zero, picture1);
builder.pop();
final DomElement content = builder.build().webOnlyRootElement!;
domDocument.body!.append(content);
List<DomHTMLImageElement> list =
content.querySelectorAll('img').cast<DomHTMLImageElement>().toList();
for (final DomHTMLImageElement image in list) {
image.alt = 'marked';
}
// Force update to scene which will utilize reuse code path.
final SurfaceSceneBuilder builder2 = SurfaceSceneBuilder();
builder2.pushClipRect(
const ui.Rect.fromLTRB(5, 10, 300, 300),
oldLayer: oldLayer
);
final ui.Picture picture2 = _drawPathImagePath();
builder2.addPicture(ui.Offset.zero, picture2);
builder2.pop();
final DomElement contentAfterReuse = builder2.build().webOnlyRootElement!;
list =
contentAfterReuse.querySelectorAll('img').cast<DomHTMLImageElement>().toList();
for (final DomHTMLImageElement image in list) {
expect(image.alt, 'marked');
}
expect(list.length, 1);
});
PersistedPicture? findPictureSurfaceChild(PersistedContainerSurface parent) {
PersistedPicture? pictureSurface;
parent.visitChildren((PersistedSurface child) {
pictureSurface = child as PersistedPicture;
});
return pictureSurface;
}
test('skips painting picture when picture fully clipped out', () async {
final ui.Picture picture = _drawPicture();
// Picture not clipped out, so we should see a `<flt-canvas>`
{
final SurfaceSceneBuilder builder = SurfaceSceneBuilder();
builder.pushOffset(0, 0);
builder.addPicture(ui.Offset.zero, picture);
builder.pop();
final DomElement content = builder.build().webOnlyRootElement!;
expect(content.querySelectorAll('flt-picture').single.children, isNotEmpty);
}
// Picture fully clipped out, so we should not see a `<flt-canvas>`
{
final SurfaceSceneBuilder builder = SurfaceSceneBuilder();
builder.pushOffset(0, 0);
final PersistedContainerSurface clip = builder.pushClipRect(const ui.Rect.fromLTRB(1000, 1000, 2000, 2000)) as PersistedContainerSurface;
builder.addPicture(ui.Offset.zero, picture);
builder.pop();
builder.pop();
final DomElement content = builder.build().webOnlyRootElement!;
expect(content.querySelectorAll('flt-picture').single.children, isEmpty);
expect(findPictureSurfaceChild(clip)!.canvas, isNull);
}
});
test('does not skip painting picture when picture is '
'inside transform with offset', () async {
final ui.Picture picture = _drawPicture();
// Picture should not be clipped out since transform will offset it to 500,500
final SurfaceSceneBuilder builder = SurfaceSceneBuilder();
builder.pushOffset(0, 0);
builder.pushClipRect(const ui.Rect.fromLTRB(0, 0, 1000, 1000)) as PersistedContainerSurface;
builder.pushTransform((Matrix4.identity()..scale(0.5, 0.5)).toFloat64());
builder.addPicture(const ui.Offset(1000, 1000), picture);
builder.pop();
builder.pop();
builder.pop();
final DomElement content = builder.build().webOnlyRootElement!;
expect(content.querySelectorAll('flt-picture').single.children, isNotEmpty);
});
test('does not skip painting picture when picture is '
'inside transform', () async {
final ui.Picture picture = _drawPicture();
// Picture should not be clipped out since transform will offset it to 500,500
final SurfaceSceneBuilder builder = SurfaceSceneBuilder();
builder.pushOffset(0, 0);
builder.pushClipRect(const ui.Rect.fromLTRB(0, 0, 1000, 1000)) as PersistedContainerSurface;
builder.pushTransform((Matrix4.identity()..scale(0.5, 0.5)).toFloat64());
builder.pushOffset(1000, 1000);
builder.addPicture(ui.Offset.zero, picture);
builder.pop();
builder.pop();
builder.pop();
final DomElement content = builder.build().webOnlyRootElement!;
expect(content.querySelectorAll('flt-picture').single.children, isNotEmpty);
});
test(
'skips painting picture when picture fully clipped out with'
' transform and offset', () async {
final ui.Picture picture = _drawPicture();
// Picture should be clipped out since transform will offset it to 500,500
final SurfaceSceneBuilder builder = SurfaceSceneBuilder();
builder.pushOffset(50, 50);
builder.pushClipRect(
const ui.Rect.fromLTRB(0, 0, 1000, 1000)) as PersistedContainerSurface;
builder.pushTransform((Matrix4.identity()
..scale(2, 2)).toFloat64());
builder.pushOffset(500, 500);
builder.addPicture(ui.Offset.zero, picture);
builder.pop();
builder.pop();
builder.pop();
builder.pop();
final DomElement content = builder
.build()
.webOnlyRootElement!;
expect(content
.querySelectorAll('flt-picture')
.single
.children, isEmpty);
});
test('releases old canvas when picture is fully clipped out after addRetained', () async {
final ui.Picture picture = _drawPicture();
// Frame 1: picture visible
final SurfaceSceneBuilder builder1 = SurfaceSceneBuilder();
final PersistedOffset offset1 = builder1.pushOffset(0, 0) as PersistedOffset;
builder1.addPicture(ui.Offset.zero, picture);
builder1.pop();
final DomElement content1 = builder1.build().webOnlyRootElement!;
expect(content1.querySelectorAll('flt-picture').single.children, isNotEmpty);
expect(findPictureSurfaceChild(offset1)!.canvas, isNotNull);
// Frame 2: picture is clipped out after an update
final SurfaceSceneBuilder builder2 = SurfaceSceneBuilder();
final PersistedOffset offset2 = builder2.pushOffset(-10000, -10000, oldLayer: offset1) as PersistedOffset;
builder2.addPicture(ui.Offset.zero, picture);
builder2.pop();
final DomElement content = builder2.build().webOnlyRootElement!;
expect(content.querySelectorAll('flt-picture').single.children, isEmpty);
expect(findPictureSurfaceChild(offset2)!.canvas, isNull);
});
test('releases old canvas when picture is fully clipped out after addRetained', () async {
final ui.Picture picture = _drawPicture();
// Frame 1: picture visible
final SurfaceSceneBuilder builder1 = SurfaceSceneBuilder();
final PersistedOffset offset1 = builder1.pushOffset(0, 0) as PersistedOffset;
final PersistedOffset subOffset1 = builder1.pushOffset(0, 0) as PersistedOffset;
builder1.addPicture(ui.Offset.zero, picture);
builder1.pop();
builder1.pop();
final DomElement content1 = builder1.build().webOnlyRootElement!;
expect(content1.querySelectorAll('flt-picture').single.children, isNotEmpty);
expect(findPictureSurfaceChild(subOffset1)!.canvas, isNotNull);
// Frame 2: picture is clipped out after addRetained
final SurfaceSceneBuilder builder2 = SurfaceSceneBuilder();
builder2.pushOffset(-10000, -10000, oldLayer: offset1);
// Even though the child offset is added as retained, the parent
// is updated with a value that causes the picture to move out of
// the clipped area. We should see the canvas being released.
builder2.addRetained(subOffset1);
builder2.pop();
final DomElement content = builder2.build().webOnlyRootElement!;
expect(content.querySelectorAll('flt-picture').single.children, isEmpty);
expect(findPictureSurfaceChild(subOffset1)!.canvas, isNull);
});
test('auto-pops pushed layers', () async {
final ui.Picture picture = _drawPicture();
final SurfaceSceneBuilder builder = SurfaceSceneBuilder();
builder.pushOffset(0, 0);
builder.pushOffset(0, 0);
builder.pushOffset(0, 0);
builder.pushOffset(0, 0);
builder.pushOffset(0, 0);
builder.addPicture(ui.Offset.zero, picture);
// Intentionally pop fewer layers than we pushed
builder.pop();
builder.pop();
builder.pop();
// Expect as many layers as we pushed (not popped).
final DomElement content = builder.build().webOnlyRootElement!;
expect(content.querySelectorAll('flt-offset'), hasLength(5));
});
test('updates child lists efficiently', () async {
// Pushes a single child that renders one character.
//
// If the character is a number, pushes an offset layer. Otherwise, pushes
// an offset layer. Test cases use this to control how layers are reused.
// Layers of the same type can be reused even if they are not explicitly
// updated. Conversely, layers of different types are never reused.
ui.EngineLayer pushChild(SurfaceSceneBuilder builder, String char, {ui.EngineLayer? oldLayer}) {
// Numbers use opacity layers, letters use offset layers. This is used to
// control DOM reuse. Layers of the same type can reuse DOM nodes from other
// dropped layers.
final bool useOffset = int.tryParse(char) == null;
final EnginePictureRecorder recorder = EnginePictureRecorder();
final RecordingCanvas canvas = recorder.beginRecording(const ui.Rect.fromLTRB(0, 0, 400, 400));
final ui.Paragraph paragraph = (ui.ParagraphBuilder(ui.ParagraphStyle())
..pushStyle(ui.TextStyle(decoration: ui.TextDecoration.lineThrough))
..addText(char))
.build();
paragraph.layout(const ui.ParagraphConstraints(width: 1000));
canvas.drawParagraph(paragraph, ui.Offset.zero);
final ui.EngineLayer newLayer = useOffset
? builder.pushOffset(0, 0, oldLayer: oldLayer == null ? null : oldLayer as ui.OffsetEngineLayer)
: builder.pushOpacity(100, oldLayer: oldLayer == null ? null : oldLayer as ui.OpacityEngineLayer);
builder.addPicture(ui.Offset.zero, recorder.endRecording());
builder.pop();
return newLayer;
}
// Maps letters to layers used to render them in the last frame, used to
// supply `oldLayer` to guarantee update.
final Map<String, ui.EngineLayer> renderedLayers = <String, ui.EngineLayer>{};
// Pump an empty scene to reset it, otherwise the first frame will attempt
// to diff left-overs from a previous test, which results in unpredictable
// DOM mutations.
await renderScene(SurfaceSceneBuilder().build());
// Renders a `string` by breaking it up into individual characters and
// rendering each character into its own layer.
Future<void> testCase(String string, String description, { int deletions = 0, int additions = 0, int moves = 0 }) {
final Set<DomNode> actualDeletions = <DomNode>{};
final Set<DomNode> actualAdditions = <DomNode>{};
// Watches DOM mutations and counts deletions and additions to the child
// list of the `<flt-scene>` element.
final DomMutationObserver observer = createDomMutationObserver((JSArray<JSAny?> mutations, _) {
for (final DomMutationRecord record in mutations.toDart.cast<DomMutationRecord>()) {
actualDeletions.addAll(record.removedNodes!);
actualAdditions.addAll(record.addedNodes!);
}
});
observer.observe(
SurfaceSceneBuilder.debugLastFrameScene!.rootElement!, childList: true);
final SurfaceSceneBuilder builder = SurfaceSceneBuilder();
for (int i = 0; i < string.length; i++) {
final String char = string[i];
renderedLayers[char] = pushChild(builder, char, oldLayer: renderedLayers[char]);
}
final SurfaceScene scene = builder.build();
final List<DomElement> pTags =
scene.webOnlyRootElement!.querySelectorAll('flt-paragraph').toList();
expect(pTags, hasLength(string.length));
expect(
scene.webOnlyRootElement!.querySelectorAll('flt-paragraph').map((DomElement p) => p.innerText).join(),
string,
);
renderedLayers.removeWhere((String key, ui.EngineLayer value) => !string.contains(key));
// Inject a zero-duration timer to allow mutation observers to receive notification.
return Future<void>.delayed(Duration.zero).then((_) {
observer.disconnect();
// Nodes that are removed then added are classified as "moves".
final int actualMoves = actualAdditions.intersection(actualDeletions).length;
// Compare all at once instead of one by one because when it fails, it's
// much more useful to see all numbers, not just the one that failed to
// match.
expect(
<String, int>{
'additions': actualAdditions.length - actualMoves,
'deletions': actualDeletions.length - actualMoves,
'moves': actualMoves,
},
<String, int>{
'additions': additions,
'deletions': deletions,
'moves': moves,
},
);
});
}
// Adding
await testCase('', 'noop');
await testCase('', 'noop');
await testCase('be', 'zero-to-many', additions: 2);
await testCase('bcde', 'insert in the middle', additions: 2);
await testCase('abcde', 'prepend', additions: 1);
await testCase('abcdef', 'append', additions: 1);
// Moving
await testCase('fbcdea', 'swap at ends', moves: 2);
await testCase('fecdba', 'swap in the middle', moves: 2);
await testCase('fedcba', 'swap adjacent in one move', moves: 1);
await testCase('fedcba', 'non-empty noop');
await testCase('afedcb', 'shift right by 1', moves: 1);
await testCase('fedcba', 'shift left by 1', moves: 1);
await testCase('abcdef', 'reverse', moves: 5);
await testCase('efabcd', 'shift right by 2', moves: 2);
await testCase('abcdef', 'shift left by 2', moves: 2);
// Scrolling without DOM reuse (numbers and letters use different types of layers)
await testCase('9abcde', 'scroll right by 1', additions: 1, deletions: 1);
await testCase('789abc', 'scroll right by 2', additions: 2, deletions: 2);
await testCase('89abcd', 'scroll left by 1', additions: 1, deletions: 1);
await testCase('abcdef', 'scroll left by 2', additions: 2, deletions: 2);
// Scrolling with DOM reuse
await testCase('zabcde', 'scroll right by 1', moves: 1);
await testCase('xyzabc', 'scroll right by 2', moves: 2);
await testCase('yzabcd', 'scroll left by 1', moves: 1);
await testCase('abcdef', 'scroll left by 2', moves: 2);
// Removing
await testCase('bcdef', 'remove as start', deletions: 1);
await testCase('bcde', 'remove as end', deletions: 1);
await testCase('be', 'remove in the middle', deletions: 2);
await testCase('', 'remove all', deletions: 2);
});
test('Canvas should allocate fewer pixels when zoomed out', () async {
final SurfaceSceneBuilder builder = SurfaceSceneBuilder();
final ui.Picture picture1 = _drawPicture();
builder.pushClipRect(const ui.Rect.fromLTRB(10, 10, 300, 300));
builder.addPicture(ui.Offset.zero, picture1);
builder.pop();
final DomElement content = builder.build().webOnlyRootElement!;
final DomCanvasElement canvas = content.querySelector('canvas')! as DomCanvasElement;
final int unscaledWidth = canvas.width!.toInt();
final int unscaledHeight = canvas.height!.toInt();
// Force update to scene which will utilize reuse code path.
final SurfaceSceneBuilder builder2 = SurfaceSceneBuilder();
builder2.pushOffset(0, 0);
builder2.pushTransform(Matrix4.identity().scaled(0.5, 0.5).toFloat64());
builder2.pushClipRect(
const ui.Rect.fromLTRB(10, 10, 300, 300),
);
builder2.addPicture(ui.Offset.zero, picture1);
builder2.pop();
builder2.pop();
builder2.pop();
final DomElement contentAfterScale = builder2.build().webOnlyRootElement!;
final DomCanvasElement canvas2 = contentAfterScale.querySelector('canvas')! as DomCanvasElement;
// Although we are drawing same picture, due to scaling the new canvas
// should have fewer pixels.
expect(canvas2.width! < unscaledWidth, isTrue);
expect(canvas2.height! < unscaledHeight, isTrue);
});
test('Canvas should allocate more pixels when zoomed in', () async {
final SurfaceSceneBuilder builder = SurfaceSceneBuilder();
final ui.Picture picture1 = _drawPicture();
builder.pushClipRect(const ui.Rect.fromLTRB(10, 10, 300, 300));
builder.addPicture(ui.Offset.zero, picture1);
builder.pop();
final DomElement content = builder.build().webOnlyRootElement!;
final DomCanvasElement canvas = content.querySelector('canvas')! as DomCanvasElement;
final int unscaledWidth = canvas.width!.toInt();
final int unscaledHeight = canvas.height!.toInt();
// Force update to scene which will utilize reuse code path.
final SurfaceSceneBuilder builder2 = SurfaceSceneBuilder();
builder2.pushOffset(0, 0);
builder2.pushTransform(Matrix4.identity().scaled(2, 2).toFloat64());
builder2.pushClipRect(
const ui.Rect.fromLTRB(10, 10, 300, 300),
);
builder2.addPicture(ui.Offset.zero, picture1);
builder2.pop();
builder2.pop();
builder2.pop();
final DomElement contentAfterScale = builder2.build().webOnlyRootElement!;
final DomCanvasElement canvas2 = contentAfterScale.querySelector('canvas')! as DomCanvasElement;
// Although we are drawing same picture, due to scaling the new canvas
// should have more pixels.
expect(canvas2.width! > unscaledWidth, isTrue);
expect(canvas2.height! > unscaledHeight, isTrue);
});
test('Should recycle canvas once', () async {
final SurfaceSceneBuilder builder = SurfaceSceneBuilder();
final ui.Picture picture1 = _drawPicture();
final ui.ClipRectEngineLayer oldLayer = builder.pushClipRect(
const ui.Rect.fromLTRB(10, 10, 300, 300),
);
builder.addPicture(ui.Offset.zero, picture1);
builder.pop();
builder.build();
// Force update to scene which will utilize reuse code path.
final SurfaceSceneBuilder builder2 = SurfaceSceneBuilder();
final ui.ClipRectEngineLayer oldLayer2 = builder2.pushClipRect(
const ui.Rect.fromLTRB(5, 10, 300, 300),
oldLayer: oldLayer
);
builder2.addPicture(ui.Offset.zero, _drawEmptyPicture());
builder2.pop();
final DomElement contentAfterReuse = builder2.build().webOnlyRootElement!;
expect(contentAfterReuse, isNotNull);
final SurfaceSceneBuilder builder3 = SurfaceSceneBuilder();
builder3.pushClipRect(
const ui.Rect.fromLTRB(25, 10, 300, 300),
oldLayer: oldLayer2
);
builder3.addPicture(ui.Offset.zero, _drawEmptyPicture());
builder3.pop();
// This build will crash if canvas gets recycled twice.
final DomElement contentAfterReuse2 = builder3.build().webOnlyRootElement!;
expect(contentAfterReuse2, isNotNull);
});
}
typedef TestLayerBuilder = ui.EngineLayer Function(
ui.SceneBuilder sceneBuilder, ui.EngineLayer? oldLayer);
typedef ExpectedHtmlGetter = String Function();
void testLayerLifeCycle(
TestLayerBuilder layerBuilder, ExpectedHtmlGetter expectedHtmlGetter) {
// Force scene builder to start from scratch. This guarantees that the first
// scene starts from the "build" phase.
SurfaceSceneBuilder.debugForgetFrameScene();
// Build: builds a brand new layer.
SurfaceSceneBuilder sceneBuilder = SurfaceSceneBuilder();
final ui.EngineLayer layer1 = layerBuilder(sceneBuilder, null);
final Type surfaceType = layer1.runtimeType;
sceneBuilder.pop();
SceneTester tester = SceneTester(sceneBuilder.build());
tester.expectSceneHtml(expectedHtmlGetter());
PersistedSurface findSurface() {
return enumerateSurfaces()
.where((PersistedSurface s) => s.runtimeType == surfaceType)
.single;
}
final PersistedSurface surface1 = findSurface();
final DomElement surfaceElement1 = surface1.rootElement!;
// Retain: reuses a layer as is along with its DOM elements.
sceneBuilder = SurfaceSceneBuilder();
sceneBuilder.addRetained(layer1);
tester = SceneTester(sceneBuilder.build());
tester.expectSceneHtml(expectedHtmlGetter());
final PersistedSurface surface2 = findSurface();
final DomElement surfaceElement2 = surface2.rootElement!;
expect(surface2, same(surface1));
expect(surfaceElement2, same(surfaceElement1));
// Reuse: reuses a layer's DOM elements by matching it.
sceneBuilder = SurfaceSceneBuilder();
final ui.EngineLayer layer3 = layerBuilder(sceneBuilder, layer1);
sceneBuilder.pop();
expect(layer3, isNot(same(layer1)));
tester = SceneTester(sceneBuilder.build());
tester.expectSceneHtml(expectedHtmlGetter());
final PersistedSurface surface3 = findSurface();
expect(surface3, same(layer3));
final DomElement surfaceElement3 = surface3.rootElement!;
expect(surface3, isNot(same(surface2)));
expect(surfaceElement3, isNotNull);
expect(surfaceElement3, same(surfaceElement2));
// Recycle: discards all the layers.
sceneBuilder = SurfaceSceneBuilder();
tester = SceneTester(sceneBuilder.build());
tester.expectSceneHtml('<s></s>');
expect(surface3.rootElement, isNull); // offset3 should be recycled.
// Retain again: the framework should be able to request that a layer is added
// as retained even after it has been recycled. In this case the
// engine would "rehydrate" the layer with new DOM elements.
sceneBuilder = SurfaceSceneBuilder();
sceneBuilder.addRetained(layer3);
tester = SceneTester(sceneBuilder.build());
tester.expectSceneHtml(expectedHtmlGetter());
expect(surface3.rootElement, isNotNull); // offset3 should be rehydrated.
// Make sure we clear retained surface list.
expect(retainedSurfaces, isEmpty);
}
class MockPersistedPicture extends PersistedPicture {
factory MockPersistedPicture() {
final EnginePictureRecorder recorder = EnginePictureRecorder();
// Use the largest cull rect so that layer clips are effective. The tests
// rely on this.
recorder.beginRecording(ui.Rect.largest).drawPaint(SurfacePaint());
return MockPersistedPicture._(recorder.endRecording());
}
MockPersistedPicture._(EnginePicture picture) : super(0, 0, picture, 0);
int retainCount = 0;
int buildCount = 0;
int updateCount = 0;
int applyPaintCount = 0;
final BitmapCanvas _fakeCanvas = BitmapCanvas(const ui.Rect.fromLTRB(0, 0, 10, 10), RenderStrategy());
@override
EngineCanvas get canvas {
return _fakeCanvas;
}
@override
double matchForUpdate(PersistedPicture existingSurface) {
return identical(existingSurface.picture, picture) ? 0.0 : 1.0;
}
@override
Matrix4 get localTransformInverse => Matrix4.identity();
@override
void build() {
super.build();
buildCount++;
}
@override
void retain() {
super.retain();
retainCount++;
}
@override
void applyPaint(EngineCanvas? oldCanvas) {
applyPaintCount++;
}
@override
void update(PersistedPicture oldSurface) {
super.update(oldSurface);
updateCount++;
}
@override
int get bitmapPixelCount => 0;
}
/// Draw 4 circles within 50, 50, 120, 120 bounds
ui.Picture _drawPicture() {
const double offsetX = 50;
const double offsetY = 50;
final EnginePictureRecorder recorder = EnginePictureRecorder();
final RecordingCanvas canvas =
recorder.beginRecording(const ui.Rect.fromLTRB(0, 0, 400, 400));
final ui.Shader gradient = ui.Gradient.radial(
const ui.Offset(100, 100), 50,
const <ui.Color>[
ui.Color.fromARGB(255, 0, 0, 0),
ui.Color.fromARGB(255, 0, 0, 255),
],
);
canvas.drawCircle(
const ui.Offset(offsetX + 10, offsetY + 10), 10,
SurfacePaint()
..style = ui.PaintingStyle.fill
..shader = gradient);
canvas.drawCircle(
const ui.Offset(offsetX + 60, offsetY + 10),
10,
SurfacePaint()
..style = ui.PaintingStyle.fill
..color = const ui.Color.fromRGBO(255, 0, 0, 1));
canvas.drawCircle(
const ui.Offset(offsetX + 10, offsetY + 60),
10,
SurfacePaint()
..style = ui.PaintingStyle.fill
..color = const ui.Color.fromRGBO(0, 255, 0, 1));
canvas.drawCircle(
const ui.Offset(offsetX + 60, offsetY + 60),
10,
SurfacePaint()
..style = ui.PaintingStyle.fill
..color = const ui.Color.fromRGBO(0, 0, 255, 1));
return recorder.endRecording();
}
EnginePicture _drawEmptyPicture() {
final EnginePictureRecorder recorder = EnginePictureRecorder();
recorder.beginRecording(const ui.Rect.fromLTRB(0, 0, 400, 400));
return recorder.endRecording();
}
EnginePicture _drawPathImagePath() {
const double offsetX = 50;
const double offsetY = 50;
final EnginePictureRecorder recorder = EnginePictureRecorder();
final RecordingCanvas canvas =
recorder.beginRecording(const ui.Rect.fromLTRB(0, 0, 400, 400));
final ui.Shader gradient = ui.Gradient.radial(
const ui.Offset(100, 100), 50,
const <ui.Color>[
ui.Color.fromARGB(255, 0, 0, 0),
ui.Color.fromARGB(255, 0, 0, 255),
],
);
canvas.drawCircle(
const ui.Offset(offsetX + 10, offsetY + 10), 10,
SurfacePaint()
..style = ui.PaintingStyle.fill
..shader = gradient);
canvas.drawCircle(
const ui.Offset(offsetX + 60, offsetY + 10),
10,
SurfacePaint()
..style = ui.PaintingStyle.fill
..color = const ui.Color.fromRGBO(255, 0, 0, 1));
canvas.drawCircle(
const ui.Offset(offsetX + 10, offsetY + 60),
10,
SurfacePaint()
..style = ui.PaintingStyle.fill
..color = const ui.Color.fromRGBO(0, 255, 0, 1));
canvas.drawImage(createTestImage(), ui.Offset.zero, SurfacePaint());
canvas.drawCircle(
const ui.Offset(offsetX + 10, offsetY + 10), 10,
SurfacePaint()
..style = ui.PaintingStyle.fill
..shader = gradient);
canvas.drawCircle(
const ui.Offset(offsetX + 60, offsetY + 60),
10,
SurfacePaint()
..style = ui.PaintingStyle.fill
..color = const ui.Color.fromRGBO(0, 0, 255, 1));
return recorder.endRecording();
}
HtmlImage createTestImage({int width = 100, int height = 50}) {
final DomCanvasElement canvas =
createDomCanvasElement(width: width, height: height);
final DomCanvasRenderingContext2D ctx = canvas.context2D;
ctx.fillStyle = '#E04040';
ctx.fillRect(0, 0, 33, 50);
ctx.fill();
ctx.fillStyle = '#40E080';
ctx.fillRect(33, 0, 33, 50);
ctx.fill();
ctx.fillStyle = '#2040E0';
ctx.fillRect(66, 0, 33, 50);
ctx.fill();
final DomHTMLImageElement imageElement = createDomHTMLImageElement();
imageElement.src = js_util.callMethod<String>(canvas, 'toDataURL', <dynamic>[]);
return HtmlImage(imageElement, width, height);
}
| engine/lib/web_ui/test/engine/surface/scene_builder_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/surface/scene_builder_test.dart",
"repo_id": "engine",
"token_count": 12904
} | 269 |
// Copyright 2013 The Flutter 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:js_util';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import '../../common/matchers.dart';
import '../../html/image_test.dart';
void main() {
internalBootstrapBrowserTest(() => doTests);
}
Future<void> doTests() async {
group('FlutterViewManager', () {
final EnginePlatformDispatcher platformDispatcher = EnginePlatformDispatcher.instance;
final FlutterViewManager viewManager = FlutterViewManager(platformDispatcher);
group('registerView', () {
test('can register view', () {
final EngineFlutterView view = EngineFlutterView(platformDispatcher, createDomElement('div'));
final int viewId = view.viewId;
viewManager.registerView(view);
expect(viewManager[viewId], view);
});
test('fails if the same viewId is already registered', () {
final EngineFlutterView view = EngineFlutterView(platformDispatcher, createDomElement('div'));
viewManager.registerView(view);
expect(() { viewManager.registerView(view); }, throwsAssertionError);
});
test('stores JSOptions that getOptions can retrieve', () {
final EngineFlutterView view = EngineFlutterView(platformDispatcher, createDomElement('div'));
final int viewId = view.viewId;
final JsFlutterViewOptions expectedOptions = jsify(<String, Object?>{
'hostElement': createDomElement('div'),
}) as JsFlutterViewOptions;
viewManager.registerView(view, jsViewOptions: expectedOptions);
final JsFlutterViewOptions? storedOptions = viewManager.getOptions(viewId);
expect(storedOptions, expectedOptions);
});
});
group('unregisterView', () {
test('unregisters a view', () {
final EngineFlutterView view = EngineFlutterView(platformDispatcher, createDomElement('div'));
final int viewId = view.viewId;
viewManager.registerView(view);
expect(viewManager[viewId], isNotNull);
viewManager.unregisterView(viewId);
expect(viewManager[viewId], isNull);
});
});
group('onViewsChanged', () {
// Prepares a "timed-out" version of the onViewsChanged Stream so tests
// can't hang "forever" waiting for this to complete. This stream will close
// after 100ms of inactivity, regardless of what the test or the code do.
final Stream<int> onViewCreated = viewManager.onViewCreated.timeout(
const Duration(milliseconds: 100), onTimeout: (EventSink<int> sink) {
sink.close();
});
final Stream<int> onViewDisposed = viewManager.onViewDisposed.timeout(
const Duration(milliseconds: 100), onTimeout: (EventSink<int> sink) {
sink.close();
});
test('on view registered/unregistered - fires event', () async {
final EngineFlutterView view = EngineFlutterView(platformDispatcher, createDomElement('div'));
final int viewId = view.viewId;
final Future<List<void>> viewCreatedEvents = onViewCreated.toList();
final Future<List<void>> viewDisposedEvents = onViewDisposed.toList();
viewManager.registerView(view);
viewManager.unregisterView(viewId);
expect(viewCreatedEvents, completes);
expect(viewDisposedEvents, completes);
final List<void> createdViewsList = await viewCreatedEvents;
final List<void> disposedViewsList = await viewCreatedEvents;
expect(createdViewsList, listEqual(<int>[viewId]),
reason: 'Should fire creation event for view');
expect(disposedViewsList, listEqual(<int>[viewId]),
reason: 'Should fire dispose event for view');
});
});
group('viewIdForRootElement', () {
test('works', () {
final EngineFlutterView view = EngineFlutterView(platformDispatcher, createDomElement('div'));
final int viewId = view.viewId;
viewManager.registerView(view);
expect(viewManager.viewIdForRootElement(view.dom.rootElement), viewId);
});
});
});
}
| engine/lib/web_ui/test/engine/view_embedder/flutter_view_manager_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/view_embedder/flutter_view_manager_test.dart",
"repo_id": "engine",
"token_count": 1540
} | 270 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' hide TextStyle;
import '../../common/test_initialization.dart';
import '../screenshot.dart';
import '../testimage.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
SurfacePaint makePaint() => Paint() as SurfacePaint;
Future<void> testMain() async {
setUpUnitTests(
withImplicitView: true,
setUpTestViewDimensions: false,
);
const Color red = Color(0xFFFF0000);
const Color green = Color(0xFF00FF00);
const Color blue = Color(0xFF2196F3);
const Color white = Color(0xFFFFFFFF);
const Color grey = Color(0xFF808080);
const Color black = Color(0xFF000000);
final List<List<BlendMode>> modes = <List<BlendMode>>[
<BlendMode>[BlendMode.clear, BlendMode.src, BlendMode.dst,
BlendMode.srcOver, BlendMode.dstOver, BlendMode.srcIn, BlendMode.dstIn,
BlendMode.srcOut],
<BlendMode>[BlendMode.dstOut, BlendMode.srcATop, BlendMode.dstATop,
BlendMode.xor, BlendMode.plus, BlendMode.modulate, BlendMode.screen,
BlendMode.overlay],
<BlendMode>[BlendMode.darken, BlendMode.lighten, BlendMode.colorDodge,
BlendMode.hardLight, BlendMode.softLight, BlendMode.difference,
BlendMode.exclusion, BlendMode.multiply],
<BlendMode>[BlendMode.hue, BlendMode.saturation, BlendMode.color,
BlendMode.luminosity],
];
for (int blendGroup = 0; blendGroup < 4; ++blendGroup) {
test('Draw image with Group$blendGroup blend modes', () async {
final RecordingCanvas rc = RecordingCanvas(
const Rect.fromLTRB(0, 0, 400, 400));
rc.save();
final List<BlendMode> blendModes = modes[blendGroup];
for (int row = 0; row < blendModes.length; row++) {
// draw white background for first 4, black for next 4 blends.
final double top = row * 50.0;
rc.drawRect(Rect.fromLTWH(0, top, 200, 50), makePaint()
..color = white);
rc.drawRect(Rect.fromLTWH(200, top, 200, 50), makePaint()
..color = grey);
final BlendMode blendMode = blendModes[row];
rc.drawImage(createFlutterLogoTestImage(), Offset(0, top),
makePaint()
..colorFilter = EngineColorFilter.mode(red, blendMode));
rc.drawImage(createFlutterLogoTestImage(), Offset(50, top),
makePaint()
..colorFilter = EngineColorFilter.mode(green, blendMode));
rc.drawImage(createFlutterLogoTestImage(), Offset(100, top),
makePaint()
..colorFilter = EngineColorFilter.mode(blue, blendMode));
rc.drawImage(createFlutterLogoTestImage(), Offset(150, top),
makePaint()
..colorFilter = EngineColorFilter.mode(black, blendMode));
rc.drawImage(createFlutterLogoTestImage(), Offset(200, top),
makePaint()
..colorFilter = EngineColorFilter.mode(red, blendMode));
rc.drawImage(createFlutterLogoTestImage(), Offset(250, top),
makePaint()
..colorFilter = EngineColorFilter.mode(green, blendMode));
rc.drawImage(createFlutterLogoTestImage(), Offset(300, top),
makePaint()
..colorFilter = EngineColorFilter.mode(blue, blendMode));
rc.drawImage(createFlutterLogoTestImage(), Offset(350, top),
makePaint()
..colorFilter = EngineColorFilter.mode(black, blendMode));
}
rc.restore();
await canvasScreenshot(rc, 'canvas_image_blend_group$blendGroup');
},
skip: isSafari);
}
// Regression test for https://github.com/flutter/flutter/issues/56971
test('Draws image and paragraph at same vertical position', () async {
final RecordingCanvas rc = RecordingCanvas(
const Rect.fromLTRB(0, 0, 400, 400));
rc.save();
rc.drawRect(const Rect.fromLTWH(0, 50, 200, 50), makePaint()
..color = white);
rc.drawImage(createFlutterLogoTestImage(), const Offset(0, 50),
makePaint()
..colorFilter = const EngineColorFilter.mode(red, BlendMode.srcIn));
final Paragraph paragraph = createTestParagraph();
const double textLeft = 80.0;
const double textTop = 50.0;
const double widthConstraint = 300.0;
paragraph.layout(const ParagraphConstraints(width: widthConstraint));
rc.drawParagraph(paragraph, const Offset(textLeft, textTop));
rc.restore();
await canvasScreenshot(rc, 'canvas_image_blend_and_text');
});
test('Does not re-use styles with same image src', () async {
final RecordingCanvas rc = RecordingCanvas(
const Rect.fromLTRB(0, 0, 400, 400));
final HtmlImage flutterImage = createFlutterLogoTestImage();
rc.save();
rc.drawRect(const Rect.fromLTWH(0, 50, 200, 50), makePaint()
..color = white);
rc.drawImage(flutterImage, const Offset(0, 50),
makePaint()
..colorFilter = const EngineColorFilter.mode(red, BlendMode.modulate));
// Expect that the colorFilter is only applied to the first image, since the
// colorFilter is applied to a clone of the flutterImage and not the original
rc.drawImage(flutterImage, const Offset(0, 100), makePaint());
rc.restore();
await canvasScreenshot(rc, 'canvas_image_same_src');
});
}
Paragraph createTestParagraph() {
final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle(
fontFamily: 'Ahem',
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
fontSize: 14.0,
));
builder.addText('FOO');
return builder.build();
}
| engine/lib/web_ui/test/html/compositing/canvas_image_blend_mode_golden_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/html/compositing/canvas_image_blend_mode_golden_test.dart",
"repo_id": "engine",
"token_count": 2232
} | 271 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart';
import 'package:web_engine_tester/golden_tester.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
const Rect region = Rect.fromLTWH(8, 8, 600, 800); // Compensate for old golden tester padding
Future<void> testPath(Path path, String goldenFileName) async {
const Rect canvasBounds = Rect.fromLTWH(0, 0, 600, 800);
final BitmapCanvas bitmapCanvas = BitmapCanvas(canvasBounds,
RenderStrategy());
final RecordingCanvas canvas = RecordingCanvas(canvasBounds);
SurfacePaint paint = SurfacePaint()
..color = const Color(0x7F7F7F7F)
..style = PaintingStyle.fill;
canvas.drawPath(path, paint);
paint = SurfacePaint()
..strokeWidth = 2.0
..color = const Color(0xFF7F007F)
..style = PaintingStyle.stroke;
canvas.drawPath(path, paint);
canvas.endRecording();
domDocument.body!.append(bitmapCanvas.rootElement);
canvas.apply(bitmapCanvas, canvasBounds);
await matchGoldenFile('$goldenFileName.png', region: region);
bitmapCanvas.rootElement.remove();
}
test('render conic with control point horizontal center', () async {
const double yStart = 20;
const Offset p0 = Offset(25, yStart + 25);
const Offset pc = Offset(60, yStart + 150);
const Offset p2 = Offset(100, yStart + 50);
final Path path = Path();
path.moveTo(p0.dx, p0.dy);
path.conicTo(pc.dx, pc.dy, p2.dx, p2.dy, 0.5);
path.close();
path.moveTo(p0.dx, p0.dy + 200);
path.conicTo(pc.dx, pc.dy + 200, p2.dx, p2.dy + 200, 10);
path.close();
await testPath(path, 'render_conic_1_w10');
});
test('render conic with control point left of start point', () async {
const double yStart = 20;
const Offset p0 = Offset(60, yStart + 25);
const Offset pc = Offset(25, yStart + 150);
const Offset p2 = Offset(100, yStart + 50);
final Path path = Path();
path.moveTo(p0.dx, p0.dy);
path.conicTo(pc.dx, pc.dy, p2.dx, p2.dy, 0.5);
path.close();
path.moveTo(p0.dx, p0.dy + 200);
path.conicTo(pc.dx, pc.dy + 200, p2.dx, p2.dy + 200, 10);
path.close();
await testPath(path, 'render_conic_2_w10');
});
test('render conic with control point above start point', () async {
const double yStart = 20;
const Offset p0 = Offset(25, yStart + 125);
const Offset pc = Offset(60, yStart + 50);
const Offset p2 = Offset(100, yStart + 150);
final Path path = Path();
path.moveTo(p0.dx, p0.dy);
path.conicTo(pc.dx, pc.dy, p2.dx, p2.dy, 0.5);
path.close();
path.moveTo(p0.dx, p0.dy + 200);
path.conicTo(pc.dx, pc.dy + 200, p2.dx, p2.dy + 200, 10);
path.close();
await testPath(path, 'render_conic_2');
});
}
| engine/lib/web_ui/test/html/drawing/conic_golden_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/html/drawing/conic_golden_test.dart",
"repo_id": "engine",
"token_count": 1222
} | 272 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart';
// TODO(yjbanov): https://github.com/flutter/flutter/issues/76885
const bool issue76885Exists = true;
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
test('PathRef.getRRect with radius', () {
final SurfacePath path = SurfacePath();
final RRect rrect = RRect.fromLTRBR(0, 0, 10, 10, const Radius.circular(2));
path.addRRect(rrect);
expect(path.toRoundedRect(), rrect);
});
test('PathRef.getRRect with radius larger than rect', () {
final SurfacePath path = SurfacePath();
final RRect rrect = RRect.fromLTRBR(0, 0, 10, 10, const Radius.circular(20));
path.addRRect(rrect);
expect(
path.toRoundedRect(),
// Path.addRRect will correct the radius to fit the dimensions, so when
// extracting the rrect out of the path we don't get the original.
RRect.fromLTRBR(0, 0, 10, 10, const Radius.circular(5)),
);
});
test('PathRef.getRRect with zero radius', () {
final SurfacePath path = SurfacePath();
final RRect rrect = RRect.fromLTRBR(0, 0, 10, 10, Radius.zero);
path.addRRect(rrect);
expect(path.toRoundedRect(), isNull);
expect(path.toRect(), rrect.outerRect);
});
test('PathRef.getRRect elliptical', () {
final SurfacePath path = SurfacePath();
final RRect rrect = RRect.fromLTRBR(0, 0, 10, 10, const Radius.elliptical(2, 4));
path.addRRect(rrect);
expect(path.toRoundedRect(), rrect);
});
test('PathRef.getRRect elliptical zero x', () {
final SurfacePath path = SurfacePath();
final RRect rrect = RRect.fromLTRBR(0, 0, 10, 10, const Radius.elliptical(0, 3));
path.addRRect(rrect);
expect(path.toRoundedRect(), isNull);
expect(path.toRect(), rrect.outerRect);
});
test('PathRef.getRRect elliptical zero y', () {
final SurfacePath path = SurfacePath();
final RRect rrect = RRect.fromLTRBR(0, 0, 10, 10, const Radius.elliptical(3, 0));
path.addRRect(rrect);
expect(path.toRoundedRect(), isNull);
expect(path.toRect(), rrect.outerRect);
});
test('PathRef.getRect returns a Rect from a valid Path and null otherwise', () {
final SurfacePath path = SurfacePath();
// Draw a line
path.moveTo(0,0);
path.lineTo(10,0);
expect(path.pathRef.getRect(), isNull);
// Draw two other lines to get a valid rectangle
path.lineTo(10,10);
path.lineTo(0,10);
expect(path.pathRef.getRect(), const Rect.fromLTWH(0, 0, 10, 10));
});
// Regression test for https://github.com/flutter/flutter/issues/111750
test('PathRef.getRect returns Rect with positive width and height', () {
final SurfacePath path = SurfacePath();
// Draw a rectangle starting from bottom right corner
path.moveTo(10,10);
path.lineTo(0,10);
path.lineTo(0,0);
path.lineTo(10,0);
// pathRef.getRect() should return a rectangle with positive height and width
expect(path.pathRef.getRect(), const Rect.fromLTWH(0, 0, 10, 10));
});
// This test demonstrates the issue with attempting to reconstruct an RRect
// with imprecision introduced by comparing double values. We should fix this
// by removing the need to reconstruct rrects:
// https://github.com/flutter/flutter/issues/76885
test('PathRef.getRRect with nearly zero corner', () {
final SurfacePath path = SurfacePath();
final RRect original = RRect.fromLTRBR(0, 0, 10, 10, const Radius.elliptical(0.00000001, 5));
path.addRRect(original);
expect(path.toRoundedRect(), original);
}, skip: issue76885Exists);
}
| engine/lib/web_ui/test/html/path_ref_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/html/path_ref_test.dart",
"repo_id": "engine",
"token_count": 1367
} | 273 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import '../../common/rendering.dart';
import '../../common/test_initialization.dart';
import '../paragraph/helper.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests(withImplicitView: true);
group('$CanvasParagraph.getBoxesForRange', () {
test('return empty list for invalid ranges', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.addText('Lorem ipsum');
})
..layout(constrain(double.infinity));
expect(paragraph.getBoxesForRange(-1, 0), <ui.TextBox>[]);
expect(paragraph.getBoxesForRange(0, 0), <ui.TextBox>[]);
expect(paragraph.getBoxesForRange(11, 11), <ui.TextBox>[]);
expect(paragraph.getBoxesForRange(11, 12), <ui.TextBox>[]);
expect(paragraph.getBoxesForRange(4, 3), <ui.TextBox>[]);
});
test('handles single-line multi-span paragraphs', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('ipsum ');
builder.pop();
builder.addText('.');
})
..layout(constrain(double.infinity));
// Within the first span "Lorem ".
expect(
// "or"
paragraph.getBoxesForRange(1, 3),
<ui.TextBox>[
box(10, 0, 30, 10),
],
);
expect(
// "Lorem"
paragraph.getBoxesForRange(0, 5),
<ui.TextBox>[
box(0, 0, 50, 10),
],
);
// Make sure the trailing space is also included in the box.
expect(
// "Lorem "
paragraph.getBoxesForRange(0, 6),
<ui.TextBox>[
// "Lorem"
box(0, 0, 50, 10),
// " "
box(50, 0, 60, 10),
],
);
// Within the second span "ipsum ".
expect(
// "psum"
paragraph.getBoxesForRange(7, 11),
<ui.TextBox>[
box(70, 0, 110, 10),
],
);
expect(
// "um "
paragraph.getBoxesForRange(9, 12),
<ui.TextBox>[
// "um"
box(90, 0, 110, 10),
// " "
box(110, 0, 120, 10),
],
);
// Across the two spans "Lorem " and "ipsum ".
expect(
// "rem ipsum"
paragraph.getBoxesForRange(2, 11),
<ui.TextBox>[
// "rem"
box(20, 0, 50, 10),
// " "
box(50, 0, 60, 10),
// "ipsum"
box(60, 0, 110, 10),
],
);
// Across all spans "Lorem ", "ipsum ", ".".
expect(
// "Lorem ipsum ."
paragraph.getBoxesForRange(0, 13),
<ui.TextBox>[
// "Lorem"
box(0, 0, 50, 10),
// " "
box(50, 0, 60, 10),
// "ipsum"
box(60, 0, 110, 10),
// " "
box(110, 0, 120, 10),
// "."
box(120, 0, 130, 10),
],
);
});
test('handles multi-line single-span paragraphs', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.addText('Lorem ipsum dolor sit');
})
..layout(constrain(90.0));
// Lines:
// "Lorem "
// "ipsum "
// "dolor sit"
// Within the first line "Lorem ".
expect(
// "or"
paragraph.getBoxesForRange(1, 3),
<ui.TextBox>[
box(10, 0, 30, 10),
],
);
// Make sure the trailing space at the end of line is also included in the
// box.
expect(
// "Lorem "
paragraph.getBoxesForRange(0, 6),
<ui.TextBox>[
// "Lorem"
box(0, 0, 50, 10),
// " "
box(50, 0, 60, 10),
],
);
// Within the second line "ipsum ".
expect(
// "psum "
paragraph.getBoxesForRange(7, 12),
<ui.TextBox>[
// "psum"
box(10, 10, 50, 20),
// " "
box(50, 10, 60, 20),
],
);
// Across all lines.
expect(
// "em "
// "ipsum "
// "dolor s"
paragraph.getBoxesForRange(3, 19),
<ui.TextBox>[
// "em"
box(30, 0, 50, 10),
// " "
box(50, 0, 60, 10),
// "ipsum"
box(0, 10, 50, 20),
// " "
box(50, 10, 60, 20),
// "dolor"
box(0, 20, 50, 30),
// " "
box(50, 20, 60, 30),
// "s"
box(60, 20, 70, 30),
],
);
});
test('handles multi-line multi-span paragraphs', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('Lorem ipsum ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('dolor ');
builder.pop();
builder.addText('sit');
})
..layout(constrain(90.0));
// Lines:
// "Lorem "
// "ipsum "
// "dolor sit"
// Within the first line "Lorem ".
expect(
// "ore"
paragraph.getBoxesForRange(1, 4),
<ui.TextBox>[
box(10, 0, 40, 10),
],
);
expect(
// "Lorem "
paragraph.getBoxesForRange(0, 6),
<ui.TextBox>[
// "Lorem"
box(0, 0, 50, 10),
// " "
box(50, 0, 60, 10),
],
);
// Within the second line "ipsum ".
expect(
// "psum "
paragraph.getBoxesForRange(7, 12),
<ui.TextBox>[
// "psum"
box(10, 10, 50, 20),
// " "
box(50, 10, 60, 20),
],
);
// Within the third line "dolor sit" which is made of 2 spans.
expect(
// "lor sit"
paragraph.getBoxesForRange(14, 21),
<ui.TextBox>[
// "lor"
box(20, 20, 50, 30),
// " "
box(50, 20, 60, 30),
// "sit"
box(60, 20, 90, 30),
],
);
// Across all lines.
expect(
// "em "
// "ipsum "
// "dolor s"
paragraph.getBoxesForRange(3, 19),
<ui.TextBox>[
// "em"
box(30, 0, 50, 10),
// " "
box(50, 0, 60, 10),
// "ipsum"
box(0, 10, 50, 20),
// " "
box(50, 10, 60, 20),
// "dolor"
box(0, 20, 50, 30),
// " "
box(50, 20, 60, 30),
// "s"
box(60, 20, 70, 30),
],
);
});
test('handles spans with varying heights/baselines', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(fontSize: 20.0));
// width = 20.0 * 6 = 120.0
// baseline = 20.0 * 80% = 16.0
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(fontSize: 40.0));
// width = 40.0 * 6 = 240.0
// baseline = 40.0 * 80% = 32.0
builder.addText('ipsum ');
builder.pushStyle(EngineTextStyle.only(fontSize: 10.0));
// width = 10.0 * 6 = 60.0
// baseline = 10.0 * 80% = 8.0
builder.addText('dolor ');
builder.pushStyle(EngineTextStyle.only(fontSize: 30.0));
// width = 30.0 * 4 = 120.0
// baseline = 30.0 * 80% = 24.0
builder.addText('sit ');
builder.pushStyle(EngineTextStyle.only(fontSize: 20.0));
// width = 20.0 * 4 = 80.0
// baseline = 20.0 * 80% = 16.0
builder.addText('amet');
})
..layout(constrain(420.0));
// Lines:
// "Lorem ipsum dolor " (width: 420, height: 40, baseline: 32)
// "sit amet" (width: 200, height: 30, baseline: 24)
expect(
// "em ipsum dol"
paragraph.getBoxesForRange(3, 15),
<ui.TextBox>[
// "em"
box(60, 16, 100, 36),
// " "
box(100, 16, 120, 36),
// "ipsum"
box(120, 0, 320, 40),
// " "
box(320, 0, 360, 40),
// "dol"
box(360, 24, 390, 34),
],
);
expect(
// "sum dolor "
// "sit amet"
paragraph.getBoxesForRange(8, 26),
<ui.TextBox>[
// "sum"
box(200, 0, 320, 40),
// " "
box(320, 0, 360, 40),
// "dolor"
box(360, 24, 410, 34),
// " "
box(410, 24, 420, 34),
// "sit"
box(0, 40, 90, 70),
// " "
box(90, 40, 120, 70),
// "amet"
box(120, 48, 200, 68),
],
);
});
test('reverts to last line break opportunity', () {
final CanvasParagraph paragraph = rich(ahemStyle, (ui.ParagraphBuilder builder) {
// Lines:
// "AAA "
// "B_C DD"
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('AAA B');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('_C ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('DD');
});
String getTextForFragment(LayoutFragment fragment) {
return paragraph.plainText.substring(fragment.start, fragment.end);
}
// The layout algorithm will keep appending segments to the line builder
// until it reaches: "AAA B_". At that point, it'll try to add the "C" but
// realizes there isn't enough width in the line. Since the line already
// had a line break opportunity, the algorithm tries to revert the line to
// that opportunity (i.e. "AAA ") and pops the segments "_" and "B".
//
// Because the segments "B" and "_" have different directionality
// preferences (LTR and no-preferenece, respectively), the algorithm
// should've already created a box for "B". When the "B" segment is popped
// we want to make sure that the "B" box is also popped.
paragraph.layout(constrain(60));
final ParagraphLine firstLine = paragraph.lines[0];
final ParagraphLine secondLine = paragraph.lines[1];
// There should be no "B" in the first line's fragments.
expect(firstLine.fragments, hasLength(2));
expect(getTextForFragment(firstLine.fragments[0]), 'AAA');
expect(firstLine.fragments[0].left, 0.0);
expect(getTextForFragment(firstLine.fragments[1]), ' ');
expect(firstLine.fragments[1].left, 30.0);
// Make sure the second line isn't missing any fragments.
expect(secondLine.fragments, hasLength(5));
expect(getTextForFragment(secondLine.fragments[0]), 'B');
expect(secondLine.fragments[0].left, 0.0);
expect(getTextForFragment(secondLine.fragments[1]), '_');
expect(secondLine.fragments[1].left, 10.0);
expect(getTextForFragment(secondLine.fragments[2]), 'C');
expect(secondLine.fragments[2].left, 20.0);
expect(getTextForFragment(secondLine.fragments[3]), ' ');
expect(secondLine.fragments[3].left, 30.0);
expect(getTextForFragment(secondLine.fragments[4]), 'DD');
expect(secondLine.fragments[4].left, 40.0);
});
});
group('$CanvasParagraph.getPositionForOffset', () {
test('handles single-line multi-span paragraphs', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('ipsum ');
builder.pop();
builder.addText('.');
})
..layout(constrain(double.infinity));
// Above the line, at the beginning.
expect(
paragraph.getPositionForOffset(const ui.Offset(0, -5)),
pos(0, ui.TextAffinity.downstream),
);
// At the top left corner of the line.
expect(
paragraph.getPositionForOffset(ui.Offset.zero),
pos(0, ui.TextAffinity.downstream),
);
// At the beginning of the line.
expect(
paragraph.getPositionForOffset(const ui.Offset(0, 5)),
pos(0, ui.TextAffinity.downstream),
);
// Below the line, at the end.
expect(
paragraph.getPositionForOffset(const ui.Offset(130, 12)),
pos(13, ui.TextAffinity.upstream),
);
// At the end of the line.
expect(
paragraph.getPositionForOffset(const ui.Offset(130, 5)),
pos(13, ui.TextAffinity.upstream),
);
// On the left half of "p" in "ipsum".
expect(
paragraph.getPositionForOffset(const ui.Offset(74, 5)),
pos(7, ui.TextAffinity.downstream),
);
// On the left half of "p" in "ipsum" (above the line).
expect(
paragraph.getPositionForOffset(const ui.Offset(74, -5)),
pos(7, ui.TextAffinity.downstream),
);
// On the left half of "p" in "ipsum" (below the line).
expect(
paragraph.getPositionForOffset(const ui.Offset(74, 15)),
pos(7, ui.TextAffinity.downstream),
);
// On the right half of "p" in "ipsum".
expect(
paragraph.getPositionForOffset(const ui.Offset(76, 5)),
pos(8, ui.TextAffinity.upstream),
);
// At the top of the line, on the left half of "p" in "ipsum".
expect(
paragraph.getPositionForOffset(const ui.Offset(74, 0)),
pos(7, ui.TextAffinity.downstream),
);
// At the top of the line, on the right half of "p" in "ipsum".
expect(
paragraph.getPositionForOffset(const ui.Offset(76, 0)),
pos(8, ui.TextAffinity.upstream),
);
});
test('handles multi-line single-span paragraphs', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.addText('Lorem ipsum dolor sit');
})
..layout(constrain(90.0));
// Lines:
// "Lorem "
// "ipsum "
// "dolor sit"
// Above the first line, at the beginning.
expect(
paragraph.getPositionForOffset(const ui.Offset(0, -5)),
pos(0, ui.TextAffinity.downstream),
);
// At the top left corner of the line.
expect(
paragraph.getPositionForOffset(ui.Offset.zero),
pos(0, ui.TextAffinity.downstream),
);
// At the beginning of the first line.
expect(
paragraph.getPositionForOffset(const ui.Offset(0, 5)),
pos(0, ui.TextAffinity.downstream),
);
// At the end of the first line.
expect(
paragraph.getPositionForOffset(const ui.Offset(60, 5)),
pos(6, ui.TextAffinity.upstream),
);
// At the end of the first line (above the line).
expect(
paragraph.getPositionForOffset(const ui.Offset(60, -5)),
pos(6, ui.TextAffinity.upstream),
);
// After the end of the first line to the right.
expect(
paragraph.getPositionForOffset(const ui.Offset(70, 5)),
pos(6, ui.TextAffinity.upstream),
);
// On the left half of " " in "Lorem ".
expect(
paragraph.getPositionForOffset(const ui.Offset(54, 5)),
pos(5, ui.TextAffinity.downstream),
);
// On the right half of " " in "Lorem ".
expect(
paragraph.getPositionForOffset(const ui.Offset(56, 5)),
pos(6, ui.TextAffinity.upstream),
);
// At the beginning of the second line "ipsum ".
expect(
paragraph.getPositionForOffset(const ui.Offset(0, 15)),
pos(6, ui.TextAffinity.downstream),
);
// At the end of the second line.
expect(
paragraph.getPositionForOffset(const ui.Offset(60, 15)),
pos(12, ui.TextAffinity.upstream),
);
// After the end of the second line to the right.
expect(
paragraph.getPositionForOffset(const ui.Offset(70, 15)),
pos(12, ui.TextAffinity.upstream),
);
// Below the third line "dolor sit", at the end.
expect(
paragraph.getPositionForOffset(const ui.Offset(90, 40)),
pos(21, ui.TextAffinity.upstream),
);
// At the end of the third line.
expect(
paragraph.getPositionForOffset(const ui.Offset(90, 25)),
pos(21, ui.TextAffinity.upstream),
);
// After the end of the third line to the right.
expect(
paragraph.getPositionForOffset(const ui.Offset(100, 25)),
pos(21, ui.TextAffinity.upstream),
);
// On the left half of " " in "dolor sit".
expect(
paragraph.getPositionForOffset(const ui.Offset(54, 25)),
pos(17, ui.TextAffinity.downstream),
);
// On the right half of " " in "dolor sit".
expect(
paragraph.getPositionForOffset(const ui.Offset(56, 25)),
pos(18, ui.TextAffinity.upstream),
);
});
test('handles multi-line multi-span paragraphs', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('Lorem ipsum ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('dolor ');
builder.pop();
builder.addText('sit');
})
..layout(constrain(90.0));
// Lines:
// "Lorem "
// "ipsum "
// "dolor sit"
// Above the first line, at the beginning.
expect(
paragraph.getPositionForOffset(const ui.Offset(0, -5)),
pos(0, ui.TextAffinity.downstream),
);
// At the beginning of the first line.
expect(
paragraph.getPositionForOffset(const ui.Offset(0, 5)),
pos(0, ui.TextAffinity.downstream),
);
// At the end of the first line.
expect(
paragraph.getPositionForOffset(const ui.Offset(60, 5)),
pos(6, ui.TextAffinity.upstream),
);
// After the end of the first line to the right.
expect(
paragraph.getPositionForOffset(const ui.Offset(70, 5)),
pos(6, ui.TextAffinity.upstream),
);
// On the left half of " " in "Lorem ".
expect(
paragraph.getPositionForOffset(const ui.Offset(54, 5)),
pos(5, ui.TextAffinity.downstream),
);
// On the right half of " " in "Lorem ".
expect(
paragraph.getPositionForOffset(const ui.Offset(56, 5)),
pos(6, ui.TextAffinity.upstream),
);
// At the beginning of the second line "ipsum ".
expect(
paragraph.getPositionForOffset(const ui.Offset(0, 15)),
pos(6, ui.TextAffinity.downstream),
);
// At the end of the second line.
expect(
paragraph.getPositionForOffset(const ui.Offset(60, 15)),
pos(12, ui.TextAffinity.upstream),
);
// After the end of the second line to the right.
expect(
paragraph.getPositionForOffset(const ui.Offset(70, 15)),
pos(12, ui.TextAffinity.upstream),
);
// Below the third line "dolor sit", at the end.
expect(
paragraph.getPositionForOffset(const ui.Offset(90, 40)),
pos(21, ui.TextAffinity.upstream),
);
// At the end of the third line.
expect(
paragraph.getPositionForOffset(const ui.Offset(90, 25)),
pos(21, ui.TextAffinity.upstream),
);
// After the end of the third line to the right.
expect(
paragraph.getPositionForOffset(const ui.Offset(100, 25)),
pos(21, ui.TextAffinity.upstream),
);
// On the left half of " " in "dolor sit".
expect(
paragraph.getPositionForOffset(const ui.Offset(54, 25)),
pos(17, ui.TextAffinity.downstream),
);
// On the right half of " " in "dolor sit".
expect(
paragraph.getPositionForOffset(const ui.Offset(56, 25)),
pos(18, ui.TextAffinity.upstream),
);
});
});
group('$CanvasParagraph.getLineBoundary', () {
test('single-line', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.addText('One single line');
})
..layout(constrain(400.0));
// "One single line".length == 15
for (int i = 0; i < 15; i++) {
expect(
paragraph.getLineBoundary(ui.TextPosition(offset: i)),
const ui.TextRange(start: 0, end: 15),
reason: 'failed at offset $i',
);
}
});
test('multi-line', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.addText('First line\n');
builder.addText('Second line\n');
builder.addText('Third line');
})
..layout(constrain(400.0));
// "First line\n".length == 11
for (int i = 0; i < 11; i++) {
expect(
paragraph.getLineBoundary(ui.TextPosition(offset: i)),
// The "\n" is not included in the line boundary.
const ui.TextRange(start: 0, end: 10),
reason: 'failed at offset $i',
);
}
// "Second line\n".length == 12
for (int i = 11; i < 23; i++) {
expect(
paragraph.getLineBoundary(ui.TextPosition(offset: i)),
// The "\n" is not included in the line boundary.
const ui.TextRange(start: 11, end: 22),
reason: 'failed at offset $i',
);
}
// "Third line".length == 10
for (int i = 23; i < 33; i++) {
expect(
paragraph.getLineBoundary(ui.TextPosition(offset: i)),
const ui.TextRange(start: 23, end: 33),
reason: 'failed at offset $i',
);
}
});
});
test('$CanvasParagraph.getWordBoundary', () {
final ui.Paragraph paragraph = plain(ahemStyle, 'Lorem ipsum dolor');
const ui.TextRange loremRange = ui.TextRange(start: 0, end: 5);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 0)), loremRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 1)), loremRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 2)), loremRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 3)), loremRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 4)), loremRange);
const ui.TextRange firstSpace = ui.TextRange(start: 5, end: 6);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 5)), firstSpace);
const ui.TextRange ipsumRange = ui.TextRange(start: 6, end: 11);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 6)), ipsumRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 7)), ipsumRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 8)), ipsumRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 9)), ipsumRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 10)), ipsumRange);
const ui.TextRange secondSpace = ui.TextRange(start: 11, end: 12);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 11)), secondSpace);
const ui.TextRange dolorRange = ui.TextRange(start: 12, end: 17);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 12)), dolorRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 13)), dolorRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 14)), dolorRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 15)), dolorRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 16)), dolorRange);
const ui.TextRange endRange = ui.TextRange(start: 17, end: 17);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 17)), endRange);
});
test('$CanvasParagraph.getWordBoundary can handle text affinity', () {
final ui.Paragraph paragraph = plain(ahemStyle, 'Lorem ipsum dolor');
const ui.TextRange loremRange = ui.TextRange(start: 0, end: 5);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 4)), loremRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 5, affinity: ui.TextAffinity.upstream)), loremRange);
});
test('$CanvasParagraph.longestLine', () {
final ui.Paragraph paragraph = plain(ahemStyle, 'abcd\nabcde abc');
paragraph.layout(const ui.ParagraphConstraints(width: 80.0));
expect(paragraph.longestLine, 50.0);
});
test('Render after dispose', () async {
final ui.Paragraph paragraph = plain(ahemStyle, 'abc');
paragraph.layout(const ui.ParagraphConstraints(width: 30.8));
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();
paragraph.dispose();
final ui.SceneBuilder builder = ui.SceneBuilder();
builder.addPicture(ui.Offset.zero, picture);
final ui.Scene scene = builder.build();
await renderScene(scene);
picture.dispose();
scene.dispose();
});
}
/// Shortcut to create a [ui.TextBox] with an optional [ui.TextDirection].
ui.TextBox box(
double left,
double top,
double right,
double bottom, [
ui.TextDirection direction = ui.TextDirection.ltr,
]) {
return ui.TextBox.fromLTRBD(left, top, right, bottom, direction);
}
/// Shortcut to create a [ui.TextPosition].
ui.TextPosition pos(int offset, ui.TextAffinity affinity) {
return ui.TextPosition(offset: offset, affinity: affinity);
}
| engine/lib/web_ui/test/html/text/canvas_paragraph_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/html/text/canvas_paragraph_test.dart",
"repo_id": "engine",
"token_count": 11898
} | 274 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/ui.dart';
import 'package:web_engine_tester/golden_tester.dart';
import '../common/test_initialization.dart';
import 'utils.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests(
withImplicitView: true,
setUpTestViewDimensions: false,
);
const Rect region = Rect.fromLTWH(0, 0, 300, 300);
test('draws lines with varying strokeWidth', () async {
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder, region);
paintLines(canvas);
await drawPictureUsingCurrentRenderer(recorder.endRecording());
await matchGoldenFile('canvas_lines_thickness.png', region: region);
});
test('draws lines with negative Offset values', () async {
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder, region);
// test rendering lines correctly with negative offset when using DOM
final Paint paintWithStyle = Paint()
..color = const Color(0xFFE91E63) // Colors.pink
..style = PaintingStyle.stroke
..strokeWidth = 16
..strokeCap = StrokeCap.round;
// canvas.drawLine ignores paint.style (defaults to fill) according to api docs.
// expect lines are rendered the same regardless of the set paint.style
final Paint paintWithoutStyle = Paint()
..color = const Color(0xFF4CAF50) // Colors.green
..strokeWidth = 16
..strokeCap = StrokeCap.round;
// test vertical, horizontal, and diagonal lines
final List<Offset> points = <Offset>[
const Offset(-25, 50), const Offset(45, 50),
const Offset(100, -25), const Offset(100, 200),
const Offset(-150, -145), const Offset(100, 200),
];
final List<Offset> shiftedPoints = points.map((Offset point) => point.translate(20, 20)).toList();
paintLinesFromPoints(canvas, paintWithStyle, points);
paintLinesFromPoints(canvas, paintWithoutStyle, shiftedPoints);
await drawPictureUsingCurrentRenderer(recorder.endRecording());
await matchGoldenFile('canvas_lines_with_negative_offset.png', region: region);
});
test('drawLines method respects strokeCap', () async {
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder, region);
final Paint paintStrokeCapRound = Paint()
..color = const Color(0xFFE91E63) // Colors.pink
..strokeWidth = 16
..strokeCap = StrokeCap.round;
final Paint paintStrokeCapSquare = Paint()
..color = const Color(0xFF4CAF50) // Colors.green
..strokeWidth = 16
..strokeCap = StrokeCap.square;
final Paint paintStrokeCapButt = Paint()
..color = const Color(0xFFFF9800) // Colors.orange
..strokeWidth = 16
..strokeCap = StrokeCap.butt;
// test vertical, horizontal, and diagonal lines
final List<Offset> points = <Offset>[
const Offset(5, 50), const Offset(45, 50),
const Offset(100, 5), const Offset(100, 200),
const Offset(5, 10), const Offset(100, 200),
];
final List<Offset> shiftedPoints = points.map((Offset point) => point.translate(50, 50)).toList();
final List<Offset> twiceShiftedPoints = shiftedPoints.map((Offset point) => point.translate(50, 50)).toList();
paintLinesFromPoints(canvas, paintStrokeCapRound, points);
paintLinesFromPoints(canvas, paintStrokeCapSquare, shiftedPoints);
paintLinesFromPoints(canvas, paintStrokeCapButt, twiceShiftedPoints);
await drawPictureUsingCurrentRenderer(recorder.endRecording());
await matchGoldenFile('canvas_lines_with_strokeCap.png', region: region);
});
}
void paintLines(Canvas canvas) {
final Paint nullPaint = Paint()
..strokeWidth = 1.0
..style = PaintingStyle.stroke;
final Paint paint1 = Paint()
..color = const Color(0xFF9E9E9E) // Colors.grey
..strokeWidth = 1.0
..style = PaintingStyle.stroke;
final Paint paint2 = Paint()
..color = const Color(0x7fff0000)
..strokeWidth = 1.0
..style = PaintingStyle.stroke;
final Paint paint3 = Paint()
..color = const Color(0xFF4CAF50) //Colors.green
..strokeWidth = 1.0
..style = PaintingStyle.stroke;
// Draw markers around 100x100 box
canvas.drawLine(const Offset(50, 40), const Offset(148, 40), nullPaint);
canvas.drawLine(const Offset(50, 50), const Offset(52, 50), paint1);
canvas.drawLine(const Offset(150, 50), const Offset(148, 50), paint1);
canvas.drawLine(const Offset(50, 150), const Offset(52, 150), paint1);
canvas.drawLine(const Offset(150, 150), const Offset(148, 150), paint1);
// Draw diagonal
canvas.drawLine(const Offset(50, 50), const Offset(150, 150), paint2);
// Draw horizontal
paint3.strokeWidth = 1.0;
paint3.color = const Color(0xFFFF0000);
canvas.drawLine(const Offset(50, 55), const Offset(150, 55), paint3);
paint3.strokeWidth = 2.0;
paint3.color = const Color(0xFF2196F3); // Colors.blue;
canvas.drawLine(const Offset(50, 60), const Offset(150, 60), paint3);
paint3.strokeWidth = 4.0;
paint3.color = const Color(0xFFFF9800); // Colors.orange;
canvas.drawLine(const Offset(50, 70), const Offset(150, 70), paint3);
}
void paintLinesFromPoints(Canvas canvas, Paint paint, List<Offset> points) {
// points list contains pairs of Offset points, so for loop step is 2
for (int i = 0; i < points.length - 1; i += 2) {
canvas.drawLine(points[i], points[i + 1], paint);
}
}
| engine/lib/web_ui/test/ui/canvas_lines_golden_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/ui/canvas_lines_golden_test.dart",
"repo_id": "engine",
"token_count": 1941
} | 275 |
// Copyright 2013 The Flutter 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:math' as math;
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/ui.dart';
import '../common/matchers.dart';
import '../common/test_initialization.dart';
const double kTolerance = 0.1;
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests();
group('PathMetric length', () {
test('empty path', () {
final Path path = Path();
expect(path.computeMetrics().isEmpty, isTrue);
});
test('simple line', () {
final Path path = Path();
path.moveTo(100.0, 50.0);
path.lineTo(200.0, 100.0);
expect(path.computeMetrics().isEmpty, isFalse);
final List<PathMetric> metrics = path.computeMetrics().toList();
expect(metrics.length, 1);
expect(metrics[0].length, within(distance: kTolerance, from: 111.803));
});
test('2 lines', () {
final Path path = Path();
path.moveTo(100.0, 50.0);
path.lineTo(200.0, 50.0);
path.lineTo(100.0, 200.0);
expect(path.computeMetrics().isEmpty, isFalse);
final List<PathMetric> metrics = path.computeMetrics().toList();
expect(metrics.length, 1);
expect(metrics[0].length, within(distance: kTolerance, from: 280.277));
});
test('2 lines forceClosed', () {
final Path path = Path();
path.moveTo(100.0, 50.0);
path.lineTo(200.0, 50.0);
path.lineTo(100.0, 200.0);
expect(path.computeMetrics(forceClosed: true).isEmpty, isFalse);
final List<PathMetric> metrics =
path.computeMetrics(forceClosed: true).toList();
expect(metrics.length, 1);
expect(metrics[0].length, within(distance: kTolerance, from: 430.277));
});
test('2 subpaths', () {
final Path path = Path();
path.moveTo(100.0, 50.0);
path.lineTo(200.0, 100.0);
path.moveTo(200.0, 100.0);
path.lineTo(200.0, 200.0);
final List<double> contourLengths = computeLengths(path.computeMetrics());
expect(contourLengths.length, 2);
expect(contourLengths[0], within(distance: kTolerance, from: 111.803));
expect(contourLengths[1], within(distance: kTolerance, from: 100.0));
});
test('quadratic curve', () {
final Path path = Path();
path.moveTo(20, 100);
path.quadraticBezierTo(80, 10, 140, 110);
final List<double> contourLengths = computeLengths(path.computeMetrics());
expect(contourLengths.length, 1);
expect(contourLengths[0], within(distance: kTolerance, from: 159.473));
});
test('cubic curve', () {
final Path path = Path();
path.moveTo(20, 100);
path.cubicTo(80, 10, 120, 90, 140, 40);
final List<double> contourLengths = computeLengths(path.computeMetrics());
expect(contourLengths.length, 1);
expect(contourLengths[0], within(distance: kTolerance, from: 146.567));
});
test('addRect', () {
final Path path = Path();
path.addRect(const Rect.fromLTRB(20, 30, 220, 130));
final List<double> contourLengths = computeLengths(path.computeMetrics());
expect(contourLengths.length, 1);
expect(contourLengths[0], within(distance: kTolerance, from: 600.0));
});
test('addRRect with zero radius', () {
final Path path = Path();
path.addRRect(RRect.fromLTRBR(20, 30, 220, 130, Radius.zero));
final List<double> contourLengths = computeLengths(path.computeMetrics());
expect(contourLengths.length, 1);
expect(contourLengths[0], within(distance: kTolerance, from: 600.0));
});
test('addRRect with elliptical radius', () {
final Path path = Path();
path.addRRect(RRect.fromLTRBR(20, 30, 220, 130, const Radius.elliptical(8, 4)));
final List<double> contourLengths = computeLengths(path.computeMetrics());
expect(contourLengths.length, 1);
expect(contourLengths[0], within(distance: kTolerance, from: 590.408));
});
test('arcToPoint < 90 degrees', () {
const double rx = 100;
const double ry = 100;
const double cx = 150;
const double cy = 100;
const double startAngle = 0.0;
const double endAngle = 90.0;
const double startRad = startAngle * math.pi / 180.0;
const double endRad = endAngle * math.pi / 180.0;
final double startX = cx + (rx * math.cos(startRad));
final double startY = cy + (ry * math.sin(startRad));
final double endX = cx + (rx * math.cos(endRad));
final double endY = cy + (ry * math.sin(endRad));
final bool largeArc = (endAngle - startAngle).abs() > 180.0;
final Path path = Path()
..moveTo(startX, startY)
..arcToPoint(Offset(endX, endY),
radius: const Radius.elliptical(rx, ry),
largeArc: largeArc);
final List<double> contourLengths = computeLengths(path.computeMetrics());
expect(contourLengths.length, 1);
expect(contourLengths[0], within(distance: kTolerance, from: 156.827));
});
test('arcToPoint 180 degrees', () {
const double rx = 100;
const double ry = 100;
const double cx = 150;
const double cy = 100;
const double startAngle = 0.0;
const double endAngle = 180.0;
const double startRad = startAngle * math.pi / 180.0;
const double endRad = endAngle * math.pi / 180.0;
final double startX = cx + (rx * math.cos(startRad));
final double startY = cy + (ry * math.sin(startRad));
final double endX = cx + (rx * math.cos(endRad));
final double endY = cy + (ry * math.sin(endRad));
final bool largeArc = (endAngle - startAngle).abs() > 180.0;
final Path path = Path()
..moveTo(startX, startY)
..arcToPoint(Offset(endX, endY),
radius: const Radius.elliptical(rx, ry),
largeArc: largeArc);
final List<double> contourLengths = computeLengths(path.computeMetrics());
expect(contourLengths.length, 1);
expect(contourLengths[0], within(distance: kTolerance, from: 313.654));
});
test('arcToPoint 270 degrees', () {
const double rx = 100;
const double ry = 100;
const double cx = 150;
const double cy = 100;
const double startAngle = 0.0;
const double endAngle = 270.0;
const double startRad = startAngle * math.pi / 180.0;
const double endRad = endAngle * math.pi / 180.0;
final double startX = cx + (rx * math.cos(startRad));
final double startY = cy + (ry * math.sin(startRad));
final double endX = cx + (rx * math.cos(endRad));
final double endY = cy + (ry * math.sin(endRad));
final bool largeArc = (endAngle - startAngle).abs() > 180.0;
final Path path = Path()
..moveTo(startX, startY)
..arcToPoint(Offset(endX, endY),
radius: const Radius.elliptical(rx, ry),
largeArc: largeArc);
final List<double> contourLengths = computeLengths(path.computeMetrics());
expect(contourLengths.length, 1);
expect(contourLengths[0], within(distance: kTolerance, from: 470.482));
});
test('arcToPoint 270 degrees rx!=ry', () {
const double rx = 100;
const double ry = 50;
const double cx = 150;
const double cy = 100;
const double startAngle = 0.0;
const double endAngle = 270.0;
const double startRad = startAngle * math.pi / 180.0;
const double endRad = endAngle * math.pi / 180.0;
final double startX = cx + (rx * math.cos(startRad));
final double startY = cy + (ry * math.sin(startRad));
final double endX = cx + (rx * math.cos(endRad));
final double endY = cy + (ry * math.sin(endRad));
final bool largeArc = (endAngle - startAngle).abs() > 180.0;
final Path path = Path()
..moveTo(startX, startY)
..arcToPoint(Offset(endX, endY),
radius: const Radius.elliptical(rx, ry),
largeArc: largeArc);
final List<double> contourLengths = computeLengths(path.computeMetrics());
expect(contourLengths.length, 1);
expect(contourLengths[0], within(distance: kTolerance, from: 362.733));
});
});
}
List<double> computeLengths(PathMetrics pathMetrics) {
final List<double> lengths = <double>[];
for (final PathMetric metric in pathMetrics) {
lengths.add(metric.length);
}
return lengths;
}
| engine/lib/web_ui/test/ui/path_metrics_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/ui/path_metrics_test.dart",
"repo_id": "engine",
"token_count": 3487
} | 276 |
// Copyright 2013 The Flutter 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/runtime/dart_isolate.h"
#include <cstdlib>
#include <tuple>
#include <utility>
#include "flutter/fml/logging.h"
#include "flutter/fml/posix_wrappers.h"
#include "flutter/fml/trace_event.h"
#include "flutter/lib/io/dart_io.h"
#include "flutter/lib/ui/dart_runtime_hooks.h"
#include "flutter/lib/ui/dart_ui.h"
#include "flutter/lib/ui/window/platform_isolate.h"
#include "flutter/runtime/dart_isolate_group_data.h"
#include "flutter/runtime/dart_plugin_registrant.h"
#include "flutter/runtime/dart_service_isolate.h"
#include "flutter/runtime/dart_vm.h"
#include "flutter/runtime/dart_vm_lifecycle.h"
#include "flutter/runtime/isolate_configuration.h"
#include "flutter/runtime/runtime_controller.h"
#include "fml/message_loop_task_queues.h"
#include "fml/task_source.h"
#include "fml/time/time_point.h"
#include "third_party/dart/runtime/include/dart_api.h"
#include "third_party/dart/runtime/include/dart_tools_api.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_class_library.h"
#include "third_party/tonic/dart_class_provider.h"
#include "third_party/tonic/dart_message_handler.h"
#include "third_party/tonic/dart_state.h"
#include "third_party/tonic/file_loader/file_loader.h"
#include "third_party/tonic/logging/dart_invoke.h"
#include "third_party/tonic/scopes/dart_api_scope.h"
#include "third_party/tonic/scopes/dart_isolate_scope.h"
namespace flutter {
namespace {
constexpr std::string_view kFileUriPrefix = "file://";
class DartErrorString {
public:
DartErrorString() {}
~DartErrorString() {
if (str_) {
::free(str_);
}
}
char** error() { return &str_; }
const char* str() const { return str_; }
explicit operator bool() const { return str_ != nullptr; }
private:
FML_DISALLOW_COPY_AND_ASSIGN(DartErrorString);
char* str_ = nullptr;
};
} // anonymous namespace
DartIsolate::Flags::Flags() : Flags(nullptr) {}
DartIsolate::Flags::Flags(const Dart_IsolateFlags* flags) {
if (flags) {
flags_ = *flags;
} else {
::Dart_IsolateFlagsInitialize(&flags_);
}
}
DartIsolate::Flags::~Flags() = default;
void DartIsolate::Flags::SetNullSafetyEnabled(bool enabled) {
flags_.null_safety = enabled;
}
void DartIsolate::Flags::SetIsDontNeedSafe(bool value) {
flags_.snapshot_is_dontneed_safe = value;
}
Dart_IsolateFlags DartIsolate::Flags::Get() const {
return flags_;
}
std::weak_ptr<DartIsolate> DartIsolate::CreateRunningRootIsolate(
const Settings& settings,
const fml::RefPtr<const DartSnapshot>& isolate_snapshot,
std::unique_ptr<PlatformConfiguration> platform_configuration,
Flags isolate_flags,
const fml::closure& root_isolate_create_callback,
const fml::closure& isolate_create_callback,
const fml::closure& isolate_shutdown_callback,
std::optional<std::string> dart_entrypoint,
std::optional<std::string> dart_entrypoint_library,
const std::vector<std::string>& dart_entrypoint_args,
std::unique_ptr<IsolateConfiguration> isolate_configuration,
const UIDartState::Context& context,
const DartIsolate* spawning_isolate) {
if (!isolate_snapshot) {
FML_LOG(ERROR) << "Invalid isolate snapshot.";
return {};
}
if (!isolate_configuration) {
FML_LOG(ERROR) << "Invalid isolate configuration.";
return {};
}
isolate_flags.SetNullSafetyEnabled(
isolate_configuration->IsNullSafetyEnabled(*isolate_snapshot));
isolate_flags.SetIsDontNeedSafe(isolate_snapshot->IsDontNeedSafe());
auto isolate = CreateRootIsolate(settings, //
isolate_snapshot, //
std::move(platform_configuration), //
isolate_flags, //
isolate_create_callback, //
isolate_shutdown_callback, //
context, //
spawning_isolate //
)
.lock();
if (!isolate) {
FML_LOG(ERROR) << "Could not create root isolate.";
return {};
}
fml::ScopedCleanupClosure shutdown_on_error([isolate]() {
if (!isolate->Shutdown()) {
FML_DLOG(ERROR) << "Could not shutdown transient isolate.";
}
});
if (isolate->GetPhase() != DartIsolate::Phase::LibrariesSetup) {
FML_LOG(ERROR) << "Root isolate was created in an incorrect phase: "
<< static_cast<int>(isolate->GetPhase());
return {};
}
if (!isolate_configuration->PrepareIsolate(*isolate.get())) {
FML_LOG(ERROR) << "Could not prepare isolate.";
return {};
}
if (isolate->GetPhase() != DartIsolate::Phase::Ready) {
FML_LOG(ERROR) << "Root isolate not in the ready phase for Dart entrypoint "
"invocation.";
return {};
}
if (settings.root_isolate_create_callback) {
// Isolate callbacks always occur in isolate scope and before user code has
// had a chance to run.
tonic::DartState::Scope scope(isolate.get());
settings.root_isolate_create_callback(*isolate.get());
}
if (root_isolate_create_callback) {
root_isolate_create_callback();
}
if (!isolate->RunFromLibrary(std::move(dart_entrypoint_library), //
std::move(dart_entrypoint), //
dart_entrypoint_args)) {
FML_LOG(ERROR) << "Could not run the run main Dart entrypoint.";
return {};
}
if (settings.root_isolate_shutdown_callback) {
isolate->AddIsolateShutdownCallback(
settings.root_isolate_shutdown_callback);
}
shutdown_on_error.Release();
return isolate;
}
void DartIsolate::SpawnIsolateShutdownCallback(
std::shared_ptr<DartIsolateGroupData>* isolate_group_data,
std::shared_ptr<DartIsolate>* isolate_data) {
DartIsolate::DartIsolateShutdownCallback(isolate_group_data, isolate_data);
}
std::weak_ptr<DartIsolate> DartIsolate::CreateRootIsolate(
const Settings& settings,
fml::RefPtr<const DartSnapshot> isolate_snapshot,
std::unique_ptr<PlatformConfiguration> platform_configuration,
const Flags& flags,
const fml::closure& isolate_create_callback,
const fml::closure& isolate_shutdown_callback,
const UIDartState::Context& context,
const DartIsolate* spawning_isolate) {
TRACE_EVENT0("flutter", "DartIsolate::CreateRootIsolate");
// Only needed if this is the main isolate for the group.
std::unique_ptr<std::shared_ptr<DartIsolateGroupData>> isolate_group_data;
auto isolate_data = std::make_unique<std::shared_ptr<DartIsolate>>(
std::shared_ptr<DartIsolate>(new DartIsolate(
/*settings=*/settings,
/*is_root_isolate=*/true,
/*context=*/context,
/*is_spawning_in_group=*/!!spawning_isolate)));
DartErrorString error;
Dart_Isolate vm_isolate = nullptr;
auto isolate_flags = flags.Get();
IsolateMaker isolate_maker;
if (spawning_isolate) {
isolate_maker =
[spawning_isolate](
std::shared_ptr<DartIsolateGroupData>* isolate_group_data,
std::shared_ptr<DartIsolate>* isolate_data,
Dart_IsolateFlags* flags, char** error) {
return Dart_CreateIsolateInGroup(
/*group_member=*/spawning_isolate->isolate(),
/*name=*/
spawning_isolate->GetIsolateGroupData()
.GetAdvisoryScriptEntrypoint()
.c_str(),
/*shutdown_callback=*/
reinterpret_cast<Dart_IsolateShutdownCallback>(
DartIsolate::SpawnIsolateShutdownCallback),
/*cleanup_callback=*/
reinterpret_cast<Dart_IsolateCleanupCallback>(
DartIsolateCleanupCallback),
/*child_isolate_data=*/isolate_data,
/*error=*/error);
};
} else {
// The child isolate preparer is null but will be set when the isolate is
// being prepared to run.
isolate_group_data =
std::make_unique<std::shared_ptr<DartIsolateGroupData>>(
std::shared_ptr<DartIsolateGroupData>(new DartIsolateGroupData(
settings, // settings
std::move(isolate_snapshot), // isolate snapshot
context.advisory_script_uri, // advisory URI
context.advisory_script_entrypoint, // advisory entrypoint
nullptr, // child isolate preparer
isolate_create_callback, // isolate create callback
isolate_shutdown_callback // isolate shutdown callback
)));
isolate_maker = [](std::shared_ptr<DartIsolateGroupData>*
isolate_group_data,
std::shared_ptr<DartIsolate>* isolate_data,
Dart_IsolateFlags* flags, char** error) {
return Dart_CreateIsolateGroup(
(*isolate_group_data)->GetAdvisoryScriptURI().c_str(),
(*isolate_group_data)->GetAdvisoryScriptEntrypoint().c_str(),
(*isolate_group_data)->GetIsolateSnapshot()->GetDataMapping(),
(*isolate_group_data)->GetIsolateSnapshot()->GetInstructionsMapping(),
flags, isolate_group_data, isolate_data, error);
};
}
vm_isolate = CreateDartIsolateGroup(std::move(isolate_group_data),
std::move(isolate_data), &isolate_flags,
error.error(), isolate_maker);
if (error) {
FML_LOG(ERROR) << "CreateRootIsolate failed: " << error.str();
}
if (vm_isolate == nullptr) {
return {};
}
std::shared_ptr<DartIsolate>* root_isolate_data =
static_cast<std::shared_ptr<DartIsolate>*>(Dart_IsolateData(vm_isolate));
(*root_isolate_data)
->SetPlatformConfiguration(std::move(platform_configuration));
return (*root_isolate_data)->GetWeakIsolatePtr();
}
Dart_Isolate DartIsolate::CreatePlatformIsolate(Dart_Handle entry_point,
char** error) {
*error = nullptr;
PlatformConfiguration* platform_config = platform_configuration();
FML_DCHECK(platform_config != nullptr);
std::shared_ptr<PlatformIsolateManager> platform_isolate_manager =
platform_config->client()->GetPlatformIsolateManager();
std::weak_ptr<PlatformIsolateManager> weak_platform_isolate_manager =
platform_isolate_manager;
if (platform_isolate_manager->HasShutdownMaybeFalseNegative()) {
// Don't set the error string. We want to silently ignore this error,
// because the engine is shutting down.
FML_LOG(INFO) << "CreatePlatformIsolate called after shutdown";
return nullptr;
}
Dart_Isolate parent_isolate = isolate();
Dart_ExitIsolate(); // Exit parent_isolate.
const TaskRunners& task_runners = GetTaskRunners();
fml::RefPtr<fml::TaskRunner> platform_task_runner =
task_runners.GetPlatformTaskRunner();
FML_DCHECK(platform_task_runner);
auto isolate_group_data = std::shared_ptr<DartIsolateGroupData>(
*static_cast<std::shared_ptr<DartIsolateGroupData>*>(
Dart_IsolateGroupData(parent_isolate)));
Settings settings(isolate_group_data->GetSettings());
// PlatformIsolate.spawn should behave like Isolate.spawn when unhandled
// exceptions happen (log the exception, but don't terminate the app). But the
// default unhandled_exception_callback may terminate the app, because it is
// only called for the root isolate (child isolates are managed by the VM and
// have a different error code path). So override it to simply log the error.
settings.unhandled_exception_callback = [](const std::string& error,
const std::string& stack_trace) {
FML_LOG(ERROR) << "Unhandled exception:\n" << error << "\n" << stack_trace;
return true;
};
// The platform isolate task observer must be added on the platform thread. So
// schedule the add function on the platform task runner.
TaskObserverAdd old_task_observer_add = settings.task_observer_add;
settings.task_observer_add = [old_task_observer_add, platform_task_runner,
weak_platform_isolate_manager](
intptr_t key, const fml::closure& callback) {
platform_task_runner->PostTask([old_task_observer_add,
weak_platform_isolate_manager, key,
callback]() {
std::shared_ptr<PlatformIsolateManager> platform_isolate_manager =
weak_platform_isolate_manager.lock();
if (platform_isolate_manager == nullptr ||
platform_isolate_manager->HasShutdown()) {
// Shutdown happened in between this task being posted, and it running.
// platform_isolate has already been shut down. Do nothing.
FML_LOG(INFO) << "Shutdown before platform isolate task observer added";
return;
}
old_task_observer_add(key, callback);
});
};
UIDartState::Context context(task_runners);
context.advisory_script_uri = isolate_group_data->GetAdvisoryScriptURI();
context.advisory_script_entrypoint =
isolate_group_data->GetAdvisoryScriptEntrypoint();
auto isolate_data = std::make_unique<std::shared_ptr<DartIsolate>>(
std::shared_ptr<DartIsolate>(
new DartIsolate(settings, context, platform_isolate_manager)));
IsolateMaker isolate_maker =
[parent_isolate](
std::shared_ptr<DartIsolateGroupData>* unused_isolate_group_data,
std::shared_ptr<DartIsolate>* isolate_data, Dart_IsolateFlags* flags,
char** error) {
return Dart_CreateIsolateInGroup(
/*group_member=*/parent_isolate,
/*name=*/"PlatformIsolate",
/*shutdown_callback=*/
reinterpret_cast<Dart_IsolateShutdownCallback>(
DartIsolate::SpawnIsolateShutdownCallback),
/*cleanup_callback=*/
reinterpret_cast<Dart_IsolateCleanupCallback>(
DartIsolateCleanupCallback),
/*child_isolate_data=*/isolate_data,
/*error=*/error);
};
Dart_Isolate platform_isolate = CreateDartIsolateGroup(
nullptr, std::move(isolate_data), nullptr, error, isolate_maker);
Dart_EnterIsolate(parent_isolate);
if (*error) {
return nullptr;
}
if (!platform_isolate_manager->RegisterPlatformIsolate(platform_isolate)) {
// The PlatformIsolateManager was shutdown while we were creating the
// isolate. This means that we're shutting down the engine. We need to
// shutdown the platform isolate.
FML_LOG(INFO) << "Shutdown during platform isolate creation";
tonic::DartIsolateScope isolate_scope(platform_isolate);
Dart_ShutdownIsolate();
return nullptr;
}
tonic::DartApiScope api_scope;
Dart_PersistentHandle entry_point_handle =
Dart_NewPersistentHandle(entry_point);
platform_task_runner->PostTask([entry_point_handle, platform_isolate,
weak_platform_isolate_manager]() {
std::shared_ptr<PlatformIsolateManager> platform_isolate_manager =
weak_platform_isolate_manager.lock();
if (platform_isolate_manager == nullptr ||
platform_isolate_manager->HasShutdown()) {
// Shutdown happened in between this task being posted, and it running.
// platform_isolate has already been shut down. Do nothing.
FML_LOG(INFO) << "Shutdown before platform isolate entry point";
return;
}
tonic::DartIsolateScope isolate_scope(platform_isolate);
tonic::DartApiScope api_scope;
Dart_Handle entry_point = Dart_HandleFromPersistent(entry_point_handle);
Dart_DeletePersistentHandle(entry_point_handle);
// Disable Isolate.exit().
Dart_Handle isolate_lib = Dart_LookupLibrary(tonic::ToDart("dart:isolate"));
FML_CHECK(!tonic::CheckAndHandleError(isolate_lib));
Dart_Handle isolate_type = Dart_GetNonNullableType(
isolate_lib, tonic::ToDart("Isolate"), 0, nullptr);
FML_CHECK(!tonic::CheckAndHandleError(isolate_type));
Dart_Handle result =
Dart_SetField(isolate_type, tonic::ToDart("_mayExit"), Dart_False());
FML_CHECK(!tonic::CheckAndHandleError(result));
tonic::DartInvokeVoid(entry_point);
});
return platform_isolate;
}
DartIsolate::DartIsolate(const Settings& settings,
bool is_root_isolate,
const UIDartState::Context& context,
bool is_spawning_in_group)
: UIDartState(settings.task_observer_add,
settings.task_observer_remove,
settings.log_tag,
settings.unhandled_exception_callback,
settings.log_message_callback,
DartVMRef::GetIsolateNameServer(),
is_root_isolate,
context),
may_insecurely_connect_to_all_domains_(
settings.may_insecurely_connect_to_all_domains),
is_platform_isolate_(false),
is_spawning_in_group_(is_spawning_in_group),
domain_network_policy_(settings.domain_network_policy) {
phase_ = Phase::Uninitialized;
}
DartIsolate::DartIsolate(
const Settings& settings,
const UIDartState::Context& context,
std::shared_ptr<PlatformIsolateManager> platform_isolate_manager)
: UIDartState(settings.task_observer_add,
settings.task_observer_remove,
settings.log_tag,
settings.unhandled_exception_callback,
settings.log_message_callback,
DartVMRef::GetIsolateNameServer(),
false, // is_root_isolate
context),
may_insecurely_connect_to_all_domains_(
settings.may_insecurely_connect_to_all_domains),
is_platform_isolate_(true),
is_spawning_in_group_(false),
domain_network_policy_(settings.domain_network_policy),
platform_isolate_manager_(std::move(platform_isolate_manager)) {
phase_ = Phase::Uninitialized;
}
DartIsolate::~DartIsolate() {
if (IsRootIsolate() && GetMessageHandlingTaskRunner()) {
FML_DCHECK(GetMessageHandlingTaskRunner()->RunsTasksOnCurrentThread());
}
}
DartIsolate::Phase DartIsolate::GetPhase() const {
return phase_;
}
std::string DartIsolate::GetServiceId() {
const char* service_id_buf = Dart_IsolateServiceId(isolate());
std::string service_id(service_id_buf);
free(const_cast<char*>(service_id_buf));
return service_id;
}
bool DartIsolate::Initialize(Dart_Isolate dart_isolate) {
TRACE_EVENT0("flutter", "DartIsolate::Initialize");
if (phase_ != Phase::Uninitialized) {
return false;
}
FML_DCHECK(dart_isolate != nullptr);
FML_DCHECK(dart_isolate == Dart_CurrentIsolate());
// After this point, isolate scopes can be safely used.
SetIsolate(dart_isolate);
// For the root isolate set the "AppStartUp" as soon as the root isolate
// has been initialized. This is to ensure that all the timeline events
// that have the set user-tag will be listed user AppStartUp.
if (IsRootIsolate()) {
tonic::DartApiScope api_scope;
Dart_SetCurrentUserTag(Dart_NewUserTag("AppStartUp"));
}
SetMessageHandlingTaskRunner(is_platform_isolate_
? GetTaskRunners().GetPlatformTaskRunner()
: GetTaskRunners().GetUITaskRunner());
if (tonic::CheckAndHandleError(
Dart_SetLibraryTagHandler(tonic::DartState::HandleLibraryTag))) {
return false;
}
if (tonic::CheckAndHandleError(
Dart_SetDeferredLoadHandler(OnDartLoadLibrary))) {
return false;
}
if (!UpdateThreadPoolNames()) {
return false;
}
phase_ = Phase::Initialized;
return true;
}
fml::RefPtr<fml::TaskRunner> DartIsolate::GetMessageHandlingTaskRunner() const {
return message_handling_task_runner_;
}
bool DartIsolate::LoadLoadingUnit(
intptr_t loading_unit_id,
std::unique_ptr<const fml::Mapping> snapshot_data,
std::unique_ptr<const fml::Mapping> snapshot_instructions) {
tonic::DartState::Scope scope(this);
fml::RefPtr<DartSnapshot> dart_snapshot =
DartSnapshot::IsolateSnapshotFromMappings(
std::move(snapshot_data), std::move(snapshot_instructions));
Dart_Handle result = Dart_DeferredLoadComplete(
loading_unit_id, dart_snapshot->GetDataMapping(),
dart_snapshot->GetInstructionsMapping());
if (tonic::CheckAndHandleError(result)) {
LoadLoadingUnitError(loading_unit_id, Dart_GetError(result),
/*transient*/ true);
return false;
}
loading_unit_snapshots_.insert(dart_snapshot);
return true;
}
void DartIsolate::LoadLoadingUnitError(intptr_t loading_unit_id,
const std::string& error_message,
bool transient) {
tonic::DartState::Scope scope(this);
Dart_Handle result = Dart_DeferredLoadCompleteError(
loading_unit_id, error_message.c_str(), transient);
tonic::CheckAndHandleError(result);
}
void DartIsolate::SetMessageHandlingTaskRunner(
const fml::RefPtr<fml::TaskRunner>& runner) {
if (!runner) {
return;
}
message_handling_task_runner_ = runner;
message_handler().Initialize([runner](std::function<void()> task) {
#ifdef OS_FUCHSIA
runner->PostTask([task = std::move(task)]() {
TRACE_EVENT0("flutter", "DartIsolate::HandleMessage");
task();
});
#else
auto task_queues = fml::MessageLoopTaskQueues::GetInstance();
task_queues->RegisterTask(
runner->GetTaskQueueId(),
[task = std::move(task)]() {
TRACE_EVENT0("flutter", "DartIsolate::HandleMessage");
task();
},
fml::TimePoint::Now(), fml::TaskSourceGrade::kDartEventLoop);
#endif
});
}
// Updating thread names here does not change the underlying OS thread names.
// Instead, this is just additional metadata for the Dart VM Service to show the
// thread name of the isolate.
bool DartIsolate::UpdateThreadPoolNames() const {
// TODO(chinmaygarde): This implementation does not account for multiple
// shells sharing the same (or subset of) threads.
const auto& task_runners = GetTaskRunners();
if (auto task_runner = task_runners.GetRasterTaskRunner()) {
task_runner->PostTask(
[label = task_runners.GetLabel() + std::string{".raster"}]() {
Dart_SetThreadName(label.c_str());
});
}
if (auto task_runner = task_runners.GetUITaskRunner()) {
task_runner->PostTask(
[label = task_runners.GetLabel() + std::string{".ui"}]() {
Dart_SetThreadName(label.c_str());
});
}
if (auto task_runner = task_runners.GetIOTaskRunner()) {
task_runner->PostTask(
[label = task_runners.GetLabel() + std::string{".io"}]() {
Dart_SetThreadName(label.c_str());
});
}
if (auto task_runner = task_runners.GetPlatformTaskRunner()) {
task_runner->PostTask(
[label = task_runners.GetLabel() + std::string{".platform"}]() {
Dart_SetThreadName(label.c_str());
});
}
return true;
}
bool DartIsolate::LoadLibraries() {
TRACE_EVENT0("flutter", "DartIsolate::LoadLibraries");
if (phase_ != Phase::Initialized) {
return false;
}
tonic::DartState::Scope scope(this);
DartIO::InitForIsolate(may_insecurely_connect_to_all_domains_,
domain_network_policy_);
DartUI::InitForIsolate(GetIsolateGroupData().GetSettings());
const bool is_service_isolate = Dart_IsServiceIsolate(isolate());
DartRuntimeHooks::Install(IsRootIsolate() && !is_service_isolate,
GetAdvisoryScriptURI());
if (!is_service_isolate) {
class_library().add_provider(
"ui", std::make_unique<tonic::DartClassProvider>(this, "dart:ui"));
}
phase_ = Phase::LibrariesSetup;
return true;
}
bool DartIsolate::PrepareForRunningFromPrecompiledCode() {
TRACE_EVENT0("flutter", "DartIsolate::PrepareForRunningFromPrecompiledCode");
if (phase_ != Phase::LibrariesSetup) {
return false;
}
tonic::DartState::Scope scope(this);
if (Dart_IsNull(Dart_RootLibrary())) {
return false;
}
if (!MarkIsolateRunnable()) {
return false;
}
if (GetIsolateGroupData().GetChildIsolatePreparer() == nullptr) {
GetIsolateGroupData().SetChildIsolatePreparer([](DartIsolate* isolate) {
return isolate->PrepareForRunningFromPrecompiledCode();
});
}
const fml::closure& isolate_create_callback =
GetIsolateGroupData().GetIsolateCreateCallback();
if (isolate_create_callback) {
isolate_create_callback();
}
phase_ = Phase::Ready;
return true;
}
bool DartIsolate::LoadKernel(const std::shared_ptr<const fml::Mapping>& mapping,
bool last_piece) {
if (!Dart_IsKernel(mapping->GetMapping(), mapping->GetSize())) {
return false;
}
// Mapping must be retained until isolate group shutdown.
GetIsolateGroupData().AddKernelBuffer(mapping);
Dart_Handle library =
Dart_LoadLibraryFromKernel(mapping->GetMapping(), mapping->GetSize());
if (tonic::CheckAndHandleError(library)) {
return false;
}
if (!last_piece) {
// More to come.
return true;
}
Dart_SetRootLibrary(library);
if (tonic::CheckAndHandleError(Dart_FinalizeLoading(false))) {
return false;
}
return true;
}
[[nodiscard]] bool DartIsolate::PrepareForRunningFromKernel(
const std::shared_ptr<const fml::Mapping>& mapping,
bool child_isolate,
bool last_piece) {
TRACE_EVENT0("flutter", "DartIsolate::PrepareForRunningFromKernel");
if (phase_ != Phase::LibrariesSetup) {
return false;
}
if (DartVM::IsRunningPrecompiledCode()) {
return false;
}
tonic::DartState::Scope scope(this);
if (!child_isolate && !is_spawning_in_group_) {
if (!mapping || mapping->GetSize() == 0) {
return false;
}
// Use root library provided by kernel in favor of one provided by snapshot.
Dart_SetRootLibrary(Dart_Null());
if (!LoadKernel(mapping, last_piece)) {
return false;
}
}
if (!last_piece) {
// More to come.
return true;
}
if (Dart_IsNull(Dart_RootLibrary())) {
return false;
}
if (!MarkIsolateRunnable()) {
return false;
}
// Child isolate shares root isolate embedder_isolate (lines 691 and 693
// below). Re-initializing child_isolate_preparer_ lambda while it is being
// executed leads to crashes.
if (GetIsolateGroupData().GetChildIsolatePreparer() == nullptr) {
GetIsolateGroupData().SetChildIsolatePreparer(
[buffers =
GetIsolateGroupData().GetKernelBuffers()](DartIsolate* isolate) {
for (uint64_t i = 0; i < buffers.size(); i++) {
bool last_piece = i + 1 == buffers.size();
const std::shared_ptr<const fml::Mapping>& buffer = buffers.at(i);
if (!isolate->PrepareForRunningFromKernel(buffer,
/*child_isolate=*/true,
last_piece)) {
return false;
}
}
return true;
});
}
const fml::closure& isolate_create_callback =
GetIsolateGroupData().GetIsolateCreateCallback();
if (isolate_create_callback) {
isolate_create_callback();
}
phase_ = Phase::Ready;
return true;
}
[[nodiscard]] bool DartIsolate::PrepareForRunningFromKernels(
std::vector<std::shared_ptr<const fml::Mapping>> kernels) {
const auto count = kernels.size();
if (count == 0) {
return false;
}
for (size_t i = 0; i < count; ++i) {
bool last = (i == (count - 1));
if (!PrepareForRunningFromKernel(kernels[i], /*child_isolate=*/false,
last)) {
return false;
}
}
return true;
}
[[nodiscard]] bool DartIsolate::PrepareForRunningFromKernels(
std::vector<std::unique_ptr<const fml::Mapping>> kernels) {
std::vector<std::shared_ptr<const fml::Mapping>> shared_kernels;
shared_kernels.reserve(kernels.size());
for (auto& kernel : kernels) {
shared_kernels.emplace_back(std::move(kernel));
}
return PrepareForRunningFromKernels(shared_kernels);
}
bool DartIsolate::MarkIsolateRunnable() {
TRACE_EVENT0("flutter", "DartIsolate::MarkIsolateRunnable");
if (phase_ != Phase::LibrariesSetup) {
return false;
}
// This function may only be called from an active isolate scope.
if (Dart_CurrentIsolate() != isolate()) {
return false;
}
// There must be no current isolate to mark an isolate as being runnable.
Dart_ExitIsolate();
char* error = Dart_IsolateMakeRunnable(isolate());
if (error) {
FML_DLOG(ERROR) << error;
::free(error);
// Failed. Restore the isolate.
Dart_EnterIsolate(isolate());
return false;
}
// Success. Restore the isolate.
Dart_EnterIsolate(isolate());
return true;
}
[[nodiscard]] static bool InvokeMainEntrypoint(
Dart_Handle user_entrypoint_function,
Dart_Handle args) {
if (tonic::CheckAndHandleError(user_entrypoint_function)) {
FML_LOG(ERROR) << "Could not resolve main entrypoint function.";
return false;
}
Dart_Handle start_main_isolate_function =
tonic::DartInvokeField(Dart_LookupLibrary(tonic::ToDart("dart:isolate")),
"_getStartMainIsolateFunction", {});
if (tonic::CheckAndHandleError(start_main_isolate_function)) {
FML_LOG(ERROR) << "Could not resolve main entrypoint trampoline.";
return false;
}
if (tonic::CheckAndHandleError(tonic::DartInvokeField(
Dart_LookupLibrary(tonic::ToDart("dart:ui")), "_runMain",
{start_main_isolate_function, user_entrypoint_function, args}))) {
FML_LOG(ERROR) << "Could not invoke the main entrypoint.";
return false;
}
return true;
}
bool DartIsolate::RunFromLibrary(std::optional<std::string> library_name,
std::optional<std::string> entrypoint,
const std::vector<std::string>& args) {
TRACE_EVENT0("flutter", "DartIsolate::RunFromLibrary");
if (phase_ != Phase::Ready) {
return false;
}
tonic::DartState::Scope scope(this);
auto library_handle =
library_name.has_value() && !library_name.value().empty()
? ::Dart_LookupLibrary(tonic::ToDart(library_name.value().c_str()))
: ::Dart_RootLibrary();
auto entrypoint_handle = entrypoint.has_value() && !entrypoint.value().empty()
? tonic::ToDart(entrypoint.value().c_str())
: tonic::ToDart("main");
if (!FindAndInvokeDartPluginRegistrant()) {
// TODO(gaaclarke): Remove once the framework PR lands that uses `--source`
// to compile the Dart Plugin Registrant
// (https://github.com/flutter/flutter/pull/100572).
InvokeDartPluginRegistrantIfAvailable(library_handle);
}
auto user_entrypoint_function =
::Dart_GetField(library_handle, entrypoint_handle);
auto entrypoint_args = tonic::ToDart(args);
if (!InvokeMainEntrypoint(user_entrypoint_function, entrypoint_args)) {
return false;
}
phase_ = Phase::Running;
return true;
}
bool DartIsolate::Shutdown() {
TRACE_EVENT0("flutter", "DartIsolate::Shutdown");
// This call may be re-entrant since Dart_ShutdownIsolate can invoke the
// cleanup callback which deletes the embedder side object of the dart isolate
// (a.k.a. this).
if (phase_ == Phase::Shutdown) {
return false;
}
phase_ = Phase::Shutdown;
Dart_Isolate vm_isolate = isolate();
// The isolate can be nullptr if this instance is the stub isolate data used
// during root isolate creation.
if (vm_isolate != nullptr) {
// We need to enter the isolate because Dart_ShutdownIsolate does not take
// the isolate to shutdown as a parameter.
FML_DCHECK(Dart_CurrentIsolate() == nullptr);
Dart_EnterIsolate(vm_isolate);
Dart_ShutdownIsolate();
FML_DCHECK(Dart_CurrentIsolate() == nullptr);
}
return true;
}
Dart_Isolate DartIsolate::DartCreateAndStartServiceIsolate(
const char* package_root,
const char* package_config,
Dart_IsolateFlags* flags,
char** error) {
auto vm_data = DartVMRef::GetVMData();
if (!vm_data) {
*error = fml::strdup(
"Could not access VM data to initialize isolates. This may be because "
"the VM has initialized shutdown on another thread already.");
return nullptr;
}
const auto& settings = vm_data->GetSettings();
if (!settings.enable_vm_service) {
return nullptr;
}
flags->load_vmservice_library = true;
#if (FLUTTER_RUNTIME_MODE != FLUTTER_RUNTIME_MODE_DEBUG)
// TODO(68663): The service isolate in debug mode is always launched without
// sound null safety. Fix after the isolate snapshot data is created with the
// right flags.
flags->null_safety = vm_data->GetServiceIsolateSnapshotNullSafety();
#endif
UIDartState::Context context(
TaskRunners("io.flutter." DART_VM_SERVICE_ISOLATE_NAME, nullptr, nullptr,
nullptr, nullptr));
context.advisory_script_uri = DART_VM_SERVICE_ISOLATE_NAME;
context.advisory_script_entrypoint = DART_VM_SERVICE_ISOLATE_NAME;
std::weak_ptr<DartIsolate> weak_service_isolate =
DartIsolate::CreateRootIsolate(vm_data->GetSettings(), //
vm_data->GetServiceIsolateSnapshot(), //
nullptr, //
DartIsolate::Flags{flags}, //
nullptr, //
nullptr, //
context); //
std::shared_ptr<DartIsolate> service_isolate = weak_service_isolate.lock();
if (!service_isolate) {
*error = fml::strdup("Could not create the service isolate.");
FML_DLOG(ERROR) << *error;
return nullptr;
}
tonic::DartState::Scope scope(service_isolate);
if (!DartServiceIsolate::Startup(
settings.vm_service_host, // server IP address
settings.vm_service_port, // server VM service port
tonic::DartState::HandleLibraryTag, // embedder library tag handler
false, // disable websocket origin check
settings.disable_service_auth_codes, // disable VM service auth codes
settings.enable_service_port_fallback, // enable fallback to port 0
// when bind fails.
error // error (out)
)) {
// Error is populated by call to startup.
FML_DLOG(ERROR) << *error;
return nullptr;
}
if (auto callback = vm_data->GetSettings().service_isolate_create_callback) {
callback();
}
if (auto service_protocol = DartVMRef::GetServiceProtocol()) {
service_protocol->ToggleHooks(true);
} else {
FML_DLOG(ERROR)
<< "Could not acquire the service protocol handlers. This might be "
"because the VM has already begun teardown on another thread.";
}
return service_isolate->isolate();
}
DartIsolateGroupData& DartIsolate::GetIsolateGroupData() {
std::shared_ptr<DartIsolateGroupData>* isolate_group_data =
static_cast<std::shared_ptr<DartIsolateGroupData>*>(
Dart_IsolateGroupData(isolate()));
return **isolate_group_data;
}
const DartIsolateGroupData& DartIsolate::GetIsolateGroupData() const {
DartIsolate* non_const_this = const_cast<DartIsolate*>(this);
return non_const_this->GetIsolateGroupData();
}
// |Dart_IsolateGroupCreateCallback|
Dart_Isolate DartIsolate::DartIsolateGroupCreateCallback(
const char* advisory_script_uri,
const char* advisory_script_entrypoint,
const char* package_root,
const char* package_config,
Dart_IsolateFlags* flags,
std::shared_ptr<DartIsolate>* parent_isolate_data,
char** error) {
TRACE_EVENT0("flutter", "DartIsolate::DartIsolateGroupCreateCallback");
if (parent_isolate_data == nullptr &&
strcmp(advisory_script_uri, DART_VM_SERVICE_ISOLATE_NAME) == 0) {
// The VM attempts to start the VM service for us on |Dart_Initialize|. In
// such a case, the callback data will be null and the script URI will be
// DART_VM_SERVICE_ISOLATE_NAME. In such cases, we just create the service
// isolate like normal but dont hold a reference to it at all. We also start
// this isolate since we will never again reference it from the engine.
return DartCreateAndStartServiceIsolate(package_root, //
package_config, //
flags, //
error //
);
}
if (!parent_isolate_data) {
return nullptr;
}
DartIsolateGroupData& parent_group_data =
(*parent_isolate_data)->GetIsolateGroupData();
if (strncmp(advisory_script_uri, kFileUriPrefix.data(),
kFileUriPrefix.size())) {
std::string error_msg =
std::string("Unsupported isolate URI: ") + advisory_script_uri;
*error = fml::strdup(error_msg.c_str());
return nullptr;
}
auto isolate_group_data =
std::make_unique<std::shared_ptr<DartIsolateGroupData>>(
std::shared_ptr<DartIsolateGroupData>(new DartIsolateGroupData(
parent_group_data.GetSettings(),
parent_group_data.GetIsolateSnapshot(), advisory_script_uri,
advisory_script_entrypoint,
parent_group_data.GetChildIsolatePreparer(),
parent_group_data.GetIsolateCreateCallback(),
parent_group_data.GetIsolateShutdownCallback())));
TaskRunners null_task_runners(advisory_script_uri,
/* platform= */ nullptr,
/* raster= */ nullptr,
/* ui= */ nullptr,
/* io= */ nullptr);
UIDartState::Context context(null_task_runners);
context.advisory_script_uri = advisory_script_uri;
context.advisory_script_entrypoint = advisory_script_entrypoint;
auto isolate_data = std::make_unique<std::shared_ptr<DartIsolate>>(
std::shared_ptr<DartIsolate>(
new DartIsolate((*isolate_group_data)->GetSettings(), // settings
false, // is_root_isolate
context))); // context
Dart_Isolate vm_isolate = CreateDartIsolateGroup(
std::move(isolate_group_data), std::move(isolate_data), flags, error,
[](std::shared_ptr<DartIsolateGroupData>* isolate_group_data,
std::shared_ptr<DartIsolate>* isolate_data, Dart_IsolateFlags* flags,
char** error) {
return Dart_CreateIsolateGroup(
(*isolate_group_data)->GetAdvisoryScriptURI().c_str(),
(*isolate_group_data)->GetAdvisoryScriptEntrypoint().c_str(),
(*isolate_group_data)->GetIsolateSnapshot()->GetDataMapping(),
(*isolate_group_data)
->GetIsolateSnapshot()
->GetInstructionsMapping(),
flags, isolate_group_data, isolate_data, error);
});
if (*error) {
FML_LOG(ERROR) << "CreateDartIsolateGroup failed: " << *error;
}
return vm_isolate;
}
// |Dart_IsolateInitializeCallback|
bool DartIsolate::DartIsolateInitializeCallback(void** child_callback_data,
char** error) {
TRACE_EVENT0("flutter", "DartIsolate::DartIsolateInitializeCallback");
Dart_Isolate isolate = Dart_CurrentIsolate();
if (isolate == nullptr) {
*error = fml::strdup("Isolate should be available in initialize callback.");
FML_DLOG(ERROR) << *error;
return false;
}
auto* isolate_group_data =
static_cast<std::shared_ptr<DartIsolateGroupData>*>(
Dart_CurrentIsolateGroupData());
TaskRunners null_task_runners((*isolate_group_data)->GetAdvisoryScriptURI(),
/* platform= */ nullptr,
/* raster= */ nullptr,
/* ui= */ nullptr,
/* io= */ nullptr);
UIDartState::Context context(null_task_runners);
context.advisory_script_uri = (*isolate_group_data)->GetAdvisoryScriptURI();
context.advisory_script_entrypoint =
(*isolate_group_data)->GetAdvisoryScriptEntrypoint();
auto embedder_isolate = std::make_unique<std::shared_ptr<DartIsolate>>(
std::shared_ptr<DartIsolate>(
new DartIsolate((*isolate_group_data)->GetSettings(), // settings
false, // is_root_isolate
context))); // context
// root isolate should have been created via CreateRootIsolate
if (!InitializeIsolate(*embedder_isolate, isolate, error)) {
return false;
}
// The ownership of the embedder object is controlled by the Dart VM. So the
// only reference returned to the caller is weak.
*child_callback_data = embedder_isolate.release();
return true;
}
Dart_Isolate DartIsolate::CreateDartIsolateGroup(
std::unique_ptr<std::shared_ptr<DartIsolateGroupData>> isolate_group_data,
std::unique_ptr<std::shared_ptr<DartIsolate>> isolate_data,
Dart_IsolateFlags* flags,
char** error,
const DartIsolate::IsolateMaker& make_isolate) {
TRACE_EVENT0("flutter", "DartIsolate::CreateDartIsolateGroup");
// Create the Dart VM isolate and give it the embedder object as the baton.
Dart_Isolate isolate =
make_isolate(isolate_group_data.get(), isolate_data.get(), flags, error);
if (isolate == nullptr) {
return nullptr;
}
bool success = false;
{
// Ownership of the isolate data objects has been transferred to the Dart
// VM.
// NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks)
std::shared_ptr<DartIsolate> embedder_isolate(*isolate_data);
isolate_group_data.release();
isolate_data.release();
// NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
success = InitializeIsolate(embedder_isolate, isolate, error);
}
if (!success) {
Dart_ShutdownIsolate();
return nullptr;
}
// Balances the implicit [Dart_EnterIsolate] by [make_isolate] above.
Dart_ExitIsolate();
return isolate;
}
bool DartIsolate::InitializeIsolate(
const std::shared_ptr<DartIsolate>& embedder_isolate,
Dart_Isolate isolate,
char** error) {
TRACE_EVENT0("flutter", "DartIsolate::InitializeIsolate");
if (!embedder_isolate->Initialize(isolate)) {
*error = fml::strdup("Embedder could not initialize the Dart isolate.");
FML_DLOG(ERROR) << *error;
return false;
}
if (!embedder_isolate->LoadLibraries()) {
*error = fml::strdup(
"Embedder could not load libraries in the new Dart isolate.");
FML_DLOG(ERROR) << *error;
return false;
}
// Root isolates will be set up by the engine and the service isolate
// (which is also a root isolate) by the utility routines in the VM.
// However, secondary isolates will be run by the VM if they are
// marked as runnable.
if (!embedder_isolate->IsRootIsolate()) {
auto child_isolate_preparer =
embedder_isolate->GetIsolateGroupData().GetChildIsolatePreparer();
FML_DCHECK(child_isolate_preparer);
if (!child_isolate_preparer(embedder_isolate.get())) {
*error = fml::strdup("Could not prepare the child isolate to run.");
FML_DLOG(ERROR) << *error;
return false;
}
}
return true;
}
// |Dart_IsolateShutdownCallback|
void DartIsolate::DartIsolateShutdownCallback(
std::shared_ptr<DartIsolateGroupData>* isolate_group_data,
std::shared_ptr<DartIsolate>* isolate_data) {
TRACE_EVENT0("flutter", "DartIsolate::DartIsolateShutdownCallback");
// If the isolate initialization failed there will be nothing to do.
// This can happen e.g. during a [DartIsolateInitializeCallback] invocation
// that fails to initialize the VM-created isolate.
if (isolate_data == nullptr) {
return;
}
isolate_data->get()->OnShutdownCallback();
}
// |Dart_IsolateGroupCleanupCallback|
void DartIsolate::DartIsolateGroupCleanupCallback(
std::shared_ptr<DartIsolateGroupData>* isolate_data) {
TRACE_EVENT0("flutter", "DartIsolate::DartIsolateGroupCleanupCallback");
delete isolate_data;
}
// |Dart_IsolateCleanupCallback|
void DartIsolate::DartIsolateCleanupCallback(
std::shared_ptr<DartIsolateGroupData>* isolate_group_data,
std::shared_ptr<DartIsolate>* isolate_data) {
TRACE_EVENT0("flutter", "DartIsolate::DartIsolateCleanupCallback");
delete isolate_data;
}
std::weak_ptr<DartIsolate> DartIsolate::GetWeakIsolatePtr() {
return std::static_pointer_cast<DartIsolate>(shared_from_this());
}
void DartIsolate::AddIsolateShutdownCallback(const fml::closure& closure) {
shutdown_callbacks_.emplace_back(std::make_unique<AutoFireClosure>(closure));
}
void DartIsolate::OnShutdownCallback() {
tonic::DartState* state = tonic::DartState::Current();
if (state != nullptr) {
state->SetIsShuttingDown();
}
{
tonic::DartApiScope api_scope;
Dart_Handle sticky_error = Dart_GetStickyError();
if (!Dart_IsNull(sticky_error) && !Dart_IsFatalError(sticky_error)) {
FML_LOG(ERROR) << Dart_GetError(sticky_error);
}
}
if (is_platform_isolate_) {
FML_DCHECK(platform_isolate_manager_ != nullptr);
platform_isolate_manager_->RemovePlatformIsolate(isolate());
}
shutdown_callbacks_.clear();
const fml::closure& isolate_shutdown_callback =
GetIsolateGroupData().GetIsolateShutdownCallback();
if (isolate_shutdown_callback) {
isolate_shutdown_callback();
}
}
Dart_Handle DartIsolate::OnDartLoadLibrary(intptr_t loading_unit_id) {
if (Current()->platform_configuration()) {
Current()->platform_configuration()->client()->RequestDartDeferredLibrary(
loading_unit_id);
return Dart_Null();
}
const std::string error_message =
"Platform Configuration was null. Deferred library load request "
"for loading unit id " +
std::to_string(loading_unit_id) + " was not sent.";
FML_LOG(ERROR) << error_message;
return Dart_NewApiError(error_message.c_str());
}
Dart_Handle DartIsolate::LoadLibraryFromKernel(
const std::shared_ptr<const fml::Mapping>& mapping) {
if (DartVM::IsRunningPrecompiledCode()) {
return Dart_Null();
}
auto* isolate_group_data =
static_cast<std::shared_ptr<DartIsolateGroupData>*>(
Dart_CurrentIsolateGroupData());
// Mapping must be retained until isolate shutdown.
(*isolate_group_data)->AddKernelBuffer(mapping);
auto lib =
Dart_LoadLibraryFromKernel(mapping->GetMapping(), mapping->GetSize());
if (tonic::CheckAndHandleError(lib)) {
return Dart_Null();
}
auto result = Dart_FinalizeLoading(false);
if (Dart_IsError(result)) {
return result;
}
return Dart_GetField(lib, Dart_NewStringFromCString("main"));
}
DartIsolate::AutoFireClosure::AutoFireClosure(const fml::closure& closure)
: closure_(closure) {}
DartIsolate::AutoFireClosure::~AutoFireClosure() {
if (closure_) {
closure_();
}
}
} // namespace flutter
| engine/runtime/dart_isolate.cc/0 | {
"file_path": "engine/runtime/dart_isolate.cc",
"repo_id": "engine",
"token_count": 19287
} | 277 |
// Copyright 2013 The Flutter 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/runtime/dart_vm.h"
#include <sys/stat.h>
#include <sstream>
#include <vector>
#include "flutter/common/settings.h"
#include "flutter/fml/compiler_specific.h"
#include "flutter/fml/cpu_affinity.h"
#include "flutter/fml/logging.h"
#include "flutter/fml/mapping.h"
#include "flutter/fml/size.h"
#include "flutter/fml/time/time_delta.h"
#include "flutter/fml/trace_event.h"
#include "flutter/lib/ui/dart_ui.h"
#include "flutter/runtime/dart_isolate.h"
#include "flutter/runtime/dart_vm_initializer.h"
#include "flutter/runtime/ptrace_check.h"
#include "third_party/dart/runtime/include/bin/dart_io_api.h"
#include "third_party/skia/include/core/SkExecutor.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_class_library.h"
#include "third_party/tonic/dart_class_provider.h"
#include "third_party/tonic/file_loader/file_loader.h"
#include "third_party/tonic/logging/dart_error.h"
#include "third_party/tonic/typed_data/typed_list.h"
namespace dart {
namespace observatory {
#if !OS_FUCHSIA && !FLUTTER_RELEASE
// These two symbols are defined in |observatory_archive.cc| which is generated
// by the |//third_party/dart/runtime/observatory:archive_observatory| rule.
// Both of these symbols will be part of the data segment and therefore are read
// only.
extern unsigned int observatory_assets_archive_len;
extern const uint8_t* observatory_assets_archive;
#endif // !OS_FUCHSIA && !FLUTTER_RELEASE
} // namespace observatory
} // namespace dart
namespace flutter {
// Arguments passed to the Dart VM in all configurations.
static const char* kDartAllConfigsArgs[] = {
// clang-format off
"--enable_mirrors=false",
"--background_compilation",
// 'mark_when_idle' appears to cause a regression, turning off for now.
// "--mark_when_idle",
// clang-format on
};
static const char* kDartPrecompilationArgs[] = {"--precompilation"};
static const char* kSerialGCArgs[] = {
// clang-format off
"--concurrent_mark=false",
"--concurrent_sweep=false",
"--compactor_tasks=1",
"--scavenger_tasks=0",
"--marker_tasks=0",
// clang-format on
};
FML_ALLOW_UNUSED_TYPE
static const char* kDartWriteProtectCodeArgs[] = {
"--no_write_protect_code",
};
FML_ALLOW_UNUSED_TYPE
static const char* kDartDisableIntegerDivisionArgs[] = {
"--no_use_integer_division",
};
static const char* kDartAssertArgs[] = {
// clang-format off
"--enable_asserts",
// clang-format on
};
static const char* kDartStartPausedArgs[]{
"--pause_isolates_on_start",
};
static const char* kDartEndlessTraceBufferArgs[]{
"--timeline_recorder=endless",
};
static const char* kDartSystraceTraceBufferArgs[] = {
"--timeline_recorder=systrace",
};
static std::string DartFileRecorderArgs(const std::string& path) {
std::ostringstream oss;
oss << "--timeline_recorder=perfettofile:" << path;
return oss.str();
}
FML_ALLOW_UNUSED_TYPE
static const char* kDartDefaultTraceStreamsArgs[]{
"--timeline_streams=Dart,Embedder,GC",
};
static const char* kDartStartupTraceStreamsArgs[]{
"--timeline_streams=Compiler,Dart,Debugger,Embedder,GC,Isolate,VM,API",
};
static const char* kDartSystraceTraceStreamsArgs[] = {
"--timeline_streams=Compiler,Dart,Debugger,Embedder,GC,Isolate,VM,API",
};
static std::string DartOldGenHeapSizeArgs(uint64_t heap_size) {
std::ostringstream oss;
oss << "--old_gen_heap_size=" << heap_size;
return oss.str();
}
constexpr char kFileUriPrefix[] = "file://";
constexpr size_t kFileUriPrefixLength = sizeof(kFileUriPrefix) - 1;
bool DartFileModifiedCallback(const char* source_url, int64_t since_ms) {
if (strncmp(source_url, kFileUriPrefix, kFileUriPrefixLength) != 0u) {
// Assume modified.
return true;
}
const char* path = source_url + kFileUriPrefixLength;
struct stat info;
if (stat(path, &info) < 0) {
return true;
}
// If st_mtime is zero, it's more likely that the file system doesn't support
// mtime than that the file was actually modified in the 1970s.
if (!info.st_mtime) {
return true;
}
// It's very unclear what time bases we're with here. The Dart API doesn't
// document the time base for since_ms. Reading the code, the value varies by
// platform, with a typical source being something like gettimeofday.
//
// We add one to st_mtime because st_mtime has less precision than since_ms
// and we want to treat the file as modified if the since time is between
// ticks of the mtime.
fml::TimeDelta mtime = fml::TimeDelta::FromSeconds(info.st_mtime + 1);
fml::TimeDelta since = fml::TimeDelta::FromMilliseconds(since_ms);
return mtime > since;
}
void ThreadExitCallback() {}
Dart_Handle GetVMServiceAssetsArchiveCallback() {
#if FLUTTER_RELEASE
return nullptr;
#elif OS_FUCHSIA
fml::UniqueFD fd = fml::OpenFile("pkg/data/observatory.tar", false,
fml::FilePermission::kRead);
fml::FileMapping mapping(fd, {fml::FileMapping::Protection::kRead});
if (mapping.GetSize() == 0 || mapping.GetMapping() == nullptr) {
FML_LOG(ERROR) << "Fail to load Observatory archive";
return nullptr;
}
return tonic::DartConverter<tonic::Uint8List>::ToDart(mapping.GetMapping(),
mapping.GetSize());
#else
return tonic::DartConverter<tonic::Uint8List>::ToDart(
::dart::observatory::observatory_assets_archive,
::dart::observatory::observatory_assets_archive_len);
#endif
}
static const char kStdoutStreamId[] = "Stdout";
static const char kStderrStreamId[] = "Stderr";
static bool ServiceStreamListenCallback(const char* stream_id) {
if (strcmp(stream_id, kStdoutStreamId) == 0) {
dart::bin::SetCaptureStdout(true);
return true;
} else if (strcmp(stream_id, kStderrStreamId) == 0) {
dart::bin::SetCaptureStderr(true);
return true;
}
return false;
}
static void ServiceStreamCancelCallback(const char* stream_id) {
if (strcmp(stream_id, kStdoutStreamId) == 0) {
dart::bin::SetCaptureStdout(false);
} else if (strcmp(stream_id, kStderrStreamId) == 0) {
dart::bin::SetCaptureStderr(false);
}
}
bool DartVM::IsRunningPrecompiledCode() {
return Dart_IsPrecompiledRuntime();
}
static std::vector<const char*> ProfilingFlags(bool enable_profiling) {
// Disable Dart's built in profiler when building a debug build. This
// works around a race condition that would sometimes stop a crash's
// stack trace from being printed on Android.
#ifndef NDEBUG
enable_profiling = false;
#endif
// We want to disable profiling by default because it overwhelms LLDB. But
// the VM enables the same by default. In either case, we have some profiling
// flags.
if (enable_profiling) {
return {
// This is the default. But just be explicit.
"--profiler",
// This instructs the profiler to walk C++ frames, and to include
// them in the profile.
"--profile-vm",
#if FML_OS_IOS && FML_ARCH_CPU_ARM_FAMILY && FML_ARCH_CPU_ARMEL
// Set the profiler interrupt period to 500Hz instead of the
// default 1000Hz on 32-bit iOS devices to reduce average and worst
// case frame build times.
//
// Note: profile_period is time in microseconds between sampling
// events, not frequency. Frequency is calculated 1/period (or
// 1,000,000 / 2,000 -> 500Hz in this case).
"--profile_period=2000",
#else
"--profile_period=1000",
#endif // FML_OS_IOS && FML_ARCH_CPU_ARM_FAMILY && FML_ARCH_CPU_ARMEL
};
} else {
return {"--no-profiler"};
}
}
void PushBackAll(std::vector<const char*>* args,
const char** argv,
size_t argc) {
for (size_t i = 0; i < argc; ++i) {
args->push_back(argv[i]);
}
}
static void EmbedderInformationCallback(Dart_EmbedderInformation* info) {
info->version = DART_EMBEDDER_INFORMATION_CURRENT_VERSION;
dart::bin::GetIOEmbedderInformation(info);
info->name = "Flutter";
}
std::shared_ptr<DartVM> DartVM::Create(
const Settings& settings,
fml::RefPtr<const DartSnapshot> vm_snapshot,
fml::RefPtr<const DartSnapshot> isolate_snapshot,
std::shared_ptr<IsolateNameServer> isolate_name_server) {
auto vm_data = DartVMData::Create(settings, //
std::move(vm_snapshot), //
std::move(isolate_snapshot) //
);
if (!vm_data) {
FML_LOG(ERROR) << "Could not set up VM data to bootstrap the VM from.";
return {};
}
// Note: std::make_shared unviable due to hidden constructor.
return std::shared_ptr<DartVM>(
new DartVM(vm_data, std::move(isolate_name_server)));
}
static std::atomic_size_t gVMLaunchCount;
size_t DartVM::GetVMLaunchCount() {
return gVMLaunchCount;
}
DartVM::DartVM(const std::shared_ptr<const DartVMData>& vm_data,
std::shared_ptr<IsolateNameServer> isolate_name_server)
: settings_(vm_data->GetSettings()),
concurrent_message_loop_(fml::ConcurrentMessageLoop::Create(
fml::EfficiencyCoreCount().value_or(
std::thread::hardware_concurrency()))),
skia_concurrent_executor_(
[runner = concurrent_message_loop_->GetTaskRunner()](
const fml::closure& work) { runner->PostTask(work); }),
vm_data_(vm_data),
isolate_name_server_(std::move(isolate_name_server)),
service_protocol_(std::make_shared<ServiceProtocol>()) {
TRACE_EVENT0("flutter", "DartVMInitializer");
gVMLaunchCount++;
// Setting the executor is not thread safe but Dart VM initialization is. So
// this call is thread-safe.
SkExecutor::SetDefault(&skia_concurrent_executor_);
FML_DCHECK(vm_data_);
FML_DCHECK(isolate_name_server_);
FML_DCHECK(service_protocol_);
{
TRACE_EVENT0("flutter", "dart::bin::BootstrapDartIo");
dart::bin::BootstrapDartIo();
if (!settings_.temp_directory_path.empty()) {
dart::bin::SetSystemTempDirectory(settings_.temp_directory_path.c_str());
}
}
std::vector<const char*> args;
// Instruct the VM to ignore unrecognized flags.
// There is a lot of diversity in a lot of combinations when it
// comes to the arguments the VM supports. And, if the VM comes across a flag
// it does not recognize, it exits immediately.
args.push_back("--ignore-unrecognized-flags");
for (auto* const profiler_flag :
ProfilingFlags(settings_.enable_dart_profiling)) {
args.push_back(profiler_flag);
}
PushBackAll(&args, kDartAllConfigsArgs, fml::size(kDartAllConfigsArgs));
if (IsRunningPrecompiledCode()) {
PushBackAll(&args, kDartPrecompilationArgs,
fml::size(kDartPrecompilationArgs));
}
// Enable Dart assertions if we are not running precompiled code. We run non-
// precompiled code only in the debug product mode.
bool enable_asserts = !settings_.disable_dart_asserts;
#if !OS_FUCHSIA
if (IsRunningPrecompiledCode()) {
enable_asserts = false;
}
#endif // !OS_FUCHSIA
#if (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG)
#if !FML_OS_IOS && !FML_OS_MACOSX
// Debug mode uses the JIT, disable code page write protection to avoid
// memory page protection changes before and after every compilation.
PushBackAll(&args, kDartWriteProtectCodeArgs,
fml::size(kDartWriteProtectCodeArgs));
#else
const bool tracing_result = EnableTracingIfNecessary(settings_);
// This check should only trip if the embedding made no attempts to enable
// tracing. At this point, it is too late display user visible messages. Just
// log and die.
FML_CHECK(tracing_result)
<< "Tracing not enabled before attempting to run JIT mode VM.";
#if TARGET_CPU_ARM
// Tell Dart in JIT mode to not use integer division on armv7
// Ideally, this would be detected at runtime by Dart.
// TODO(dnfield): Remove this code
// https://github.com/dart-lang/sdk/issues/24743
PushBackAll(&args, kDartDisableIntegerDivisionArgs,
fml::size(kDartDisableIntegerDivisionArgs));
#endif // TARGET_CPU_ARM
#endif // !FML_OS_IOS && !FML_OS_MACOSX
#endif // (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG)
if (enable_asserts) {
PushBackAll(&args, kDartAssertArgs, fml::size(kDartAssertArgs));
}
// On low power devices with lesser number of cores, using concurrent
// marking or sweeping causes contention for the UI thread leading to
// Jank, this option can be used to turn off all concurrent GC activities.
if (settings_.enable_serial_gc) {
PushBackAll(&args, kSerialGCArgs, fml::size(kSerialGCArgs));
}
if (settings_.start_paused) {
PushBackAll(&args, kDartStartPausedArgs, fml::size(kDartStartPausedArgs));
}
if (settings_.endless_trace_buffer || settings_.trace_startup) {
// If we are tracing startup, make sure the trace buffer is endless so we
// don't lose early traces.
PushBackAll(&args, kDartEndlessTraceBufferArgs,
fml::size(kDartEndlessTraceBufferArgs));
}
if (settings_.trace_systrace) {
PushBackAll(&args, kDartSystraceTraceBufferArgs,
fml::size(kDartSystraceTraceBufferArgs));
PushBackAll(&args, kDartSystraceTraceStreamsArgs,
fml::size(kDartSystraceTraceStreamsArgs));
}
std::string file_recorder_args;
if (!settings_.trace_to_file.empty()) {
file_recorder_args = DartFileRecorderArgs(settings_.trace_to_file);
args.push_back(file_recorder_args.c_str());
PushBackAll(&args, kDartSystraceTraceStreamsArgs,
fml::size(kDartSystraceTraceStreamsArgs));
}
if (settings_.trace_startup) {
PushBackAll(&args, kDartStartupTraceStreamsArgs,
fml::size(kDartStartupTraceStreamsArgs));
}
#if defined(OS_FUCHSIA)
PushBackAll(&args, kDartSystraceTraceBufferArgs,
fml::size(kDartSystraceTraceBufferArgs));
PushBackAll(&args, kDartSystraceTraceStreamsArgs,
fml::size(kDartSystraceTraceStreamsArgs));
#else
if (!settings_.trace_systrace && !settings_.trace_startup) {
PushBackAll(&args, kDartDefaultTraceStreamsArgs,
fml::size(kDartDefaultTraceStreamsArgs));
}
#endif // defined(OS_FUCHSIA)
std::string old_gen_heap_size_args;
if (settings_.old_gen_heap_size >= 0) {
old_gen_heap_size_args =
DartOldGenHeapSizeArgs(settings_.old_gen_heap_size);
args.push_back(old_gen_heap_size_args.c_str());
}
for (size_t i = 0; i < settings_.dart_flags.size(); i++) {
args.push_back(settings_.dart_flags[i].c_str());
}
char* flags_error = Dart_SetVMFlags(args.size(), args.data());
if (flags_error) {
FML_LOG(FATAL) << "Error while setting Dart VM flags: " << flags_error;
::free(flags_error);
}
dart::bin::SetExecutableName(settings_.executable_name.c_str());
{
TRACE_EVENT0("flutter", "Dart_Initialize");
Dart_InitializeParams params = {};
params.version = DART_INITIALIZE_PARAMS_CURRENT_VERSION;
params.vm_snapshot_data = vm_data_->GetVMSnapshot().GetDataMapping();
params.vm_snapshot_instructions =
vm_data_->GetVMSnapshot().GetInstructionsMapping();
params.create_group = reinterpret_cast<decltype(params.create_group)>(
DartIsolate::DartIsolateGroupCreateCallback);
params.initialize_isolate =
reinterpret_cast<decltype(params.initialize_isolate)>(
DartIsolate::DartIsolateInitializeCallback);
params.shutdown_isolate =
reinterpret_cast<decltype(params.shutdown_isolate)>(
DartIsolate::DartIsolateShutdownCallback);
params.cleanup_isolate = reinterpret_cast<decltype(params.cleanup_isolate)>(
DartIsolate::DartIsolateCleanupCallback);
params.cleanup_group = reinterpret_cast<decltype(params.cleanup_group)>(
DartIsolate::DartIsolateGroupCleanupCallback);
params.thread_exit = ThreadExitCallback;
params.file_open = dart::bin::OpenFile;
params.file_read = dart::bin::ReadFile;
params.file_write = dart::bin::WriteFile;
params.file_close = dart::bin::CloseFile;
params.entropy_source = dart::bin::GetEntropy;
params.get_service_assets = GetVMServiceAssetsArchiveCallback;
DartVMInitializer::Initialize(¶ms,
settings_.enable_timeline_event_handler,
settings_.trace_systrace);
// Send the earliest available timestamp in the application lifecycle to
// timeline. The difference between this timestamp and the time we render
// the very first frame gives us a good idea about Flutter's startup time.
// Use an instant event because the call to Dart_TimelineGetMicros
// may behave differently before and after the Dart VM is initialized.
// As this call is immediately after initialization of the Dart VM,
// we are interested in only one timestamp.
int64_t micros = Dart_TimelineGetMicros();
Dart_RecordTimelineEvent("FlutterEngineMainEnter", // label
micros, // timestamp0
micros, // timestamp1_or_async_id
0, // flow_id_count
nullptr, // flow_ids
Dart_Timeline_Event_Instant, // event type
0, // argument_count
nullptr, // argument_names
nullptr // argument_values
);
}
Dart_SetFileModifiedCallback(&DartFileModifiedCallback);
// Allow streaming of stdout and stderr by the Dart vm.
Dart_SetServiceStreamCallbacks(&ServiceStreamListenCallback,
&ServiceStreamCancelCallback);
Dart_SetEmbedderInformationCallback(&EmbedderInformationCallback);
if (settings_.dart_library_sources_kernel != nullptr) {
std::unique_ptr<fml::Mapping> dart_library_sources =
settings_.dart_library_sources_kernel();
// Set sources for dart:* libraries for debugging.
Dart_SetDartLibrarySourcesKernel(dart_library_sources->GetMapping(),
dart_library_sources->GetSize());
}
// Update thread names now that the Dart VM is initialized.
concurrent_message_loop_->PostTaskToAllWorkers(
[] { Dart_SetThreadName("FlutterConcurrentMessageLoopWorker"); });
}
DartVM::~DartVM() {
// Setting the executor is not thread safe but Dart VM shutdown is. So
// this call is thread-safe.
SkExecutor::SetDefault(nullptr);
if (Dart_CurrentIsolate() != nullptr) {
Dart_ExitIsolate();
}
DartVMInitializer::Cleanup();
dart::bin::CleanupDartIo();
}
std::shared_ptr<const DartVMData> DartVM::GetVMData() const {
return vm_data_;
}
const Settings& DartVM::GetSettings() const {
return settings_;
}
std::shared_ptr<ServiceProtocol> DartVM::GetServiceProtocol() const {
return service_protocol_;
}
std::shared_ptr<IsolateNameServer> DartVM::GetIsolateNameServer() const {
return isolate_name_server_;
}
std::shared_ptr<fml::ConcurrentTaskRunner>
DartVM::GetConcurrentWorkerTaskRunner() const {
return concurrent_message_loop_->GetTaskRunner();
}
std::shared_ptr<fml::ConcurrentMessageLoop> DartVM::GetConcurrentMessageLoop() {
return concurrent_message_loop_;
}
} // namespace flutter
| engine/runtime/dart_vm.cc/0 | {
"file_path": "engine/runtime/dart_vm.cc",
"repo_id": "engine",
"token_count": 7572
} | 278 |
// Copyright 2013 The Flutter 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_RUNTIME_ISOLATE_CONFIGURATION_H_
#define FLUTTER_RUNTIME_ISOLATE_CONFIGURATION_H_
#include <future>
#include <memory>
#include <string>
#include "flutter/assets/asset_manager.h"
#include "flutter/assets/asset_resolver.h"
#include "flutter/common/settings.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/mapping.h"
#include "flutter/fml/memory/weak_ptr.h"
#include "flutter/runtime/dart_isolate.h"
namespace flutter {
/// Describes whether the isolate is part of a group or not.
///
/// If the isolate is part of a group, it avoids reloading the kernel snapshot.
enum class IsolateLaunchType {
/// The isolate is launched as a solo isolate or to start a new group.
kNewGroup,
/// The isolate is launched as part of a group, and avoids reloading the
/// kernel snapshot.
kExistingGroup,
};
//------------------------------------------------------------------------------
/// @brief An isolate configuration is a collection of snapshots and asset
/// managers that the engine will use to configure the isolate
/// before invoking its root entrypoint. The set of snapshots must
/// be sufficient for the engine to move the isolate from the
/// |DartIsolate::Phase::LibrariesSetup| phase to the
/// |DartIsolate::Phase::Ready| phase. Note that the isolate
/// configuration will not be collected till the isolate tied to the
/// configuration as well as any and all child isolates of that
/// isolate are collected. The engine may ask the configuration to
/// prepare multiple isolates. All subclasses of this class must be
/// thread safe as the configuration may be created, collected and
/// used on multiple threads. Usually these threads are engine or VM
/// managed so care must be taken to ensure that subclasses do not
/// reference any thread local state.
///
class IsolateConfiguration {
public:
//----------------------------------------------------------------------------
/// @brief Attempts to infer the isolate configuration from the
/// `Settings` object. If the VM is configured for AOT mode,
/// snapshot resolution is attempted with predefined symbols
/// present in the currently loaded process. In JIT mode, Dart
/// kernel file resolution is attempted in the assets directory.
/// If an IO worker is specified, snapshot resolution may be
/// attempted on the serial worker task runner. The worker task
/// runner thread must remain valid and running till after the
/// shell associated with the engine used to launch the isolate
/// for which this run configuration is used is collected.
///
/// @param[in] settings The settings
/// @param[in] asset_manager The optional asset manager. This is used when
/// using the legacy settings fields that specify
/// the asset by name instead of a mappings
/// callback.
/// @param[in] io_worker An optional IO worker. Specify `nullptr` if a
/// worker should not be used or one is not
/// available.
/// @param[in] launch_type Whether the isolate is launching to form a new
/// group or as part of an existing group. If it is
/// part of an existing group, the isolate will
/// reuse resources if it can.
///
/// @return An isolate configuration if one can be inferred from the
/// settings. If not, returns `nullptr`.
///
[[nodiscard]] static std::unique_ptr<IsolateConfiguration> InferFromSettings(
const Settings& settings,
const std::shared_ptr<AssetManager>& asset_manager = nullptr,
const fml::RefPtr<fml::TaskRunner>& io_worker = nullptr,
IsolateLaunchType launch_type = IsolateLaunchType::kNewGroup);
//----------------------------------------------------------------------------
/// @brief Creates an AOT isolate configuration using snapshot symbols
/// present in the currently loaded process. These symbols need to
/// be given to the Dart VM on bootstrap and hence have already
/// been resolved.
///
/// @return An AOT isolate configuration.
///
static std::unique_ptr<IsolateConfiguration> CreateForAppSnapshot();
//----------------------------------------------------------------------------
/// @brief Creates a JIT isolate configuration using a list of futures to
/// snapshots defining the ready isolate state. In environments
/// where snapshot resolution is extremely expensive, embedders
/// attempt to resolve snapshots on worker thread(s) and return
/// the future of the promise of snapshot resolution to this
/// method. That way, snapshot resolution begins well before
/// isolate launch is attempted by the engine.
///
/// @param[in] kernel_pieces The list of futures to Dart kernel snapshots.
///
/// @return A JIT isolate configuration.
///
static std::unique_ptr<IsolateConfiguration> CreateForKernelList(
std::vector<std::future<std::unique_ptr<const fml::Mapping>>>
kernel_pieces);
//----------------------------------------------------------------------------
/// @brief Creates a JIT isolate configuration using the specified
/// snapshot. This is a convenience method for the
/// `CreateForKernelList` method that takes a list of futures to
/// Dart kernel snapshots.
///
/// @see CreateForKernelList()
///
/// @param[in] kernel The kernel snapshot.
///
/// @return A JIT isolate configuration.
///
static std::unique_ptr<IsolateConfiguration> CreateForKernel(
std::unique_ptr<const fml::Mapping> kernel);
//----------------------------------------------------------------------------
/// @brief Creates a JIT isolate configuration using the specified
/// snapshots. This is a convenience method for the
/// `CreateForKernelList` method that takes a list of futures to
/// Dart kernel snapshots.
///
/// @see CreateForKernelList()
///
/// @param[in] kernel_pieces The kernel pieces
///
/// @return { description_of_the_return_value }
///
static std::unique_ptr<IsolateConfiguration> CreateForKernelList(
std::vector<std::unique_ptr<const fml::Mapping>> kernel_pieces);
//----------------------------------------------------------------------------
/// @brief Create an isolate configuration. This has no threading
/// restrictions.
///
IsolateConfiguration();
//----------------------------------------------------------------------------
/// @brief Destroys an isolate configuration. This has no threading
/// restrictions and may be collection of configurations may occur
/// on any thread (and usually happens on an internal VM managed
/// thread pool thread).
///
virtual ~IsolateConfiguration();
//----------------------------------------------------------------------------
/// @brief When an isolate is created and sufficiently initialized to
/// move it into the `DartIsolate::Phase::LibrariesSetup` phase,
/// this method is invoked on the isolate to then move the isolate
/// into the `DartIsolate::Phase::Ready` phase. Then isolate's
/// main entrypoint is then invoked to move it into the
/// `DartIsolate::Phase::Running` phase. This method will be
/// called each time the root isolate is launched (which may be
/// multiple times in cold-restart scenarios) as well as one each
/// for any child isolates referenced by that isolate.
///
/// @param isolate The isolate which is already in the
/// `DartIsolate::Phase::LibrariesSetup` phase.
///
/// @return Returns true if the isolate could be configured. Unless this
/// returns true, the engine will not move the isolate to the
/// `DartIsolate::Phase::Ready` phase for subsequent run.
///
[[nodiscard]] bool PrepareIsolate(DartIsolate& isolate);
virtual bool IsNullSafetyEnabled(const DartSnapshot& snapshot) = 0;
protected:
virtual bool DoPrepareIsolate(DartIsolate& isolate) = 0;
private:
FML_DISALLOW_COPY_AND_ASSIGN(IsolateConfiguration);
};
} // namespace flutter
#endif // FLUTTER_RUNTIME_ISOLATE_CONFIGURATION_H_
| engine/runtime/isolate_configuration.h/0 | {
"file_path": "engine/runtime/isolate_configuration.h",
"repo_id": "engine",
"token_count": 3005
} | 279 |
// Copyright 2013 The Flutter 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_RUNTIME_SKIA_CONCURRENT_EXECUTOR_H_
#define FLUTTER_RUNTIME_SKIA_CONCURRENT_EXECUTOR_H_
#include "flutter/fml/closure.h"
#include "flutter/fml/macros.h"
#include "third_party/skia/include/core/SkExecutor.h"
namespace flutter {
//------------------------------------------------------------------------------
/// @brief An interface used by Skia to schedule work on engine managed
/// threads (usually workers in a concurrent message loop).
///
/// Skia may decide that certain workloads don't have thread
/// affinity and may be performed on a background thread. However,
/// Skia does not manage its own threads. So, it delegates the
/// scheduling of this work to the engine via this interface. The
/// engine has a dedicated pool of threads it uses for scheduling
/// background tasks that have no thread affinity. This thread
/// worker pool is held next to the process global Dart VM instance.
/// The Skia executor is wired up there as well.
///
class SkiaConcurrentExecutor : public SkExecutor {
public:
//----------------------------------------------------------------------------
/// The callback invoked by the executor to schedule the given task onto an
/// engine managed background thread.
///
using OnWorkCallback = std::function<void(fml::closure work)>;
//----------------------------------------------------------------------------
/// @brief Create a new instance of the executor.
///
/// @param[in] on_work The work callback.
///
explicit SkiaConcurrentExecutor(const OnWorkCallback& on_work);
// |SkExecutor|
~SkiaConcurrentExecutor() override;
// |SkExecutor|
void add(fml::closure work) override;
private:
OnWorkCallback on_work_;
FML_DISALLOW_COPY_AND_ASSIGN(SkiaConcurrentExecutor);
};
} // namespace flutter
#endif // FLUTTER_RUNTIME_SKIA_CONCURRENT_EXECUTOR_H_
| engine/runtime/skia_concurrent_executor.h/0 | {
"file_path": "engine/runtime/skia_concurrent_executor.h",
"repo_id": "engine",
"token_count": 665
} | 280 |
// Copyright 2013 The Flutter 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/common/pipeline.h"
namespace flutter {
size_t GetNextPipelineTraceID() {
static std::atomic_size_t PipelineLastTraceID = {0};
return ++PipelineLastTraceID;
}
} // namespace flutter
| engine/shell/common/pipeline.cc/0 | {
"file_path": "engine/shell/common/pipeline.cc",
"repo_id": "engine",
"token_count": 122
} | 281 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/fml/logging.h"
#include "third_party/skia/include/core/SkColorSpace.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkImageInfo.h"
#include "third_party/skia/include/core/SkStream.h"
#include "third_party/skia/include/core/SkTypeface.h"
namespace flutter {
sk_sp<SkData> SerializeTypefaceWithoutData(SkTypeface* typeface, void* ctx) {
return SkData::MakeEmpty();
}
sk_sp<SkData> SerializeTypefaceWithData(SkTypeface* typeface, void* ctx) {
return typeface->serialize(SkTypeface::SerializeBehavior::kDoIncludeData);
}
sk_sp<SkTypeface> DeserializeTypefaceWithoutData(const void* data,
size_t length,
void* ctx) {
return nullptr;
}
struct ImageMetaData {
int32_t width;
int32_t height;
uint32_t color_type;
uint32_t alpha_type;
bool has_color_space;
} __attribute__((packed));
sk_sp<SkData> SerializeImageWithoutData(SkImage* image, void* ctx) {
const auto& info = image->imageInfo();
SkDynamicMemoryWStream stream;
ImageMetaData metadata = {info.width(), info.height(),
static_cast<uint32_t>(info.colorType()),
static_cast<uint32_t>(info.alphaType()),
static_cast<bool>(info.colorSpace())};
stream.write(&metadata, sizeof(ImageMetaData));
if (info.colorSpace()) {
auto color_space_data = info.colorSpace()->serialize();
FML_CHECK(color_space_data);
SkMemoryStream color_space_stream(color_space_data);
stream.writeStream(&color_space_stream, color_space_data->size());
}
return stream.detachAsData();
};
sk_sp<SkImage> DeserializeImageWithoutData(const void* data,
size_t length,
void* ctx) {
FML_CHECK(length >= sizeof(ImageMetaData));
auto metadata = static_cast<const ImageMetaData*>(data);
sk_sp<SkColorSpace> color_space = nullptr;
if (metadata->has_color_space) {
color_space = SkColorSpace::Deserialize(
static_cast<const uint8_t*>(data) + sizeof(ImageMetaData),
length - sizeof(ImageMetaData));
}
auto image_size = SkISize::Make(metadata->width, metadata->height);
auto info = SkImageInfo::Make(
image_size, static_cast<SkColorType>(metadata->color_type),
static_cast<SkAlphaType>(metadata->alpha_type), color_space);
sk_sp<SkData> image_data =
SkData::MakeUninitialized(image_size.width() * image_size.height() * 4);
memset(image_data->writable_data(), 0x0f, image_data->size());
sk_sp<SkImage> image =
SkImages::RasterFromData(info, image_data, image_size.width() * 4);
return image;
};
} // namespace flutter
| engine/shell/common/serialization_callbacks.cc/0 | {
"file_path": "engine/shell/common/serialization_callbacks.cc",
"repo_id": "engine",
"token_count": 1209
} | 282 |
// Copyright 2013 The Flutter 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_COMMON_SHELL_TEST_PLATFORM_VIEW_GL_H_
#define FLUTTER_SHELL_COMMON_SHELL_TEST_PLATFORM_VIEW_GL_H_
#include "flutter/shell/common/shell_test_external_view_embedder.h"
#include "flutter/shell/common/shell_test_platform_view.h"
#include "flutter/shell/gpu/gpu_surface_gl_delegate.h"
#include "flutter/testing/test_gl_surface.h"
#include "impeller/renderer/backend/gles/context_gles.h"
namespace flutter {
namespace testing {
class ShellTestPlatformViewGL : public ShellTestPlatformView,
public GPUSurfaceGLDelegate {
public:
ShellTestPlatformViewGL(PlatformView::Delegate& delegate,
const TaskRunners& task_runners,
std::shared_ptr<ShellTestVsyncClock> vsync_clock,
CreateVsyncWaiter create_vsync_waiter,
std::shared_ptr<ShellTestExternalViewEmbedder>
shell_test_external_view_embedder);
// |ShellTestPlatformView|
virtual ~ShellTestPlatformViewGL() override;
// |ShellTestPlatformView|
virtual void SimulateVSync() override;
// |PlatformView|
std::shared_ptr<impeller::Context> GetImpellerContext() const {
return impeller_context_;
}
private:
std::shared_ptr<impeller::ContextGLES> impeller_context_;
TestGLSurface gl_surface_;
CreateVsyncWaiter create_vsync_waiter_;
std::shared_ptr<ShellTestVsyncClock> vsync_clock_;
std::shared_ptr<ShellTestExternalViewEmbedder>
shell_test_external_view_embedder_;
// |PlatformView|
std::unique_ptr<Surface> CreateRenderingSurface() override;
// |PlatformView|
std::shared_ptr<ExternalViewEmbedder> CreateExternalViewEmbedder() override;
// |PlatformView|
std::unique_ptr<VsyncWaiter> CreateVSyncWaiter() override;
// |PlatformView|
PointerDataDispatcherMaker GetDispatcherMaker() override;
// |GPUSurfaceGLDelegate|
std::unique_ptr<GLContextResult> GLContextMakeCurrent() override;
// |GPUSurfaceGLDelegate|
bool GLContextClearCurrent() override;
// |GPUSurfaceGLDelegate|
bool GLContextPresent(const GLPresentInfo& present_info) override;
// |GPUSurfaceGLDelegate|
GLFBOInfo GLContextFBO(GLFrameInfo frame_info) const override;
// |GPUSurfaceGLDelegate|
GLProcResolver GetGLProcResolver() const override;
FML_DISALLOW_COPY_AND_ASSIGN(ShellTestPlatformViewGL);
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_COMMON_SHELL_TEST_PLATFORM_VIEW_GL_H_
| engine/shell/common/shell_test_platform_view_gl.h/0 | {
"file_path": "engine/shell/common/shell_test_platform_view_gl.h",
"repo_id": "engine",
"token_count": 1012
} | 283 |
// Copyright 2013 The Flutter 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 <string_view>
#include "flutter/common/settings.h"
#include "flutter/fml/command_line.h"
#ifndef FLUTTER_SHELL_COMMON_SWITCHES_H_
#define FLUTTER_SHELL_COMMON_SWITCHES_H_
namespace flutter {
// clang-format off
#ifndef DEF_SWITCHES_START
#define DEF_SWITCHES_START enum class Switch {
#endif
#ifndef DEF_SWITCH
#define DEF_SWITCH(swtch, flag, help) swtch,
#endif
#ifndef DEF_SWITCHES_END
#define DEF_SWITCHES_END Sentinel, } ;
#endif
// clang-format on
DEF_SWITCHES_START
DEF_SWITCH(AotSharedLibraryName,
"aot-shared-library-name",
"Name of the *.so containing AOT compiled Dart assets.")
DEF_SWITCH(AotVMServiceSharedLibraryName,
"aot-vmservice-shared-library-name",
"Name of the *.so containing AOT compiled Dart assets for "
"launching the service isolate.")
DEF_SWITCH(SnapshotAssetPath,
"snapshot-asset-path",
"Path to the directory containing the four files specified by "
"VmSnapshotData, VmSnapshotInstructions, "
"VmSnapshotInstructions and IsolateSnapshotInstructions.")
DEF_SWITCH(VmSnapshotData,
"vm-snapshot-data",
"The VM snapshot data that will be memory mapped as read-only. "
"SnapshotAssetPath must be present.")
DEF_SWITCH(VmSnapshotInstructions,
"vm-snapshot-instr",
"The VM instructions snapshot that will be memory mapped as read "
"and executable. SnapshotAssetPath must be present.")
DEF_SWITCH(IsolateSnapshotData,
"isolate-snapshot-data",
"The isolate snapshot data that will be memory mapped as read-only. "
"SnapshotAssetPath must be present.")
DEF_SWITCH(IsolateSnapshotInstructions,
"isolate-snapshot-instr",
"The isolate instructions snapshot that will be memory mapped as "
"read and executable. SnapshotAssetPath must be present.")
DEF_SWITCH(CacheDirPath,
"cache-dir-path",
"Path to the cache directory. "
"This is different from the persistent_cache_path in embedder.h, "
"which is used for Skia shader cache.")
DEF_SWITCH(ICUDataFilePath, "icu-data-file-path", "Path to the ICU data file.")
DEF_SWITCH(ICUSymbolPrefix,
"icu-symbol-prefix",
"Prefix for the symbols representing ICU data linked into the "
"Flutter library.")
DEF_SWITCH(ICUNativeLibPath,
"icu-native-lib-path",
"Path to the library file that exports the ICU data.")
DEF_SWITCH(DartFlags,
"dart-flags",
"Flags passed directly to the Dart VM without being interpreted "
"by the Flutter shell.")
DEF_SWITCH(DeviceVMServiceHost,
"vm-service-host",
"The hostname/IP address on which the Dart VM Service should "
"be served. If not set, defaults to 127.0.0.1 or ::1 depending on "
"whether --ipv6 is specified.")
// TODO(bkonyi): remove once flutter_tools no longer uses this option.
// See https://github.com/dart-lang/sdk/issues/50233
DEF_SWITCH(
DeviceObservatoryHost,
"observatory-host",
"(deprecated) The hostname/IP address on which the Dart VM Service should "
"be served. If not set, defaults to 127.0.0.1 or ::1 depending on "
"whether --ipv6 is specified.")
DEF_SWITCH(DeviceVMServicePort,
"vm-service-port",
"A custom Dart VM Service port. The default is to pick a randomly "
"available open port.")
// TODO(bkonyi): remove once flutter_tools no longer uses this option.
// See https://github.com/dart-lang/sdk/issues/50233
DEF_SWITCH(DeviceObservatoryPort,
"observatory-port",
"(deprecated) A custom Dart VM Service port. The default is to pick "
"a randomly "
"available open port.")
DEF_SWITCH(
DisableVMService,
"disable-vm-service",
"Disable the Dart VM Service. The Dart VM Service is never available "
"in release mode.")
// TODO(bkonyi): remove once flutter_tools no longer uses this option.
// See https://github.com/dart-lang/sdk/issues/50233
DEF_SWITCH(DisableObservatory,
"disable-observatory",
"(deprecated) Disable the Dart VM Service. The Dart VM Service is "
"never available "
"in release mode.")
DEF_SWITCH(DisableVMServicePublication,
"disable-vm-service-publication",
"Disable mDNS Dart VM Service publication.")
// TODO(bkonyi): remove once flutter_tools no longer uses this option.
// See https://github.com/dart-lang/sdk/issues/50233
DEF_SWITCH(DisableObservatoryPublication,
"disable-observatory-publication",
"(deprecated) Disable mDNS Dart VM Service publication.")
DEF_SWITCH(IPv6,
"ipv6",
"Bind to the IPv6 localhost address for the Dart VM Service. "
"Ignored if --vm-service-host is set.")
DEF_SWITCH(EnableDartProfiling,
"enable-dart-profiling",
"Enable Dart profiling. Profiling information can be viewed from "
"Dart / Flutter DevTools.")
DEF_SWITCH(EndlessTraceBuffer,
"endless-trace-buffer",
"Enable an endless trace buffer. The default is a ring buffer. "
"This is useful when very old events need to viewed. For example, "
"during application launch. Memory usage will continue to grow "
"indefinitely however.")
DEF_SWITCH(EnableSoftwareRendering,
"enable-software-rendering",
"Enable rendering using the Skia software backend. This is useful "
"when testing Flutter on emulators. By default, Flutter will "
"attempt to either use OpenGL, Metal, or Vulkan.")
DEF_SWITCH(Route,
"route",
"Start app with an specific route defined on the framework")
DEF_SWITCH(SkiaDeterministicRendering,
"skia-deterministic-rendering",
"Skips the call to SkGraphics::Init(), thus avoiding swapping out "
"some Skia function pointers based on available CPU features. This "
"is used to obtain 100% deterministic behavior in Skia rendering.")
DEF_SWITCH(FlutterAssetsDir,
"flutter-assets-dir",
"Path to the Flutter assets directory.")
DEF_SWITCH(Help, "help", "Display this help text.")
DEF_SWITCH(LogTag, "log-tag", "Tag associated with log messages.")
DEF_SWITCH(DisableServiceAuthCodes,
"disable-service-auth-codes",
"Disable the requirement for authentication codes for communicating"
" with the VM service.")
DEF_SWITCH(EnableServicePortFallback,
"enable-service-port-fallback",
"Allow the VM service to fallback to automatic port selection if"
" binding to a specified port fails.")
DEF_SWITCH(StartPaused,
"start-paused",
"Start the application paused in the Dart debugger.")
DEF_SWITCH(EnableCheckedMode, "enable-checked-mode", "Enable checked mode.")
DEF_SWITCH(TraceStartup,
"trace-startup",
"Trace early application lifecycle. Automatically switches to an "
"endless trace buffer.")
DEF_SWITCH(TraceSkia,
"trace-skia",
"Trace Skia calls. This is useful when debugging the GPU threed."
"By default, Skia tracing is not enabled to reduce the number of "
"traced events")
DEF_SWITCH(TraceSkiaAllowlist,
"trace-skia-allowlist",
"Filters out all Skia trace event categories except those that are "
"specified in this comma separated list.")
DEF_SWITCH(
TraceAllowlist,
"trace-allowlist",
"Filters out all trace events except those that are specified in this "
"comma separated list of allowed prefixes.")
DEF_SWITCH(DumpSkpOnShaderCompilation,
"dump-skp-on-shader-compilation",
"Automatically dump the skp that triggers new shader compilations. "
"This is useful for writing custom ShaderWarmUp to reduce jank. "
"By default, this is not enabled to reduce the overhead. ")
DEF_SWITCH(CacheSkSL,
"cache-sksl",
"Only cache the shader in SkSL instead of binary or GLSL. This "
"should only be used during development phases. The generated SkSLs "
"can later be used in the release build for shader precompilation "
"at launch in order to eliminate the shader-compile jank.")
DEF_SWITCH(PurgePersistentCache,
"purge-persistent-cache",
"Remove all existing persistent cache. This is mainly for debugging "
"purposes such as reproducing the shader compilation jank.")
DEF_SWITCH(
TraceSystrace,
"trace-systrace",
"Trace to the system tracer (instead of the timeline) on platforms where "
"such a tracer is available. Currently only supported on Android and "
"Fuchsia.")
DEF_SWITCH(TraceToFile,
"trace-to-file",
"Write the timeline trace to a file at the specified path. The file "
"will be in Perfetto's proto format; it will be possible to load "
"the file into Perfetto's trace viewer.")
DEF_SWITCH(UseTestFonts,
"use-test-fonts",
"Running tests that layout and measure text will not yield "
"consistent results across various platforms. Enabling this option "
"will make font resolution default to the Ahem test font on all "
"platforms (See https://www.w3.org/Style/CSS/Test/Fonts/Ahem/). "
"This option is only available on the desktop test shells.")
DEF_SWITCH(DisableAssetFonts,
"disable-asset-fonts",
"Prevents usage of any non-test fonts unless they were explicitly "
"Loaded via dart:ui font APIs. This option is only available on the "
"desktop test shells.")
DEF_SWITCH(PrefetchedDefaultFontManager,
"prefetched-default-font-manager",
"Indicates whether the embedding started a prefetch of the "
"default font manager before creating the engine.")
DEF_SWITCH(VerboseLogging,
"verbose-logging",
"By default, only errors are logged. This flag enabled logging at "
"all severity levels. This is NOT a per shell flag and affect log "
"levels for all shells in the process.")
DEF_SWITCH(RunForever,
"run-forever",
"In non-interactive mode, keep the shell running after the Dart "
"script has completed.")
DEF_SWITCH(DisableDartAsserts,
"disable-dart-asserts",
"Dart code runs with assertions enabled when the runtime mode is "
"debug. In profile and release product modes, assertions are "
"disabled. This flag may be specified if the user wishes to run "
"with assertions disabled in the debug product mode (i.e. with JIT "
"or DBC).")
DEF_SWITCH(EnableSerialGC,
"enable-serial-gc",
"On low power devices with low core counts, running concurrent "
"GC tasks on threads can cause them to contend with the UI thread "
"which could potentially lead to jank. This option turns off all "
"concurrent GC activities")
DEF_SWITCH(DisallowInsecureConnections,
"disallow-insecure-connections",
"By default, dart:io allows all socket connections. If this switch "
"is set, all insecure connections are rejected.")
DEF_SWITCH(DomainNetworkPolicy,
"domain-network-policy",
"JSON encoded network policy per domain. This overrides the "
"DisallowInsecureConnections switch. Embedder can specify whether "
"to allow or disallow insecure connections at a domain level.")
DEF_SWITCH(
ForceMultithreading,
"force-multithreading",
"Uses separate threads for the platform, UI, GPU and IO task runners. "
"By default, a single thread is used for all task runners. Only available "
"in the flutter_tester.")
DEF_SWITCH(OldGenHeapSize,
"old-gen-heap-size",
"The size limit in megabytes for the Dart VM old gen heap space.")
DEF_SWITCH(ResourceCacheMaxBytesThreshold,
"resource-cache-max-bytes-threshold",
"The max bytes threshold of resource cache, or 0 for unlimited.")
DEF_SWITCH(EnableImpeller,
"enable-impeller",
"Enable the Impeller renderer on supported platforms. Ignored if "
"Impeller is not supported on the platform.")
DEF_SWITCH(ImpellerBackend,
"impeller-backend",
"Requests a particular Impeller backend on platforms that support "
"multiple backends. (ex `opengles` or `vulkan`)")
DEF_SWITCH(EnableVulkanValidation,
"enable-vulkan-validation",
"Enable loading Vulkan validation layers. The layers must be "
"available to the application and loadable. On non-Vulkan backends, "
"this flag does nothing.")
DEF_SWITCH(EnableOpenGLGPUTracing,
"enable-opengl-gpu-tracing",
"Enable tracing of GPU execution time when using the Impeller "
"OpenGLES backend.")
DEF_SWITCH(EnableVulkanGPUTracing,
"enable-vulkan-gpu-tracing",
"Enable tracing of GPU execution time when using the Impeller "
"Vulkan backend.")
DEF_SWITCH(LeakVM,
"leak-vm",
"When the last shell shuts down, the shared VM is leaked by default "
"(the leak_vm in VM settings is true). To clean up the leak VM, set "
"this value to false.")
DEF_SWITCH(
MsaaSamples,
"msaa-samples",
"The minimum number of samples to require for multisampled anti-aliasing. "
"Setting this value to 0 or 1 disables MSAA. If it is not 0 or 1, it must "
"be one of 2, 4, 8, or 16. However, if the GPU does not support the "
"requested sampling value, MSAA will be disabled.")
DEF_SWITCH(EnableEmbedderAPI,
"enable-embedder-api",
"Enable the embedder api. Defaults to false. iOS only.")
DEF_SWITCHES_END
void PrintUsage(const std::string& executable_name);
const std::string_view FlagForSwitch(Switch swtch);
Settings SettingsFromCommandLine(const fml::CommandLine& command_line);
} // namespace flutter
#endif // FLUTTER_SHELL_COMMON_SWITCHES_H_
| engine/shell/common/switches.h/0 | {
"file_path": "engine/shell/common/switches.h",
"repo_id": "engine",
"token_count": 5574
} | 284 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//flutter/common/config.gni")
import("//flutter/impeller/tools/impeller.gni")
import("//flutter/shell/config.gni")
gpu_common_deps = [
"//flutter/common",
"//flutter/common/graphics",
"//flutter/flow",
"//flutter/fml",
"//flutter/shell/common",
"//flutter/skia",
]
source_set("gpu_surface_software") {
sources = [
"gpu_surface_software.cc",
"gpu_surface_software.h",
"gpu_surface_software_delegate.cc",
"gpu_surface_software_delegate.h",
]
public_deps = gpu_common_deps
}
source_set("gpu_surface_gl") {
sources = [
"gpu_surface_gl_delegate.cc",
"gpu_surface_gl_delegate.h",
"gpu_surface_gl_skia.cc",
"gpu_surface_gl_skia.h",
]
public_deps = gpu_common_deps
if (impeller_enable_opengles) {
sources += [
"gpu_surface_gl_impeller.cc",
"gpu_surface_gl_impeller.h",
]
public_deps += [ "//flutter/impeller" ]
}
}
source_set("gpu_surface_vulkan") {
sources = [
"gpu_surface_vulkan.cc",
"gpu_surface_vulkan.h",
"gpu_surface_vulkan_delegate.cc",
"gpu_surface_vulkan_delegate.h",
]
public_deps = gpu_common_deps + [
"//flutter/shell/platform/embedder:embedder_headers",
"//flutter/vulkan",
"//flutter/vulkan/procs",
]
if (impeller_enable_vulkan) {
sources += [
"gpu_surface_vulkan_impeller.cc",
"gpu_surface_vulkan_impeller.h",
]
public_deps += [ "//flutter/impeller" ]
}
}
source_set("gpu_surface_metal") {
sources = [
"gpu_surface_metal_delegate.cc",
"gpu_surface_metal_delegate.h",
"gpu_surface_metal_skia.h",
"gpu_surface_metal_skia.mm",
]
public_deps = gpu_common_deps
if (impeller_enable_metal) {
sources += [
"gpu_surface_metal_impeller.h",
"gpu_surface_metal_impeller.mm",
]
public_deps += [ "//flutter/impeller" ]
}
}
if (is_mac) {
impeller_component("gpu_surface_metal_unittests") {
testonly = true
target_type = "executable"
sources = [ "gpu_surface_metal_impeller_unittests.mm" ]
frameworks = [
"AppKit.framework",
"QuartzCore.framework",
]
deps = [
"//flutter/testing",
":gpu_surface_metal",
"//flutter/impeller/fixtures",
"//flutter/fml",
"//flutter/runtime",
"//flutter/runtime:libdart",
"//flutter/testing",
] + gpu_common_deps
}
}
| engine/shell/gpu/BUILD.gn/0 | {
"file_path": "engine/shell/gpu/BUILD.gn",
"repo_id": "engine",
"token_count": 1223
} | 285 |
// Copyright 2013 The Flutter 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_GPU_GPU_SURFACE_SOFTWARE_H_
#define FLUTTER_SHELL_GPU_GPU_SURFACE_SOFTWARE_H_
#include "flutter/flow/surface.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/memory/weak_ptr.h"
#include "flutter/shell/gpu/gpu_surface_software_delegate.h"
namespace flutter {
class GPUSurfaceSoftware : public Surface {
public:
GPUSurfaceSoftware(GPUSurfaceSoftwareDelegate* delegate,
bool render_to_surface);
~GPUSurfaceSoftware() override;
// |Surface|
bool IsValid() override;
// |Surface|
std::unique_ptr<SurfaceFrame> AcquireFrame(const SkISize& size) override;
// |Surface|
SkMatrix GetRootTransformation() const override;
// |Surface|
GrDirectContext* GetContext() override;
private:
GPUSurfaceSoftwareDelegate* delegate_;
// TODO(38466): Refactor GPU surface APIs take into account the fact that an
// external view embedder may want to render to the root surface. This is a
// hack to make avoid allocating resources for the root surface when an
// external view embedder is present.
const bool render_to_surface_;
fml::TaskRunnerAffineWeakPtrFactory<GPUSurfaceSoftware> weak_factory_;
FML_DISALLOW_COPY_AND_ASSIGN(GPUSurfaceSoftware);
};
} // namespace flutter
#endif // FLUTTER_SHELL_GPU_GPU_SURFACE_SOFTWARE_H_
| engine/shell/gpu/gpu_surface_software.h/0 | {
"file_path": "engine/shell/gpu/gpu_surface_software.h",
"repo_id": "engine",
"token_count": 497
} | 286 |
// Copyright 2013 The Flutter 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/android/android_context_gl_impeller.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
using ::testing::_;
using ::testing::AllOf;
using ::testing::ByMove;
using ::testing::Field;
using ::testing::Matcher;
using ::testing::Return;
using ::impeller::egl::Config;
using ::impeller::egl::ConfigDescriptor;
namespace {
class MockDisplay : public impeller::egl::Display {
public:
MOCK_METHOD(bool, IsValid, (), (const, override));
MOCK_METHOD(std::unique_ptr<Config>,
ChooseConfig,
(ConfigDescriptor),
(const, override));
};
} // namespace
TEST(AndroidContextGLImpeller, MSAAFirstAttempt) {
auto display = std::make_unique<MockDisplay>();
EXPECT_CALL(*display, IsValid).WillRepeatedly(Return(true));
auto first_result = std::make_unique<Config>(ConfigDescriptor(), EGLConfig());
auto second_result =
std::make_unique<Config>(ConfigDescriptor(), EGLConfig());
EXPECT_CALL(
*display,
ChooseConfig(Matcher<ConfigDescriptor>(AllOf(
Field(&ConfigDescriptor::samples, impeller::egl::Samples::kFour),
Field(&ConfigDescriptor::surface_type,
impeller::egl::SurfaceType::kWindow)))))
.WillOnce(Return(ByMove(std::move(first_result))));
EXPECT_CALL(*display, ChooseConfig(Matcher<ConfigDescriptor>(
Field(&ConfigDescriptor::surface_type,
impeller::egl::SurfaceType::kPBuffer))))
.WillOnce(Return(ByMove(std::move(second_result))));
ON_CALL(*display, ChooseConfig(_))
.WillByDefault(Return(ByMove(std::unique_ptr<Config>())));
auto context =
std::make_unique<AndroidContextGLImpeller>(std::move(display), true);
ASSERT_TRUE(context);
}
TEST(AndroidContextGLImpeller, FallbackForEmulator) {
auto display = std::make_unique<MockDisplay>();
EXPECT_CALL(*display, IsValid).WillRepeatedly(Return(true));
std::unique_ptr<Config> first_result;
auto second_result =
std::make_unique<Config>(ConfigDescriptor(), EGLConfig());
auto third_result = std::make_unique<Config>(ConfigDescriptor(), EGLConfig());
EXPECT_CALL(
*display,
ChooseConfig(Matcher<ConfigDescriptor>(AllOf(
Field(&ConfigDescriptor::samples, impeller::egl::Samples::kFour),
Field(&ConfigDescriptor::surface_type,
impeller::egl::SurfaceType::kWindow)))))
.WillOnce(Return(ByMove(std::move(first_result))));
EXPECT_CALL(
*display,
ChooseConfig(Matcher<ConfigDescriptor>(
AllOf(Field(&ConfigDescriptor::samples, impeller::egl::Samples::kOne),
Field(&ConfigDescriptor::surface_type,
impeller::egl::SurfaceType::kWindow)))))
.WillOnce(Return(ByMove(std::move(second_result))));
EXPECT_CALL(*display, ChooseConfig(Matcher<ConfigDescriptor>(
Field(&ConfigDescriptor::surface_type,
impeller::egl::SurfaceType::kPBuffer))))
.WillOnce(Return(ByMove(std::move(third_result))));
ON_CALL(*display, ChooseConfig(_))
.WillByDefault(Return(ByMove(std::unique_ptr<Config>())));
auto context =
std::make_unique<AndroidContextGLImpeller>(std::move(display), true);
ASSERT_TRUE(context);
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/android/android_context_gl_impeller_unittests.cc/0 | {
"file_path": "engine/shell/platform/android/android_context_gl_impeller_unittests.cc",
"repo_id": "engine",
"token_count": 1419
} | 287 |
// Copyright 2013 The Flutter 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_ANDROID_ANDROID_SHELL_HOLDER_H_
#define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SHELL_HOLDER_H_
#include <memory>
#include "flutter/assets/asset_manager.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/unique_fd.h"
#include "flutter/lib/ui/window/viewport_metrics.h"
#include "flutter/runtime/platform_data.h"
#include "flutter/shell/common/run_configuration.h"
#include "flutter/shell/common/shell.h"
#include "flutter/shell/common/thread_host.h"
#include "flutter/shell/platform/android/apk_asset_provider.h"
#include "flutter/shell/platform/android/jni/platform_view_android_jni.h"
#include "flutter/shell/platform/android/platform_message_handler_android.h"
#include "flutter/shell/platform/android/platform_view_android.h"
namespace flutter {
//----------------------------------------------------------------------------
/// @brief This is the Android owner of the core engine Shell.
///
/// @details This is the top orchestrator class on the C++ side for the
/// Android embedding. It corresponds to a FlutterEngine on the
/// Java side. This class is in C++ because the Shell is in
/// C++ and an Android orchestrator needs to exist to
/// compose it with other Android specific C++ components such as
/// the PlatformViewAndroid. This composition of many-to-one
/// C++ components would be difficult to do through JNI whereas
/// a FlutterEngine and AndroidShellHolder has a 1:1 relationship.
///
/// Technically, the FlutterJNI class owns this AndroidShellHolder
/// class instance, but the FlutterJNI class is meant to be mostly
/// static and has minimal state to perform the C++ pointer <->
/// Java class instance translation.
///
class AndroidShellHolder {
public:
AndroidShellHolder(const flutter::Settings& settings,
std::shared_ptr<PlatformViewAndroidJNI> jni_facade);
~AndroidShellHolder();
bool IsValid() const;
//----------------------------------------------------------------------------
/// @brief This is a factory for a derived AndroidShellHolder from an
/// existing AndroidShellHolder.
///
/// @details Creates one Shell from another Shell where the created
/// Shell takes the opportunity to share any internal components
/// it can. This results is a Shell that has a smaller startup
/// time cost and a smaller memory footprint than an Shell created
/// with a Create function.
///
/// The new Shell is returned in a new AndroidShellHolder
/// instance.
///
/// The new Shell's flutter::Settings cannot be changed from that
/// of the initial Shell. The RunConfiguration subcomponent can
/// be changed however in the spawned Shell to run a different
/// entrypoint than the existing shell.
///
/// Since the AndroidShellHolder both binds downwards to a Shell
/// and also upwards to JNI callbacks that the PlatformViewAndroid
/// makes, the JNI instance holding this AndroidShellHolder should
/// be created first to supply the jni_facade callback.
///
/// @param[in] jni_facade this argument should be the JNI callback facade of
/// a new JNI instance meant to hold this AndroidShellHolder.
///
/// @returns A new AndroidShellHolder containing a new Shell. Returns
/// nullptr when a new Shell can't be created.
///
std::unique_ptr<AndroidShellHolder> Spawn(
std::shared_ptr<PlatformViewAndroidJNI> jni_facade,
const std::string& entrypoint,
const std::string& libraryUrl,
const std::string& initial_route,
const std::vector<std::string>& entrypoint_args) const;
void Launch(std::unique_ptr<APKAssetProvider> apk_asset_provider,
const std::string& entrypoint,
const std::string& libraryUrl,
const std::vector<std::string>& entrypoint_args);
const flutter::Settings& GetSettings() const;
fml::WeakPtr<PlatformViewAndroid> GetPlatformView();
Rasterizer::Screenshot Screenshot(Rasterizer::ScreenshotType type,
bool base64_encode);
void NotifyLowMemoryWarning();
const std::shared_ptr<PlatformMessageHandler>& GetPlatformMessageHandler()
const {
return shell_->GetPlatformMessageHandler();
}
void UpdateDisplayMetrics();
private:
const flutter::Settings settings_;
const std::shared_ptr<PlatformViewAndroidJNI> jni_facade_;
fml::WeakPtr<PlatformViewAndroid> platform_view_;
std::shared_ptr<ThreadHost> thread_host_;
std::unique_ptr<Shell> shell_;
bool is_valid_ = false;
uint64_t next_pointer_flow_id_ = 0;
std::unique_ptr<APKAssetProvider> apk_asset_provider_;
//----------------------------------------------------------------------------
/// @brief Constructor with its components injected.
///
/// @details This is similar to the standard constructor, except its
/// members were constructed elsewhere and injected.
///
/// All injected components must be non-null and valid.
///
/// Used when constructing the Shell from the inside out when
/// spawning from an existing Shell.
///
AndroidShellHolder(const flutter::Settings& settings,
const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade,
const std::shared_ptr<ThreadHost>& thread_host,
std::unique_ptr<Shell> shell,
std::unique_ptr<APKAssetProvider> apk_asset_provider,
const fml::WeakPtr<PlatformViewAndroid>& platform_view);
static void ThreadDestructCallback(void* value);
std::optional<RunConfiguration> BuildRunConfiguration(
const std::string& entrypoint,
const std::string& libraryUrl,
const std::vector<std::string>& entrypoint_args) const;
bool IsNDKImageDecoderAvailable();
FML_DISALLOW_COPY_AND_ASSIGN(AndroidShellHolder);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SHELL_HOLDER_H_
| engine/shell/platform/android/android_shell_holder.h/0 | {
"file_path": "engine/shell/platform/android/android_shell_holder.h",
"repo_id": "engine",
"token_count": 2302
} | 288 |
// Copyright 2013 The Flutter 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_ANDROID_CONTEXT_ANDROID_CONTEXT_H_
#define FLUTTER_SHELL_PLATFORM_ANDROID_CONTEXT_ANDROID_CONTEXT_H_
#include "common/settings.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/task_runner.h"
#include "flutter/impeller/renderer/context.h"
#include "third_party/skia/include/gpu/GrDirectContext.h"
namespace flutter {
//------------------------------------------------------------------------------
/// @brief Holds state that is shared across Android surfaces.
///
class AndroidContext {
public:
explicit AndroidContext(AndroidRenderingAPI rendering_api);
virtual ~AndroidContext();
AndroidRenderingAPI RenderingApi() const;
virtual bool IsValid() const;
//----------------------------------------------------------------------------
/// @brief Setter for the Skia context to be used by subsequent
/// AndroidSurfaces.
/// @details This is useful to reduce memory consumption when creating
/// multiple AndroidSurfaces for the same AndroidContext.
///
/// The first AndroidSurface should set this for the
/// AndroidContext if the AndroidContext does not yet have a
/// Skia context to share via GetMainSkiaContext.
///
void SetMainSkiaContext(const sk_sp<GrDirectContext>& main_context);
//----------------------------------------------------------------------------
/// @brief Accessor for the Skia context associated with AndroidSurfaces
/// and the raster thread.
/// @details This context is created lazily by the AndroidSurface based
/// on their respective rendering backend and set on this
/// AndroidContext to share via SetMainSkiaContext.
/// @returns `nullptr` when no Skia context has been set yet by its
/// AndroidSurface via SetMainSkiaContext.
/// @attention The software context doesn't have a Skia context, so this
/// value will be nullptr.
///
sk_sp<GrDirectContext> GetMainSkiaContext() const;
//----------------------------------------------------------------------------
/// @brief Accessor for the Impeller context associated with
/// AndroidSurfaces and the raster thread.
///
std::shared_ptr<impeller::Context> GetImpellerContext() const;
protected:
/// Intended to be called from a subclass constructor after setup work for the
/// context has completed.
void SetImpellerContext(const std::shared_ptr<impeller::Context>& context);
private:
const AndroidRenderingAPI rendering_api_;
// This is the Skia context used for on-screen rendering.
sk_sp<GrDirectContext> main_context_;
std::shared_ptr<impeller::Context> impeller_context_;
FML_DISALLOW_COPY_AND_ASSIGN(AndroidContext);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_ANDROID_CONTEXT_ANDROID_CONTEXT_H_
| engine/shell/platform/android/context/android_context.h/0 | {
"file_path": "engine/shell/platform/android/context/android_context.h",
"repo_id": "engine",
"token_count": 953
} | 289 |
// Copyright 2013 The Flutter 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/android/image_external_texture_vk.h"
#include <cstdint>
#include "flutter/impeller/core/formats.h"
#include "flutter/impeller/core/texture_descriptor.h"
#include "flutter/impeller/display_list/dl_image_impeller.h"
#include "flutter/impeller/renderer/backend/vulkan/android/ahb_texture_source_vk.h"
#include "flutter/impeller/renderer/backend/vulkan/command_buffer_vk.h"
#include "flutter/impeller/renderer/backend/vulkan/command_encoder_vk.h"
#include "flutter/impeller/renderer/backend/vulkan/texture_vk.h"
#include "flutter/impeller/toolkit/android/hardware_buffer.h"
namespace flutter {
ImageExternalTextureVK::ImageExternalTextureVK(
const std::shared_ptr<impeller::ContextVK>& impeller_context,
int64_t id,
const fml::jni::ScopedJavaGlobalRef<jobject>& image_texture_entry,
const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade)
: ImageExternalTexture(id, image_texture_entry, jni_facade),
impeller_context_(impeller_context) {}
ImageExternalTextureVK::~ImageExternalTextureVK() {}
void ImageExternalTextureVK::Attach(PaintContext& context) {
if (state_ == AttachmentState::kUninitialized) {
// First processed frame we are attached.
state_ = AttachmentState::kAttached;
}
}
void ImageExternalTextureVK::Detach() {}
void ImageExternalTextureVK::ProcessFrame(PaintContext& context,
const SkRect& bounds) {
JavaLocalRef image = AcquireLatestImage();
if (image.is_null()) {
return;
}
JavaLocalRef hardware_buffer = HardwareBufferFor(image);
AHardwareBuffer* latest_hardware_buffer = AHardwareBufferFor(hardware_buffer);
auto hb_desc =
impeller::android::HardwareBuffer::Describe(latest_hardware_buffer);
std::optional<HardwareBufferKey> key =
impeller::android::HardwareBuffer::GetSystemUniqueID(
latest_hardware_buffer);
auto existing_image = image_lru_.FindImage(key);
if (existing_image != nullptr || !hb_desc.has_value()) {
dl_image_ = existing_image;
CloseHardwareBuffer(hardware_buffer);
return;
}
auto texture_source = std::make_shared<impeller::AHBTextureSourceVK>(
impeller_context_, latest_hardware_buffer, hb_desc.value());
if (!texture_source->IsValid()) {
CloseHardwareBuffer(hardware_buffer);
return;
}
auto texture =
std::make_shared<impeller::TextureVK>(impeller_context_, texture_source);
// Transition the layout to shader read.
{
auto buffer = impeller_context_->CreateCommandBuffer();
impeller::CommandBufferVK& buffer_vk =
impeller::CommandBufferVK::Cast(*buffer);
impeller::BarrierVK barrier;
barrier.cmd_buffer = buffer_vk.GetEncoder()->GetCommandBuffer();
barrier.src_access = impeller::vk::AccessFlagBits::eColorAttachmentWrite |
impeller::vk::AccessFlagBits::eTransferWrite;
barrier.src_stage =
impeller::vk::PipelineStageFlagBits::eColorAttachmentOutput |
impeller::vk::PipelineStageFlagBits::eTransfer;
barrier.dst_access = impeller::vk::AccessFlagBits::eShaderRead;
barrier.dst_stage = impeller::vk::PipelineStageFlagBits::eFragmentShader;
barrier.new_layout = impeller::vk::ImageLayout::eShaderReadOnlyOptimal;
if (!texture->SetLayout(barrier)) {
return;
}
if (!impeller_context_->GetCommandQueue()->Submit({buffer}).ok()) {
return;
}
}
dl_image_ = impeller::DlImageImpeller::Make(texture);
if (key.has_value()) {
image_lru_.AddImage(dl_image_, key.value());
}
CloseHardwareBuffer(hardware_buffer);
}
} // namespace flutter
| engine/shell/platform/android/image_external_texture_vk.cc/0 | {
"file_path": "engine/shell/platform/android/image_external_texture_vk.cc",
"repo_id": "engine",
"token_count": 1392
} | 290 |
package io.flutter.embedding.android;
import static io.flutter.Build.API_LEVELS;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Matrix;
import android.os.Build;
import android.util.TypedValue;
import android.view.InputDevice;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import io.flutter.embedding.engine.renderer.FlutterRenderer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.HashMap;
import java.util.Map;
/** Sends touch information from Android to Flutter in a format that Flutter understands. */
public class AndroidTouchProcessor {
private static final String TAG = "AndroidTouchProcessor";
// Must match the PointerChange enum in pointer.dart.
@IntDef({
PointerChange.CANCEL,
PointerChange.ADD,
PointerChange.REMOVE,
PointerChange.HOVER,
PointerChange.DOWN,
PointerChange.MOVE,
PointerChange.UP,
PointerChange.PAN_ZOOM_START,
PointerChange.PAN_ZOOM_UPDATE,
PointerChange.PAN_ZOOM_END
})
public @interface PointerChange {
int CANCEL = 0;
int ADD = 1;
int REMOVE = 2;
int HOVER = 3;
int DOWN = 4;
int MOVE = 5;
int UP = 6;
int PAN_ZOOM_START = 7;
int PAN_ZOOM_UPDATE = 8;
int PAN_ZOOM_END = 9;
}
// Must match the PointerDeviceKind enum in pointer.dart.
@IntDef({
PointerDeviceKind.TOUCH,
PointerDeviceKind.MOUSE,
PointerDeviceKind.STYLUS,
PointerDeviceKind.INVERTED_STYLUS,
PointerDeviceKind.TRACKPAD,
PointerDeviceKind.UNKNOWN
})
public @interface PointerDeviceKind {
int TOUCH = 0;
int MOUSE = 1;
int STYLUS = 2;
int INVERTED_STYLUS = 3;
int TRACKPAD = 4;
int UNKNOWN = 5;
}
// Must match the PointerSignalKind enum in pointer.dart.
@IntDef({
PointerSignalKind.NONE,
PointerSignalKind.SCROLL,
PointerSignalKind.SCROLL_INERTIA_CANCEL,
PointerSignalKind.SCALE,
PointerSignalKind.UNKNOWN
})
public @interface PointerSignalKind {
int NONE = 0;
int SCROLL = 1;
int SCROLL_INERTIA_CANCEL = 2;
int SCALE = 3;
int UNKNOWN = 4;
}
// This value must match kPointerDataFieldCount in pointer_data.cc. (The
// pointer_data.cc also lists other locations that must be kept consistent.)
private static final int POINTER_DATA_FIELD_COUNT = 36;
@VisibleForTesting static final int BYTES_PER_FIELD = 8;
// Default if context is null, chosen to ensure reasonable speed scrolling.
@VisibleForTesting static final int DEFAULT_VERTICAL_SCROLL_FACTOR = 48;
@VisibleForTesting static final int DEFAULT_HORIZONTAL_SCROLL_FACTOR = 48;
// This value must match the value in framework's platform_view.dart.
// This flag indicates whether the original Android pointer events were batched together.
private static final int POINTER_DATA_FLAG_BATCHED = 1;
// The view ID for the only view in a single-view Flutter app.
private static final int IMPLICIT_VIEW_ID = 0;
@NonNull private final FlutterRenderer renderer;
@NonNull private final MotionEventTracker motionEventTracker;
private static final Matrix IDENTITY_TRANSFORM = new Matrix();
private final boolean trackMotionEvents;
private final Map<Integer, float[]> ongoingPans = new HashMap<>();
// Only used on api 25 and below to avoid requerying display metrics.
private int cachedVerticalScrollFactor;
/**
* Constructs an {@code AndroidTouchProcessor} that will send touch event data to the Flutter
* execution context represented by the given {@link FlutterRenderer}.
*
* @param renderer The object that manages textures for rendering.
* @param trackMotionEvents This is used to query motion events when platform views are rendered.
*/
// TODO(mattcarroll): consider moving packet behavior to a FlutterInteractionSurface instead of
// FlutterRenderer
public AndroidTouchProcessor(@NonNull FlutterRenderer renderer, boolean trackMotionEvents) {
this.renderer = renderer;
this.motionEventTracker = MotionEventTracker.getInstance();
this.trackMotionEvents = trackMotionEvents;
}
public boolean onTouchEvent(@NonNull MotionEvent event) {
return onTouchEvent(event, IDENTITY_TRANSFORM);
}
/**
* Sends the given {@link MotionEvent} data to Flutter in a format that Flutter understands.
*
* @param event The motion event from the view.
* @param transformMatrix Applies to the view that originated the event. It's used to transform
* the gesture pointers into screen coordinates.
* @return True if the event was handled.
*/
public boolean onTouchEvent(@NonNull MotionEvent event, @NonNull Matrix transformMatrix) {
int pointerCount = event.getPointerCount();
// The following packing code must match the struct in pointer_data.h.
// Prepare a data packet of the appropriate size and order.
ByteBuffer packet =
ByteBuffer.allocateDirect(pointerCount * POINTER_DATA_FIELD_COUNT * BYTES_PER_FIELD);
packet.order(ByteOrder.LITTLE_ENDIAN);
int maskedAction = event.getActionMasked();
int pointerChange = getPointerChangeForAction(event.getActionMasked());
boolean updateForSinglePointer =
maskedAction == MotionEvent.ACTION_DOWN || maskedAction == MotionEvent.ACTION_POINTER_DOWN;
boolean updateForMultiplePointers =
!updateForSinglePointer
&& (maskedAction == MotionEvent.ACTION_UP
|| maskedAction == MotionEvent.ACTION_POINTER_UP);
if (updateForSinglePointer) {
// ACTION_DOWN and ACTION_POINTER_DOWN always apply to a single pointer only.
addPointerForIndex(event, event.getActionIndex(), pointerChange, 0, transformMatrix, packet);
} else if (updateForMultiplePointers) {
// ACTION_UP and ACTION_POINTER_UP may contain position updates for other pointers.
// We are converting these updates to move events here in order to preserve this data.
// We also mark these events with a flag in order to help the framework reassemble
// the original Android event later, should it need to forward it to a PlatformView.
for (int p = 0; p < pointerCount; p++) {
if (p != event.getActionIndex() && event.getToolType(p) == MotionEvent.TOOL_TYPE_FINGER) {
addPointerForIndex(
event, p, PointerChange.MOVE, POINTER_DATA_FLAG_BATCHED, transformMatrix, packet);
}
}
// It's important that we're sending the UP event last. This allows PlatformView
// to correctly batch everything back into the original Android event if needed.
addPointerForIndex(event, event.getActionIndex(), pointerChange, 0, transformMatrix, packet);
} else {
// ACTION_MOVE may not actually mean all pointers have moved
// but it's the responsibility of a later part of the system to
// ignore 0-deltas if desired.
for (int p = 0; p < pointerCount; p++) {
addPointerForIndex(event, p, pointerChange, 0, transformMatrix, packet);
}
}
// Verify that the packet is the expected size.
if (packet.position() % (POINTER_DATA_FIELD_COUNT * BYTES_PER_FIELD) != 0) {
throw new AssertionError("Packet position is not on field boundary");
}
// Send the packet to Flutter.
renderer.dispatchPointerDataPacket(packet, packet.position());
return true;
}
/**
* Sends the given generic {@link MotionEvent} data to Flutter in a format that Flutter
* understands.
*
* <p>Generic motion events include joystick movement, mouse hover, track pad touches, scroll
* wheel movements, etc.
*
* @param event The generic motion event being processed.
* @param context For use by ViewConfiguration.get(context) to scale input.
* @return True if the event was handled.
*/
public boolean onGenericMotionEvent(@NonNull MotionEvent event, @NonNull Context context) {
// Method isFromSource is only available in API 18+ (Jelly Bean MR2)
// Mouse hover support is not implemented for API < 18.
boolean isPointerEvent = event.isFromSource(InputDevice.SOURCE_CLASS_POINTER);
boolean isMovementEvent =
(event.getActionMasked() == MotionEvent.ACTION_HOVER_MOVE
|| event.getActionMasked() == MotionEvent.ACTION_SCROLL);
if (isPointerEvent && isMovementEvent) {
// Continue.
} else {
return false;
}
int pointerChange = getPointerChangeForAction(event.getActionMasked());
ByteBuffer packet =
ByteBuffer.allocateDirect(
event.getPointerCount() * POINTER_DATA_FIELD_COUNT * BYTES_PER_FIELD);
packet.order(ByteOrder.LITTLE_ENDIAN);
// ACTION_HOVER_MOVE always applies to a single pointer only.
addPointerForIndex(
event, event.getActionIndex(), pointerChange, 0, IDENTITY_TRANSFORM, packet, context);
if (packet.position() % (POINTER_DATA_FIELD_COUNT * BYTES_PER_FIELD) != 0) {
throw new AssertionError("Packet position is not on field boundary.");
}
renderer.dispatchPointerDataPacket(packet, packet.position());
return true;
}
/// Calls addPointerForIndex with null for context.
///
/// Without context the scroll wheel will not mimick android's scroll speed.
private void addPointerForIndex(
MotionEvent event,
int pointerIndex,
int pointerChange,
int pointerData,
Matrix transformMatrix,
ByteBuffer packet) {
addPointerForIndex(
event, pointerIndex, pointerChange, pointerData, transformMatrix, packet, null);
}
// TODO: consider creating a PointerPacket class instead of using a procedure that
// mutates inputs. https://github.com/flutter/flutter/issues/132853
private void addPointerForIndex(
MotionEvent event,
int pointerIndex,
int pointerChange,
int pointerData,
Matrix transformMatrix,
ByteBuffer packet,
Context context) {
if (pointerChange == -1) {
return;
}
// TODO(dkwingsmt): Use the correct source view ID once Android supports
// multiple views.
// https://github.com/flutter/flutter/issues/134405
final int viewId = IMPLICIT_VIEW_ID;
final int pointerId = event.getPointerId(pointerIndex);
int pointerKind = getPointerDeviceTypeForToolType(event.getToolType(pointerIndex));
// We use this in lieu of using event.getRawX and event.getRawY as we wish to support
// earlier versions than API level 29.
float viewToScreenCoords[] = {event.getX(pointerIndex), event.getY(pointerIndex)};
transformMatrix.mapPoints(viewToScreenCoords);
long buttons;
if (pointerKind == PointerDeviceKind.MOUSE) {
buttons = event.getButtonState() & 0x1F;
if (buttons == 0
&& event.getSource() == InputDevice.SOURCE_MOUSE
&& pointerChange == PointerChange.DOWN) {
// Some implementations translate trackpad scrolling into a mouse down-move-up event
// sequence with buttons: 0, such as ARC on a Chromebook. See #11420, a legacy
// implementation that uses the same condition but converts differently.
ongoingPans.put(pointerId, viewToScreenCoords);
}
} else if (pointerKind == PointerDeviceKind.STYLUS) {
// Returns converted android button state into flutter framework normalized state
// and updates ongoingPans for chromebook trackpad scrolling.
// See
// https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/gestures/events.dart
// for target button constants.
buttons = (event.getButtonState() >> 4) & 0xF;
} else {
buttons = 0;
}
int panZoomType = -1;
boolean isTrackpadPan = ongoingPans.containsKey(pointerId);
if (isTrackpadPan) {
panZoomType = getPointerChangeForPanZoom(pointerChange);
if (panZoomType == -1) {
return;
}
}
long motionEventId = 0;
if (trackMotionEvents) {
MotionEventTracker.MotionEventId trackedEvent = motionEventTracker.track(event);
motionEventId = trackedEvent.getId();
}
int signalKind =
event.getActionMasked() == MotionEvent.ACTION_SCROLL
? PointerSignalKind.SCROLL
: PointerSignalKind.NONE;
long timeStamp = event.getEventTime() * 1000; // Convert from milliseconds to microseconds.
packet.putLong(motionEventId); // motionEventId
packet.putLong(timeStamp); // time_stamp
if (isTrackpadPan) {
packet.putLong(panZoomType); // change
packet.putLong(PointerDeviceKind.TRACKPAD); // kind
} else {
packet.putLong(pointerChange); // change
packet.putLong(pointerKind); // kind
}
packet.putLong(signalKind); // signal_kind
packet.putLong(pointerId); // device
packet.putLong(0); // pointer_identifier, will be generated in pointer_data_packet_converter.cc.
if (isTrackpadPan) {
float[] panStart = ongoingPans.get(pointerId);
packet.putDouble(panStart[0]); // physical_x
packet.putDouble(panStart[1]); // physical_y
} else {
packet.putDouble(viewToScreenCoords[0]); // physical_x
packet.putDouble(viewToScreenCoords[1]); // physical_y
}
packet.putDouble(
0.0); // physical_delta_x, will be generated in pointer_data_packet_converter.cc.
packet.putDouble(
0.0); // physical_delta_y, will be generated in pointer_data_packet_converter.cc.
packet.putLong(buttons); // buttons
packet.putLong(0); // obscured
packet.putLong(0); // synthesized
packet.putDouble(event.getPressure(pointerIndex)); // pressure
double pressureMin = 0.0;
double pressureMax = 1.0;
if (event.getDevice() != null) {
InputDevice.MotionRange pressureRange =
event.getDevice().getMotionRange(MotionEvent.AXIS_PRESSURE);
if (pressureRange != null) {
pressureMin = pressureRange.getMin();
pressureMax = pressureRange.getMax();
}
}
packet.putDouble(pressureMin); // pressure_min
packet.putDouble(pressureMax); // pressure_max
if (pointerKind == PointerDeviceKind.STYLUS) {
packet.putDouble(event.getAxisValue(MotionEvent.AXIS_DISTANCE, pointerIndex)); // distance
packet.putDouble(0.0); // distance_max
} else {
packet.putDouble(0.0); // distance
packet.putDouble(0.0); // distance_max
}
packet.putDouble(event.getSize(pointerIndex)); // size
packet.putDouble(event.getToolMajor(pointerIndex)); // radius_major
packet.putDouble(event.getToolMinor(pointerIndex)); // radius_minor
packet.putDouble(0.0); // radius_min
packet.putDouble(0.0); // radius_max
packet.putDouble(event.getAxisValue(MotionEvent.AXIS_ORIENTATION, pointerIndex)); // orientation
if (pointerKind == PointerDeviceKind.STYLUS) {
packet.putDouble(event.getAxisValue(MotionEvent.AXIS_TILT, pointerIndex)); // tilt
} else {
packet.putDouble(0.0); // tilt
}
packet.putLong(pointerData); // platformData
// See android scrollview for inspiration.
// https://cs.android.com/android/platform/superproject/main/+/main:frameworks/base/core/java/android/widget/ScrollView.java?q=function:onGenericMotionEvent%20filepath:widget%2FScrollView.java&ss=android%2Fplatform%2Fsuperproject%2Fmain
if (signalKind == PointerSignalKind.SCROLL) {
double horizontalScaleFactor = DEFAULT_HORIZONTAL_SCROLL_FACTOR;
double verticalScaleFactor = DEFAULT_VERTICAL_SCROLL_FACTOR;
if (context != null) {
horizontalScaleFactor = getHorizontalScrollFactor(context);
verticalScaleFactor = getVerticalScrollFactor(context);
}
// We flip the sign of the scroll value below because it aligns the pixel value with the
// scroll direction in native android.
final double horizontalScrollPixels =
horizontalScaleFactor * -event.getAxisValue(MotionEvent.AXIS_HSCROLL, pointerIndex);
final double verticalScrollPixels =
verticalScaleFactor * -event.getAxisValue(MotionEvent.AXIS_VSCROLL, pointerIndex);
packet.putDouble(horizontalScrollPixels); // scroll_delta_x
packet.putDouble(verticalScrollPixels); // scroll_delta_y
} else {
packet.putDouble(0.0); // scroll_delta_x
packet.putDouble(0.0); // scroll_delta_y
}
if (isTrackpadPan) {
float[] panStart = ongoingPans.get(pointerId);
packet.putDouble(viewToScreenCoords[0] - panStart[0]);
packet.putDouble(viewToScreenCoords[1] - panStart[1]);
} else {
packet.putDouble(0.0); // pan_x
packet.putDouble(0.0); // pan_y
}
packet.putDouble(0.0); // pan_delta_x
packet.putDouble(0.0); // pan_delta_y
packet.putDouble(1.0); // scale
packet.putDouble(0.0); // rotation
packet.putLong(viewId); // view_id
if (isTrackpadPan && (panZoomType == PointerChange.PAN_ZOOM_END)) {
ongoingPans.remove(pointerId);
}
}
private float getHorizontalScrollFactor(@NonNull Context context) {
if (Build.VERSION.SDK_INT >= API_LEVELS.API_26) {
return ViewConfiguration.get(context).getScaledHorizontalScrollFactor();
} else {
// Vertical scroll factor is not a typo. This is what View.java does in android.
return getVerticalScrollFactorPre26(context);
}
}
private float getVerticalScrollFactor(@NonNull Context context) {
if (Build.VERSION.SDK_INT >= API_LEVELS.API_26) {
return getVerticalScrollFactorAbove26(context);
} else {
return getVerticalScrollFactorPre26(context);
}
}
@TargetApi(API_LEVELS.API_26)
private float getVerticalScrollFactorAbove26(@NonNull Context context) {
return ViewConfiguration.get(context).getScaledVerticalScrollFactor();
}
// See
// https://cs.android.com/android/platform/superproject/main/+/main:frameworks/base/core/java/android/view/View.java?q=function:getVerticalScrollFactor%20filepath:android%2Fview%2FView.java&ss=android%2Fplatform%2Fsuperproject%2Fmain
private int getVerticalScrollFactorPre26(@NonNull Context context) {
if (cachedVerticalScrollFactor == 0) {
TypedValue outValue = new TypedValue();
if (!context
.getTheme()
.resolveAttribute(android.R.attr.listPreferredItemHeight, outValue, true)) {
return DEFAULT_VERTICAL_SCROLL_FACTOR;
}
cachedVerticalScrollFactor =
(int) outValue.getDimension(context.getResources().getDisplayMetrics());
}
return cachedVerticalScrollFactor;
}
@PointerChange
private int getPointerChangeForAction(int maskedAction) {
// Primary pointer:
if (maskedAction == MotionEvent.ACTION_DOWN) {
return PointerChange.DOWN;
}
if (maskedAction == MotionEvent.ACTION_UP) {
return PointerChange.UP;
}
// Secondary pointer:
if (maskedAction == MotionEvent.ACTION_POINTER_DOWN) {
return PointerChange.DOWN;
}
if (maskedAction == MotionEvent.ACTION_POINTER_UP) {
return PointerChange.UP;
}
// All pointers:
if (maskedAction == MotionEvent.ACTION_MOVE) {
return PointerChange.MOVE;
}
if (maskedAction == MotionEvent.ACTION_HOVER_MOVE) {
return PointerChange.HOVER;
}
if (maskedAction == MotionEvent.ACTION_CANCEL) {
return PointerChange.CANCEL;
}
if (maskedAction == MotionEvent.ACTION_SCROLL) {
return PointerChange.HOVER;
}
return -1;
}
@PointerChange
private int getPointerChangeForPanZoom(int pointerChange) {
if (pointerChange == PointerChange.DOWN) {
return PointerChange.PAN_ZOOM_START;
} else if (pointerChange == PointerChange.MOVE) {
return PointerChange.PAN_ZOOM_UPDATE;
} else if (pointerChange == PointerChange.UP || pointerChange == PointerChange.CANCEL) {
return PointerChange.PAN_ZOOM_END;
}
return -1;
}
@PointerDeviceKind
private int getPointerDeviceTypeForToolType(int toolType) {
switch (toolType) {
case MotionEvent.TOOL_TYPE_FINGER:
return PointerDeviceKind.TOUCH;
case MotionEvent.TOOL_TYPE_STYLUS:
return PointerDeviceKind.STYLUS;
case MotionEvent.TOOL_TYPE_MOUSE:
return PointerDeviceKind.MOUSE;
case MotionEvent.TOOL_TYPE_ERASER:
return PointerDeviceKind.INVERTED_STYLUS;
default:
// MotionEvent.TOOL_TYPE_UNKNOWN will reach here.
return PointerDeviceKind.UNKNOWN;
}
}
}
| engine/shell/platform/android/io/flutter/embedding/android/AndroidTouchProcessor.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/embedding/android/AndroidTouchProcessor.java",
"repo_id": "engine",
"token_count": 7280
} | 291 |
// Copyright 2013 The Flutter 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.embedding.android;
import android.view.InputDevice;
import android.view.KeyEvent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.Log;
import io.flutter.embedding.android.KeyboardMap.PressingGoal;
import io.flutter.embedding.android.KeyboardMap.TogglingGoal;
import io.flutter.plugin.common.BinaryMessenger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* A {@link KeyboardManager.Responder} of {@link KeyboardManager} that handles events by sending
* processed information in {@link KeyData}.
*
* <p>This class corresponds to the HardwareKeyboard API in the framework.
*/
public class KeyEmbedderResponder implements KeyboardManager.Responder {
private static final String TAG = "KeyEmbedderResponder";
// Maps KeyEvent's action and repeatCount to a KeyData type.
private static KeyData.Type getEventType(KeyEvent event) {
final boolean isRepeatEvent = event.getRepeatCount() > 0;
switch (event.getAction()) {
case KeyEvent.ACTION_DOWN:
return isRepeatEvent ? KeyData.Type.kRepeat : KeyData.Type.kDown;
case KeyEvent.ACTION_UP:
return KeyData.Type.kUp;
default:
throw new AssertionError("Unexpected event type");
}
}
// The messenger that is used to send Flutter key events to the framework.
//
// On `handleEvent`, Flutter events are marshalled into byte buffers in the format specified by
// `KeyData.toBytes`.
@NonNull private final BinaryMessenger messenger;
// The keys being pressed currently, mapped from physical keys to logical keys.
@NonNull private final HashMap<Long, Long> pressingRecords = new HashMap<>();
// Map from logical key to toggling goals.
//
// Besides immutable configuration, the toggling goals are also used to store the current enabling
// states in their `enabled` field.
@NonNull private final HashMap<Long, TogglingGoal> togglingGoals = new HashMap<>();
@NonNull
private final KeyboardManager.CharacterCombiner characterCombiner =
new KeyboardManager.CharacterCombiner();
public KeyEmbedderResponder(BinaryMessenger messenger) {
this.messenger = messenger;
for (final TogglingGoal goal : KeyboardMap.getTogglingGoals()) {
togglingGoals.put(goal.logicalKey, goal);
}
}
private static long keyOfPlane(long key, long plane) {
// Apply '& kValueMask' in case the key is a negative number before being converted to long.
return plane | (key & KeyboardMap.kValueMask);
}
// Get the physical key for this event.
//
// The returned value is never null.
private Long getPhysicalKey(@NonNull KeyEvent event) {
final long scancode = event.getScanCode();
// Scancode 0 can occur during emulation using `adb shell input keyevent`. Synthesize a physical
// key from the key code so that keys can be told apart.
if (scancode == 0) {
// The key code can't also be 0, since those events have been filtered.
return keyOfPlane(event.getKeyCode(), KeyboardMap.kAndroidPlane);
}
final Long byMapping = KeyboardMap.scanCodeToPhysical.get(scancode);
if (byMapping != null) {
return byMapping;
}
return keyOfPlane(event.getScanCode(), KeyboardMap.kAndroidPlane);
}
// Get the logical key for this event.
//
// The returned value is never null.
private Long getLogicalKey(@NonNull KeyEvent event) {
final Long byMapping = KeyboardMap.keyCodeToLogical.get((long) event.getKeyCode());
if (byMapping != null) {
return byMapping;
}
return keyOfPlane(event.getKeyCode(), KeyboardMap.kAndroidPlane);
}
// Update `pressingRecords`.
//
// If the key indicated by `physicalKey` is currently not pressed, then `logicalKey` must not be
// null and this key will be marked pressed.
//
// If the key indicated by `physicalKey` is currently pressed, then `logicalKey` must be null
// and this key will be marked released.
void updatePressingState(@NonNull Long physicalKey, @Nullable Long logicalKey) {
if (logicalKey != null) {
final Long previousValue = pressingRecords.put(physicalKey, logicalKey);
if (previousValue != null) {
throw new AssertionError("The key was not empty");
}
} else {
final Long previousValue = pressingRecords.remove(physicalKey);
if (previousValue == null) {
throw new AssertionError("The key was empty");
}
}
}
// Synchronize for a pressing modifier (such as Shift or Ctrl).
//
// A pressing modifier is defined by a `PressingGoal`, which consists of a mask to get the true
// state out of `KeyEvent.getMetaState`, and a list of keys. The synchronization process
// dispatches synthesized events so that the state of these keys matches the true state taking
// the current event in consideration.
//
// Events that should be synthesized before the main event are synthesized
// immediately, while events that should be synthesized after the main event are appended to
// `postSynchronize`.
//
// Although Android KeyEvent defined bitmasks for sided modifiers (SHIFT_LEFT_ON and
// SHIFT_RIGHT_ON),
// this function only uses the unsided modifiers (SHIFT_ON), due to the weird behaviors observed
// on ChromeOS, where right modifiers produce events with UNSIDED | LEFT_SIDE meta state bits.
void synchronizePressingKey(
PressingGoal goal,
boolean truePressed,
long eventLogicalKey,
long eventPhysicalKey,
KeyEvent event,
ArrayList<Runnable> postSynchronize) {
// During an incoming event, there might be a synthesized Flutter event for each key of each
// pressing goal, followed by an eventual main Flutter event.
//
// NowState ----------------> PreEventState --------------> -------------->TrueState
// PreSynchronize Event PostSynchronize
//
// The goal of the synchronization algorithm is to derive a pre-event state that can satisfy the
// true state (`truePressed`) after the event, and that requires as few synthesized events based
// on the current state (`nowStates`) as possible.
final boolean[] nowStates = new boolean[goal.keys.length];
final Boolean[] preEventStates = new Boolean[goal.keys.length];
boolean postEventAnyPressed = false;
// 1. Find the current states of all keys.
// 2. Derive the pre-event state of the event key (if applicable.)
for (int keyIdx = 0; keyIdx < goal.keys.length; keyIdx += 1) {
final KeyboardMap.KeyPair key = goal.keys[keyIdx];
nowStates[keyIdx] = pressingRecords.containsKey(key.physicalKey);
if (key.logicalKey == eventLogicalKey) {
switch (getEventType(event)) {
case kDown:
preEventStates[keyIdx] = false;
postEventAnyPressed = true;
if (!truePressed) {
postSynchronize.add(
() ->
synthesizeEvent(
false, key.logicalKey, eventPhysicalKey, event.getEventTime()));
}
break;
case kUp:
// Incoming event is an up. Although the previous state should be pressed, don't
// synthesize a down event even if it's not. The later code will handle such cases by
// skipping abrupt up events. Obviously don't synthesize up events either.
preEventStates[keyIdx] = nowStates[keyIdx];
break;
case kRepeat:
// Incoming event is repeat. The previous state can be either pressed or released. Don't
// synthesize a down event here, or there will be a down event *and* a repeat event,
// both of which have printable characters. Obviously don't synthesize up events either.
if (!truePressed) {
postSynchronize.add(
() ->
synthesizeEvent(
false, key.logicalKey, key.physicalKey, event.getEventTime()));
}
preEventStates[keyIdx] = nowStates[keyIdx];
postEventAnyPressed = true;
break;
}
} else {
postEventAnyPressed = postEventAnyPressed || nowStates[keyIdx];
}
}
// Fill the rest of the pre-event states to match the true state.
if (truePressed) {
// It is required that at least one key is pressed.
for (int keyIdx = 0; keyIdx < goal.keys.length; keyIdx += 1) {
if (preEventStates[keyIdx] != null) {
continue;
}
if (postEventAnyPressed) {
preEventStates[keyIdx] = nowStates[keyIdx];
} else {
preEventStates[keyIdx] = true;
postEventAnyPressed = true;
}
}
if (!postEventAnyPressed) {
preEventStates[0] = true;
}
} else {
for (int keyIdx = 0; keyIdx < goal.keys.length; keyIdx += 1) {
if (preEventStates[keyIdx] != null) {
continue;
}
preEventStates[keyIdx] = false;
}
}
// Dispatch synthesized events for state differences.
for (int keyIdx = 0; keyIdx < goal.keys.length; keyIdx += 1) {
if (nowStates[keyIdx] != preEventStates[keyIdx]) {
final KeyboardMap.KeyPair key = goal.keys[keyIdx];
synthesizeEvent(
preEventStates[keyIdx], key.logicalKey, key.physicalKey, event.getEventTime());
}
}
}
// Synchronize for a toggling modifier (such as CapsLock).
//
// A toggling modifier is defined by a `TogglingGoal`, which consists of a mask to get the true
// state out of `KeyEvent.getMetaState`, and a key. The synchronization process dispatches
// synthesized events so that the state of these keys matches the true state taking the current
// event in consideration.
//
// Although Android KeyEvent defined bitmasks for all "lock" modifiers and define them as the
// "lock" state, weird behaviors are observed on ChromeOS. First, ScrollLock and NumLock presses
// do not set metaState bits. Second, CapsLock key events set the CapsLock bit as if it is a
// pressing modifier (key down having state 1, key up having state 0), while other key events set
// the CapsLock bit correctly (locked having state 1, unlocked having state 0). Therefore this
// function only synchronizes the CapsLock state, and only does so during non-CapsLock key events.
void synchronizeTogglingKey(
TogglingGoal goal, boolean trueEnabled, long eventLogicalKey, KeyEvent event) {
if (goal.logicalKey == eventLogicalKey) {
// Don't synthesize for self events, because the self events have weird metaStates on
// ChromeOS.
return;
}
if (goal.enabled != trueEnabled) {
final boolean firstIsDown = !pressingRecords.containsKey(goal.physicalKey);
if (firstIsDown) {
goal.enabled = !goal.enabled;
}
synthesizeEvent(firstIsDown, goal.logicalKey, goal.physicalKey, event.getEventTime());
if (!firstIsDown) {
goal.enabled = !goal.enabled;
}
synthesizeEvent(!firstIsDown, goal.logicalKey, goal.physicalKey, event.getEventTime());
}
}
// Implements the core algorithm of `handleEvent`.
//
// Returns whether any events are dispatched.
private boolean handleEventImpl(
@NonNull KeyEvent event, @NonNull OnKeyEventHandledCallback onKeyEventHandledCallback) {
// Events with no codes at all can not be recognized.
if (event.getScanCode() == 0 && event.getKeyCode() == 0) {
return false;
}
final Long physicalKey = getPhysicalKey(event);
final Long logicalKey = getLogicalKey(event);
final ArrayList<Runnable> postSynchronizeEvents = new ArrayList<>();
for (final PressingGoal goal : KeyboardMap.pressingGoals) {
synchronizePressingKey(
goal,
(event.getMetaState() & goal.mask) != 0,
logicalKey,
physicalKey,
event,
postSynchronizeEvents);
}
for (final TogglingGoal goal : togglingGoals.values()) {
synchronizeTogglingKey(goal, (event.getMetaState() & goal.mask) != 0, logicalKey, event);
}
boolean isDownEvent;
switch (event.getAction()) {
case KeyEvent.ACTION_DOWN:
isDownEvent = true;
break;
case KeyEvent.ACTION_UP:
isDownEvent = false;
break;
default:
return false;
}
KeyData.Type type;
String character = null;
final Long lastLogicalRecord = pressingRecords.get(physicalKey);
if (isDownEvent) {
if (lastLogicalRecord == null) {
type = KeyData.Type.kDown;
} else {
// A key has been pressed that has the exact physical key as a currently
// pressed one.
if (event.getRepeatCount() > 0) {
type = KeyData.Type.kRepeat;
} else {
synthesizeEvent(false, lastLogicalRecord, physicalKey, event.getEventTime());
type = KeyData.Type.kDown;
}
}
final char complexChar =
characterCombiner.applyCombiningCharacterToBaseCharacter(event.getUnicodeChar());
if (complexChar != 0) {
character = "" + complexChar;
}
} else { // isDownEvent is false
if (lastLogicalRecord == null) {
// Ignore abrupt up events.
return false;
} else {
type = KeyData.Type.kUp;
}
}
if (type != KeyData.Type.kRepeat) {
updatePressingState(physicalKey, isDownEvent ? logicalKey : null);
}
if (type == KeyData.Type.kDown) {
final TogglingGoal maybeTogglingGoal = togglingGoals.get(logicalKey);
if (maybeTogglingGoal != null) {
maybeTogglingGoal.enabled = !maybeTogglingGoal.enabled;
}
}
final KeyData output = new KeyData();
switch (event.getSource()) {
default:
case InputDevice.SOURCE_KEYBOARD:
output.deviceType = KeyData.DeviceType.kKeyboard;
break;
case InputDevice.SOURCE_DPAD:
output.deviceType = KeyData.DeviceType.kDirectionalPad;
break;
case InputDevice.SOURCE_GAMEPAD:
output.deviceType = KeyData.DeviceType.kGamepad;
break;
case InputDevice.SOURCE_JOYSTICK:
output.deviceType = KeyData.DeviceType.kJoystick;
break;
case InputDevice.SOURCE_HDMI:
output.deviceType = KeyData.DeviceType.kHdmi;
break;
}
output.timestamp = event.getEventTime();
output.type = type;
output.logicalKey = logicalKey;
output.physicalKey = physicalKey;
output.character = character;
output.synthesized = false;
output.deviceType = KeyData.DeviceType.kKeyboard;
sendKeyEvent(output, onKeyEventHandledCallback);
for (final Runnable postSyncEvent : postSynchronizeEvents) {
postSyncEvent.run();
}
return true;
}
private void synthesizeEvent(boolean isDown, Long logicalKey, Long physicalKey, long timestamp) {
final KeyData output = new KeyData();
output.timestamp = timestamp;
output.type = isDown ? KeyData.Type.kDown : KeyData.Type.kUp;
output.logicalKey = logicalKey;
output.physicalKey = physicalKey;
output.character = null;
output.synthesized = true;
output.deviceType = KeyData.DeviceType.kKeyboard;
if (physicalKey != 0 && logicalKey != 0) {
updatePressingState(physicalKey, isDown ? logicalKey : null);
}
sendKeyEvent(output, null);
}
private void sendKeyEvent(KeyData data, OnKeyEventHandledCallback onKeyEventHandledCallback) {
final BinaryMessenger.BinaryReply handleMessageReply =
onKeyEventHandledCallback == null
? null
: message -> {
Boolean handled = false;
if (message != null) {
message.rewind();
if (message.capacity() != 0) {
handled = message.get() != 0;
}
} else {
Log.w(TAG, "A null reply was received when sending a key event to the framework.");
}
onKeyEventHandledCallback.onKeyEventHandled(handled);
};
messenger.send(KeyData.CHANNEL, data.toBytes(), handleMessageReply);
}
/**
* Parses an Android key event, performs synchronization, and dispatches Flutter events through
* the messenger to the framework with the given callback.
*
* <p>At least one event will be dispatched. If there are no others, an empty event with 0
* physical key and 0 logical key will be synthesized.
*
* @param event The Android key event to be handled.
* @param onKeyEventHandledCallback the method to call when the framework has decided whether to
* handle this event. This callback will always be called once and only once. If there are no
* non-synthesized out of this event, this callback will be called during this method with
* true.
*/
@Override
public void handleEvent(
@NonNull KeyEvent event, @NonNull OnKeyEventHandledCallback onKeyEventHandledCallback) {
final boolean sentAny = handleEventImpl(event, onKeyEventHandledCallback);
if (!sentAny) {
synthesizeEvent(true, 0L, 0L, 0L);
onKeyEventHandledCallback.onKeyEventHandled(true);
}
}
/**
* Returns an unmodifiable view of the pressed state.
*
* @return A map whose keys are physical keyboard key IDs and values are the corresponding logical
* keyboard key IDs.
*/
public Map<Long, Long> getPressedState() {
return Collections.unmodifiableMap(pressingRecords);
}
}
| engine/shell/platform/android/io/flutter/embedding/android/KeyEmbedderResponder.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/embedding/android/KeyEmbedderResponder.java",
"repo_id": "engine",
"token_count": 6451
} | 292 |
// Copyright 2013 The Flutter 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.embedding.engine.dart;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import io.flutter.FlutterInjector;
import io.flutter.Log;
import io.flutter.embedding.engine.FlutterJNI;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.util.TraceSection;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Message conduit for 2-way communication between Android and Dart.
*
* <p>See {@link BinaryMessenger}, which sends messages from Android to Dart
*
* <p>See {@link PlatformMessageHandler}, which handles messages to Android from Dart
*/
class DartMessenger implements BinaryMessenger, PlatformMessageHandler {
private static final String TAG = "DartMessenger";
@NonNull private final FlutterJNI flutterJNI;
/**
* Maps a channel name to an object that contains the task queue and the handler associated with
* the channel.
*
* <p>Reads and writes to this map must lock {@code handlersLock}.
*/
@NonNull private final Map<String, HandlerInfo> messageHandlers = new HashMap<>();
/**
* Maps a channel name to an object that holds information about the incoming Dart message.
*
* <p>Reads and writes to this map must lock {@code handlersLock}.
*/
@NonNull private Map<String, List<BufferedMessageInfo>> bufferedMessages = new HashMap<>();
@NonNull private final Object handlersLock = new Object();
@NonNull private final AtomicBoolean enableBufferingIncomingMessages = new AtomicBoolean(false);
@NonNull private final Map<Integer, BinaryMessenger.BinaryReply> pendingReplies = new HashMap<>();
private int nextReplyId = 1;
@NonNull private final DartMessengerTaskQueue platformTaskQueue = new PlatformTaskQueue();
@NonNull
private WeakHashMap<TaskQueue, DartMessengerTaskQueue> createdTaskQueues =
new WeakHashMap<TaskQueue, DartMessengerTaskQueue>();
@NonNull private TaskQueueFactory taskQueueFactory;
DartMessenger(@NonNull FlutterJNI flutterJNI, @NonNull TaskQueueFactory taskQueueFactory) {
this.flutterJNI = flutterJNI;
this.taskQueueFactory = taskQueueFactory;
}
DartMessenger(@NonNull FlutterJNI flutterJNI) {
this(flutterJNI, new DefaultTaskQueueFactory());
}
private static class TaskQueueToken implements TaskQueue {}
interface DartMessengerTaskQueue {
void dispatch(@NonNull Runnable runnable);
}
interface TaskQueueFactory {
DartMessengerTaskQueue makeBackgroundTaskQueue(TaskQueueOptions options);
}
private static class DefaultTaskQueueFactory implements TaskQueueFactory {
ExecutorService executorService;
DefaultTaskQueueFactory() {
executorService = FlutterInjector.instance().executorService();
}
public DartMessengerTaskQueue makeBackgroundTaskQueue(TaskQueueOptions options) {
if (options.getIsSerial()) {
return new SerialTaskQueue(executorService);
} else {
return new ConcurrentTaskQueue(executorService);
}
}
}
/**
* Holds information about a platform handler, such as the task queue that processes messages from
* Dart.
*/
private static class HandlerInfo {
@NonNull public final BinaryMessenger.BinaryMessageHandler handler;
@Nullable public final DartMessengerTaskQueue taskQueue;
HandlerInfo(
@NonNull BinaryMessenger.BinaryMessageHandler handler,
@Nullable DartMessengerTaskQueue taskQueue) {
this.handler = handler;
this.taskQueue = taskQueue;
}
}
/**
* Holds information that allows to dispatch a Dart message to a platform handler when it becomes
* available.
*/
private static class BufferedMessageInfo {
@NonNull public final ByteBuffer message;
int replyId;
long messageData;
BufferedMessageInfo(@NonNull ByteBuffer message, int replyId, long messageData) {
this.message = message;
this.replyId = replyId;
this.messageData = messageData;
}
}
static class ConcurrentTaskQueue implements DartMessengerTaskQueue {
@NonNull private final ExecutorService executor;
ConcurrentTaskQueue(ExecutorService executor) {
this.executor = executor;
}
@Override
public void dispatch(@NonNull Runnable runnable) {
executor.execute(runnable);
}
}
/** A serial task queue that can run on a concurrent ExecutorService. */
static class SerialTaskQueue implements DartMessengerTaskQueue {
@NonNull private final ExecutorService executor;
@NonNull private final ConcurrentLinkedQueue<Runnable> queue;
@NonNull private final AtomicBoolean isRunning;
SerialTaskQueue(ExecutorService executor) {
this.executor = executor;
queue = new ConcurrentLinkedQueue<>();
isRunning = new AtomicBoolean(false);
}
@Override
public void dispatch(@NonNull Runnable runnable) {
queue.add(runnable);
executor.execute(
() -> {
flush();
});
}
private void flush() {
// Don't execute if we are already executing (enforce serial execution).
if (isRunning.compareAndSet(false, true)) {
try {
@Nullable Runnable runnable = queue.poll();
if (runnable != null) {
runnable.run();
}
} finally {
isRunning.set(false);
if (!queue.isEmpty()) {
// Schedule the next event.
executor.execute(
() -> {
flush();
});
}
}
}
}
}
@Override
public TaskQueue makeBackgroundTaskQueue(TaskQueueOptions options) {
DartMessengerTaskQueue taskQueue = taskQueueFactory.makeBackgroundTaskQueue(options);
TaskQueueToken token = new TaskQueueToken();
createdTaskQueues.put(token, taskQueue);
return token;
}
@Override
public void setMessageHandler(
@NonNull String channel, @Nullable BinaryMessenger.BinaryMessageHandler handler) {
setMessageHandler(channel, handler, null);
}
@Override
public void setMessageHandler(
@NonNull String channel,
@Nullable BinaryMessenger.BinaryMessageHandler handler,
@Nullable TaskQueue taskQueue) {
if (handler == null) {
Log.v(TAG, "Removing handler for channel '" + channel + "'");
synchronized (handlersLock) {
messageHandlers.remove(channel);
}
return;
}
DartMessengerTaskQueue dartMessengerTaskQueue = null;
if (taskQueue != null) {
dartMessengerTaskQueue = createdTaskQueues.get(taskQueue);
if (dartMessengerTaskQueue == null) {
throw new IllegalArgumentException(
"Unrecognized TaskQueue, use BinaryMessenger to create your TaskQueue (ex makeBackgroundTaskQueue).");
}
}
Log.v(TAG, "Setting handler for channel '" + channel + "'");
List<BufferedMessageInfo> list;
synchronized (handlersLock) {
messageHandlers.put(channel, new HandlerInfo(handler, dartMessengerTaskQueue));
list = bufferedMessages.remove(channel);
if (list == null) {
return;
}
}
for (BufferedMessageInfo info : list) {
dispatchMessageToQueue(
channel, messageHandlers.get(channel), info.message, info.replyId, info.messageData);
}
}
@Override
public void enableBufferingIncomingMessages() {
enableBufferingIncomingMessages.set(true);
}
@Override
public void disableBufferingIncomingMessages() {
Map<String, List<BufferedMessageInfo>> pendingMessages;
synchronized (handlersLock) {
enableBufferingIncomingMessages.set(false);
pendingMessages = bufferedMessages;
bufferedMessages = new HashMap<>();
}
for (Map.Entry<String, List<BufferedMessageInfo>> channel : pendingMessages.entrySet()) {
for (BufferedMessageInfo info : channel.getValue()) {
dispatchMessageToQueue(
channel.getKey(), null, info.message, info.replyId, info.messageData);
}
}
}
@Override
@UiThread
public void send(@NonNull String channel, @NonNull ByteBuffer message) {
Log.v(TAG, "Sending message over channel '" + channel + "'");
send(channel, message, null);
}
@Override
public void send(
@NonNull String channel,
@Nullable ByteBuffer message,
@Nullable BinaryMessenger.BinaryReply callback) {
try (TraceSection e = TraceSection.scoped("DartMessenger#send on " + channel)) {
Log.v(TAG, "Sending message with callback over channel '" + channel + "'");
int replyId = nextReplyId++;
if (callback != null) {
pendingReplies.put(replyId, callback);
}
if (message == null) {
flutterJNI.dispatchEmptyPlatformMessage(channel, replyId);
} else {
flutterJNI.dispatchPlatformMessage(channel, message, message.position(), replyId);
}
}
}
private void invokeHandler(
@Nullable HandlerInfo handlerInfo, @Nullable ByteBuffer message, final int replyId) {
// Called from any thread.
if (handlerInfo != null) {
try {
Log.v(TAG, "Deferring to registered handler to process message.");
handlerInfo.handler.onMessage(message, new Reply(flutterJNI, replyId));
} catch (Exception ex) {
Log.e(TAG, "Uncaught exception in binary message listener", ex);
flutterJNI.invokePlatformMessageEmptyResponseCallback(replyId);
} catch (Error err) {
handleError(err);
}
} else {
Log.v(TAG, "No registered handler for message. Responding to Dart with empty reply message.");
flutterJNI.invokePlatformMessageEmptyResponseCallback(replyId);
}
}
private void dispatchMessageToQueue(
@NonNull String channel,
@Nullable HandlerInfo handlerInfo,
@Nullable ByteBuffer message,
int replyId,
long messageData) {
// Called from any thread.
final DartMessengerTaskQueue taskQueue = (handlerInfo != null) ? handlerInfo.taskQueue : null;
TraceSection.beginAsyncSection("PlatformChannel ScheduleHandler on " + channel, replyId);
Runnable myRunnable =
() -> {
TraceSection.endAsyncSection("PlatformChannel ScheduleHandler on " + channel, replyId);
try (TraceSection e =
TraceSection.scoped("DartMessenger#handleMessageFromDart on " + channel)) {
invokeHandler(handlerInfo, message, replyId);
if (message != null && message.isDirect()) {
// This ensures that if a user retains an instance to the ByteBuffer and it
// happens to be direct they will get a deterministic error.
message.limit(0);
}
} finally {
// This is deleting the data underneath the message object.
flutterJNI.cleanupMessageData(messageData);
}
};
final DartMessengerTaskQueue nonnullTaskQueue =
taskQueue == null ? platformTaskQueue : taskQueue;
nonnullTaskQueue.dispatch(myRunnable);
}
@Override
public void handleMessageFromDart(
@NonNull String channel, @Nullable ByteBuffer message, int replyId, long messageData) {
// Called from any thread.
Log.v(TAG, "Received message from Dart over channel '" + channel + "'");
HandlerInfo handlerInfo;
boolean messageDeferred;
// This lock can potentially be a bottleneck and could replaced with a
// read/write lock.
synchronized (handlersLock) {
handlerInfo = messageHandlers.get(channel);
messageDeferred = (enableBufferingIncomingMessages.get() && handlerInfo == null);
if (messageDeferred) {
// The channel is not defined when the Dart VM sends a message before the channels are
// registered.
//
// This is possible if the Dart VM starts before channel registration, and if the thread
// that registers the channels is busy or slow at registering the channel handlers.
//
// In such cases, the task dispatchers are queued, and processed when the channel is
// defined.
if (!bufferedMessages.containsKey(channel)) {
bufferedMessages.put(channel, new LinkedList<>());
}
List<BufferedMessageInfo> buffer = bufferedMessages.get(channel);
buffer.add(new BufferedMessageInfo(message, replyId, messageData));
}
}
if (!messageDeferred) {
dispatchMessageToQueue(channel, handlerInfo, message, replyId, messageData);
}
}
@Override
public void handlePlatformMessageResponse(int replyId, @Nullable ByteBuffer reply) {
Log.v(TAG, "Received message reply from Dart.");
BinaryMessenger.BinaryReply callback = pendingReplies.remove(replyId);
if (callback != null) {
try {
Log.v(TAG, "Invoking registered callback for reply from Dart.");
callback.reply(reply);
if (reply != null && reply.isDirect()) {
// This ensures that if a user retains an instance to the ByteBuffer and it happens to
// be direct they will get a deterministic error.
reply.limit(0);
}
} catch (Exception ex) {
Log.e(TAG, "Uncaught exception in binary message reply handler", ex);
} catch (Error err) {
handleError(err);
}
}
}
/**
* Returns the number of pending channel callback replies.
*
* <p>When sending messages to the Flutter application using {@link BinaryMessenger#send(String,
* ByteBuffer, io.flutter.plugin.common.BinaryMessenger.BinaryReply)}, developers can optionally
* specify a reply callback if they expect a reply from the Flutter application.
*
* <p>This method tracks all the pending callbacks that are waiting for response, and is supposed
* to be called from the main thread (as other methods). Calling from a different thread could
* possibly capture an indeterministic internal state, so don't do it.
*/
@UiThread
public int getPendingChannelResponseCount() {
return pendingReplies.size();
}
// Handles `Error` objects which are not supposed to be caught.
//
// We forward them to the thread's uncaught exception handler if there is one. If not, they
// are rethrown.
private static void handleError(Error err) {
Thread currentThread = Thread.currentThread();
if (currentThread.getUncaughtExceptionHandler() == null) {
throw err;
}
currentThread.getUncaughtExceptionHandler().uncaughtException(currentThread, err);
}
static class Reply implements BinaryMessenger.BinaryReply {
@NonNull private final FlutterJNI flutterJNI;
private final int replyId;
private final AtomicBoolean done = new AtomicBoolean(false);
Reply(@NonNull FlutterJNI flutterJNI, int replyId) {
this.flutterJNI = flutterJNI;
this.replyId = replyId;
}
@Override
public void reply(@Nullable ByteBuffer reply) {
if (done.getAndSet(true)) {
throw new IllegalStateException("Reply already submitted");
}
if (reply == null) {
flutterJNI.invokePlatformMessageEmptyResponseCallback(replyId);
} else {
flutterJNI.invokePlatformMessageResponseCallback(replyId, reply, reply.position());
}
}
}
}
| engine/shell/platform/android/io/flutter/embedding/engine/dart/DartMessenger.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/embedding/engine/dart/DartMessenger.java",
"repo_id": "engine",
"token_count": 5353
} | 293 |
// Copyright 2013 The Flutter 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.embedding.engine.plugins.broadcastreceiver;
import androidx.annotation.NonNull;
/**
* A {@link io.flutter.embedding.engine.plugins.FlutterPlugin} that wants to know when it is running
* within a {@link android.content.BroadcastReceiver}.
*/
public interface BroadcastReceiverAware {
/**
* Callback triggered when a {@code BroadcastReceiverAware} {@link
* io.flutter.embedding.engine.plugins.FlutterPlugin} is associated with a {@link
* android.content.BroadcastReceiver}.
*/
void onAttachedToBroadcastReceiver(@NonNull BroadcastReceiverPluginBinding binding);
/**
* Callback triggered when a {@code BroadcastReceiverAware} {@link
* io.flutter.embedding.engine.plugins.FlutterPlugin} is detached from a {@link
* android.content.BroadcastReceiver}.
*/
void onDetachedFromBroadcastReceiver();
}
| engine/shell/platform/android/io/flutter/embedding/engine/plugins/broadcastreceiver/BroadcastReceiverAware.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/embedding/engine/plugins/broadcastreceiver/BroadcastReceiverAware.java",
"repo_id": "engine",
"token_count": 306
} | 294 |
package io.flutter.embedding.engine.renderer;
import android.graphics.SurfaceTexture;
import android.os.Handler;
import android.view.Surface;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.embedding.engine.FlutterJNI;
import io.flutter.view.TextureRegistry;
/** Uses a {@link android.graphics.SurfaceTexture} to populate the texture registry. */
final class SurfaceTextureSurfaceProducer
implements TextureRegistry.SurfaceProducer, TextureRegistry.GLTextureConsumer {
private final long id;
private int requestBufferWidth;
private int requestedBufferHeight;
private boolean released;
@Nullable private Surface surface;
@NonNull private final TextureRegistry.SurfaceTextureEntry texture;
@NonNull private final Handler handler;
@NonNull private final FlutterJNI flutterJNI;
SurfaceTextureSurfaceProducer(
long id,
@NonNull Handler handler,
@NonNull FlutterJNI flutterJNI,
@NonNull TextureRegistry.SurfaceTextureEntry texture) {
this.id = id;
this.handler = handler;
this.flutterJNI = flutterJNI;
this.texture = texture;
}
@Override
protected void finalize() throws Throwable {
try {
if (released) {
return;
}
release();
handler.post(new FlutterRenderer.TextureFinalizerRunnable(id, flutterJNI));
} finally {
super.finalize();
}
}
@Override
public long id() {
return id;
}
@Override
public void release() {
texture.release();
released = true;
}
@Override
@NonNull
public SurfaceTexture getSurfaceTexture() {
return texture.surfaceTexture();
}
@Override
public void setSize(int width, int height) {
requestBufferWidth = width;
requestedBufferHeight = height;
getSurfaceTexture().setDefaultBufferSize(width, height);
}
@Override
public int getWidth() {
return requestBufferWidth;
}
@Override
public int getHeight() {
return requestedBufferHeight;
}
@Override
public Surface getSurface() {
if (surface == null) {
surface = new Surface(texture.surfaceTexture());
}
return surface;
}
@Override
public void scheduleFrame() {
flutterJNI.markTextureFrameAvailable(id);
}
}
| engine/shell/platform/android/io/flutter/embedding/engine/renderer/SurfaceTextureSurfaceProducer.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/embedding/engine/renderer/SurfaceTextureSurfaceProducer.java",
"repo_id": "engine",
"token_count": 742
} | 295 |
// Copyright 2013 The Flutter 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.embedding.engine.systemchannels;
import androidx.annotation.NonNull;
import io.flutter.Log;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.plugin.common.BasicMessageChannel;
import io.flutter.plugin.common.JSONMessageCodec;
import java.util.HashMap;
import java.util.Map;
/** TODO(mattcarroll): fill in javadoc for SystemChannel. */
public class SystemChannel {
private static final String TAG = "SystemChannel";
@NonNull public final BasicMessageChannel<Object> channel;
public SystemChannel(@NonNull DartExecutor dartExecutor) {
this.channel =
new BasicMessageChannel<>(dartExecutor, "flutter/system", JSONMessageCodec.INSTANCE);
}
public void sendMemoryPressureWarning() {
Log.v(TAG, "Sending memory pressure warning to Flutter.");
Map<String, Object> message = new HashMap<>(1);
message.put("type", "memoryPressure");
channel.send(message);
}
}
| engine/shell/platform/android/io/flutter/embedding/engine/systemchannels/SystemChannel.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/embedding/engine/systemchannels/SystemChannel.java",
"repo_id": "engine",
"token_count": 344
} | 296 |
// Copyright 2013 The Flutter 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.plugin.common;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.platform.PlatformViewRegistry;
import io.flutter.view.FlutterNativeView;
import io.flutter.view.FlutterView;
import io.flutter.view.TextureRegistry;
/**
* Container class for Android API listeners used by {@link ActivityPluginBinding}.
*
* <p>This class also contains deprecated v1 embedding APIs used for plugin registration.
*
* <p>In v1 Android applications, an auto-generated and auto-updated plugin registrant class
* (GeneratedPluginRegistrant) makes use of a {@link PluginRegistry} to register contributions from
* each plugin mentioned in the application's pubspec file. The generated registrant class is, again
* by default, called from the application's main {@link android.app.Activity}, which defaults to an
* instance of {@link io.flutter.app.FlutterActivity}, itself a {@link PluginRegistry}.
*/
public interface PluginRegistry {
/**
* Returns a {@link Registrar} for receiving the registrations pertaining to the specified plugin.
*
* @param pluginKey a unique String identifying the plugin; typically the fully qualified name of
* the plugin's main class.
* @return A {@link Registrar} for receiving the registrations pertianing to the specified plugin.
* @deprecated See https://flutter.dev/go/android-project-migration for migration details.
*/
@Deprecated
@NonNull
Registrar registrarFor(@NonNull String pluginKey);
/**
* Returns whether the specified plugin is known to this registry.
*
* @param pluginKey a unique String identifying the plugin; typically the fully qualified name of
* the plugin's main class.
* @return true if this registry has handed out a registrar for the specified plugin.
* @deprecated See https://flutter.dev/go/android-project-migration for migration details.
*/
@Deprecated
boolean hasPlugin(@NonNull String pluginKey);
/**
* Returns the value published by the specified plugin, if any.
*
* <p>Plugins may publish a single value, such as an instance of the plugin's main class, for
* situations where external control or interaction is needed. Clients are expected to know the
* value's type.
*
* @param <T> The type of the value.
* @param pluginKey a unique String identifying the plugin; typically the fully qualified name of
* the plugin's main class.
* @return the published value, possibly null.
* @deprecated See https://flutter.dev/go/android-project-migration for migration details.
*/
@Deprecated
@Nullable
<T> T valuePublishedByPlugin(@NonNull String pluginKey);
/**
* Receiver of registrations from a single plugin.
*
* @deprecated This registrar is for Flutter's v1 embedding. For instructions on migrating a
* plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*/
@Deprecated
interface Registrar {
/**
* Returns the {@link android.app.Activity} that forms the plugin's operating context.
*
* <p>Plugin authors should not assume the type returned by this method is any specific subclass
* of {@code Activity} (such as {@link io.flutter.app.FlutterActivity} or {@link
* io.flutter.app.FlutterFragmentActivity}), as applications are free to use any activity
* subclass.
*
* <p>When there is no foreground activity in the application, this will return null. If a
* {@link Context} is needed, use context() to get the application's context.
*
* <p>This registrar is for Flutter's v1 embedding. To access an {@code Activity} from a plugin
* using the v2 embedding, see {@link ActivityPluginBinding#getActivity()}. To obtain an
* instance of an {@link ActivityPluginBinding} in a Flutter plugin, implement the {@link
* ActivityAware} interface. A binding is provided in {@link
* ActivityAware#onAttachedToActivity(ActivityPluginBinding)} and {@link
* ActivityAware#onReattachedToActivityForConfigChanges(ActivityPluginBinding)}.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*/
@Nullable
Activity activity();
/**
* Returns the {@link android.app.Application}'s {@link Context}.
*
* <p>This registrar is for Flutter's v1 embedding. To access a {@code Context} from a plugin
* using the v2 embedding, see {@link
* FlutterPlugin.FlutterPluginBinding#getApplicationContext()}
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*/
@NonNull
Context context();
/**
* Returns the active {@link Context}.
*
* <p>This registrar is for Flutter's v1 embedding. In the v2 embedding, there is no concept of
* an "active context". Either use the application {@code Context} or an attached {@code
* Activity}. See {@link #context()} and {@link #activity()} for more details.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*
* @return the current {@link #activity() Activity}, if not null, otherwise the {@link
* #context() Application}.
*/
@NonNull
Context activeContext();
/**
* Returns a {@link BinaryMessenger} which the plugin can use for creating channels for
* communicating with the Dart side.
*
* <p>This registrar is for Flutter's v1 embedding. To access a {@code BinaryMessenger} from a
* plugin using the v2 embedding, see {@link
* FlutterPlugin.FlutterPluginBinding#getBinaryMessenger()}
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*/
@NonNull
BinaryMessenger messenger();
/**
* Returns a {@link TextureRegistry} which the plugin can use for managing backend textures.
*
* <p>This registrar is for Flutter's v1 embedding. To access a {@code TextureRegistry} from a
* plugin using the v2 embedding, see {@link
* FlutterPlugin.FlutterPluginBinding#getTextureRegistry()}
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*/
@NonNull
TextureRegistry textures();
/**
* Returns the application's {@link PlatformViewRegistry}.
*
* <p>Plugins can use the platform registry to register their view factories.
*
* <p>This registrar is for Flutter's v1 embedding. To access a {@code PlatformViewRegistry}
* from a plugin using the v2 embedding, see {@link
* FlutterPlugin.FlutterPluginBinding#getPlatformViewRegistry()}
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*/
@NonNull
PlatformViewRegistry platformViewRegistry();
/**
* Returns the {@link FlutterView} that's instantiated by this plugin's {@link #activity()
* activity}.
*
* <p>This registrar is for Flutter's v1 embedding. The {@link FlutterView} referenced by this
* method does not exist in the v2 embedding. Additionally, no {@code View} is exposed to any
* plugins in the v2 embedding. Platform views can access their containing {@code View} using
* the platform views APIs. If you have a use-case that absolutely requires a plugin to access
* an Android {@code View}, please file a ticket on GitHub.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*/
@NonNull
FlutterView view();
/**
* Returns the file name for the given asset. The returned file name can be used to access the
* asset in the APK through the {@link android.content.res.AssetManager} API.
*
* <p>TODO(mattcarroll): point this method towards new lookup method.
*
* @param asset the name of the asset. The name can be hierarchical
* @return the filename to be used with {@link android.content.res.AssetManager}
*/
@NonNull
String lookupKeyForAsset(@NonNull String asset);
/**
* Returns the file name for the given asset which originates from the specified packageName.
* The returned file name can be used to access the asset in the APK through the {@link
* android.content.res.AssetManager} API.
*
* <p>TODO(mattcarroll): point this method towards new lookup method.
*
* @param asset the name of the asset. The name can be hierarchical
* @param packageName the name of the package from which the asset originates
* @return the file name to be used with {@link android.content.res.AssetManager}
*/
@NonNull
String lookupKeyForAsset(@NonNull String asset, @NonNull String packageName);
/**
* Publishes a value associated with the plugin being registered.
*
* <p>The published value is available to interested clients via {@link
* PluginRegistry#valuePublishedByPlugin(String)}.
*
* <p>Publication should be done only when client code needs to interact with the plugin in a
* way that cannot be accomplished by the plugin registering callbacks with client APIs.
*
* <p>Overwrites any previously published value.
*
* <p>This registrar is for Flutter's v1 embedding. The concept of publishing values from
* plugins is not supported in the v2 embedding.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*
* @param value the value, possibly null.
* @return this {@link Registrar}.
*/
@NonNull
Registrar publish(@Nullable Object value);
/**
* Adds a callback allowing the plugin to take part in handling incoming calls to {@code
* Activity#onRequestPermissionsResult(int, String[], int[])} or {@code
* androidx.core.app.ActivityCompat.OnRequestPermissionsResultCallback#onRequestPermissionsResult(int,
* String[], int[])}.
*
* <p>This registrar is for Flutter's v1 embedding. To listen for permission results in the v2
* embedding, use {@link
* ActivityPluginBinding#addRequestPermissionsResultListener(PluginRegistry.RequestPermissionsResultListener)}.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*
* @param listener a {@link RequestPermissionsResultListener} callback.
* @return this {@link Registrar}.
*/
@NonNull
Registrar addRequestPermissionsResultListener(
@NonNull RequestPermissionsResultListener listener);
/**
* Adds a callback allowing the plugin to take part in handling incoming calls to {@link
* Activity#onActivityResult(int, int, Intent)}.
*
* <p>This registrar is for Flutter's v1 embedding. To listen for {@code Activity} results in
* the v2 embedding, use {@link
* ActivityPluginBinding#addActivityResultListener(PluginRegistry.ActivityResultListener)}.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*
* @param listener an {@link ActivityResultListener} callback.
* @return this {@link Registrar}.
*/
@NonNull
Registrar addActivityResultListener(@NonNull ActivityResultListener listener);
/**
* Adds a callback allowing the plugin to take part in handling incoming calls to {@link
* Activity#onNewIntent(Intent)}.
*
* <p>This registrar is for Flutter's v1 embedding. To listen for new {@code Intent}s in the v2
* embedding, use {@link
* ActivityPluginBinding#addOnNewIntentListener(PluginRegistry.NewIntentListener)}.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*
* @param listener a {@link NewIntentListener} callback.
* @return this {@link Registrar}.
*/
@NonNull
Registrar addNewIntentListener(@NonNull NewIntentListener listener);
/**
* Adds a callback allowing the plugin to take part in handling incoming calls to {@link
* Activity#onUserLeaveHint()}.
*
* <p>This registrar is for Flutter's v1 embedding. To listen for leave hints in the v2
* embedding, use {@link
* ActivityPluginBinding#addOnUserLeaveHintListener(PluginRegistry.UserLeaveHintListener)}.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*
* @param listener a {@link UserLeaveHintListener} callback.
* @return this {@link Registrar}.
*/
@NonNull
Registrar addUserLeaveHintListener(@NonNull UserLeaveHintListener listener);
/**
* Adds a callback allowing the plugin to take part in handling incoming calls to {@link
* Activity#onWindowFocusChanged(boolean)}.
*
* <p>This registrar is for Flutter's v1 embedding. To listen for leave hints in the v2
* embedding, use {@link
* ActivityPluginBinding#addOnWindowFocusChangedListener(PluginRegistry.WindowFocusChangedListener)}.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*
* @param listener a {@link WindowFocusChangedListener} callback.
* @return this {@link Registrar}.
*/
@NonNull
Registrar addWindowFocusChangedListener(@NonNull WindowFocusChangedListener listener);
/**
* Adds a callback allowing the plugin to take part in handling incoming calls to {@link
* Activity#onDestroy()}.
*
* <p>This registrar is for Flutter's v1 embedding. The concept of {@code View} destruction does
* not exist in the v2 embedding. However, plugins in the v2 embedding can respond to {@link
* ActivityAware#onDetachedFromActivityForConfigChanges()} and {@link
* ActivityAware#onDetachedFromActivity()}, which indicate the loss of a visual context for the
* running Flutter experience. Developers should implement {@link ActivityAware} for their
* {@link FlutterPlugin} if such callbacks are needed. Also, plugins can respond to {@link
* FlutterPlugin#onDetachedFromEngine(FlutterPlugin.FlutterPluginBinding)}, which indicates that
* the given plugin has been completely disconnected from the associated Flutter experience and
* should clean up any resources.
*
* <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit
* http://flutter.dev/go/android-plugin-migration
*
* @param listener a {@link ViewDestroyListener} callback.
* @return this {@link Registrar}.
*/
// TODO(amirh): Add a line in the javadoc above that points to a Platform Views website guide
// when one is available (but not a website API doc)
@NonNull
Registrar addViewDestroyListener(@NonNull ViewDestroyListener listener);
}
/**
* Delegate interface for handling result of permissions requests on behalf of the main {@link
* Activity}.
*/
interface RequestPermissionsResultListener {
/**
* @param requestCode The request code passed in {@code
* ActivityCompat.requestPermissions(android.app.Activity, String[], int)}.
* @param permissions The requested permissions.
* @param grantResults The grant results for the corresponding permissions which is either
* {@code PackageManager.PERMISSION_GRANTED} or {@code PackageManager.PERMISSION_DENIED}.
* @return true if the result has been handled.
*/
boolean onRequestPermissionsResult(
int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults);
}
/**
* Delegate interface for handling activity results on behalf of the main {@link
* android.app.Activity}.
*/
interface ActivityResultListener {
/**
* @param requestCode The integer request code originally supplied to {@code
* startActivityForResult()}, allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its {@code
* setResult()}.
* @param data An Intent, which can return result data to the caller (various data can be
* attached to Intent "extras").
* @return true if the result has been handled.
*/
boolean onActivityResult(int requestCode, int resultCode, @Nullable Intent data);
}
/**
* Delegate interface for handling new intents on behalf of the main {@link android.app.Activity}.
*/
interface NewIntentListener {
/**
* @param intent The new intent that was started for the activity.
* @return true if the new intent has been handled.
*/
boolean onNewIntent(@NonNull Intent intent);
}
/**
* Delegate interface for handling user leave hints on behalf of the main {@link
* android.app.Activity}.
*/
interface UserLeaveHintListener {
void onUserLeaveHint();
}
/**
* Delegate interface for handling window focus changes on behalf of the main {@link
* android.app.Activity}.
*/
interface WindowFocusChangedListener {
void onWindowFocusChanged(boolean hasFocus);
}
/**
* Delegate interface for handling an {@link android.app.Activity}'s onDestroy method being
* called. A plugin that implements this interface can adopt the {@link FlutterNativeView} by
* retaining a reference and returning true.
*
* @deprecated See https://flutter.dev/go/android-project-migration for migration details.
*/
@Deprecated
interface ViewDestroyListener {
boolean onViewDestroy(@NonNull FlutterNativeView view);
}
/**
* Callback interface for registering plugins with a plugin registry.
*
* <p>For example, an Application may use this callback interface to provide a background service
* with a callback for calling its GeneratedPluginRegistrant.registerWith method.
*
* @deprecated See https://flutter.dev/go/android-project-migration for migration details.
*/
@Deprecated
interface PluginRegistrantCallback {
void registerWith(@NonNull PluginRegistry registry);
}
}
| engine/shell/platform/android/io/flutter/plugin/common/PluginRegistry.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/plugin/common/PluginRegistry.java",
"repo_id": "engine",
"token_count": 6102
} | 297 |
// Copyright 2013 The Flutter 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.plugin.platform;
import static io.flutter.Build.API_LEVELS;
import android.app.Activity;
import android.app.ActivityManager.TaskDescription;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.net.Uri;
import android.os.Build;
import android.view.HapticFeedbackConstants;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import androidx.activity.OnBackPressedDispatcherOwner;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.core.view.WindowInsetsControllerCompat;
import io.flutter.Log;
import io.flutter.embedding.engine.systemchannels.PlatformChannel;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
/** Android implementation of the platform plugin. */
public class PlatformPlugin {
public static final int DEFAULT_SYSTEM_UI =
View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
private final Activity activity;
private final PlatformChannel platformChannel;
@Nullable private final PlatformPluginDelegate platformPluginDelegate;
private PlatformChannel.SystemChromeStyle currentTheme;
private int mEnabledOverlays;
private static final String TAG = "PlatformPlugin";
/**
* The {@link PlatformPlugin} generally has default behaviors implemented for platform
* functionalities requested by the Flutter framework. However, functionalities exposed through
* this interface could be customized by the more public-facing APIs that implement this interface
* such as the {@link io.flutter.embedding.android.FlutterActivity} or the {@link
* io.flutter.embedding.android.FlutterFragment}.
*/
public interface PlatformPluginDelegate {
/**
* Allow implementer to customize the behavior needed when the Flutter framework calls to pop
* the Android-side navigation stack.
*
* @return true if the implementation consumed the pop signal. If false, a default behavior of
* finishing the activity or sending the signal to {@link
* androidx.activity.OnBackPressedDispatcher} will be executed.
*/
boolean popSystemNavigator();
/**
* The Flutter application would or would not like to handle navigation pop events itself.
*
* <p>Relevant for registering and unregistering the app's OnBackInvokedCallback for the
* Predictive Back feature, for example as in {@link
* io.flutter.embedding.android.FlutterActivity}.
*/
default void setFrameworkHandlesBack(boolean frameworkHandlesBack) {}
}
@VisibleForTesting
final PlatformChannel.PlatformMessageHandler mPlatformMessageHandler =
new PlatformChannel.PlatformMessageHandler() {
@Override
public void playSystemSound(@NonNull PlatformChannel.SoundType soundType) {
PlatformPlugin.this.playSystemSound(soundType);
}
@Override
public void vibrateHapticFeedback(
@NonNull PlatformChannel.HapticFeedbackType feedbackType) {
PlatformPlugin.this.vibrateHapticFeedback(feedbackType);
}
@Override
public void setPreferredOrientations(int androidOrientation) {
setSystemChromePreferredOrientations(androidOrientation);
}
@Override
public void setApplicationSwitcherDescription(
@NonNull PlatformChannel.AppSwitcherDescription description) {
setSystemChromeApplicationSwitcherDescription(description);
}
@Override
public void showSystemOverlays(@NonNull List<PlatformChannel.SystemUiOverlay> overlays) {
setSystemChromeEnabledSystemUIOverlays(overlays);
}
@Override
public void showSystemUiMode(@NonNull PlatformChannel.SystemUiMode mode) {
setSystemChromeEnabledSystemUIMode(mode);
}
@Override
public void setSystemUiChangeListener() {
setSystemChromeChangeListener();
}
@Override
public void restoreSystemUiOverlays() {
restoreSystemChromeSystemUIOverlays();
}
@Override
public void setSystemUiOverlayStyle(
@NonNull PlatformChannel.SystemChromeStyle systemUiOverlayStyle) {
setSystemChromeSystemUIOverlayStyle(systemUiOverlayStyle);
}
@Override
public void setFrameworkHandlesBack(boolean frameworkHandlesBack) {
PlatformPlugin.this.setFrameworkHandlesBack(frameworkHandlesBack);
}
@Override
public void popSystemNavigator() {
PlatformPlugin.this.popSystemNavigator();
}
@Override
public CharSequence getClipboardData(
@Nullable PlatformChannel.ClipboardContentFormat format) {
return PlatformPlugin.this.getClipboardData(format);
}
@Override
public void setClipboardData(@NonNull String text) {
PlatformPlugin.this.setClipboardData(text);
}
@Override
public boolean clipboardHasStrings() {
return PlatformPlugin.this.clipboardHasStrings();
}
@Override
public void share(@NonNull String text) {
PlatformPlugin.this.share(text);
}
};
public PlatformPlugin(@NonNull Activity activity, @NonNull PlatformChannel platformChannel) {
this(activity, platformChannel, null);
}
public PlatformPlugin(
@NonNull Activity activity,
@NonNull PlatformChannel platformChannel,
@Nullable PlatformPluginDelegate delegate) {
this.activity = activity;
this.platformChannel = platformChannel;
this.platformChannel.setPlatformMessageHandler(mPlatformMessageHandler);
this.platformPluginDelegate = delegate;
mEnabledOverlays = DEFAULT_SYSTEM_UI;
}
/**
* Releases all resources held by this {@code PlatformPlugin}.
*
* <p>Do not invoke any methods on a {@code PlatformPlugin} after invoking this method.
*/
public void destroy() {
this.platformChannel.setPlatformMessageHandler(null);
}
private void playSystemSound(@NonNull PlatformChannel.SoundType soundType) {
if (soundType == PlatformChannel.SoundType.CLICK) {
View view = activity.getWindow().getDecorView();
view.playSoundEffect(SoundEffectConstants.CLICK);
}
}
@VisibleForTesting
/* package */ void vibrateHapticFeedback(
@NonNull PlatformChannel.HapticFeedbackType feedbackType) {
View view = activity.getWindow().getDecorView();
switch (feedbackType) {
case STANDARD:
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
break;
case LIGHT_IMPACT:
view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
break;
case MEDIUM_IMPACT:
view.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
break;
case HEAVY_IMPACT:
if (Build.VERSION.SDK_INT >= API_LEVELS.API_23) {
view.performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
}
break;
case SELECTION_CLICK:
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK);
break;
}
}
private void setSystemChromePreferredOrientations(int androidOrientation) {
activity.setRequestedOrientation(androidOrientation);
}
@SuppressWarnings("deprecation")
private void setSystemChromeApplicationSwitcherDescription(
PlatformChannel.AppSwitcherDescription description) {
if (Build.VERSION.SDK_INT < API_LEVELS.API_28) {
activity.setTaskDescription(
new TaskDescription(description.label, /* icon= */ null, description.color));
} else {
TaskDescription taskDescription =
new TaskDescription(description.label, 0, description.color);
activity.setTaskDescription(taskDescription);
}
}
private void setSystemChromeChangeListener() {
// Set up a listener to notify the framework when the system ui has changed.
View decorView = activity.getWindow().getDecorView();
decorView.setOnSystemUiVisibilityChangeListener(
new View.OnSystemUiVisibilityChangeListener() {
@Override
public void onSystemUiVisibilityChange(int visibility) {
// `platformChannel.systemChromeChanged` may trigger a callback that eventually results
// in a call to `setSystemUiVisibility`.
// `setSystemUiVisibility` must not be called in the same frame as when
// `onSystemUiVisibilityChange` is received though.
//
// As such, post `platformChannel.systemChromeChanged` to the view handler to ensure
// that downstream callbacks are trigged on the next frame.
decorView.post(
() -> {
if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
// The system bars are visible. Make any desired adjustments to
// your UI, such as showing the action bar or other navigational
// controls. Another common action is to set a timer to dismiss
// the system bars and restore the fullscreen mode that was
// previously enabled.
platformChannel.systemChromeChanged(true);
} else {
// The system bars are NOT visible. Make any desired adjustments
// to your UI, such as hiding the action bar or other
// navigational controls.
platformChannel.systemChromeChanged(false);
}
});
}
});
}
private void setSystemChromeEnabledSystemUIMode(PlatformChannel.SystemUiMode systemUiMode) {
int enabledOverlays;
if (systemUiMode == PlatformChannel.SystemUiMode.LEAN_BACK) {
// LEAN BACK
// Available starting at SDK 16
// Should not show overlays, tap to reveal overlays, needs onChange callback
// When the overlays come in on tap, the app does not receive the gesture and does not know
// the system overlay has changed. The overlays cannot be dismissed, so adding the callback
// support will allow users to restore the system ui and dismiss the overlays.
// Not compatible with top/bottom overlays enabled.
enabledOverlays =
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN;
} else if (systemUiMode == PlatformChannel.SystemUiMode.IMMERSIVE) {
// IMMERSIVE
// Available starting at 19
// Should not show overlays, swipe from edges to reveal overlays, needs onChange callback
// When the overlays come in on swipe, the app does not receive the gesture and does not know
// the system overlay has changed. The overlays cannot be dismissed, so adding callback
// support will allow users to restore the system ui and dismiss the overlays.
// Not compatible with top/bottom overlays enabled.
enabledOverlays =
View.SYSTEM_UI_FLAG_IMMERSIVE
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN;
} else if (systemUiMode == PlatformChannel.SystemUiMode.IMMERSIVE_STICKY) {
// STICKY IMMERSIVE
// Available starting at 19
// Should not show overlays, swipe from edges to reveal overlays. The app will also receive
// the swipe gesture. The overlays cannot be dismissed, so adding callback support will
// allow users to restore the system ui and dismiss the overlays.
// Not compatible with top/bottom overlays enabled.
enabledOverlays =
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN;
} else if (systemUiMode == PlatformChannel.SystemUiMode.EDGE_TO_EDGE
&& Build.VERSION.SDK_INT >= API_LEVELS.API_29) {
// EDGE TO EDGE
// Available starting at 29
// SDK 29 and up will apply a translucent body scrim behind 2/3 button navigation bars
// to ensure contrast with buttons on the nav and status bars, unless the contrast is not
// enforced in the overlay styling.
enabledOverlays =
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
} else {
// When none of the conditions are matched, return without updating the system UI overlays.
return;
}
mEnabledOverlays = enabledOverlays;
updateSystemUiOverlays();
}
private void setSystemChromeEnabledSystemUIOverlays(
List<PlatformChannel.SystemUiOverlay> overlaysToShow) {
// Start by assuming we want to hide all system overlays (like an immersive
// game).
int enabledOverlays =
DEFAULT_SYSTEM_UI
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
if (overlaysToShow.size() == 0) {
enabledOverlays |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
}
// Re-add any desired system overlays.
for (int i = 0; i < overlaysToShow.size(); ++i) {
PlatformChannel.SystemUiOverlay overlayToShow = overlaysToShow.get(i);
switch (overlayToShow) {
case TOP_OVERLAYS:
enabledOverlays &= ~View.SYSTEM_UI_FLAG_FULLSCREEN;
break;
case BOTTOM_OVERLAYS:
enabledOverlays &= ~View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
enabledOverlays &= ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
break;
}
}
mEnabledOverlays = enabledOverlays;
updateSystemUiOverlays();
}
/**
* Refreshes Android's window system UI (AKA system chrome) to match Flutter's desired {@link
* PlatformChannel.SystemChromeStyle}.
*
* <p>Updating the system UI Overlays is accomplished by altering the decor view of the {@link
* Window} associated with the {@link android.app.Activity} that was provided to this {@code
* PlatformPlugin}.
*/
public void updateSystemUiOverlays() {
activity.getWindow().getDecorView().setSystemUiVisibility(mEnabledOverlays);
if (currentTheme != null) {
setSystemChromeSystemUIOverlayStyle(currentTheme);
}
}
private void restoreSystemChromeSystemUIOverlays() {
updateSystemUiOverlays();
}
@SuppressWarnings("deprecation")
private void setSystemChromeSystemUIOverlayStyle(
PlatformChannel.SystemChromeStyle systemChromeStyle) {
Window window = activity.getWindow();
View view = window.getDecorView();
WindowInsetsControllerCompat windowInsetsControllerCompat =
new WindowInsetsControllerCompat(window, view);
if (Build.VERSION.SDK_INT < API_LEVELS.API_30) {
// Flag set to specify that this window is responsible for drawing the background for the
// system bars. Must be set for all operations on API < 30 excluding enforcing system
// bar contrasts. Deprecated in API 30.
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// Flag set to dismiss any requests for translucent system bars to be provided in lieu of what
// is specified by systemChromeStyle. Must be set for all operations on API < 30 operations
// excluding enforcing system bar contrasts. Deprecated in API 30.
window.clearFlags(
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
| WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
// SYSTEM STATUS BAR -------------------------------------------------------------------
// You can't change the color of the system status bar until SDK 21, and you can't change the
// color of the status icons until SDK 23. We only allow both starting at 23 to ensure buttons
// and icons can be visible when changing the background color.
// If transparent, SDK 29 and higher may apply a translucent scrim behind the bar to ensure
// proper contrast. This can be overridden with
// SystemChromeStyle.systemStatusBarContrastEnforced.
if (Build.VERSION.SDK_INT >= API_LEVELS.API_23) {
if (systemChromeStyle.statusBarIconBrightness != null) {
switch (systemChromeStyle.statusBarIconBrightness) {
case DARK:
// Dark status bar icon brightness.
// Light status bar appearance.
windowInsetsControllerCompat.setAppearanceLightStatusBars(true);
break;
case LIGHT:
// Light status bar icon brightness.
// Dark status bar appearance.
windowInsetsControllerCompat.setAppearanceLightStatusBars(false);
break;
}
}
if (systemChromeStyle.statusBarColor != null) {
window.setStatusBarColor(systemChromeStyle.statusBarColor);
}
}
// You can't override the enforced contrast for a transparent status bar until SDK 29.
// This overrides the translucent scrim that may be placed behind the bar on SDK 29+ to ensure
// contrast is appropriate when using full screen layout modes like Edge to Edge.
if (systemChromeStyle.systemStatusBarContrastEnforced != null
&& Build.VERSION.SDK_INT >= API_LEVELS.API_29) {
window.setStatusBarContrastEnforced(systemChromeStyle.systemStatusBarContrastEnforced);
}
// SYSTEM NAVIGATION BAR --------------------------------------------------------------
// You can't change the color of the system navigation bar until SDK 21, and you can't change
// the color of the navigation buttons until SDK 26. We only allow both starting at 26 to
// ensure buttons can be visible when changing the background color.
// If transparent, SDK 29 and higher may apply a translucent scrim behind 2/3 button navigation
// bars to ensure proper contrast. This can be overridden with
// SystemChromeStyle.systemNavigationBarContrastEnforced.
if (Build.VERSION.SDK_INT >= API_LEVELS.API_26) {
if (systemChromeStyle.systemNavigationBarIconBrightness != null) {
switch (systemChromeStyle.systemNavigationBarIconBrightness) {
case DARK:
// Dark navigation bar icon brightness.
// Light navigation bar appearance.
windowInsetsControllerCompat.setAppearanceLightNavigationBars(true);
break;
case LIGHT:
// Light navigation bar icon brightness.
// Dark navigation bar appearance.
windowInsetsControllerCompat.setAppearanceLightNavigationBars(false);
break;
}
}
if (systemChromeStyle.systemNavigationBarColor != null) {
window.setNavigationBarColor(systemChromeStyle.systemNavigationBarColor);
}
}
// You can't change the color of the navigation bar divider color until SDK 28.
if (systemChromeStyle.systemNavigationBarDividerColor != null
&& Build.VERSION.SDK_INT >= API_LEVELS.API_28) {
window.setNavigationBarDividerColor(systemChromeStyle.systemNavigationBarDividerColor);
}
// You can't override the enforced contrast for a transparent navigation bar until SDK 29.
// This overrides the translucent scrim that may be placed behind 2/3 button navigation bars on
// SDK 29+ to ensure contrast is appropriate when using full screen layout modes like
// Edge to Edge.
if (systemChromeStyle.systemNavigationBarContrastEnforced != null
&& Build.VERSION.SDK_INT >= API_LEVELS.API_29) {
window.setNavigationBarContrastEnforced(
systemChromeStyle.systemNavigationBarContrastEnforced);
}
currentTheme = systemChromeStyle;
}
private void setFrameworkHandlesBack(boolean frameworkHandlesBack) {
if (platformPluginDelegate != null) {
platformPluginDelegate.setFrameworkHandlesBack(frameworkHandlesBack);
}
}
private void popSystemNavigator() {
if (platformPluginDelegate != null && platformPluginDelegate.popSystemNavigator()) {
// A custom behavior was executed by the delegate. Don't execute default behavior.
return;
}
if (activity instanceof OnBackPressedDispatcherOwner) {
((OnBackPressedDispatcherOwner) activity).getOnBackPressedDispatcher().onBackPressed();
} else {
activity.finish();
}
}
private CharSequence getClipboardData(PlatformChannel.ClipboardContentFormat format) {
ClipboardManager clipboard =
(ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
if (!clipboard.hasPrimaryClip()) return null;
CharSequence itemText = null;
try {
ClipData clip = clipboard.getPrimaryClip();
if (clip == null) return null;
if (format == null || format == PlatformChannel.ClipboardContentFormat.PLAIN_TEXT) {
ClipData.Item item = clip.getItemAt(0);
// First, try getting clipboard data as text; no further processing
// required if so.
itemText = item.getText();
if (itemText == null) {
// Clipboard data does not contain text, so check whether or not it
// contains a URI to extract text from.
Uri itemUri = item.getUri();
if (itemUri == null) {
Log.w(
TAG, "Clipboard item contained no textual content nor a URI to retrieve it from.");
return null;
}
// Will only try to extract text from URI if it has the content scheme.
String uriScheme = itemUri.getScheme();
if (!uriScheme.equals("content")) {
Log.w(
TAG,
"Clipboard item contains a Uri with scheme '" + uriScheme + "'that is unhandled.");
return null;
}
AssetFileDescriptor assetFileDescriptor =
activity.getContentResolver().openTypedAssetFileDescriptor(itemUri, "text/*", null);
// Safely return clipboard data coerced into text; will return either
// itemText or text retrieved from its URI.
itemText = item.coerceToText(activity);
if (assetFileDescriptor != null) assetFileDescriptor.close();
}
return itemText;
}
} catch (SecurityException e) {
Log.w(
TAG,
"Attempted to get clipboard data that requires additional permission(s).\n"
+ "See the exception details for which permission(s) are required, and consider adding them to your Android Manifest as described in:\n"
+ "https://developer.android.com/guide/topics/permissions/overview",
e);
return null;
} catch (FileNotFoundException e) {
Log.w(TAG, "Clipboard text was unable to be received from content URI.");
return null;
} catch (IOException e) {
Log.w(TAG, "Failed to close AssetFileDescriptor while trying to read text from URI.", e);
return itemText;
}
return null;
}
private void setClipboardData(String text) {
ClipboardManager clipboard =
(ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("text label?", text);
clipboard.setPrimaryClip(clip);
}
private boolean clipboardHasStrings() {
ClipboardManager clipboard =
(ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
// Android 12 introduces a toast message that appears when an app reads the clipboard. To avoid
// unintended access, call the appropriate APIs to receive information about the current content
// that's on the clipboard (rather than the actual content itself).
if (!clipboard.hasPrimaryClip()) {
return false;
}
ClipDescription description = clipboard.getPrimaryClipDescription();
if (description == null) {
return false;
}
return description.hasMimeType("text/*");
}
private void share(@NonNull String text) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, text);
activity.startActivity(Intent.createChooser(intent, null));
}
}
| engine/shell/platform/android/io/flutter/plugin/platform/PlatformPlugin.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/plugin/platform/PlatformPlugin.java",
"repo_id": "engine",
"token_count": 9142
} | 298 |
// Copyright 2013 The Flutter 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.plugin.text;
import static io.flutter.Build.API_LEVELS;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.embedding.engine.systemchannels.ProcessTextChannel;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.PluginRegistry.ActivityResultListener;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ProcessTextPlugin
implements FlutterPlugin,
ActivityAware,
ActivityResultListener,
ProcessTextChannel.ProcessTextMethodHandler {
private static final String TAG = "ProcessTextPlugin";
@NonNull private final ProcessTextChannel processTextChannel;
@NonNull private final PackageManager packageManager;
@Nullable private ActivityPluginBinding activityBinding;
private Map<String, ResolveInfo> resolveInfosById;
@NonNull
private Map<Integer, MethodChannel.Result> requestsByCode =
new HashMap<Integer, MethodChannel.Result>();
public ProcessTextPlugin(@NonNull ProcessTextChannel processTextChannel) {
this.processTextChannel = processTextChannel;
this.packageManager = processTextChannel.packageManager;
processTextChannel.setMethodHandler(this);
}
@Override
public Map<String, String> queryTextActions() {
if (resolveInfosById == null) {
cacheResolveInfos();
}
Map<String, String> result = new HashMap<String, String>();
for (String id : resolveInfosById.keySet()) {
final ResolveInfo info = resolveInfosById.get(id);
result.put(id, info.loadLabel(packageManager).toString());
}
return result;
}
@Override
public void processTextAction(
@NonNull String id,
@NonNull String text,
@NonNull boolean readOnly,
@NonNull MethodChannel.Result result) {
if (activityBinding == null) {
result.error("error", "Plugin not bound to an Activity", null);
return;
}
if (Build.VERSION.SDK_INT < API_LEVELS.API_23) {
result.error("error", "Android version not supported", null);
return;
}
if (resolveInfosById == null) {
result.error("error", "Can not process text actions before calling queryTextActions", null);
return;
}
final ResolveInfo info = resolveInfosById.get(id);
if (info == null) {
result.error("error", "Text processing activity not found", null);
return;
}
Integer requestCode = result.hashCode();
requestsByCode.put(requestCode, result);
Intent intent = new Intent();
intent.setClassName(info.activityInfo.packageName, info.activityInfo.name);
intent.setAction(Intent.ACTION_PROCESS_TEXT);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_PROCESS_TEXT, text);
intent.putExtra(Intent.EXTRA_PROCESS_TEXT_READONLY, readOnly);
// Start the text processing activity. When the activity completes, the onActivityResult
// callback
// is called.
activityBinding.getActivity().startActivityForResult(intent, requestCode);
}
private void cacheResolveInfos() {
resolveInfosById = new HashMap<String, ResolveInfo>();
if (Build.VERSION.SDK_INT < API_LEVELS.API_23) {
return;
}
Intent intent = new Intent().setAction(Intent.ACTION_PROCESS_TEXT).setType("text/plain");
List<ResolveInfo> infos;
if (Build.VERSION.SDK_INT >= API_LEVELS.API_33) {
infos = packageManager.queryIntentActivities(intent, PackageManager.ResolveInfoFlags.of(0));
} else {
infos = packageManager.queryIntentActivities(intent, 0);
}
for (ResolveInfo info : infos) {
final String id = info.activityInfo.name;
final String label = info.loadLabel(packageManager).toString();
resolveInfosById.put(id, info);
}
}
/**
* Executed when a text processing activity terminates.
*
* <p>When an activity returns a value, the request is completed successfully and returns the
* processed text.
*
* <p>When an activity does not return a value. the request is completed successfully and returns
* null.
*/
@TargetApi(API_LEVELS.API_23)
@RequiresApi(API_LEVELS.API_23)
public boolean onActivityResult(int requestCode, int resultCode, @Nullable Intent intent) {
// Return early if the result is not related to a request sent by this plugin.
if (!requestsByCode.containsKey(requestCode)) {
return false;
}
String result = null;
if (resultCode == Activity.RESULT_OK) {
result = intent.getStringExtra(Intent.EXTRA_PROCESS_TEXT);
}
requestsByCode.remove(requestCode).success(result);
return true;
}
/**
* Unregisters this {@code ProcessTextPlugin} as the {@code
* ProcessTextChannel.ProcessTextMethodHandler}, for the {@link
* io.flutter.embedding.engine.systemchannels.ProcessTextChannel}.
*
* <p>Do not invoke any methods on a {@code ProcessTextPlugin} after invoking this method.
*/
public void destroy() {
processTextChannel.setMethodHandler(null);
}
// FlutterPlugin interface implementation.
public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
// Nothing to do because this plugin is instantiated by the engine.
}
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
// Nothing to do because this plugin is instantiated by the engine.
}
// ActivityAware interface implementation.
//
// Store the binding and manage the activity result listener.
public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
this.activityBinding = binding;
this.activityBinding.addActivityResultListener(this);
};
public void onDetachedFromActivityForConfigChanges() {
this.activityBinding.removeActivityResultListener(this);
this.activityBinding = null;
}
public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {
this.activityBinding = binding;
this.activityBinding.addActivityResultListener(this);
}
public void onDetachedFromActivity() {
this.activityBinding.removeActivityResultListener(this);
this.activityBinding = null;
}
}
| engine/shell/platform/android/io/flutter/plugin/text/ProcessTextPlugin.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/plugin/text/ProcessTextPlugin.java",
"repo_id": "engine",
"token_count": 2180
} | 299 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//flutter/common/config.gni")
import("//flutter/testing/testing.gni")
source_set("jni") {
sources = [
"platform_view_android_jni.cc",
"platform_view_android_jni.h",
]
public_configs = [ "//flutter:config" ]
deps = [
"//flutter/flow",
"//flutter/fml",
"//flutter/lib/ui",
"//flutter/shell/platform/android/surface:native_window",
"//flutter/skia",
]
}
source_set("jni_mock") {
testonly = true
sources = [ "jni_mock.h" ]
public_configs = [ "//flutter:config" ]
deps = [ ":jni" ]
}
test_fixtures("jni_fixtures") {
fixtures = []
}
executable("jni_unittests") {
testonly = true
sources = [ "jni_mock_unittest.cc" ]
deps = [
":jni_fixtures",
":jni_mock",
"//flutter/testing",
"//flutter/testing:dart",
"//flutter/testing:skia",
]
}
| engine/shell/platform/android/jni/BUILD.gn/0 | {
"file_path": "engine/shell/platform/android/jni/BUILD.gn",
"repo_id": "engine",
"token_count": 412
} | 300 |
// Copyright 2013 The Flutter 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/android/platform_view_android_jni_impl.h"
#include <android/hardware_buffer_jni.h>
#include <android/native_window_jni.h>
#include <dlfcn.h>
#include <jni.h>
#include <memory>
#include <sstream>
#include <utility>
#include "include/android/SkImageAndroid.h"
#include "unicode/uchar.h"
#include "flutter/assets/directory_asset_bundle.h"
#include "flutter/common/constants.h"
#include "flutter/fml/file.h"
#include "flutter/fml/mapping.h"
#include "flutter/fml/native_library.h"
#include "flutter/fml/platform/android/jni_util.h"
#include "flutter/fml/platform/android/jni_weak_ref.h"
#include "flutter/fml/platform/android/scoped_java_ref.h"
#include "flutter/fml/size.h"
#include "flutter/lib/ui/plugins/callback_cache.h"
#include "flutter/runtime/dart_service_isolate.h"
#include "flutter/shell/common/run_configuration.h"
#include "flutter/shell/platform/android/android_shell_holder.h"
#include "flutter/shell/platform/android/apk_asset_provider.h"
#include "flutter/shell/platform/android/flutter_main.h"
#include "flutter/shell/platform/android/image_external_texture_gl.h"
#include "flutter/shell/platform/android/jni/platform_view_android_jni.h"
#include "flutter/shell/platform/android/platform_view_android.h"
#include "flutter/shell/platform/android/surface_texture_external_texture_gl.h"
#define ANDROID_SHELL_HOLDER \
(reinterpret_cast<AndroidShellHolder*>(shell_holder))
namespace flutter {
static fml::jni::ScopedJavaGlobalRef<jclass>* g_flutter_callback_info_class =
nullptr;
static fml::jni::ScopedJavaGlobalRef<jclass>* g_flutter_jni_class = nullptr;
static fml::jni::ScopedJavaGlobalRef<jclass>* g_java_weak_reference_class =
nullptr;
static fml::jni::ScopedJavaGlobalRef<jclass>* g_texture_wrapper_class = nullptr;
static fml::jni::ScopedJavaGlobalRef<jclass>*
g_image_consumer_texture_registry_interface = nullptr;
static fml::jni::ScopedJavaGlobalRef<jclass>* g_image_class = nullptr;
static fml::jni::ScopedJavaGlobalRef<jclass>* g_hardware_buffer_class = nullptr;
static fml::jni::ScopedJavaGlobalRef<jclass>* g_java_long_class = nullptr;
static fml::jni::ScopedJavaGlobalRef<jclass>* g_bitmap_class = nullptr;
static fml::jni::ScopedJavaGlobalRef<jclass>* g_bitmap_config_class = nullptr;
// Called By Native
static jmethodID g_flutter_callback_info_constructor = nullptr;
jobject CreateFlutterCallbackInformation(
JNIEnv* env,
const std::string& callbackName,
const std::string& callbackClassName,
const std::string& callbackLibraryPath) {
return env->NewObject(g_flutter_callback_info_class->obj(),
g_flutter_callback_info_constructor,
env->NewStringUTF(callbackName.c_str()),
env->NewStringUTF(callbackClassName.c_str()),
env->NewStringUTF(callbackLibraryPath.c_str()));
}
static jfieldID g_jni_shell_holder_field = nullptr;
static jmethodID g_jni_constructor = nullptr;
static jmethodID g_long_constructor = nullptr;
static jmethodID g_handle_platform_message_method = nullptr;
static jmethodID g_handle_platform_message_response_method = nullptr;
static jmethodID g_update_semantics_method = nullptr;
static jmethodID g_update_custom_accessibility_actions_method = nullptr;
static jmethodID g_get_scaled_font_size_method = nullptr;
static jmethodID g_on_first_frame_method = nullptr;
static jmethodID g_on_engine_restart_method = nullptr;
static jmethodID g_create_overlay_surface_method = nullptr;
static jmethodID g_destroy_overlay_surfaces_method = nullptr;
static jmethodID g_on_begin_frame_method = nullptr;
static jmethodID g_on_end_frame_method = nullptr;
static jmethodID g_java_weak_reference_get_method = nullptr;
static jmethodID g_attach_to_gl_context_method = nullptr;
static jmethodID g_surface_texture_wrapper_should_update = nullptr;
static jmethodID g_update_tex_image_method = nullptr;
static jmethodID g_get_transform_matrix_method = nullptr;
static jmethodID g_detach_from_gl_context_method = nullptr;
static jmethodID g_acquire_latest_image_method = nullptr;
static jmethodID g_image_get_hardware_buffer_method = nullptr;
static jmethodID g_image_close_method = nullptr;
static jmethodID g_hardware_buffer_close_method = nullptr;
static jmethodID g_compute_platform_resolved_locale_method = nullptr;
static jmethodID g_request_dart_deferred_library_method = nullptr;
// Called By Java
static jmethodID g_on_display_platform_view_method = nullptr;
// static jmethodID g_on_composite_platform_view_method = nullptr;
static jmethodID g_on_display_overlay_surface_method = nullptr;
static jmethodID g_overlay_surface_id_method = nullptr;
static jmethodID g_overlay_surface_surface_method = nullptr;
static jmethodID g_bitmap_create_bitmap_method = nullptr;
static jmethodID g_bitmap_copy_pixels_from_buffer_method = nullptr;
static jmethodID g_bitmap_config_value_of = nullptr;
// Mutators
static fml::jni::ScopedJavaGlobalRef<jclass>* g_mutators_stack_class = nullptr;
static jmethodID g_mutators_stack_init_method = nullptr;
static jmethodID g_mutators_stack_push_transform_method = nullptr;
static jmethodID g_mutators_stack_push_cliprect_method = nullptr;
static jmethodID g_mutators_stack_push_cliprrect_method = nullptr;
// Called By Java
static jlong AttachJNI(JNIEnv* env, jclass clazz, jobject flutterJNI) {
fml::jni::JavaObjectWeakGlobalRef java_object(env, flutterJNI);
std::shared_ptr<PlatformViewAndroidJNI> jni_facade =
std::make_shared<PlatformViewAndroidJNIImpl>(java_object);
auto shell_holder = std::make_unique<AndroidShellHolder>(
FlutterMain::Get().GetSettings(), jni_facade);
if (shell_holder->IsValid()) {
return reinterpret_cast<jlong>(shell_holder.release());
} else {
return 0;
}
}
static void DestroyJNI(JNIEnv* env, jobject jcaller, jlong shell_holder) {
delete ANDROID_SHELL_HOLDER;
}
// Signature is similar to RunBundleAndSnapshotFromLibrary but it can't change
// the bundle path or asset manager since we can only spawn with the same
// AOT.
//
// The shell_holder instance must be a pointer address to the current
// AndroidShellHolder whose Shell will be used to spawn a new Shell.
//
// This creates a Java Long that points to the newly created
// AndroidShellHolder's raw pointer, connects that Long to a newly created
// FlutterJNI instance, then returns the FlutterJNI instance.
static jobject SpawnJNI(JNIEnv* env,
jobject jcaller,
jlong shell_holder,
jstring jEntrypoint,
jstring jLibraryUrl,
jstring jInitialRoute,
jobject jEntrypointArgs) {
jobject jni = env->NewObject(g_flutter_jni_class->obj(), g_jni_constructor);
if (jni == nullptr) {
FML_LOG(ERROR) << "Could not create a FlutterJNI instance";
return nullptr;
}
fml::jni::JavaObjectWeakGlobalRef java_jni(env, jni);
std::shared_ptr<PlatformViewAndroidJNI> jni_facade =
std::make_shared<PlatformViewAndroidJNIImpl>(java_jni);
auto entrypoint = fml::jni::JavaStringToString(env, jEntrypoint);
auto libraryUrl = fml::jni::JavaStringToString(env, jLibraryUrl);
auto initial_route = fml::jni::JavaStringToString(env, jInitialRoute);
auto entrypoint_args = fml::jni::StringListToVector(env, jEntrypointArgs);
auto spawned_shell_holder = ANDROID_SHELL_HOLDER->Spawn(
jni_facade, entrypoint, libraryUrl, initial_route, entrypoint_args);
if (spawned_shell_holder == nullptr || !spawned_shell_holder->IsValid()) {
FML_LOG(ERROR) << "Could not spawn Shell";
return nullptr;
}
jobject javaLong = env->CallStaticObjectMethod(
g_java_long_class->obj(), g_long_constructor,
reinterpret_cast<jlong>(spawned_shell_holder.release()));
if (javaLong == nullptr) {
FML_LOG(ERROR) << "Could not create a Long instance";
return nullptr;
}
env->SetObjectField(jni, g_jni_shell_holder_field, javaLong);
return jni;
}
static void SurfaceCreated(JNIEnv* env,
jobject jcaller,
jlong shell_holder,
jobject jsurface) {
// Note: This frame ensures that any local references used by
// ANativeWindow_fromSurface are released immediately. This is needed as a
// workaround for https://code.google.com/p/android/issues/detail?id=68174
fml::jni::ScopedJavaLocalFrame scoped_local_reference_frame(env);
auto window = fml::MakeRefCounted<AndroidNativeWindow>(
ANativeWindow_fromSurface(env, jsurface));
ANDROID_SHELL_HOLDER->GetPlatformView()->NotifyCreated(std::move(window));
}
static void SurfaceWindowChanged(JNIEnv* env,
jobject jcaller,
jlong shell_holder,
jobject jsurface) {
// Note: This frame ensures that any local references used by
// ANativeWindow_fromSurface are released immediately. This is needed as a
// workaround for https://code.google.com/p/android/issues/detail?id=68174
fml::jni::ScopedJavaLocalFrame scoped_local_reference_frame(env);
auto window = fml::MakeRefCounted<AndroidNativeWindow>(
ANativeWindow_fromSurface(env, jsurface));
ANDROID_SHELL_HOLDER->GetPlatformView()->NotifySurfaceWindowChanged(
std::move(window));
}
static void SurfaceChanged(JNIEnv* env,
jobject jcaller,
jlong shell_holder,
jint width,
jint height) {
ANDROID_SHELL_HOLDER->GetPlatformView()->NotifyChanged(
SkISize::Make(width, height));
}
static void SurfaceDestroyed(JNIEnv* env, jobject jcaller, jlong shell_holder) {
ANDROID_SHELL_HOLDER->GetPlatformView()->NotifyDestroyed();
}
static void RunBundleAndSnapshotFromLibrary(JNIEnv* env,
jobject jcaller,
jlong shell_holder,
jstring jBundlePath,
jstring jEntrypoint,
jstring jLibraryUrl,
jobject jAssetManager,
jobject jEntrypointArgs) {
auto apk_asset_provider = std::make_unique<flutter::APKAssetProvider>(
env, // jni environment
jAssetManager, // asset manager
fml::jni::JavaStringToString(env, jBundlePath) // apk asset dir
);
auto entrypoint = fml::jni::JavaStringToString(env, jEntrypoint);
auto libraryUrl = fml::jni::JavaStringToString(env, jLibraryUrl);
auto entrypoint_args = fml::jni::StringListToVector(env, jEntrypointArgs);
ANDROID_SHELL_HOLDER->Launch(std::move(apk_asset_provider), entrypoint,
libraryUrl, entrypoint_args);
}
static jobject LookupCallbackInformation(JNIEnv* env,
/* unused */ jobject,
jlong handle) {
auto cbInfo = flutter::DartCallbackCache::GetCallbackInformation(handle);
if (cbInfo == nullptr) {
return nullptr;
}
return CreateFlutterCallbackInformation(env, cbInfo->name, cbInfo->class_name,
cbInfo->library_path);
}
static void SetViewportMetrics(JNIEnv* env,
jobject jcaller,
jlong shell_holder,
jfloat devicePixelRatio,
jint physicalWidth,
jint physicalHeight,
jint physicalPaddingTop,
jint physicalPaddingRight,
jint physicalPaddingBottom,
jint physicalPaddingLeft,
jint physicalViewInsetTop,
jint physicalViewInsetRight,
jint physicalViewInsetBottom,
jint physicalViewInsetLeft,
jint systemGestureInsetTop,
jint systemGestureInsetRight,
jint systemGestureInsetBottom,
jint systemGestureInsetLeft,
jint physicalTouchSlop,
jintArray javaDisplayFeaturesBounds,
jintArray javaDisplayFeaturesType,
jintArray javaDisplayFeaturesState) {
// Convert java->c++. javaDisplayFeaturesBounds, javaDisplayFeaturesType and
// javaDisplayFeaturesState cannot be null
jsize rectSize = env->GetArrayLength(javaDisplayFeaturesBounds);
std::vector<int> boundsIntVector(rectSize);
env->GetIntArrayRegion(javaDisplayFeaturesBounds, 0, rectSize,
&boundsIntVector[0]);
std::vector<double> displayFeaturesBounds(boundsIntVector.begin(),
boundsIntVector.end());
jsize typeSize = env->GetArrayLength(javaDisplayFeaturesType);
std::vector<int> displayFeaturesType(typeSize);
env->GetIntArrayRegion(javaDisplayFeaturesType, 0, typeSize,
&displayFeaturesType[0]);
jsize stateSize = env->GetArrayLength(javaDisplayFeaturesState);
std::vector<int> displayFeaturesState(stateSize);
env->GetIntArrayRegion(javaDisplayFeaturesState, 0, stateSize,
&displayFeaturesState[0]);
const flutter::ViewportMetrics metrics{
static_cast<double>(devicePixelRatio),
static_cast<double>(physicalWidth),
static_cast<double>(physicalHeight),
static_cast<double>(physicalPaddingTop),
static_cast<double>(physicalPaddingRight),
static_cast<double>(physicalPaddingBottom),
static_cast<double>(physicalPaddingLeft),
static_cast<double>(physicalViewInsetTop),
static_cast<double>(physicalViewInsetRight),
static_cast<double>(physicalViewInsetBottom),
static_cast<double>(physicalViewInsetLeft),
static_cast<double>(systemGestureInsetTop),
static_cast<double>(systemGestureInsetRight),
static_cast<double>(systemGestureInsetBottom),
static_cast<double>(systemGestureInsetLeft),
static_cast<double>(physicalTouchSlop),
displayFeaturesBounds,
displayFeaturesType,
displayFeaturesState,
0, // Display ID
};
ANDROID_SHELL_HOLDER->GetPlatformView()->SetViewportMetrics(
kFlutterImplicitViewId, metrics);
}
static void UpdateDisplayMetrics(JNIEnv* env,
jobject jcaller,
jlong shell_holder) {
ANDROID_SHELL_HOLDER->UpdateDisplayMetrics();
}
static jobject GetBitmap(JNIEnv* env, jobject jcaller, jlong shell_holder) {
auto screenshot = ANDROID_SHELL_HOLDER->Screenshot(
Rasterizer::ScreenshotType::UncompressedImage, false);
if (screenshot.data == nullptr) {
return nullptr;
}
jstring argb = env->NewStringUTF("ARGB_8888");
if (argb == nullptr) {
return nullptr;
}
jobject bitmap_config = env->CallStaticObjectMethod(
g_bitmap_config_class->obj(), g_bitmap_config_value_of, argb);
if (bitmap_config == nullptr) {
return nullptr;
}
auto bitmap = env->CallStaticObjectMethod(
g_bitmap_class->obj(), g_bitmap_create_bitmap_method,
screenshot.frame_size.width(), screenshot.frame_size.height(),
bitmap_config);
fml::jni::ScopedJavaLocalRef<jobject> buffer(
env,
env->NewDirectByteBuffer(const_cast<uint8_t*>(screenshot.data->bytes()),
screenshot.data->size()));
env->CallVoidMethod(bitmap, g_bitmap_copy_pixels_from_buffer_method,
buffer.obj());
return bitmap;
}
static void DispatchPlatformMessage(JNIEnv* env,
jobject jcaller,
jlong shell_holder,
jstring channel,
jobject message,
jint position,
jint responseId) {
ANDROID_SHELL_HOLDER->GetPlatformView()->DispatchPlatformMessage(
env, //
fml::jni::JavaStringToString(env, channel), //
message, //
position, //
responseId //
);
}
static void DispatchEmptyPlatformMessage(JNIEnv* env,
jobject jcaller,
jlong shell_holder,
jstring channel,
jint responseId) {
ANDROID_SHELL_HOLDER->GetPlatformView()->DispatchEmptyPlatformMessage(
env, //
fml::jni::JavaStringToString(env, channel), //
responseId //
);
}
static void CleanupMessageData(JNIEnv* env,
jobject jcaller,
jlong message_data) {
// Called from any thread.
free(reinterpret_cast<void*>(message_data));
}
static void DispatchPointerDataPacket(JNIEnv* env,
jobject jcaller,
jlong shell_holder,
jobject buffer,
jint position) {
uint8_t* data = static_cast<uint8_t*>(env->GetDirectBufferAddress(buffer));
auto packet = std::make_unique<flutter::PointerDataPacket>(data, position);
ANDROID_SHELL_HOLDER->GetPlatformView()->DispatchPointerDataPacket(
std::move(packet));
}
static void DispatchSemanticsAction(JNIEnv* env,
jobject jcaller,
jlong shell_holder,
jint id,
jint action,
jobject args,
jint args_position) {
ANDROID_SHELL_HOLDER->GetPlatformView()->DispatchSemanticsAction(
env, //
id, //
action, //
args, //
args_position //
);
}
static void SetSemanticsEnabled(JNIEnv* env,
jobject jcaller,
jlong shell_holder,
jboolean enabled) {
ANDROID_SHELL_HOLDER->GetPlatformView()->SetSemanticsEnabled(enabled);
}
static void SetAccessibilityFeatures(JNIEnv* env,
jobject jcaller,
jlong shell_holder,
jint flags) {
ANDROID_SHELL_HOLDER->GetPlatformView()->SetAccessibilityFeatures(flags);
}
static jboolean GetIsSoftwareRendering(JNIEnv* env, jobject jcaller) {
return FlutterMain::Get().GetSettings().enable_software_rendering;
}
static void RegisterTexture(JNIEnv* env,
jobject jcaller,
jlong shell_holder,
jlong texture_id,
jobject surface_texture) {
ANDROID_SHELL_HOLDER->GetPlatformView()->RegisterExternalTexture(
static_cast<int64_t>(texture_id), //
fml::jni::ScopedJavaGlobalRef<jobject>(env, surface_texture) //
);
}
static void RegisterImageTexture(JNIEnv* env,
jobject jcaller,
jlong shell_holder,
jlong texture_id,
jobject image_texture_entry) {
ANDROID_SHELL_HOLDER->GetPlatformView()->RegisterImageTexture(
static_cast<int64_t>(texture_id), //
fml::jni::ScopedJavaGlobalRef<jobject>(env, image_texture_entry) //
);
}
static void UnregisterTexture(JNIEnv* env,
jobject jcaller,
jlong shell_holder,
jlong texture_id) {
ANDROID_SHELL_HOLDER->GetPlatformView()->UnregisterTexture(
static_cast<int64_t>(texture_id));
}
static void MarkTextureFrameAvailable(JNIEnv* env,
jobject jcaller,
jlong shell_holder,
jlong texture_id) {
ANDROID_SHELL_HOLDER->GetPlatformView()->MarkTextureFrameAvailable(
static_cast<int64_t>(texture_id));
}
static void ScheduleFrame(JNIEnv* env, jobject jcaller, jlong shell_holder) {
ANDROID_SHELL_HOLDER->GetPlatformView()->ScheduleFrame();
}
static void InvokePlatformMessageResponseCallback(JNIEnv* env,
jobject jcaller,
jlong shell_holder,
jint responseId,
jobject message,
jint position) {
uint8_t* response_data =
static_cast<uint8_t*>(env->GetDirectBufferAddress(message));
FML_DCHECK(response_data != nullptr);
auto mapping = std::make_unique<fml::MallocMapping>(
fml::MallocMapping::Copy(response_data, response_data + position));
ANDROID_SHELL_HOLDER->GetPlatformMessageHandler()
->InvokePlatformMessageResponseCallback(responseId, std::move(mapping));
}
static void InvokePlatformMessageEmptyResponseCallback(JNIEnv* env,
jobject jcaller,
jlong shell_holder,
jint responseId) {
ANDROID_SHELL_HOLDER->GetPlatformMessageHandler()
->InvokePlatformMessageEmptyResponseCallback(responseId);
}
static void NotifyLowMemoryWarning(JNIEnv* env,
jobject obj,
jlong shell_holder) {
ANDROID_SHELL_HOLDER->NotifyLowMemoryWarning();
}
static jboolean FlutterTextUtilsIsEmoji(JNIEnv* env,
jobject obj,
jint codePoint) {
return u_hasBinaryProperty(codePoint, UProperty::UCHAR_EMOJI);
}
static jboolean FlutterTextUtilsIsEmojiModifier(JNIEnv* env,
jobject obj,
jint codePoint) {
return u_hasBinaryProperty(codePoint, UProperty::UCHAR_EMOJI_MODIFIER);
}
static jboolean FlutterTextUtilsIsEmojiModifierBase(JNIEnv* env,
jobject obj,
jint codePoint) {
return u_hasBinaryProperty(codePoint, UProperty::UCHAR_EMOJI_MODIFIER_BASE);
}
static jboolean FlutterTextUtilsIsVariationSelector(JNIEnv* env,
jobject obj,
jint codePoint) {
return u_hasBinaryProperty(codePoint, UProperty::UCHAR_VARIATION_SELECTOR);
}
static jboolean FlutterTextUtilsIsRegionalIndicator(JNIEnv* env,
jobject obj,
jint codePoint) {
return u_hasBinaryProperty(codePoint, UProperty::UCHAR_REGIONAL_INDICATOR);
}
static void LoadLoadingUnitFailure(intptr_t loading_unit_id,
const std::string& message,
bool transient) {
// TODO(garyq): Implement
}
static void DeferredComponentInstallFailure(JNIEnv* env,
jobject obj,
jint jLoadingUnitId,
jstring jError,
jboolean jTransient) {
LoadLoadingUnitFailure(static_cast<intptr_t>(jLoadingUnitId),
fml::jni::JavaStringToString(env, jError),
static_cast<bool>(jTransient));
}
static void LoadDartDeferredLibrary(JNIEnv* env,
jobject obj,
jlong shell_holder,
jint jLoadingUnitId,
jobjectArray jSearchPaths) {
// Convert java->c++
intptr_t loading_unit_id = static_cast<intptr_t>(jLoadingUnitId);
std::vector<std::string> search_paths =
fml::jni::StringArrayToVector(env, jSearchPaths);
// Use dlopen here to directly check if handle is nullptr before creating a
// NativeLibrary.
void* handle = nullptr;
while (handle == nullptr && !search_paths.empty()) {
std::string path = search_paths.back();
handle = ::dlopen(path.c_str(), RTLD_NOW);
search_paths.pop_back();
}
if (handle == nullptr) {
LoadLoadingUnitFailure(loading_unit_id,
"No lib .so found for provided search paths.", true);
return;
}
fml::RefPtr<fml::NativeLibrary> native_lib =
fml::NativeLibrary::CreateWithHandle(handle, false);
// Resolve symbols.
std::unique_ptr<const fml::SymbolMapping> data_mapping =
std::make_unique<const fml::SymbolMapping>(
native_lib, DartSnapshot::kIsolateDataSymbol);
std::unique_ptr<const fml::SymbolMapping> instructions_mapping =
std::make_unique<const fml::SymbolMapping>(
native_lib, DartSnapshot::kIsolateInstructionsSymbol);
ANDROID_SHELL_HOLDER->GetPlatformView()->LoadDartDeferredLibrary(
loading_unit_id, std::move(data_mapping),
std::move(instructions_mapping));
}
static void UpdateJavaAssetManager(JNIEnv* env,
jobject obj,
jlong shell_holder,
jobject jAssetManager,
jstring jAssetBundlePath) {
auto asset_resolver = std::make_unique<flutter::APKAssetProvider>(
env, // jni environment
jAssetManager, // asset manager
fml::jni::JavaStringToString(env, jAssetBundlePath)); // apk asset dir
ANDROID_SHELL_HOLDER->GetPlatformView()->UpdateAssetResolverByType(
std::move(asset_resolver),
AssetResolver::AssetResolverType::kApkAssetProvider);
}
bool RegisterApi(JNIEnv* env) {
static const JNINativeMethod flutter_jni_methods[] = {
// Start of methods from FlutterJNI
{
.name = "nativeAttach",
.signature = "(Lio/flutter/embedding/engine/FlutterJNI;)J",
.fnPtr = reinterpret_cast<void*>(&AttachJNI),
},
{
.name = "nativeDestroy",
.signature = "(J)V",
.fnPtr = reinterpret_cast<void*>(&DestroyJNI),
},
{
.name = "nativeSpawn",
.signature = "(JLjava/lang/String;Ljava/lang/String;Ljava/lang/"
"String;Ljava/util/List;)Lio/flutter/"
"embedding/engine/FlutterJNI;",
.fnPtr = reinterpret_cast<void*>(&SpawnJNI),
},
{
.name = "nativeRunBundleAndSnapshotFromLibrary",
.signature = "(JLjava/lang/String;Ljava/lang/String;"
"Ljava/lang/String;Landroid/content/res/"
"AssetManager;Ljava/util/List;)V",
.fnPtr = reinterpret_cast<void*>(&RunBundleAndSnapshotFromLibrary),
},
{
.name = "nativeDispatchEmptyPlatformMessage",
.signature = "(JLjava/lang/String;I)V",
.fnPtr = reinterpret_cast<void*>(&DispatchEmptyPlatformMessage),
},
{
.name = "nativeCleanupMessageData",
.signature = "(J)V",
.fnPtr = reinterpret_cast<void*>(&CleanupMessageData),
},
{
.name = "nativeDispatchPlatformMessage",
.signature = "(JLjava/lang/String;Ljava/nio/ByteBuffer;II)V",
.fnPtr = reinterpret_cast<void*>(&DispatchPlatformMessage),
},
{
.name = "nativeInvokePlatformMessageResponseCallback",
.signature = "(JILjava/nio/ByteBuffer;I)V",
.fnPtr =
reinterpret_cast<void*>(&InvokePlatformMessageResponseCallback),
},
{
.name = "nativeInvokePlatformMessageEmptyResponseCallback",
.signature = "(JI)V",
.fnPtr = reinterpret_cast<void*>(
&InvokePlatformMessageEmptyResponseCallback),
},
{
.name = "nativeNotifyLowMemoryWarning",
.signature = "(J)V",
.fnPtr = reinterpret_cast<void*>(&NotifyLowMemoryWarning),
},
// Start of methods from FlutterView
{
.name = "nativeGetBitmap",
.signature = "(J)Landroid/graphics/Bitmap;",
.fnPtr = reinterpret_cast<void*>(&GetBitmap),
},
{
.name = "nativeSurfaceCreated",
.signature = "(JLandroid/view/Surface;)V",
.fnPtr = reinterpret_cast<void*>(&SurfaceCreated),
},
{
.name = "nativeSurfaceWindowChanged",
.signature = "(JLandroid/view/Surface;)V",
.fnPtr = reinterpret_cast<void*>(&SurfaceWindowChanged),
},
{
.name = "nativeSurfaceChanged",
.signature = "(JII)V",
.fnPtr = reinterpret_cast<void*>(&SurfaceChanged),
},
{
.name = "nativeSurfaceDestroyed",
.signature = "(J)V",
.fnPtr = reinterpret_cast<void*>(&SurfaceDestroyed),
},
{
.name = "nativeSetViewportMetrics",
.signature = "(JFIIIIIIIIIIIIIII[I[I[I)V",
.fnPtr = reinterpret_cast<void*>(&SetViewportMetrics),
},
{
.name = "nativeDispatchPointerDataPacket",
.signature = "(JLjava/nio/ByteBuffer;I)V",
.fnPtr = reinterpret_cast<void*>(&DispatchPointerDataPacket),
},
{
.name = "nativeDispatchSemanticsAction",
.signature = "(JIILjava/nio/ByteBuffer;I)V",
.fnPtr = reinterpret_cast<void*>(&DispatchSemanticsAction),
},
{
.name = "nativeSetSemanticsEnabled",
.signature = "(JZ)V",
.fnPtr = reinterpret_cast<void*>(&SetSemanticsEnabled),
},
{
.name = "nativeSetAccessibilityFeatures",
.signature = "(JI)V",
.fnPtr = reinterpret_cast<void*>(&SetAccessibilityFeatures),
},
{
.name = "nativeGetIsSoftwareRenderingEnabled",
.signature = "()Z",
.fnPtr = reinterpret_cast<void*>(&GetIsSoftwareRendering),
},
{
.name = "nativeRegisterTexture",
.signature = "(JJLjava/lang/ref/"
"WeakReference;)V",
.fnPtr = reinterpret_cast<void*>(&RegisterTexture),
},
{
.name = "nativeRegisterImageTexture",
.signature = "(JJLjava/lang/ref/"
"WeakReference;)V",
.fnPtr = reinterpret_cast<void*>(&RegisterImageTexture),
},
{
.name = "nativeMarkTextureFrameAvailable",
.signature = "(JJ)V",
.fnPtr = reinterpret_cast<void*>(&MarkTextureFrameAvailable),
},
{
.name = "nativeScheduleFrame",
.signature = "(J)V",
.fnPtr = reinterpret_cast<void*>(&ScheduleFrame),
},
{
.name = "nativeUnregisterTexture",
.signature = "(JJ)V",
.fnPtr = reinterpret_cast<void*>(&UnregisterTexture),
},
// Methods for Dart callback functionality.
{
.name = "nativeLookupCallbackInformation",
.signature = "(J)Lio/flutter/view/FlutterCallbackInformation;",
.fnPtr = reinterpret_cast<void*>(&LookupCallbackInformation),
},
// Start of methods for FlutterTextUtils
{
.name = "nativeFlutterTextUtilsIsEmoji",
.signature = "(I)Z",
.fnPtr = reinterpret_cast<void*>(&FlutterTextUtilsIsEmoji),
},
{
.name = "nativeFlutterTextUtilsIsEmojiModifier",
.signature = "(I)Z",
.fnPtr = reinterpret_cast<void*>(&FlutterTextUtilsIsEmojiModifier),
},
{
.name = "nativeFlutterTextUtilsIsEmojiModifierBase",
.signature = "(I)Z",
.fnPtr =
reinterpret_cast<void*>(&FlutterTextUtilsIsEmojiModifierBase),
},
{
.name = "nativeFlutterTextUtilsIsVariationSelector",
.signature = "(I)Z",
.fnPtr =
reinterpret_cast<void*>(&FlutterTextUtilsIsVariationSelector),
},
{
.name = "nativeFlutterTextUtilsIsRegionalIndicator",
.signature = "(I)Z",
.fnPtr =
reinterpret_cast<void*>(&FlutterTextUtilsIsRegionalIndicator),
},
{
.name = "nativeLoadDartDeferredLibrary",
.signature = "(JI[Ljava/lang/String;)V",
.fnPtr = reinterpret_cast<void*>(&LoadDartDeferredLibrary),
},
{
.name = "nativeUpdateJavaAssetManager",
.signature =
"(JLandroid/content/res/AssetManager;Ljava/lang/String;)V",
.fnPtr = reinterpret_cast<void*>(&UpdateJavaAssetManager),
},
{
.name = "nativeDeferredComponentInstallFailure",
.signature = "(ILjava/lang/String;Z)V",
.fnPtr = reinterpret_cast<void*>(&DeferredComponentInstallFailure),
},
{
.name = "nativeUpdateDisplayMetrics",
.signature = "(J)V",
.fnPtr = reinterpret_cast<void*>(&UpdateDisplayMetrics),
},
};
if (env->RegisterNatives(g_flutter_jni_class->obj(), flutter_jni_methods,
fml::size(flutter_jni_methods)) != 0) {
FML_LOG(ERROR) << "Failed to RegisterNatives with FlutterJNI";
return false;
}
g_jni_shell_holder_field = env->GetFieldID(
g_flutter_jni_class->obj(), "nativeShellHolderId", "Ljava/lang/Long;");
if (g_jni_shell_holder_field == nullptr) {
FML_LOG(ERROR) << "Could not locate FlutterJNI's nativeShellHolderId field";
return false;
}
g_jni_constructor =
env->GetMethodID(g_flutter_jni_class->obj(), "<init>", "()V");
if (g_jni_constructor == nullptr) {
FML_LOG(ERROR) << "Could not locate FlutterJNI's constructor";
return false;
}
g_long_constructor = env->GetStaticMethodID(g_java_long_class->obj(),
"valueOf", "(J)Ljava/lang/Long;");
if (g_long_constructor == nullptr) {
FML_LOG(ERROR) << "Could not locate Long's constructor";
return false;
}
g_handle_platform_message_method =
env->GetMethodID(g_flutter_jni_class->obj(), "handlePlatformMessage",
"(Ljava/lang/String;Ljava/nio/ByteBuffer;IJ)V");
if (g_handle_platform_message_method == nullptr) {
FML_LOG(ERROR) << "Could not locate handlePlatformMessage method";
return false;
}
g_handle_platform_message_response_method = env->GetMethodID(
g_flutter_jni_class->obj(), "handlePlatformMessageResponse",
"(ILjava/nio/ByteBuffer;)V");
if (g_handle_platform_message_response_method == nullptr) {
FML_LOG(ERROR) << "Could not locate handlePlatformMessageResponse method";
return false;
}
g_get_scaled_font_size_method = env->GetMethodID(
g_flutter_jni_class->obj(), "getScaledFontSize", "(FI)F");
if (g_get_scaled_font_size_method == nullptr) {
FML_LOG(ERROR) << "Could not locate FlutterJNI#getScaledFontSize method";
return false;
}
g_update_semantics_method = env->GetMethodID(
g_flutter_jni_class->obj(), "updateSemantics",
"(Ljava/nio/ByteBuffer;[Ljava/lang/String;[Ljava/nio/ByteBuffer;)V");
if (g_update_semantics_method == nullptr) {
FML_LOG(ERROR) << "Could not locate updateSemantics method";
return false;
}
g_update_custom_accessibility_actions_method = env->GetMethodID(
g_flutter_jni_class->obj(), "updateCustomAccessibilityActions",
"(Ljava/nio/ByteBuffer;[Ljava/lang/String;)V");
if (g_update_custom_accessibility_actions_method == nullptr) {
FML_LOG(ERROR)
<< "Could not locate updateCustomAccessibilityActions method";
return false;
}
g_on_first_frame_method =
env->GetMethodID(g_flutter_jni_class->obj(), "onFirstFrame", "()V");
if (g_on_first_frame_method == nullptr) {
FML_LOG(ERROR) << "Could not locate onFirstFrame method";
return false;
}
g_on_engine_restart_method =
env->GetMethodID(g_flutter_jni_class->obj(), "onPreEngineRestart", "()V");
if (g_on_engine_restart_method == nullptr) {
FML_LOG(ERROR) << "Could not locate onEngineRestart method";
return false;
}
g_create_overlay_surface_method =
env->GetMethodID(g_flutter_jni_class->obj(), "createOverlaySurface",
"()Lio/flutter/embedding/engine/FlutterOverlaySurface;");
if (g_create_overlay_surface_method == nullptr) {
FML_LOG(ERROR) << "Could not locate createOverlaySurface method";
return false;
}
g_destroy_overlay_surfaces_method = env->GetMethodID(
g_flutter_jni_class->obj(), "destroyOverlaySurfaces", "()V");
if (g_destroy_overlay_surfaces_method == nullptr) {
FML_LOG(ERROR) << "Could not locate destroyOverlaySurfaces method";
return false;
}
fml::jni::ScopedJavaLocalRef<jclass> overlay_surface_class(
env, env->FindClass("io/flutter/embedding/engine/FlutterOverlaySurface"));
if (overlay_surface_class.is_null()) {
FML_LOG(ERROR) << "Could not locate FlutterOverlaySurface class";
return false;
}
g_overlay_surface_id_method =
env->GetMethodID(overlay_surface_class.obj(), "getId", "()I");
if (g_overlay_surface_id_method == nullptr) {
FML_LOG(ERROR) << "Could not locate FlutterOverlaySurface#getId() method";
return false;
}
g_overlay_surface_surface_method = env->GetMethodID(
overlay_surface_class.obj(), "getSurface", "()Landroid/view/Surface;");
if (g_overlay_surface_surface_method == nullptr) {
FML_LOG(ERROR)
<< "Could not locate FlutterOverlaySurface#getSurface() method";
return false;
}
g_bitmap_class = new fml::jni::ScopedJavaGlobalRef<jclass>(
env, env->FindClass("android/graphics/Bitmap"));
if (g_bitmap_class->is_null()) {
FML_LOG(ERROR) << "Could not locate Bitmap Class";
return false;
}
g_bitmap_create_bitmap_method = env->GetStaticMethodID(
g_bitmap_class->obj(), "createBitmap",
"(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;");
if (g_bitmap_create_bitmap_method == nullptr) {
FML_LOG(ERROR) << "Could not locate Bitmap.createBitmap method";
return false;
}
g_bitmap_copy_pixels_from_buffer_method = env->GetMethodID(
g_bitmap_class->obj(), "copyPixelsFromBuffer", "(Ljava/nio/Buffer;)V");
if (g_bitmap_copy_pixels_from_buffer_method == nullptr) {
FML_LOG(ERROR) << "Could not locate Bitmap.copyPixelsFromBuffer method";
return false;
}
g_bitmap_config_class = new fml::jni::ScopedJavaGlobalRef<jclass>(
env, env->FindClass("android/graphics/Bitmap$Config"));
if (g_bitmap_config_class->is_null()) {
FML_LOG(ERROR) << "Could not locate Bitmap.Config Class";
return false;
}
g_bitmap_config_value_of = env->GetStaticMethodID(
g_bitmap_config_class->obj(), "valueOf",
"(Ljava/lang/String;)Landroid/graphics/Bitmap$Config;");
if (g_bitmap_config_value_of == nullptr) {
FML_LOG(ERROR) << "Could not locate Bitmap.Config.valueOf method";
return false;
}
return true;
}
bool PlatformViewAndroid::Register(JNIEnv* env) {
if (env == nullptr) {
FML_LOG(ERROR) << "No JNIEnv provided";
return false;
}
g_flutter_callback_info_class = new fml::jni::ScopedJavaGlobalRef<jclass>(
env, env->FindClass("io/flutter/view/FlutterCallbackInformation"));
if (g_flutter_callback_info_class->is_null()) {
FML_LOG(ERROR) << "Could not locate FlutterCallbackInformation class";
return false;
}
g_flutter_callback_info_constructor = env->GetMethodID(
g_flutter_callback_info_class->obj(), "<init>",
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
if (g_flutter_callback_info_constructor == nullptr) {
FML_LOG(ERROR) << "Could not locate FlutterCallbackInformation constructor";
return false;
}
g_flutter_jni_class = new fml::jni::ScopedJavaGlobalRef<jclass>(
env, env->FindClass("io/flutter/embedding/engine/FlutterJNI"));
if (g_flutter_jni_class->is_null()) {
FML_LOG(ERROR) << "Failed to find FlutterJNI Class.";
return false;
}
g_mutators_stack_class = new fml::jni::ScopedJavaGlobalRef<jclass>(
env,
env->FindClass(
"io/flutter/embedding/engine/mutatorsstack/FlutterMutatorsStack"));
if (g_mutators_stack_class == nullptr) {
FML_LOG(ERROR) << "Could not locate FlutterMutatorsStack";
return false;
}
g_mutators_stack_init_method =
env->GetMethodID(g_mutators_stack_class->obj(), "<init>", "()V");
if (g_mutators_stack_init_method == nullptr) {
FML_LOG(ERROR) << "Could not locate FlutterMutatorsStack.init method";
return false;
}
g_mutators_stack_push_transform_method =
env->GetMethodID(g_mutators_stack_class->obj(), "pushTransform", "([F)V");
if (g_mutators_stack_push_transform_method == nullptr) {
FML_LOG(ERROR)
<< "Could not locate FlutterMutatorsStack.pushTransform method";
return false;
}
g_mutators_stack_push_cliprect_method = env->GetMethodID(
g_mutators_stack_class->obj(), "pushClipRect", "(IIII)V");
if (g_mutators_stack_push_cliprect_method == nullptr) {
FML_LOG(ERROR)
<< "Could not locate FlutterMutatorsStack.pushClipRect method";
return false;
}
g_mutators_stack_push_cliprrect_method = env->GetMethodID(
g_mutators_stack_class->obj(), "pushClipRRect", "(IIII[F)V");
if (g_mutators_stack_push_cliprrect_method == nullptr) {
FML_LOG(ERROR)
<< "Could not locate FlutterMutatorsStack.pushClipRRect method";
return false;
}
g_on_display_platform_view_method =
env->GetMethodID(g_flutter_jni_class->obj(), "onDisplayPlatformView",
"(IIIIIIILio/flutter/embedding/engine/mutatorsstack/"
"FlutterMutatorsStack;)V");
if (g_on_display_platform_view_method == nullptr) {
FML_LOG(ERROR) << "Could not locate onDisplayPlatformView method";
return false;
}
g_on_begin_frame_method =
env->GetMethodID(g_flutter_jni_class->obj(), "onBeginFrame", "()V");
if (g_on_begin_frame_method == nullptr) {
FML_LOG(ERROR) << "Could not locate onBeginFrame method";
return false;
}
g_on_end_frame_method =
env->GetMethodID(g_flutter_jni_class->obj(), "onEndFrame", "()V");
if (g_on_end_frame_method == nullptr) {
FML_LOG(ERROR) << "Could not locate onEndFrame method";
return false;
}
g_on_display_overlay_surface_method = env->GetMethodID(
g_flutter_jni_class->obj(), "onDisplayOverlaySurface", "(IIIII)V");
if (g_on_display_overlay_surface_method == nullptr) {
FML_LOG(ERROR) << "Could not locate onDisplayOverlaySurface method";
return false;
}
g_java_weak_reference_class = new fml::jni::ScopedJavaGlobalRef<jclass>(
env, env->FindClass("java/lang/ref/WeakReference"));
if (g_java_weak_reference_class->is_null()) {
FML_LOG(ERROR) << "Could not locate WeakReference class";
return false;
}
g_java_weak_reference_get_method = env->GetMethodID(
g_java_weak_reference_class->obj(), "get", "()Ljava/lang/Object;");
if (g_java_weak_reference_get_method == nullptr) {
FML_LOG(ERROR) << "Could not locate WeakReference.get method";
return false;
}
g_texture_wrapper_class = new fml::jni::ScopedJavaGlobalRef<jclass>(
env, env->FindClass(
"io/flutter/embedding/engine/renderer/SurfaceTextureWrapper"));
if (g_texture_wrapper_class->is_null()) {
FML_LOG(ERROR) << "Could not locate SurfaceTextureWrapper class";
return false;
}
g_attach_to_gl_context_method = env->GetMethodID(
g_texture_wrapper_class->obj(), "attachToGLContext", "(I)V");
if (g_attach_to_gl_context_method == nullptr) {
FML_LOG(ERROR) << "Could not locate attachToGlContext method";
return false;
}
g_surface_texture_wrapper_should_update =
env->GetMethodID(g_texture_wrapper_class->obj(), "shouldUpdate", "()Z");
if (g_surface_texture_wrapper_should_update == nullptr) {
FML_LOG(ERROR)
<< "Could not locate SurfaceTextureWrapper.shouldUpdate method";
return false;
}
g_update_tex_image_method =
env->GetMethodID(g_texture_wrapper_class->obj(), "updateTexImage", "()V");
if (g_update_tex_image_method == nullptr) {
FML_LOG(ERROR) << "Could not locate updateTexImage method";
return false;
}
g_get_transform_matrix_method = env->GetMethodID(
g_texture_wrapper_class->obj(), "getTransformMatrix", "([F)V");
if (g_get_transform_matrix_method == nullptr) {
FML_LOG(ERROR) << "Could not locate getTransformMatrix method";
return false;
}
g_detach_from_gl_context_method = env->GetMethodID(
g_texture_wrapper_class->obj(), "detachFromGLContext", "()V");
if (g_detach_from_gl_context_method == nullptr) {
FML_LOG(ERROR) << "Could not locate detachFromGlContext method";
return false;
}
g_image_consumer_texture_registry_interface =
new fml::jni::ScopedJavaGlobalRef<jclass>(
env, env->FindClass("io/flutter/view/TextureRegistry$ImageConsumer"));
if (g_image_consumer_texture_registry_interface->is_null()) {
FML_LOG(ERROR) << "Could not locate TextureRegistry.ImageConsumer class";
return false;
}
g_acquire_latest_image_method =
env->GetMethodID(g_image_consumer_texture_registry_interface->obj(),
"acquireLatestImage", "()Landroid/media/Image;");
if (g_acquire_latest_image_method == nullptr) {
FML_LOG(ERROR) << "Could not locate acquireLatestImage on "
"TextureRegistry.ImageConsumer class";
return false;
}
g_image_class = new fml::jni::ScopedJavaGlobalRef<jclass>(
env, env->FindClass("android/media/Image"));
if (g_image_class->is_null()) {
FML_LOG(ERROR) << "Could not locate Image class";
return false;
}
// Ensure we don't have any pending exceptions.
FML_CHECK(fml::jni::CheckException(env));
g_image_get_hardware_buffer_method =
env->GetMethodID(g_image_class->obj(), "getHardwareBuffer",
"()Landroid/hardware/HardwareBuffer;");
if (g_image_get_hardware_buffer_method == nullptr) {
// Continue on as this method may not exist at API <= 29.
fml::jni::ClearException(env, true);
}
g_image_close_method = env->GetMethodID(g_image_class->obj(), "close", "()V");
if (g_image_close_method == nullptr) {
FML_LOG(ERROR) << "Could not locate close on Image class";
return false;
}
// Ensure we don't have any pending exceptions.
FML_CHECK(fml::jni::CheckException(env));
g_hardware_buffer_class = new fml::jni::ScopedJavaGlobalRef<jclass>(
env, env->FindClass("android/hardware/HardwareBuffer"));
if (!g_hardware_buffer_class->is_null()) {
g_hardware_buffer_close_method =
env->GetMethodID(g_hardware_buffer_class->obj(), "close", "()V");
if (g_hardware_buffer_close_method == nullptr) {
// Continue on as this class may not exist at API <= 26.
fml::jni::ClearException(env, true);
}
} else {
// Continue on as this class may not exist at API <= 26.
fml::jni::ClearException(env, true);
}
g_compute_platform_resolved_locale_method = env->GetMethodID(
g_flutter_jni_class->obj(), "computePlatformResolvedLocale",
"([Ljava/lang/String;)[Ljava/lang/String;");
if (g_compute_platform_resolved_locale_method == nullptr) {
FML_LOG(ERROR) << "Could not locate computePlatformResolvedLocale method";
return false;
}
g_request_dart_deferred_library_method = env->GetMethodID(
g_flutter_jni_class->obj(), "requestDartDeferredLibrary", "(I)V");
if (g_request_dart_deferred_library_method == nullptr) {
FML_LOG(ERROR) << "Could not locate requestDartDeferredLibrary method";
return false;
}
g_java_long_class = new fml::jni::ScopedJavaGlobalRef<jclass>(
env, env->FindClass("java/lang/Long"));
if (g_java_long_class->is_null()) {
FML_LOG(ERROR) << "Could not locate java.lang.Long class";
return false;
}
return RegisterApi(env);
}
PlatformViewAndroidJNIImpl::PlatformViewAndroidJNIImpl(
const fml::jni::JavaObjectWeakGlobalRef& java_object)
: java_object_(java_object) {}
PlatformViewAndroidJNIImpl::~PlatformViewAndroidJNIImpl() = default;
void PlatformViewAndroidJNIImpl::FlutterViewHandlePlatformMessage(
std::unique_ptr<flutter::PlatformMessage> message,
int responseId) {
// Called from any thread.
JNIEnv* env = fml::jni::AttachCurrentThread();
auto java_object = java_object_.get(env);
if (java_object.is_null()) {
return;
}
fml::jni::ScopedJavaLocalRef<jstring> java_channel =
fml::jni::StringToJavaString(env, message->channel());
if (message->hasData()) {
fml::jni::ScopedJavaLocalRef<jobject> message_array(
env, env->NewDirectByteBuffer(
const_cast<uint8_t*>(message->data().GetMapping()),
message->data().GetSize()));
// Message data is deleted in CleanupMessageData.
fml::MallocMapping mapping = message->releaseData();
env->CallVoidMethod(java_object.obj(), g_handle_platform_message_method,
java_channel.obj(), message_array.obj(), responseId,
reinterpret_cast<jlong>(mapping.Release()));
} else {
env->CallVoidMethod(java_object.obj(), g_handle_platform_message_method,
java_channel.obj(), nullptr, responseId, nullptr);
}
FML_CHECK(fml::jni::CheckException(env));
}
void PlatformViewAndroidJNIImpl::FlutterViewHandlePlatformMessageResponse(
int responseId,
std::unique_ptr<fml::Mapping> data) {
// We are on the platform thread. Attempt to get the strong reference to
// the Java object.
JNIEnv* env = fml::jni::AttachCurrentThread();
auto java_object = java_object_.get(env);
if (java_object.is_null()) {
// The Java object was collected before this message response got to
// it. Drop the response on the floor.
return;
}
if (data == nullptr) { // Empty response.
env->CallVoidMethod(java_object.obj(),
g_handle_platform_message_response_method, responseId,
nullptr);
} else {
// Convert the vector to a Java byte array.
fml::jni::ScopedJavaLocalRef<jobject> data_array(
env, env->NewDirectByteBuffer(const_cast<uint8_t*>(data->GetMapping()),
data->GetSize()));
env->CallVoidMethod(java_object.obj(),
g_handle_platform_message_response_method, responseId,
data_array.obj());
}
FML_CHECK(fml::jni::CheckException(env));
}
double PlatformViewAndroidJNIImpl::FlutterViewGetScaledFontSize(
double font_size,
int configuration_id) const {
JNIEnv* env = fml::jni::AttachCurrentThread();
auto java_object = java_object_.get(env);
if (java_object.is_null()) {
return -3;
}
const jfloat scaledSize =
env->CallFloatMethod(java_object.obj(), g_get_scaled_font_size_method,
(jfloat)font_size, (jint)configuration_id);
FML_CHECK(fml::jni::CheckException(env));
return (double)scaledSize;
}
void PlatformViewAndroidJNIImpl::FlutterViewUpdateSemantics(
std::vector<uint8_t> buffer,
std::vector<std::string> strings,
std::vector<std::vector<uint8_t>> string_attribute_args) {
JNIEnv* env = fml::jni::AttachCurrentThread();
auto java_object = java_object_.get(env);
if (java_object.is_null()) {
return;
}
fml::jni::ScopedJavaLocalRef<jobject> direct_buffer(
env, env->NewDirectByteBuffer(buffer.data(), buffer.size()));
fml::jni::ScopedJavaLocalRef<jobjectArray> jstrings =
fml::jni::VectorToStringArray(env, strings);
fml::jni::ScopedJavaLocalRef<jobjectArray> jstring_attribute_args =
fml::jni::VectorToBufferArray(env, string_attribute_args);
env->CallVoidMethod(java_object.obj(), g_update_semantics_method,
direct_buffer.obj(), jstrings.obj(),
jstring_attribute_args.obj());
FML_CHECK(fml::jni::CheckException(env));
}
void PlatformViewAndroidJNIImpl::FlutterViewUpdateCustomAccessibilityActions(
std::vector<uint8_t> actions_buffer,
std::vector<std::string> strings) {
JNIEnv* env = fml::jni::AttachCurrentThread();
auto java_object = java_object_.get(env);
if (java_object.is_null()) {
return;
}
fml::jni::ScopedJavaLocalRef<jobject> direct_actions_buffer(
env,
env->NewDirectByteBuffer(actions_buffer.data(), actions_buffer.size()));
fml::jni::ScopedJavaLocalRef<jobjectArray> jstrings =
fml::jni::VectorToStringArray(env, strings);
env->CallVoidMethod(java_object.obj(),
g_update_custom_accessibility_actions_method,
direct_actions_buffer.obj(), jstrings.obj());
FML_CHECK(fml::jni::CheckException(env));
}
void PlatformViewAndroidJNIImpl::FlutterViewOnFirstFrame() {
JNIEnv* env = fml::jni::AttachCurrentThread();
auto java_object = java_object_.get(env);
if (java_object.is_null()) {
return;
}
env->CallVoidMethod(java_object.obj(), g_on_first_frame_method);
FML_CHECK(fml::jni::CheckException(env));
}
void PlatformViewAndroidJNIImpl::FlutterViewOnPreEngineRestart() {
JNIEnv* env = fml::jni::AttachCurrentThread();
auto java_object = java_object_.get(env);
if (java_object.is_null()) {
return;
}
env->CallVoidMethod(java_object.obj(), g_on_engine_restart_method);
FML_CHECK(fml::jni::CheckException(env));
}
void PlatformViewAndroidJNIImpl::SurfaceTextureAttachToGLContext(
JavaLocalRef surface_texture,
int textureId) {
JNIEnv* env = fml::jni::AttachCurrentThread();
if (surface_texture.is_null()) {
return;
}
fml::jni::ScopedJavaLocalRef<jobject> surface_texture_local_ref(
env, env->CallObjectMethod(surface_texture.obj(),
g_java_weak_reference_get_method));
if (surface_texture_local_ref.is_null()) {
return;
}
env->CallVoidMethod(surface_texture_local_ref.obj(),
g_attach_to_gl_context_method, textureId);
FML_CHECK(fml::jni::CheckException(env));
}
bool PlatformViewAndroidJNIImpl::SurfaceTextureShouldUpdate(
JavaLocalRef surface_texture) {
JNIEnv* env = fml::jni::AttachCurrentThread();
if (surface_texture.is_null()) {
return false;
}
fml::jni::ScopedJavaLocalRef<jobject> surface_texture_local_ref(
env, env->CallObjectMethod(surface_texture.obj(),
g_java_weak_reference_get_method));
if (surface_texture_local_ref.is_null()) {
return false;
}
jboolean shouldUpdate = env->CallBooleanMethod(
surface_texture_local_ref.obj(), g_surface_texture_wrapper_should_update);
FML_CHECK(fml::jni::CheckException(env));
return shouldUpdate;
}
void PlatformViewAndroidJNIImpl::SurfaceTextureUpdateTexImage(
JavaLocalRef surface_texture) {
JNIEnv* env = fml::jni::AttachCurrentThread();
if (surface_texture.is_null()) {
return;
}
fml::jni::ScopedJavaLocalRef<jobject> surface_texture_local_ref(
env, env->CallObjectMethod(surface_texture.obj(),
g_java_weak_reference_get_method));
if (surface_texture_local_ref.is_null()) {
return;
}
env->CallVoidMethod(surface_texture_local_ref.obj(),
g_update_tex_image_method);
FML_CHECK(fml::jni::CheckException(env));
}
void PlatformViewAndroidJNIImpl::SurfaceTextureGetTransformMatrix(
JavaLocalRef surface_texture,
SkMatrix& transform) {
JNIEnv* env = fml::jni::AttachCurrentThread();
if (surface_texture.is_null()) {
return;
}
fml::jni::ScopedJavaLocalRef<jobject> surface_texture_local_ref(
env, env->CallObjectMethod(surface_texture.obj(),
g_java_weak_reference_get_method));
if (surface_texture_local_ref.is_null()) {
return;
}
fml::jni::ScopedJavaLocalRef<jfloatArray> transformMatrix(
env, env->NewFloatArray(16));
env->CallVoidMethod(surface_texture_local_ref.obj(),
g_get_transform_matrix_method, transformMatrix.obj());
FML_CHECK(fml::jni::CheckException(env));
float* m = env->GetFloatArrayElements(transformMatrix.obj(), nullptr);
// SurfaceTexture 4x4 Column Major -> Skia 3x3 Row Major
// SurfaceTexture 4x4 (Column Major):
// | m[0] m[4] m[ 8] m[12] |
// | m[1] m[5] m[ 9] m[13] |
// | m[2] m[6] m[10] m[14] |
// | m[3] m[7] m[11] m[15] |
// According to Android documentation, the 4x4 matrix returned should be used
// with texture coordinates in the form (s, t, 0, 1). Since the z component is
// always 0.0, we are free to ignore any element that multiplies with the z
// component. Converting this to a 3x3 matrix is easy:
// SurfaceTexture 3x3 (Column Major):
// | m[0] m[4] m[12] |
// | m[1] m[5] m[13] |
// | m[3] m[7] m[15] |
// Skia (Row Major):
// | m[0] m[1] m[2] |
// | m[3] m[4] m[5] |
// | m[6] m[7] m[8] |
SkScalar matrix3[] = {
m[0], m[4], m[12], //
m[1], m[5], m[13], //
m[3], m[7], m[15], //
};
env->ReleaseFloatArrayElements(transformMatrix.obj(), m, JNI_ABORT);
transform.set9(matrix3);
}
void PlatformViewAndroidJNIImpl::SurfaceTextureDetachFromGLContext(
JavaLocalRef surface_texture) {
JNIEnv* env = fml::jni::AttachCurrentThread();
if (surface_texture.is_null()) {
return;
}
fml::jni::ScopedJavaLocalRef<jobject> surface_texture_local_ref(
env, env->CallObjectMethod(surface_texture.obj(),
g_java_weak_reference_get_method));
if (surface_texture_local_ref.is_null()) {
return;
}
env->CallVoidMethod(surface_texture_local_ref.obj(),
g_detach_from_gl_context_method);
FML_CHECK(fml::jni::CheckException(env));
}
JavaLocalRef
PlatformViewAndroidJNIImpl::ImageProducerTextureEntryAcquireLatestImage(
JavaLocalRef image_producer_texture_entry) {
JNIEnv* env = fml::jni::AttachCurrentThread();
if (image_producer_texture_entry.is_null()) {
// Return null.
return JavaLocalRef();
}
// Convert the weak reference to ImageTextureEntry into a strong local
// reference.
fml::jni::ScopedJavaLocalRef<jobject> image_producer_texture_entry_local_ref(
env, env->CallObjectMethod(image_producer_texture_entry.obj(),
g_java_weak_reference_get_method));
if (image_producer_texture_entry_local_ref.is_null()) {
// Return null.
return JavaLocalRef();
}
JavaLocalRef r = JavaLocalRef(
env, env->CallObjectMethod(image_producer_texture_entry_local_ref.obj(),
g_acquire_latest_image_method));
FML_CHECK(fml::jni::CheckException(env));
return r;
}
JavaLocalRef PlatformViewAndroidJNIImpl::ImageGetHardwareBuffer(
JavaLocalRef image) {
FML_CHECK(g_image_get_hardware_buffer_method != nullptr);
JNIEnv* env = fml::jni::AttachCurrentThread();
if (image.is_null()) {
// Return null.
return JavaLocalRef();
}
JavaLocalRef r = JavaLocalRef(
env,
env->CallObjectMethod(image.obj(), g_image_get_hardware_buffer_method));
FML_CHECK(fml::jni::CheckException(env));
return r;
}
void PlatformViewAndroidJNIImpl::ImageClose(JavaLocalRef image) {
JNIEnv* env = fml::jni::AttachCurrentThread();
if (image.is_null()) {
return;
}
env->CallVoidMethod(image.obj(), g_image_close_method);
FML_CHECK(fml::jni::CheckException(env));
}
void PlatformViewAndroidJNIImpl::HardwareBufferClose(
JavaLocalRef hardware_buffer) {
FML_CHECK(g_hardware_buffer_close_method != nullptr);
JNIEnv* env = fml::jni::AttachCurrentThread();
if (hardware_buffer.is_null()) {
return;
}
env->CallVoidMethod(hardware_buffer.obj(), g_hardware_buffer_close_method);
FML_CHECK(fml::jni::CheckException(env));
}
void PlatformViewAndroidJNIImpl::FlutterViewOnDisplayPlatformView(
int view_id,
int x,
int y,
int width,
int height,
int viewWidth,
int viewHeight,
MutatorsStack mutators_stack) {
JNIEnv* env = fml::jni::AttachCurrentThread();
auto java_object = java_object_.get(env);
if (java_object.is_null()) {
return;
}
jobject mutatorsStack = env->NewObject(g_mutators_stack_class->obj(),
g_mutators_stack_init_method);
std::vector<std::shared_ptr<Mutator>>::const_iterator iter =
mutators_stack.Begin();
while (iter != mutators_stack.End()) {
switch ((*iter)->GetType()) {
case kTransform: {
const SkMatrix& matrix = (*iter)->GetMatrix();
SkScalar matrix_array[9];
matrix.get9(matrix_array);
fml::jni::ScopedJavaLocalRef<jfloatArray> transformMatrix(
env, env->NewFloatArray(9));
env->SetFloatArrayRegion(transformMatrix.obj(), 0, 9, matrix_array);
env->CallVoidMethod(mutatorsStack,
g_mutators_stack_push_transform_method,
transformMatrix.obj());
break;
}
case kClipRect: {
const SkRect& rect = (*iter)->GetRect();
env->CallVoidMethod(
mutatorsStack, g_mutators_stack_push_cliprect_method,
static_cast<int>(rect.left()), static_cast<int>(rect.top()),
static_cast<int>(rect.right()), static_cast<int>(rect.bottom()));
break;
}
case kClipRRect: {
const SkRRect& rrect = (*iter)->GetRRect();
const SkRect& rect = rrect.rect();
const SkVector& upper_left = rrect.radii(SkRRect::kUpperLeft_Corner);
const SkVector& upper_right = rrect.radii(SkRRect::kUpperRight_Corner);
const SkVector& lower_right = rrect.radii(SkRRect::kLowerRight_Corner);
const SkVector& lower_left = rrect.radii(SkRRect::kLowerLeft_Corner);
SkScalar radiis[8] = {
upper_left.x(), upper_left.y(), upper_right.x(), upper_right.y(),
lower_right.x(), lower_right.y(), lower_left.x(), lower_left.y(),
};
fml::jni::ScopedJavaLocalRef<jfloatArray> radiisArray(
env, env->NewFloatArray(8));
env->SetFloatArrayRegion(radiisArray.obj(), 0, 8, radiis);
env->CallVoidMethod(
mutatorsStack, g_mutators_stack_push_cliprrect_method,
static_cast<int>(rect.left()), static_cast<int>(rect.top()),
static_cast<int>(rect.right()), static_cast<int>(rect.bottom()),
radiisArray.obj());
break;
}
// TODO(cyanglaz): Implement other mutators.
// https://github.com/flutter/flutter/issues/58426
case kClipPath:
case kOpacity:
case kBackdropFilter:
break;
}
++iter;
}
env->CallVoidMethod(java_object.obj(), g_on_display_platform_view_method,
view_id, x, y, width, height, viewWidth, viewHeight,
mutatorsStack);
FML_CHECK(fml::jni::CheckException(env));
}
void PlatformViewAndroidJNIImpl::FlutterViewDisplayOverlaySurface(
int surface_id,
int x,
int y,
int width,
int height) {
JNIEnv* env = fml::jni::AttachCurrentThread();
auto java_object = java_object_.get(env);
if (java_object.is_null()) {
return;
}
env->CallVoidMethod(java_object.obj(), g_on_display_overlay_surface_method,
surface_id, x, y, width, height);
FML_CHECK(fml::jni::CheckException(env));
}
void PlatformViewAndroidJNIImpl::FlutterViewBeginFrame() {
JNIEnv* env = fml::jni::AttachCurrentThread();
auto java_object = java_object_.get(env);
if (java_object.is_null()) {
return;
}
env->CallVoidMethod(java_object.obj(), g_on_begin_frame_method);
FML_CHECK(fml::jni::CheckException(env));
}
void PlatformViewAndroidJNIImpl::FlutterViewEndFrame() {
JNIEnv* env = fml::jni::AttachCurrentThread();
auto java_object = java_object_.get(env);
if (java_object.is_null()) {
return;
}
env->CallVoidMethod(java_object.obj(), g_on_end_frame_method);
FML_CHECK(fml::jni::CheckException(env));
}
std::unique_ptr<PlatformViewAndroidJNI::OverlayMetadata>
PlatformViewAndroidJNIImpl::FlutterViewCreateOverlaySurface() {
JNIEnv* env = fml::jni::AttachCurrentThread();
auto java_object = java_object_.get(env);
if (java_object.is_null()) {
return nullptr;
}
fml::jni::ScopedJavaLocalRef<jobject> overlay(
env, env->CallObjectMethod(java_object.obj(),
g_create_overlay_surface_method));
FML_CHECK(fml::jni::CheckException(env));
if (overlay.is_null()) {
return std::make_unique<PlatformViewAndroidJNI::OverlayMetadata>(0,
nullptr);
}
jint overlay_id =
env->CallIntMethod(overlay.obj(), g_overlay_surface_id_method);
jobject overlay_surface =
env->CallObjectMethod(overlay.obj(), g_overlay_surface_surface_method);
auto overlay_window = fml::MakeRefCounted<AndroidNativeWindow>(
ANativeWindow_fromSurface(env, overlay_surface));
return std::make_unique<PlatformViewAndroidJNI::OverlayMetadata>(
overlay_id, std::move(overlay_window));
}
void PlatformViewAndroidJNIImpl::FlutterViewDestroyOverlaySurfaces() {
JNIEnv* env = fml::jni::AttachCurrentThread();
auto java_object = java_object_.get(env);
if (java_object.is_null()) {
return;
}
env->CallVoidMethod(java_object.obj(), g_destroy_overlay_surfaces_method);
FML_CHECK(fml::jni::CheckException(env));
}
std::unique_ptr<std::vector<std::string>>
PlatformViewAndroidJNIImpl::FlutterViewComputePlatformResolvedLocale(
std::vector<std::string> supported_locales_data) {
JNIEnv* env = fml::jni::AttachCurrentThread();
std::unique_ptr<std::vector<std::string>> out =
std::make_unique<std::vector<std::string>>();
auto java_object = java_object_.get(env);
if (java_object.is_null()) {
return out;
}
fml::jni::ScopedJavaLocalRef<jobjectArray> j_locales_data =
fml::jni::VectorToStringArray(env, supported_locales_data);
jobjectArray result = static_cast<jobjectArray>(env->CallObjectMethod(
java_object.obj(), g_compute_platform_resolved_locale_method,
j_locales_data.obj()));
FML_CHECK(fml::jni::CheckException(env));
int length = env->GetArrayLength(result);
for (int i = 0; i < length; i++) {
out->emplace_back(fml::jni::JavaStringToString(
env, static_cast<jstring>(env->GetObjectArrayElement(result, i))));
}
return out;
}
double PlatformViewAndroidJNIImpl::GetDisplayRefreshRate() {
JNIEnv* env = fml::jni::AttachCurrentThread();
auto java_object = java_object_.get(env);
if (java_object.is_null()) {
return kUnknownDisplayRefreshRate;
}
fml::jni::ScopedJavaLocalRef<jclass> clazz(
env, env->GetObjectClass(java_object.obj()));
if (clazz.is_null()) {
return kUnknownDisplayRefreshRate;
}
jfieldID fid = env->GetStaticFieldID(clazz.obj(), "refreshRateFPS", "F");
return static_cast<double>(env->GetStaticFloatField(clazz.obj(), fid));
}
double PlatformViewAndroidJNIImpl::GetDisplayWidth() {
JNIEnv* env = fml::jni::AttachCurrentThread();
auto java_object = java_object_.get(env);
if (java_object.is_null()) {
return -1;
}
fml::jni::ScopedJavaLocalRef<jclass> clazz(
env, env->GetObjectClass(java_object.obj()));
if (clazz.is_null()) {
return -1;
}
jfieldID fid = env->GetStaticFieldID(clazz.obj(), "displayWidth", "F");
return static_cast<double>(env->GetStaticFloatField(clazz.obj(), fid));
}
double PlatformViewAndroidJNIImpl::GetDisplayHeight() {
JNIEnv* env = fml::jni::AttachCurrentThread();
auto java_object = java_object_.get(env);
if (java_object.is_null()) {
return -1;
}
fml::jni::ScopedJavaLocalRef<jclass> clazz(
env, env->GetObjectClass(java_object.obj()));
if (clazz.is_null()) {
return -1;
}
jfieldID fid = env->GetStaticFieldID(clazz.obj(), "displayHeight", "F");
return static_cast<double>(env->GetStaticFloatField(clazz.obj(), fid));
}
double PlatformViewAndroidJNIImpl::GetDisplayDensity() {
JNIEnv* env = fml::jni::AttachCurrentThread();
auto java_object = java_object_.get(env);
if (java_object.is_null()) {
return -1;
}
fml::jni::ScopedJavaLocalRef<jclass> clazz(
env, env->GetObjectClass(java_object.obj()));
if (clazz.is_null()) {
return -1;
}
jfieldID fid = env->GetStaticFieldID(clazz.obj(), "displayDensity", "F");
return static_cast<double>(env->GetStaticFloatField(clazz.obj(), fid));
}
bool PlatformViewAndroidJNIImpl::RequestDartDeferredLibrary(
int loading_unit_id) {
JNIEnv* env = fml::jni::AttachCurrentThread();
auto java_object = java_object_.get(env);
if (java_object.is_null()) {
return true;
}
env->CallVoidMethod(java_object.obj(), g_request_dart_deferred_library_method,
loading_unit_id);
FML_CHECK(fml::jni::CheckException(env));
return true;
}
} // namespace flutter
| engine/shell/platform/android/platform_view_android_jni_impl.cc/0 | {
"file_path": "engine/shell/platform/android/platform_view_android_jni_impl.cc",
"repo_id": "engine",
"token_count": 30737
} | 301 |
# Unit testing Java code
All Java code in the engine should now be able to be tested with Robolectric 4.11.1
and JUnit 4. The test suite has been added after the bulk of the Java code was
first written, so most of these classes do not have existing tests. Ideally code
after this point should be tested, either with unit tests here or with
integration tests in other repos.
## Adding a new test
1. Create a file under `test/` matching the path and name of the class under
test. For example,
`shell/platform/android/io/flutter/util/Preconditions.java` ->
`shell/platform/android/**test**/io/flutter/util/Preconditions**Test**.java`.
2. Add your file to the `sources` of the `robolectric_tests` build target in
`/shell/platform/android/BUILD.gn`. This compiles the test class into the
test jar.
3. Import your test class and add it to the `@SuiteClasses` annotation in
`FlutterTestSuite.java`. This makes sure the test is actually executed at
run time.
4. Write your test.
5. Build and run with `testing/run_tests.py [--type=java] [--java-filter=<test_class_name>]`.
Note that `testing/run_tests.py` does not build the engine binaries; instead they
should be built prior to running this command and also when the source files
change. See [Compiling the engine](https://github.com/flutter/flutter/wiki/Compiling-the-engine)
for details on how to do so.
## Q&A
### My new test won't run. There's a "ClassNotFoundException".
See [Updating Embedding Dependencies](/tools/cipd/android_embedding_bundle).
### My new test won't compile. It can't find one of my imports.
See [Updating Embedding Dependencies](/tools/cipd/android_embedding_bundle).
| engine/shell/platform/android/test/README.md/0 | {
"file_path": "engine/shell/platform/android/test/README.md",
"repo_id": "engine",
"token_count": 500
} | 302 |
package io.flutter.embedding.engine;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
@Config(manifest = Config.NONE)
@RunWith(AndroidJUnit4.class)
public class FlutterEngineCacheTest {
@Test
public void itHoldsFlutterEngines() {
// --- Test Setup ---
FlutterEngine flutterEngine = mock(FlutterEngine.class);
FlutterEngineCache cache = new FlutterEngineCache();
// --- Execute Test ---
cache.put("my_flutter_engine", flutterEngine);
// --- Verify Results ---
assertEquals(flutterEngine, cache.get("my_flutter_engine"));
}
@Test
public void itQueriesFlutterEngineExistence() {
// --- Test Setup ---
FlutterEngine flutterEngine = mock(FlutterEngine.class);
FlutterEngineCache cache = new FlutterEngineCache();
// --- Execute Test ---
assertFalse(cache.contains("my_flutter_engine"));
cache.put("my_flutter_engine", flutterEngine);
// --- Verify Results ---
assertTrue(cache.contains("my_flutter_engine"));
}
@Test
public void itRemovesFlutterEngines() {
// --- Test Setup ---
FlutterEngine flutterEngine = mock(FlutterEngine.class);
FlutterEngineCache cache = new FlutterEngineCache();
// --- Execute Test ---
cache.put("my_flutter_engine", flutterEngine);
cache.remove("my_flutter_engine");
// --- Verify Results ---
assertNull(cache.get("my_flutter_engine"));
}
@Test
public void itRemovesAllFlutterEngines() {
// --- Test Setup ---
FlutterEngine flutterEngine = mock(FlutterEngine.class);
FlutterEngine flutterEngine2 = mock(FlutterEngine.class);
FlutterEngineCache cache = new FlutterEngineCache();
// --- Execute Test ---
cache.put("my_flutter_engine", flutterEngine);
cache.put("my_flutter_engine_2", flutterEngine2);
// --- Verify Results ---
assertEquals(flutterEngine, cache.get("my_flutter_engine"));
assertEquals(flutterEngine2, cache.get("my_flutter_engine_2"));
cache.clear();
// --- Verify Results ---
assertNull(cache.get("my_flutter_engine"));
assertNull(cache.get("my_flutter_engine_2"));
}
}
| engine/shell/platform/android/test/io/flutter/embedding/engine/FlutterEngineCacheTest.java/0 | {
"file_path": "engine/shell/platform/android/test/io/flutter/embedding/engine/FlutterEngineCacheTest.java",
"repo_id": "engine",
"token_count": 835
} | 303 |
package io.flutter.embedding.engine.renderer;
import static android.content.ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyFloat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Shadows.shadowOf;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
import android.media.Image;
import android.os.Looper;
import android.view.Surface;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import io.flutter.embedding.engine.FlutterJNI;
import io.flutter.view.TextureRegistry;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.robolectric.annotation.Config;
@Config(manifest = Config.NONE)
@RunWith(AndroidJUnit4.class)
public class FlutterRendererTest {
private FlutterJNI fakeFlutterJNI;
private Surface fakeSurface;
private Surface fakeSurface2;
@Before
public void init() {
// Uncomment the following line to enable logging output in test.
// ShadowLog.stream = System.out;
}
@Before
public void setup() {
fakeFlutterJNI = mock(FlutterJNI.class);
fakeSurface = mock(Surface.class);
fakeSurface2 = mock(Surface.class);
}
@Test
public void itForwardsSurfaceCreationNotificationToFlutterJNI() {
// Setup the test.
Surface fakeSurface = mock(Surface.class);
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
// Execute the behavior under test.
flutterRenderer.startRenderingToSurface(fakeSurface, false);
// Verify the behavior under test.
verify(fakeFlutterJNI, times(1)).onSurfaceCreated(eq(fakeSurface));
}
@Test
public void itForwardsSurfaceChangeNotificationToFlutterJNI() {
// Setup the test.
Surface fakeSurface = mock(Surface.class);
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
flutterRenderer.startRenderingToSurface(fakeSurface, false);
// Execute the behavior under test.
flutterRenderer.surfaceChanged(100, 50);
// Verify the behavior under test.
verify(fakeFlutterJNI, times(1)).onSurfaceChanged(eq(100), eq(50));
}
@Test
public void itForwardsSurfaceDestructionNotificationToFlutterJNI() {
// Setup the test.
Surface fakeSurface = mock(Surface.class);
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
flutterRenderer.startRenderingToSurface(fakeSurface, false);
// Execute the behavior under test.
flutterRenderer.stopRenderingToSurface();
// Verify the behavior under test.
verify(fakeFlutterJNI, times(1)).onSurfaceDestroyed();
}
@Test
public void itStopsRenderingToOneSurfaceBeforeRenderingToANewSurface() {
// Setup the test.
Surface fakeSurface2 = mock(Surface.class);
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
flutterRenderer.startRenderingToSurface(fakeSurface, false);
// Execute behavior under test.
flutterRenderer.startRenderingToSurface(fakeSurface2, false);
// Verify behavior under test.
verify(fakeFlutterJNI, times(1)).onSurfaceDestroyed(); // notification of 1st surface's removal.
}
@Test
public void itStopsRenderingToSurfaceWhenRequested() {
// Setup the test.
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
flutterRenderer.startRenderingToSurface(fakeSurface, false);
// Execute the behavior under test.
flutterRenderer.stopRenderingToSurface();
// Verify behavior under test.
verify(fakeFlutterJNI, times(1)).onSurfaceDestroyed();
}
@Test
public void iStopsRenderingToSurfaceWhenSurfaceAlreadySet() {
// Setup the test.
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
flutterRenderer.startRenderingToSurface(fakeSurface, false);
flutterRenderer.startRenderingToSurface(fakeSurface, false);
// Verify behavior under test.
verify(fakeFlutterJNI, times(1)).onSurfaceDestroyed();
}
@Test
public void itNeverStopsRenderingToSurfaceWhenRequested() {
// Setup the test.
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
flutterRenderer.startRenderingToSurface(fakeSurface, false);
flutterRenderer.startRenderingToSurface(fakeSurface, true);
// Verify behavior under test.
verify(fakeFlutterJNI, never()).onSurfaceDestroyed();
}
@Test
public void itStopsSurfaceTextureCallbackWhenDetached() {
// Setup the test.
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
fakeFlutterJNI.detachFromNativeAndReleaseResources();
FlutterRenderer.SurfaceTextureRegistryEntry entry =
(FlutterRenderer.SurfaceTextureRegistryEntry) flutterRenderer.createSurfaceTexture();
flutterRenderer.startRenderingToSurface(fakeSurface, false);
// Execute the behavior under test.
flutterRenderer.stopRenderingToSurface();
// Verify behavior under test.
verify(fakeFlutterJNI, times(0)).markTextureFrameAvailable(eq(entry.id()));
}
@Test
public void itRegistersExistingSurfaceTexture() {
// Setup the test.
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
fakeFlutterJNI.detachFromNativeAndReleaseResources();
SurfaceTexture surfaceTexture = new SurfaceTexture(0);
// Execute the behavior under test.
FlutterRenderer.SurfaceTextureRegistryEntry entry =
(FlutterRenderer.SurfaceTextureRegistryEntry)
flutterRenderer.registerSurfaceTexture(surfaceTexture);
flutterRenderer.startRenderingToSurface(fakeSurface, false);
// Verify behavior under test.
assertEquals(surfaceTexture, entry.surfaceTexture());
verify(fakeFlutterJNI, times(1)).registerTexture(eq(entry.id()), eq(entry.textureWrapper()));
}
@Test
public void itUnregistersTextureWhenSurfaceTextureFinalized() {
// Setup the test.
FlutterJNI fakeFlutterJNI = mock(FlutterJNI.class);
when(fakeFlutterJNI.isAttached()).thenReturn(true);
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
fakeFlutterJNI.detachFromNativeAndReleaseResources();
FlutterRenderer.SurfaceTextureRegistryEntry entry =
(FlutterRenderer.SurfaceTextureRegistryEntry) flutterRenderer.createSurfaceTexture();
long id = entry.id();
flutterRenderer.startRenderingToSurface(fakeSurface, false);
// Execute the behavior under test.
runFinalization(entry);
shadowOf(Looper.getMainLooper()).idle();
flutterRenderer.stopRenderingToSurface();
// Verify behavior under test.
verify(fakeFlutterJNI, times(1)).unregisterTexture(eq(id));
}
@Test
public void itStopsUnregisteringTextureWhenDetached() {
// Setup the test.
FlutterJNI fakeFlutterJNI = mock(FlutterJNI.class);
when(fakeFlutterJNI.isAttached()).thenReturn(false);
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
fakeFlutterJNI.detachFromNativeAndReleaseResources();
FlutterRenderer.SurfaceTextureRegistryEntry entry =
(FlutterRenderer.SurfaceTextureRegistryEntry) flutterRenderer.createSurfaceTexture();
long id = entry.id();
flutterRenderer.startRenderingToSurface(fakeSurface, false);
flutterRenderer.stopRenderingToSurface();
// Execute the behavior under test.
runFinalization(entry);
shadowOf(Looper.getMainLooper()).idle();
// Verify behavior under test.
verify(fakeFlutterJNI, times(0)).unregisterTexture(eq(id));
}
void runFinalization(FlutterRenderer.SurfaceTextureRegistryEntry entry) {
CountDownLatch latch = new CountDownLatch(1);
Thread fakeFinalizer =
new Thread(
new Runnable() {
public void run() {
try {
entry.finalize();
latch.countDown();
} catch (Throwable e) {
// do nothing
}
}
});
fakeFinalizer.start();
try {
latch.await();
} catch (InterruptedException e) {
// do nothing
}
}
@Test
public void itConvertsDisplayFeatureArrayToPrimitiveArrays() {
// Setup the test.
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
FlutterRenderer.ViewportMetrics metrics = new FlutterRenderer.ViewportMetrics();
metrics.width = 1000;
metrics.height = 1000;
metrics.devicePixelRatio = 2;
metrics.displayFeatures.add(
new FlutterRenderer.DisplayFeature(
new Rect(10, 20, 30, 40),
FlutterRenderer.DisplayFeatureType.FOLD,
FlutterRenderer.DisplayFeatureState.POSTURE_HALF_OPENED));
metrics.displayFeatures.add(
new FlutterRenderer.DisplayFeature(
new Rect(50, 60, 70, 80), FlutterRenderer.DisplayFeatureType.CUTOUT));
// Execute the behavior under test.
flutterRenderer.setViewportMetrics(metrics);
// Verify behavior under test.
ArgumentCaptor<int[]> boundsCaptor = ArgumentCaptor.forClass(int[].class);
ArgumentCaptor<int[]> typeCaptor = ArgumentCaptor.forClass(int[].class);
ArgumentCaptor<int[]> stateCaptor = ArgumentCaptor.forClass(int[].class);
verify(fakeFlutterJNI)
.setViewportMetrics(
anyFloat(),
anyInt(),
anyInt(),
anyInt(),
anyInt(),
anyInt(),
anyInt(),
anyInt(),
anyInt(),
anyInt(),
anyInt(),
anyInt(),
anyInt(),
anyInt(),
anyInt(),
anyInt(),
boundsCaptor.capture(),
typeCaptor.capture(),
stateCaptor.capture());
assertArrayEquals(new int[] {10, 20, 30, 40, 50, 60, 70, 80}, boundsCaptor.getValue());
assertArrayEquals(
new int[] {
FlutterRenderer.DisplayFeatureType.FOLD.encodedValue,
FlutterRenderer.DisplayFeatureType.CUTOUT.encodedValue
},
typeCaptor.getValue());
assertArrayEquals(
new int[] {
FlutterRenderer.DisplayFeatureState.POSTURE_HALF_OPENED.encodedValue,
FlutterRenderer.DisplayFeatureState.UNKNOWN.encodedValue
},
stateCaptor.getValue());
}
@Test
public void itNotifyImageFrameListener() {
// Setup the test.
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
AtomicInteger invocationCount = new AtomicInteger(0);
final TextureRegistry.OnFrameConsumedListener listener =
new TextureRegistry.OnFrameConsumedListener() {
@Override
public void onFrameConsumed() {
invocationCount.incrementAndGet();
}
};
FlutterRenderer.SurfaceTextureRegistryEntry entry =
(FlutterRenderer.SurfaceTextureRegistryEntry) flutterRenderer.createSurfaceTexture();
entry.setOnFrameConsumedListener(listener);
// Execute the behavior under test.
entry.textureWrapper().updateTexImage();
// Verify behavior under test.
assertEquals(1, invocationCount.get());
}
@Test
public void itAddsListenerWhenSurfaceTextureEntryCreated() {
// Setup the test.
FlutterRenderer flutterRenderer = spy(new FlutterRenderer(fakeFlutterJNI));
// Execute the behavior under test.
FlutterRenderer.SurfaceTextureRegistryEntry entry =
(FlutterRenderer.SurfaceTextureRegistryEntry) flutterRenderer.createSurfaceTexture();
// Verify behavior under test.
verify(flutterRenderer, times(1)).addOnTrimMemoryListener(entry);
}
@Test
public void itRemovesListenerWhenSurfaceTextureEntryReleased() {
// Setup the test.
FlutterRenderer flutterRenderer = spy(new FlutterRenderer(fakeFlutterJNI));
FlutterRenderer.SurfaceTextureRegistryEntry entry =
(FlutterRenderer.SurfaceTextureRegistryEntry) flutterRenderer.createSurfaceTexture();
// Execute the behavior under test.
entry.release();
// Verify behavior under test.
verify(flutterRenderer, times(1)).removeOnTrimMemoryListener(entry);
}
@Test
public void itNotifySurfaceTextureEntryWhenMemoryPressureWarning() {
// Setup the test.
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
AtomicInteger invocationCount = new AtomicInteger(0);
final TextureRegistry.OnTrimMemoryListener listener =
new TextureRegistry.OnTrimMemoryListener() {
@Override
public void onTrimMemory(int level) {
invocationCount.incrementAndGet();
}
};
FlutterRenderer.SurfaceTextureRegistryEntry entry =
(FlutterRenderer.SurfaceTextureRegistryEntry) flutterRenderer.createSurfaceTexture();
entry.setOnTrimMemoryListener(listener);
// Execute the behavior under test.
flutterRenderer.onTrimMemory(TRIM_MEMORY_COMPLETE);
// Verify behavior under test.
assertEquals(1, invocationCount.get());
}
@Test
public void itDoesDispatchSurfaceDestructionNotificationOnlyOnce() {
// Setup the test.
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
flutterRenderer.startRenderingToSurface(fakeSurface, false);
// Execute the behavior under test.
// Simulate calling |FlutterRenderer#stopRenderingToSurface| twice with different code paths.
flutterRenderer.stopRenderingToSurface();
flutterRenderer.stopRenderingToSurface();
// Verify behavior under test.
verify(fakeFlutterJNI, times(1)).onSurfaceDestroyed();
}
@Test
public void itInvokesCreatesSurfaceWhenStartingRendering() {
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
flutterRenderer.startRenderingToSurface(fakeSurface, false);
verify(fakeFlutterJNI, times(1)).onSurfaceCreated(eq(fakeSurface));
}
@Test
public void itDoesNotInvokeCreatesSurfaceWhenResumingRendering() {
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
// The following call sequence mimics the behaviour of FlutterView when it exits from hybrid
// composition mode.
// Install initial rendering surface.
flutterRenderer.startRenderingToSurface(fakeSurface, false);
verify(fakeFlutterJNI, times(1)).onSurfaceCreated(eq(fakeSurface));
verify(fakeFlutterJNI, times(0)).onSurfaceWindowChanged(eq(fakeSurface));
// Install the image view.
flutterRenderer.startRenderingToSurface(fakeSurface2, true);
verify(fakeFlutterJNI, times(1)).onSurfaceCreated(eq(fakeSurface));
verify(fakeFlutterJNI, times(0)).onSurfaceWindowChanged(eq(fakeSurface));
verify(fakeFlutterJNI, times(0)).onSurfaceCreated(eq(fakeSurface2));
verify(fakeFlutterJNI, times(1)).onSurfaceWindowChanged(eq(fakeSurface2));
flutterRenderer.startRenderingToSurface(fakeSurface, true);
verify(fakeFlutterJNI, times(1)).onSurfaceCreated(eq(fakeSurface));
verify(fakeFlutterJNI, times(1)).onSurfaceWindowChanged(eq(fakeSurface));
verify(fakeFlutterJNI, times(0)).onSurfaceCreated(eq(fakeSurface2));
verify(fakeFlutterJNI, times(1)).onSurfaceWindowChanged(eq(fakeSurface2));
}
@Test
public void ImageReaderSurfaceProducerProducesImageOfCorrectSize() {
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
FlutterRenderer.ImageReaderSurfaceProducer texture =
flutterRenderer.new ImageReaderSurfaceProducer(0);
texture.disableFenceForTest();
// Returns a null image when one hasn't been produced.
assertNull(texture.acquireLatestImage());
// Give the texture an initial size.
texture.setSize(1, 1);
// Render a frame.
Surface surface = texture.getSurface();
assertNotNull(surface);
Canvas canvas = surface.lockHardwareCanvas();
canvas.drawARGB(255, 255, 0, 0);
surface.unlockCanvasAndPost(canvas);
// Let callbacks run.
shadowOf(Looper.getMainLooper()).idle();
// Extract the image and check its size.
Image image = texture.acquireLatestImage();
assertEquals(1, image.getWidth());
assertEquals(1, image.getHeight());
image.close();
// Resize the texture.
texture.setSize(5, 5);
// Render a frame.
surface = texture.getSurface();
assertNotNull(surface);
canvas = surface.lockHardwareCanvas();
canvas.drawARGB(255, 255, 0, 0);
surface.unlockCanvasAndPost(canvas);
// Let callbacks run.
shadowOf(Looper.getMainLooper()).idle();
// Extract the image and check its size.
image = texture.acquireLatestImage();
assertEquals(5, image.getWidth());
assertEquals(5, image.getHeight());
image.close();
assertNull(texture.acquireLatestImage());
texture.release();
}
@Test
public void ImageReaderSurfaceProducerDoesNotDropFramesWhenResizeInflight() {
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
FlutterRenderer.ImageReaderSurfaceProducer texture =
flutterRenderer.new ImageReaderSurfaceProducer(0);
texture.disableFenceForTest();
// Returns a null image when one hasn't been produced.
assertNull(texture.acquireLatestImage());
// Give the texture an initial size.
texture.setSize(1, 1);
// Render a frame.
Surface surface = texture.getSurface();
assertNotNull(surface);
Canvas canvas = surface.lockHardwareCanvas();
canvas.drawARGB(255, 255, 0, 0);
surface.unlockCanvasAndPost(canvas);
// Resize.
texture.setSize(4, 4);
// Let callbacks run. The rendered frame will manifest here.
shadowOf(Looper.getMainLooper()).idle();
// We acquired the frame produced above.
assertNotNull(texture.acquireLatestImage());
}
@Test
public void ImageReaderSurfaceProducerImageReadersAndImagesCount() {
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
FlutterRenderer.ImageReaderSurfaceProducer texture =
flutterRenderer.new ImageReaderSurfaceProducer(0);
texture.disableFenceForTest();
// Returns a null image when one hasn't been produced.
assertNull(texture.acquireLatestImage());
// Give the texture an initial size.
texture.setSize(1, 1);
// Grab the surface so we can render a frame at 1x1 after resizing.
Surface surface = texture.getSurface();
assertNotNull(surface);
Canvas canvas = surface.lockHardwareCanvas();
canvas.drawARGB(255, 255, 0, 0);
surface.unlockCanvasAndPost(canvas);
// Let callbacks run, this will produce a single frame.
shadowOf(Looper.getMainLooper()).idle();
assertEquals(1, texture.numImageReaders());
assertEquals(1, texture.numImages());
// Resize.
texture.setSize(4, 4);
// Render a frame at the old size (by using the pre-resized Surface)
canvas = surface.lockHardwareCanvas();
canvas.drawARGB(255, 255, 0, 0);
surface.unlockCanvasAndPost(canvas);
// Let callbacks run.
shadowOf(Looper.getMainLooper()).idle();
assertEquals(1, texture.numImageReaders());
assertEquals(2, texture.numImages());
// Render a new frame with the current size.
surface = texture.getSurface();
assertNotNull(surface);
canvas = surface.lockHardwareCanvas();
canvas.drawARGB(255, 255, 0, 0);
surface.unlockCanvasAndPost(canvas);
// Let callbacks run.
shadowOf(Looper.getMainLooper()).idle();
assertEquals(2, texture.numImageReaders());
assertEquals(3, texture.numImages());
// Acquire first frame.
Image produced = texture.acquireLatestImage();
assertNotNull(produced);
assertEquals(1, produced.getWidth());
assertEquals(1, produced.getHeight());
assertEquals(2, texture.numImageReaders());
assertEquals(2, texture.numImages());
// Acquire second frame. This won't result in the first reader being closed because it has
// an active image from it.
produced = texture.acquireLatestImage();
assertNotNull(produced);
assertEquals(1, produced.getWidth());
assertEquals(1, produced.getHeight());
assertEquals(2, texture.numImageReaders());
assertEquals(1, texture.numImages());
// Acquire third frame. We will now close the first reader.
produced = texture.acquireLatestImage();
assertNotNull(produced);
assertEquals(4, produced.getWidth());
assertEquals(4, produced.getHeight());
assertEquals(1, texture.numImageReaders());
assertEquals(0, texture.numImages());
// Returns null image when no more images are queued.
assertNull(texture.acquireLatestImage());
assertEquals(1, texture.numImageReaders());
assertEquals(0, texture.numImages());
}
@Test
public void ImageReaderSurfaceProducerTrimMemoryCallback() {
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
FlutterRenderer.ImageReaderSurfaceProducer texture =
flutterRenderer.new ImageReaderSurfaceProducer(0);
texture.disableFenceForTest();
// Returns a null image when one hasn't been produced.
assertNull(texture.acquireLatestImage());
// Give the texture an initial size.
texture.setSize(1, 1);
// Grab the surface so we can render a frame at 1x1 after resizing.
Surface surface = texture.getSurface();
assertNotNull(surface);
Canvas canvas = surface.lockHardwareCanvas();
canvas.drawARGB(255, 255, 0, 0);
surface.unlockCanvasAndPost(canvas);
// Let callbacks run, this will produce a single frame.
shadowOf(Looper.getMainLooper()).idle();
assertEquals(1, texture.numImageReaders());
assertEquals(1, texture.numImages());
// Invoke the onTrimMemory callback.
// This should do nothing.
texture.onTrimMemory(0);
shadowOf(Looper.getMainLooper()).idle();
assertEquals(1, texture.numImageReaders());
assertEquals(1, texture.numImages());
}
// A 0x0 ImageReader is a runtime error.
@Test
public void ImageReaderSurfaceProducerClampsWidthAndHeightTo1() {
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
FlutterRenderer.ImageReaderSurfaceProducer texture =
flutterRenderer.new ImageReaderSurfaceProducer(0);
// Default values.
assertEquals(texture.getWidth(), 1);
assertEquals(texture.getHeight(), 1);
// Try setting width and height to 0.
texture.setSize(0, 0);
// Ensure we can still create/get a surface without an exception being raised.
assertNotNull(texture.getSurface());
// Expect clamp to 1.
assertEquals(texture.getWidth(), 1);
assertEquals(texture.getHeight(), 1);
}
@Test
public void SurfaceTextureSurfaceProducerCreatesAConnectedTexture() {
// Force creating a SurfaceTextureSurfaceProducer regardless of Android API version.
FlutterRenderer.debugForceSurfaceProducerGlTextures = true;
FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI);
TextureRegistry.SurfaceProducer producer = flutterRenderer.createSurfaceProducer();
flutterRenderer.startRenderingToSurface(fakeSurface, false);
// Verify behavior under test.
assertEquals(producer.id(), 0);
verify(fakeFlutterJNI, times(1)).registerTexture(eq(producer.id()), any());
}
}
| engine/shell/platform/android/test/io/flutter/embedding/engine/renderer/FlutterRendererTest.java/0 | {
"file_path": "engine/shell/platform/android/test/io/flutter/embedding/engine/renderer/FlutterRendererTest.java",
"repo_id": "engine",
"token_count": 8560
} | 304 |
package io.flutter.plugin.common;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import android.text.SpannableString;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
@Config(manifest = Config.NONE)
@RunWith(AndroidJUnit4.class)
public class StandardMessageCodecTest {
// Data types defined as per StandardMessageCodec.Java
// XXX Please consider exposing these so that tests can access them
private static final byte NULL = 0;
private static final byte TRUE = 1;
private static final byte FALSE = 2;
private static final byte INT = 3;
private static final byte LONG = 4;
private static final byte BIGINT = 5;
private static final byte DOUBLE = 6;
private static final byte STRING = 7;
private static final byte BYTE_ARRAY = 8;
private static final byte INT_ARRAY = 9;
private static final byte LONG_ARRAY = 10;
private static final byte DOUBLE_ARRAY = 11;
private static final byte LIST = 12;
private static final byte MAP = 13;
private static final byte FLOAT_ARRAY = 14;
@Test
public void itEncodesNullLiterals() {
// Setup message codec
StandardMessageCodec codec = new StandardMessageCodec();
// Attempt to encode message with a null literal inside a list
// A list with a null is used instead of just a null literal because if
// only null is encoded, then no message is returned; null is returned instead
ArrayList<Object> messageContent = new ArrayList();
messageContent.add(null);
ByteBuffer message = codec.encodeMessage(messageContent);
message.flip();
ByteBuffer expected = ByteBuffer.allocateDirect(3);
expected.put(new byte[] {LIST, 1, NULL});
expected.flip();
assertEquals(expected, message);
}
@Test
public void itEncodesNullObjects() {
// An example class that equals null
class ExampleNullObject {
@Override
public boolean equals(Object other) {
return other == null || other == this;
}
@Override
public int hashCode() {
return 0;
}
}
// Setup message codec
StandardMessageCodec codec = new StandardMessageCodec();
// Same as itEncodesNullLiterals but with objects that equal null instead
ArrayList<Object> messageContent = new ArrayList();
messageContent.add(new ExampleNullObject());
ByteBuffer message = codec.encodeMessage(messageContent);
message.flip();
ByteBuffer expected = ByteBuffer.allocateDirect(3);
expected.put(new byte[] {LIST, 1, NULL});
expected.flip();
assertEquals(expected, message);
}
@Test
@SuppressWarnings("deprecation")
public void itEncodesBooleans() {
// Setup message codec
StandardMessageCodec codec = new StandardMessageCodec();
ArrayList<Object> messageContent = new ArrayList();
// Test handling of Boolean objects other than the static TRUE and FALSE constants.
messageContent.add(new Boolean(true));
messageContent.add(new Boolean(false));
ByteBuffer message = codec.encodeMessage(messageContent);
message.flip();
ByteBuffer expected = ByteBuffer.allocateDirect(4);
expected.put(new byte[] {LIST, 2, TRUE, FALSE});
expected.flip();
assertEquals(expected, message);
}
@Test
public void itEncodesFloatArrays() {
StandardMessageCodec codec = new StandardMessageCodec();
float[] expectedValues = new float[] {1.0f, 2.2f, 5.3f};
ByteBuffer message = codec.encodeMessage(expectedValues);
message.flip();
float[] values = (float[]) codec.decodeMessage(message);
assertArrayEquals(expectedValues, values, 0.01f);
}
@Test
public void itEncodesCharSequences() {
StandardMessageCodec codec = new StandardMessageCodec();
CharSequence cs = new SpannableString("hello world");
ByteBuffer message = codec.encodeMessage(cs);
message.flip();
String value = (String) codec.decodeMessage(message);
assertEquals(value, "hello world");
}
private static class NotEncodable {
@Override
public String toString() {
return "not encodable";
}
}
@Test
public void errorHasType() {
StandardMessageCodec codec = new StandardMessageCodec();
NotEncodable notEncodable = new NotEncodable();
Exception exception =
assertThrows(
IllegalArgumentException.class,
() -> {
codec.encodeMessage(notEncodable);
});
assertTrue(exception.getMessage().contains("NotEncodable"));
}
}
| engine/shell/platform/android/test/io/flutter/plugin/common/StandardMessageCodecTest.java/0 | {
"file_path": "engine/shell/platform/android/test/io/flutter/plugin/common/StandardMessageCodecTest.java",
"repo_id": "engine",
"token_count": 1538
} | 305 |
// Copyright 2013 The Flutter 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.plugin.platform;
import static io.flutter.Build.API_LEVELS;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.SurfaceTexture;
import android.view.Surface;
import android.view.View;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import io.flutter.view.TextureRegistry.SurfaceTextureEntry;
import org.junit.Test;
import org.junit.runner.RunWith;
@TargetApi(API_LEVELS.API_31)
@RunWith(AndroidJUnit4.class)
public class SurfaceTexturePlatformViewRenderTargetTest {
private final Context ctx = ApplicationProvider.getApplicationContext();
@Test
public void viewDraw_writesToBuffer() {
final Canvas canvas = mock(Canvas.class);
final Surface surface = mock(Surface.class);
when(surface.lockHardwareCanvas()).thenReturn(canvas);
when(surface.isValid()).thenReturn(true);
final SurfaceTexture surfaceTexture = mock(SurfaceTexture.class);
final SurfaceTextureEntry surfaceTextureEntry = mock(SurfaceTextureEntry.class);
when(surfaceTextureEntry.surfaceTexture()).thenReturn(surfaceTexture);
when(surfaceTexture.isReleased()).thenReturn(false);
final SurfaceTexturePlatformViewRenderTarget renderTarget =
new SurfaceTexturePlatformViewRenderTarget(surfaceTextureEntry) {
@Override
protected Surface createSurface() {
return surface;
}
};
// Custom view.
final View platformView =
new View(ctx) {
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
canvas.drawColor(Color.RED);
}
};
final int size = 100;
platformView.measure(size, size);
platformView.layout(0, 0, size, size);
// Test.
final Surface s = renderTarget.getSurface();
final Canvas c = s.lockHardwareCanvas();
platformView.draw(c);
s.unlockCanvasAndPost(c);
// Verify.
verify(canvas, times(1)).drawColor(Color.RED);
verify(surface, times(1)).lockHardwareCanvas();
verify(surface, times(1)).unlockCanvasAndPost(canvas);
verifyNoMoreInteractions(surface);
}
@Test
public void release() {
final Canvas canvas = mock(Canvas.class);
final Surface surface = mock(Surface.class);
when(surface.lockHardwareCanvas()).thenReturn(canvas);
when(surface.isValid()).thenReturn(true);
final SurfaceTexture surfaceTexture = mock(SurfaceTexture.class);
final SurfaceTextureEntry surfaceTextureEntry = mock(SurfaceTextureEntry.class);
when(surfaceTextureEntry.surfaceTexture()).thenReturn(surfaceTexture);
when(surfaceTexture.isReleased()).thenReturn(false);
final SurfaceTexturePlatformViewRenderTarget renderTarget =
new SurfaceTexturePlatformViewRenderTarget(surfaceTextureEntry) {
@Override
protected Surface createSurface() {
return surface;
}
};
final Surface s = renderTarget.getSurface();
final Canvas c = s.lockHardwareCanvas();
s.unlockCanvasAndPost(c);
reset(surface);
reset(surfaceTexture);
// Test.
renderTarget.release();
// Verify.
verify(surface, times(1)).release();
verifyNoMoreInteractions(surface);
verifyNoMoreInteractions(surfaceTexture);
}
}
| engine/shell/platform/android/test/io/flutter/plugin/platform/SurfaceTexturePlatformViewRenderTargetTest.java/0 | {
"file_path": "engine/shell/platform/android/test/io/flutter/plugin/platform/SurfaceTexturePlatformViewRenderTargetTest.java",
"repo_id": "engine",
"token_count": 1259
} | 306 |
sdk=33
shadows=io.flutter.CustomShadowContextImpl
| engine/shell/platform/android/test_runner/src/main/resources/robolectric.properties/0 | {
"file_path": "engine/shell/platform/android/test_runner/src/main/resources/robolectric.properties",
"repo_id": "engine",
"token_count": 18
} | 307 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
core_cpp_client_wrapper_includes =
get_path_info([
"include/flutter/basic_message_channel.h",
"include/flutter/binary_messenger.h",
"include/flutter/byte_streams.h",
"include/flutter/encodable_value.h",
"include/flutter/engine_method_result.h",
"include/flutter/event_channel.h",
"include/flutter/event_sink.h",
"include/flutter/event_stream_handler_functions.h",
"include/flutter/event_stream_handler.h",
"include/flutter/message_codec.h",
"include/flutter/method_call.h",
"include/flutter/method_channel.h",
"include/flutter/method_codec.h",
"include/flutter/method_result_functions.h",
"include/flutter/method_result.h",
"include/flutter/plugin_registrar.h",
"include/flutter/plugin_registry.h",
"include/flutter/standard_codec_serializer.h",
"include/flutter/standard_message_codec.h",
"include/flutter/standard_method_codec.h",
"include/flutter/texture_registrar.h",
],
"abspath")
# Headers that aren't public for clients of the wrapper, but are considered
# public for the purpose of BUILD dependencies (e.g., to allow
# windows/client_wrapper implementation files to include them).
core_cpp_client_wrapper_internal_headers =
get_path_info([
"binary_messenger_impl.h",
"byte_buffer_streams.h",
"texture_registrar_impl.h",
],
"abspath")
# TODO: Once the wrapper API is more stable, consolidate to as few files as is
# reasonable (without forcing different kinds of clients to take unnecessary
# code) to simplify use.
core_cpp_client_wrapper_sources = get_path_info([
"core_implementations.cc",
"plugin_registrar.cc",
"standard_codec.cc",
],
"abspath")
# Temporary shim, published for backwards compatibility.
# See comment in the file for more detail.
temporary_shim_files = get_path_info([ "engine_method_result.cc" ], "abspath")
| engine/shell/platform/common/client_wrapper/core_wrapper_files.gni/0 | {
"file_path": "engine/shell/platform/common/client_wrapper/core_wrapper_files.gni",
"repo_id": "engine",
"token_count": 1408
} | 308 |
// Copyright 2013 The Flutter 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_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CODEC_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CODEC_H_
#include <memory>
#include <string>
#include <vector>
#include "method_call.h"
#include "method_result.h"
namespace flutter {
// Translates between a binary message and higher-level method call and
// response/error objects.
template <typename T>
class MethodCodec {
public:
MethodCodec() = default;
virtual ~MethodCodec() = default;
// Prevent copying.
MethodCodec(MethodCodec<T> const&) = delete;
MethodCodec& operator=(MethodCodec<T> const&) = delete;
// Returns the MethodCall encoded in |message|, or nullptr if it cannot be
// decoded.
std::unique_ptr<MethodCall<T>> DecodeMethodCall(const uint8_t* message,
size_t message_size) const {
return std::move(DecodeMethodCallInternal(message, message_size));
}
// Returns the MethodCall encoded in |message|, or nullptr if it cannot be
// decoded.
std::unique_ptr<MethodCall<T>> DecodeMethodCall(
const std::vector<uint8_t>& message) const {
size_t size = message.size();
const uint8_t* data = size > 0 ? &message[0] : nullptr;
return std::move(DecodeMethodCallInternal(data, size));
}
// Returns a binary encoding of the given |method_call|, or nullptr if the
// method call cannot be serialized by this codec.
std::unique_ptr<std::vector<uint8_t>> EncodeMethodCall(
const MethodCall<T>& method_call) const {
return std::move(EncodeMethodCallInternal(method_call));
}
// Returns a binary encoding of |result|. |result| must be a type supported
// by the codec.
std::unique_ptr<std::vector<uint8_t>> EncodeSuccessEnvelope(
const T* result = nullptr) const {
return std::move(EncodeSuccessEnvelopeInternal(result));
}
// Returns a binary encoding of |error|. The |error_details| must be a type
// supported by the codec.
std::unique_ptr<std::vector<uint8_t>> EncodeErrorEnvelope(
const std::string& error_code,
const std::string& error_message = "",
const T* error_details = nullptr) const {
return std::move(
EncodeErrorEnvelopeInternal(error_code, error_message, error_details));
}
// Decodes the response envelope encoded in |response|, calling the
// appropriate method on |result|.
//
// Returns false if |response| cannot be decoded. In that case the caller is
// responsible for calling a |result| method.
bool DecodeAndProcessResponseEnvelope(const uint8_t* response,
size_t response_size,
MethodResult<T>* result) const {
return DecodeAndProcessResponseEnvelopeInternal(response, response_size,
result);
}
protected:
// Implementation of the public interface, to be provided by subclasses.
virtual std::unique_ptr<MethodCall<T>> DecodeMethodCallInternal(
const uint8_t* message,
size_t message_size) const = 0;
// Implementation of the public interface, to be provided by subclasses.
virtual std::unique_ptr<std::vector<uint8_t>> EncodeMethodCallInternal(
const MethodCall<T>& method_call) const = 0;
// Implementation of the public interface, to be provided by subclasses.
virtual std::unique_ptr<std::vector<uint8_t>> EncodeSuccessEnvelopeInternal(
const T* result) const = 0;
// Implementation of the public interface, to be provided by subclasses.
virtual std::unique_ptr<std::vector<uint8_t>> EncodeErrorEnvelopeInternal(
const std::string& error_code,
const std::string& error_message,
const T* error_details) const = 0;
// Implementation of the public interface, to be provided by subclasses.
virtual bool DecodeAndProcessResponseEnvelopeInternal(
const uint8_t* response,
size_t response_size,
MethodResult<T>* result) const = 0;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CODEC_H_
| engine/shell/platform/common/client_wrapper/include/flutter/method_codec.h/0 | {
"file_path": "engine/shell/platform/common/client_wrapper/include/flutter/method_codec.h",
"repo_id": "engine",
"token_count": 1530
} | 309 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/common/client_wrapper/include/flutter/standard_message_codec.h"
#include <map>
#include <vector>
#include "flutter/shell/platform/common/client_wrapper/testing/test_codec_extensions.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace flutter {
namespace {
class MockStandardCodecSerializer : public StandardCodecSerializer {
public:
MOCK_METHOD(void,
WriteValue,
(const EncodableValue& value, ByteStreamWriter* stream),
(const, override));
MOCK_METHOD(EncodableValue,
ReadValueOfType,
(uint8_t type, ByteStreamReader* stream),
(const, override));
};
} // namespace
// Validates round-trip encoding and decoding of |value|, and checks that the
// encoded value matches |expected_encoding|.
//
// If testing with CustomEncodableValues, |serializer| must be provided to
// handle the encoding/decoding, and |custom_comparator| must be provided to
// validate equality since CustomEncodableValue doesn't define a useful ==.
static void CheckEncodeDecode(
const EncodableValue& value,
const std::vector<uint8_t>& expected_encoding,
const StandardCodecSerializer* serializer = nullptr,
const std::function<bool(const EncodableValue& a, const EncodableValue& b)>&
custom_comparator = nullptr) {
const StandardMessageCodec& codec =
StandardMessageCodec::GetInstance(serializer);
auto encoded = codec.EncodeMessage(value);
ASSERT_TRUE(encoded);
EXPECT_EQ(*encoded, expected_encoding);
auto decoded = codec.DecodeMessage(*encoded);
if (custom_comparator) {
EXPECT_TRUE(custom_comparator(value, *decoded));
} else {
EXPECT_EQ(value, *decoded);
}
}
// Validates round-trip encoding and decoding of |value|, and checks that the
// encoded value has the given prefix and length.
//
// This should be used only for Map, where asserting the order of the elements
// in a test is undesirable.
static void CheckEncodeDecodeWithEncodePrefix(
const EncodableValue& value,
const std::vector<uint8_t>& expected_encoding_prefix,
size_t expected_encoding_length) {
EXPECT_TRUE(std::holds_alternative<EncodableMap>(value));
const StandardMessageCodec& codec = StandardMessageCodec::GetInstance();
auto encoded = codec.EncodeMessage(value);
ASSERT_TRUE(encoded);
EXPECT_EQ(encoded->size(), expected_encoding_length);
ASSERT_GT(encoded->size(), expected_encoding_prefix.size());
EXPECT_TRUE(std::equal(
encoded->begin(), encoded->begin() + expected_encoding_prefix.size(),
expected_encoding_prefix.begin(), expected_encoding_prefix.end()));
auto decoded = codec.DecodeMessage(*encoded);
EXPECT_EQ(value, *decoded);
}
TEST(StandardMessageCodec, GetInstanceCachesInstance) {
const StandardMessageCodec& codec_a =
StandardMessageCodec::GetInstance(nullptr);
const StandardMessageCodec& codec_b =
StandardMessageCodec::GetInstance(nullptr);
EXPECT_EQ(&codec_a, &codec_b);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeNull) {
std::vector<uint8_t> bytes = {0x00};
CheckEncodeDecode(EncodableValue(), bytes);
}
TEST(StandardMessageCodec, CanDecodeEmptyBytesAsNullWithoutCallingSerializer) {
std::vector<uint8_t> bytes = {};
const MockStandardCodecSerializer serializer;
const StandardMessageCodec& codec =
StandardMessageCodec::GetInstance(&serializer);
auto decoded = codec.DecodeMessage(bytes);
EXPECT_EQ(EncodableValue(), *decoded);
EXPECT_CALL(serializer, ReadValueOfType(::testing::_, ::testing::_)).Times(0);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeTrue) {
std::vector<uint8_t> bytes = {0x01};
CheckEncodeDecode(EncodableValue(true), bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeFalse) {
std::vector<uint8_t> bytes = {0x02};
CheckEncodeDecode(EncodableValue(false), bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeInt32) {
std::vector<uint8_t> bytes = {0x03, 0x78, 0x56, 0x34, 0x12};
CheckEncodeDecode(EncodableValue(0x12345678), bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeInt64) {
std::vector<uint8_t> bytes = {0x04, 0xef, 0xcd, 0xab, 0x90,
0x78, 0x56, 0x34, 0x12};
CheckEncodeDecode(EncodableValue(INT64_C(0x1234567890abcdef)), bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeDouble) {
std::vector<uint8_t> bytes = {0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x2d, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40};
CheckEncodeDecode(EncodableValue(3.14159265358979311599796346854), bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeString) {
std::vector<uint8_t> bytes = {0x07, 0x0b, 0x68, 0x65, 0x6c, 0x6c, 0x6f,
0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64};
CheckEncodeDecode(EncodableValue(u8"hello world"), bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeStringWithNonAsciiCodePoint) {
std::vector<uint8_t> bytes = {0x07, 0x05, 0x68, 0xe2, 0x98, 0xba, 0x77};
CheckEncodeDecode(EncodableValue(u8"h\u263Aw"), bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeStringWithNonBMPCodePoint) {
std::vector<uint8_t> bytes = {0x07, 0x06, 0x68, 0xf0, 0x9f, 0x98, 0x82, 0x77};
CheckEncodeDecode(EncodableValue(u8"h\U0001F602w"), bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeEmptyString) {
std::vector<uint8_t> bytes = {0x07, 0x00};
CheckEncodeDecode(EncodableValue(u8""), bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeList) {
std::vector<uint8_t> bytes = {
0x0c, 0x05, 0x00, 0x07, 0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x06,
0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x85, 0xeb, 0x51, 0xb8, 0x1e,
0x09, 0x40, 0x03, 0x2f, 0x00, 0x00, 0x00, 0x0c, 0x02, 0x03, 0x2a,
0x00, 0x00, 0x00, 0x07, 0x06, 0x6e, 0x65, 0x73, 0x74, 0x65, 0x64,
};
EncodableValue value(EncodableList{
EncodableValue(),
EncodableValue("hello"),
EncodableValue(3.14),
EncodableValue(47),
EncodableValue(EncodableList{
EncodableValue(42),
EncodableValue("nested"),
}),
});
CheckEncodeDecode(value, bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeEmptyList) {
std::vector<uint8_t> bytes = {0x0c, 0x00};
CheckEncodeDecode(EncodableValue(EncodableList{}), bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeMap) {
std::vector<uint8_t> bytes_prefix = {0x0d, 0x04};
EncodableValue value(EncodableMap{
{EncodableValue("a"), EncodableValue(3.14)},
{EncodableValue("b"), EncodableValue(47)},
{EncodableValue(), EncodableValue()},
{EncodableValue(3.14), EncodableValue(EncodableList{
EncodableValue("nested"),
})},
});
CheckEncodeDecodeWithEncodePrefix(value, bytes_prefix, 48);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeByteArray) {
std::vector<uint8_t> bytes = {0x08, 0x04, 0xba, 0x5e, 0xba, 0x11};
EncodableValue value(std::vector<uint8_t>{0xba, 0x5e, 0xba, 0x11});
CheckEncodeDecode(value, bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeInt32Array) {
std::vector<uint8_t> bytes = {0x09, 0x03, 0x00, 0x00, 0x78, 0x56, 0x34, 0x12,
0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00};
EncodableValue value(std::vector<int32_t>{0x12345678, -1, 0});
CheckEncodeDecode(value, bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeInt64Array) {
std::vector<uint8_t> bytes = {0x0a, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xef, 0xcd, 0xab, 0x90, 0x78, 0x56, 0x34, 0x12,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
EncodableValue value(std::vector<int64_t>{0x1234567890abcdef, -1});
CheckEncodeDecode(value, bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeFloat32Array) {
std::vector<uint8_t> bytes = {0x0e, 0x02, 0x00, 0x00, 0xd8, 0x0f,
0x49, 0x40, 0x00, 0x00, 0x7a, 0x44};
EncodableValue value(std::vector<float>{3.1415920257568359375f, 1000.0f});
CheckEncodeDecode(value, bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeFloat64Array) {
std::vector<uint8_t> bytes = {0x0b, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x2d, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40,
0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x8f, 0x40};
EncodableValue value(
std::vector<double>{3.14159265358979311599796346854, 1000.0});
CheckEncodeDecode(value, bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeSimpleCustomType) {
std::vector<uint8_t> bytes = {0x80, 0x09, 0x00, 0x00, 0x00,
0x10, 0x00, 0x00, 0x00};
auto point_comparator = [](const EncodableValue& a, const EncodableValue& b) {
const Point& a_point =
std::any_cast<Point>(std::get<CustomEncodableValue>(a));
const Point& b_point =
std::any_cast<Point>(std::get<CustomEncodableValue>(b));
return a_point == b_point;
};
CheckEncodeDecode(CustomEncodableValue(Point(9, 16)), bytes,
&PointExtensionSerializer::GetInstance(), point_comparator);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeVariableLengthCustomType) {
std::vector<uint8_t> bytes = {
0x81, // custom type
0x06, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, // data
0x07, 0x04, // string type and length
0x74, 0x65, 0x73, 0x74 // string characters
};
auto some_data_comparator = [](const EncodableValue& a,
const EncodableValue& b) {
const SomeData& data_a =
std::any_cast<SomeData>(std::get<CustomEncodableValue>(a));
const SomeData& data_b =
std::any_cast<SomeData>(std::get<CustomEncodableValue>(b));
return data_a.data() == data_b.data() && data_a.label() == data_b.label();
};
CheckEncodeDecode(CustomEncodableValue(
SomeData("test", {0x00, 0x01, 0x02, 0x03, 0x04, 0x05})),
bytes, &SomeDataExtensionSerializer::GetInstance(),
some_data_comparator);
}
} // namespace flutter
| engine/shell/platform/common/client_wrapper/standard_message_codec_unittests.cc/0 | {
"file_path": "engine/shell/platform/common/client_wrapper/standard_message_codec_unittests.cc",
"repo_id": "engine",
"token_count": 4614
} | 310 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/common/incoming_message_dispatcher.h"
namespace flutter {
IncomingMessageDispatcher::IncomingMessageDispatcher(
FlutterDesktopMessengerRef messenger)
: messenger_(messenger) {}
IncomingMessageDispatcher::~IncomingMessageDispatcher() = default;
/// @note Procedure doesn't copy all closures.
void IncomingMessageDispatcher::HandleMessage(
const FlutterDesktopMessage& message,
const std::function<void(void)>& input_block_cb,
const std::function<void(void)>& input_unblock_cb) {
std::string channel(message.channel);
auto callback_iterator = callbacks_.find(channel);
// Find the handler for the channel; if there isn't one, report the failure.
if (callback_iterator == callbacks_.end()) {
FlutterDesktopMessengerSendResponse(messenger_, message.response_handle,
nullptr, 0);
return;
}
auto& callback_info = callback_iterator->second;
const FlutterDesktopMessageCallback& message_callback = callback_info.first;
// Process the call, handling input blocking if requested.
bool block_input = input_blocking_channels_.count(channel) > 0;
if (block_input) {
input_block_cb();
}
message_callback(messenger_, &message, callback_info.second);
if (block_input) {
input_unblock_cb();
}
}
void IncomingMessageDispatcher::SetMessageCallback(
const std::string& channel,
FlutterDesktopMessageCallback callback,
void* user_data) {
if (!callback) {
callbacks_.erase(channel);
return;
}
callbacks_[channel] = std::make_pair(callback, user_data);
}
void IncomingMessageDispatcher::EnableInputBlockingForChannel(
const std::string& channel) {
input_blocking_channels_.insert(channel);
}
} // namespace flutter
| engine/shell/platform/common/incoming_message_dispatcher.cc/0 | {
"file_path": "engine/shell/platform/common/incoming_message_dispatcher.cc",
"repo_id": "engine",
"token_count": 630
} | 311 |
// Copyright 2013 The Flutter 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_COMMON_PUBLIC_FLUTTER_PLUGIN_REGISTRAR_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_PLUGIN_REGISTRAR_H_
#include <stddef.h>
#include <stdint.h>
#include "flutter_export.h"
#include "flutter_messenger.h"
#include "flutter_texture_registrar.h"
#if defined(__cplusplus)
extern "C" {
#endif // defined(__cplusplus)
// Opaque reference to a plugin registrar.
typedef struct FlutterDesktopPluginRegistrar* FlutterDesktopPluginRegistrarRef;
// Function pointer type for registrar destruction callback.
typedef void (*FlutterDesktopOnPluginRegistrarDestroyed)(
FlutterDesktopPluginRegistrarRef);
// Returns the engine messenger associated with this registrar.
FLUTTER_EXPORT FlutterDesktopMessengerRef
FlutterDesktopPluginRegistrarGetMessenger(
FlutterDesktopPluginRegistrarRef registrar);
// Returns the texture registrar associated with this registrar.
FLUTTER_EXPORT FlutterDesktopTextureRegistrarRef
FlutterDesktopRegistrarGetTextureRegistrar(
FlutterDesktopPluginRegistrarRef registrar);
// Registers a callback to be called when the plugin registrar is destroyed.
FLUTTER_EXPORT void FlutterDesktopPluginRegistrarSetDestructionHandler(
FlutterDesktopPluginRegistrarRef registrar,
FlutterDesktopOnPluginRegistrarDestroyed callback);
#if defined(__cplusplus)
} // extern "C"
#endif
#endif // FLUTTER_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_PLUGIN_REGISTRAR_H_
| engine/shell/platform/common/public/flutter_plugin_registrar.h/0 | {
"file_path": "engine/shell/platform/common/public/flutter_plugin_registrar.h",
"repo_id": "engine",
"token_count": 519
} | 312 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/darwin/common/availability_version_check.h"
#include <cstdint>
#include <optional>
#include <tuple>
#include <CoreFoundation/CoreFoundation.h>
#include <dispatch/dispatch.h>
#include <dlfcn.h>
#include "flutter/fml/build_config.h"
#include "flutter/fml/file.h"
#include "flutter/fml/logging.h"
#include "flutter/fml/mapping.h"
#include "flutter/fml/platform/darwin/cf_utils.h"
// The implementation of _availability_version_check defined in this file is
// based on the code in the clang-rt library at:
//
// https://github.com/llvm/llvm-project/blob/e315bf25a843582de39257e1345408a10dc08224/compiler-rt/lib/builtins/os_version_check.c
//
// Flutter provides its own implementation due to an issue introduced in recent
// versions of Clang following Clang 18 in which the clang-rt library declares
// weak linkage against the _availability_version_check symbol. This declaration
// causes apps to be rejected from the App Store. When Flutter statically links
// the implementation below, the weak linkage is satisfied at Engine build time,
// the symbol is no longer exposed from the Engine dylib, and apps will then
// not be rejected from the App Store.
//
// The implementation of _availability_version_check can delegate to the
// dynamically looked-up symbol on recent iOS versions, but the lookup will fail
// on iOS 11 and 12. When the lookup fails, the current OS version must be
// retrieved from a plist file at a well-known path. The logic for this below is
// copied from the clang-rt implementation and adapted for the Engine.
// See more context in https://github.com/flutter/flutter/issues/132130 and
// https://github.com/flutter/engine/pull/44711.
// TODO(zanderso): Remove this after Clang 18 rolls into Xcode.
// https://github.com/flutter/flutter/issues/133203.
#define CF_PROPERTY_LIST_IMMUTABLE 0
namespace flutter {
// This function parses the platform's version information out of a plist file
// at a well-known path. It parses the plist file using CoreFoundation functions
// to match the implementation in the clang-rt library.
std::optional<ProductVersion> ProductVersionFromSystemVersionPList() {
std::string plist_path = "/System/Library/CoreServices/SystemVersion.plist";
#if FML_OS_IOS_SIMULATOR
char* plist_path_prefix = getenv("IPHONE_SIMULATOR_ROOT");
if (!plist_path_prefix) {
FML_DLOG(ERROR) << "Failed to getenv IPHONE_SIMULATOR_ROOT";
return std::nullopt;
}
plist_path = std::string(plist_path_prefix) + plist_path;
#endif // FML_OS_IOS_SIMULATOR
auto plist_mapping = fml::FileMapping::CreateReadOnly(plist_path);
// Get the file buffer into CF's format. We pass in a null allocator here *
// because we free PListBuf ourselves
auto file_contents = fml::CFRef<CFDataRef>(CFDataCreateWithBytesNoCopy(
nullptr, plist_mapping->GetMapping(),
static_cast<CFIndex>(plist_mapping->GetSize()), kCFAllocatorNull));
if (!file_contents) {
FML_DLOG(ERROR) << "Failed to CFDataCreateWithBytesNoCopyFunc";
return std::nullopt;
}
auto plist = fml::CFRef<CFDictionaryRef>(
reinterpret_cast<CFDictionaryRef>(CFPropertyListCreateWithData(
nullptr, file_contents, CF_PROPERTY_LIST_IMMUTABLE, nullptr,
nullptr)));
if (!plist) {
FML_DLOG(ERROR) << "Failed to CFPropertyListCreateWithDataFunc or "
"CFPropertyListCreateFromXMLDataFunc";
return std::nullopt;
}
auto product_version =
fml::CFRef<CFStringRef>(CFStringCreateWithCStringNoCopy(
nullptr, "ProductVersion", kCFStringEncodingASCII, kCFAllocatorNull));
if (!product_version) {
FML_DLOG(ERROR) << "Failed to CFStringCreateWithCStringNoCopyFunc";
return std::nullopt;
}
CFTypeRef opaque_value = CFDictionaryGetValue(plist, product_version);
if (!opaque_value || CFGetTypeID(opaque_value) != CFStringGetTypeID()) {
FML_DLOG(ERROR) << "Failed to CFDictionaryGetValueFunc";
return std::nullopt;
}
char version_str[32];
if (!CFStringGetCString(reinterpret_cast<CFStringRef>(opaque_value),
version_str, sizeof(version_str),
kCFStringEncodingUTF8)) {
FML_DLOG(ERROR) << "Failed to CFStringGetCStringFunc";
return std::nullopt;
}
int32_t major = 0;
int32_t minor = 0;
int32_t subminor = 0;
int matches = sscanf(version_str, "%d.%d.%d", &major, &minor, &subminor);
// A major version number is sufficient. The minor and subminor numbers might
// not be present.
if (matches < 1) {
FML_DLOG(ERROR) << "Failed to match product version string: "
<< version_str;
return std::nullopt;
}
return ProductVersion{major, minor, subminor};
}
bool IsEncodedVersionLessThanOrSame(uint32_t encoded_lhs, ProductVersion rhs) {
// Parse the values out of encoded_lhs, then compare against rhs.
const int32_t major = (encoded_lhs >> 16) & 0xffff;
const int32_t minor = (encoded_lhs >> 8) & 0xff;
const int32_t subminor = encoded_lhs & 0xff;
auto lhs = ProductVersion{major, minor, subminor};
return lhs <= rhs;
}
} // namespace flutter
namespace {
// The host's OS version when the dynamic lookup of _availability_version_check
// has failed.
static flutter::ProductVersion g_version;
typedef uint32_t dyld_platform_t;
typedef struct {
dyld_platform_t platform;
uint32_t version;
} dyld_build_version_t;
typedef bool (*AvailabilityVersionCheckFn)(uint32_t count,
dyld_build_version_t versions[]);
AvailabilityVersionCheckFn AvailabilityVersionCheck;
dispatch_once_t DispatchOnceCounter;
void InitializeAvailabilityCheck(void* unused) {
if (AvailabilityVersionCheck) {
return;
}
AvailabilityVersionCheck = reinterpret_cast<AvailabilityVersionCheckFn>(
dlsym(RTLD_DEFAULT, "_availability_version_check"));
if (AvailabilityVersionCheck) {
return;
}
// If _availability_version_check can't be dynamically loaded, then version
// information must be parsed out of a system plist file.
auto product_version = flutter::ProductVersionFromSystemVersionPList();
if (product_version.has_value()) {
g_version = product_version.value();
} else {
// If reading version info out of the system plist file fails, then
// fall back to the minimum version that Flutter supports.
#if FML_OS_IOS || FML_OS_IOS_SIMULATOR
g_version = std::make_tuple(11, 0, 0);
#elif FML_OS_MACOSX
g_version = std::make_tuple(10, 14, 0);
#endif // FML_OS_MACOSX
}
}
extern "C" bool _availability_version_check(uint32_t count,
dyld_build_version_t versions[]) {
dispatch_once_f(&DispatchOnceCounter, NULL, InitializeAvailabilityCheck);
if (AvailabilityVersionCheck) {
return AvailabilityVersionCheck(count, versions);
}
if (count == 0) {
return true;
}
// This function is called in only one place in the clang-rt implementation
// where there is only one element in the array.
return flutter::IsEncodedVersionLessThanOrSame(versions[0].version,
g_version);
}
} // namespace
| engine/shell/platform/darwin/common/availability_version_check.cc/0 | {
"file_path": "engine/shell/platform/darwin/common/availability_version_check.cc",
"repo_id": "engine",
"token_count": 2585
} | 313 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h"
FLUTTER_ASSERT_ARC
#pragma mark - Basic message channel
static NSString* const kFlutterChannelBuffersChannel = @"dev.flutter/channel-buffers";
static NSString* const kResizeMethod = @"resize";
static NSString* const kOverflowMethod = @"overflow";
static void ResizeChannelBuffer(NSObject<FlutterBinaryMessenger>* binaryMessenger,
NSString* channel,
NSInteger newSize) {
NSCAssert(newSize >= 0, @"Channel buffer size must be non-negative");
// Cast newSize to int because the deserialization logic handles only 32 bits values,
// see
// https://github.com/flutter/engine/blob/93e8901490e78c7ba7e319cce4470d9c6478c6dc/lib/ui/channel_buffers.dart#L495.
NSArray* args = @[ channel, @(static_cast<int>(newSize)) ];
FlutterMethodCall* resizeMethodCall = [FlutterMethodCall methodCallWithMethodName:kResizeMethod
arguments:args];
NSObject<FlutterMethodCodec>* codec = [FlutterStandardMethodCodec sharedInstance];
NSData* message = [codec encodeMethodCall:resizeMethodCall];
[binaryMessenger sendOnChannel:kFlutterChannelBuffersChannel message:message];
}
/**
* Defines whether a channel should show warning messages when discarding messages
* due to overflow.
*
* @param binaryMessenger The binary messenger.
* @param channel The channel name.
* @param warns When false, the channel is expected to overflow and warning messages
* will not be shown.
*/
static void SetWarnsOnOverflow(NSObject<FlutterBinaryMessenger>* binaryMessenger,
NSString* channel,
BOOL warns) {
FlutterMethodCall* overflowMethodCall =
[FlutterMethodCall methodCallWithMethodName:kOverflowMethod
arguments:@[ channel, @(!warns) ]];
NSObject<FlutterMethodCodec>* codec = [FlutterStandardMethodCodec sharedInstance];
NSData* message = [codec encodeMethodCall:overflowMethodCall];
[binaryMessenger sendOnChannel:kFlutterChannelBuffersChannel message:message];
}
static FlutterBinaryMessengerConnection SetMessageHandler(
NSObject<FlutterBinaryMessenger>* messenger,
NSString* name,
FlutterBinaryMessageHandler handler,
NSObject<FlutterTaskQueue>* taskQueue) {
if (taskQueue) {
NSCAssert([messenger respondsToSelector:@selector(setMessageHandlerOnChannel:
binaryMessageHandler:taskQueue:)],
@"");
return [messenger setMessageHandlerOnChannel:name
binaryMessageHandler:handler
taskQueue:taskQueue];
} else {
return [messenger setMessageHandlerOnChannel:name binaryMessageHandler:handler];
}
}
////////////////////////////////////////////////////////////////////////////////
@implementation FlutterBasicMessageChannel {
NSObject<FlutterBinaryMessenger>* _messenger;
NSString* _name;
NSObject<FlutterMessageCodec>* _codec;
FlutterBinaryMessengerConnection _connection;
NSObject<FlutterTaskQueue>* _taskQueue;
}
+ (instancetype)messageChannelWithName:(NSString*)name
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger {
NSObject<FlutterMessageCodec>* codec = [FlutterStandardMessageCodec sharedInstance];
return [FlutterBasicMessageChannel messageChannelWithName:name
binaryMessenger:messenger
codec:codec];
}
+ (instancetype)messageChannelWithName:(NSString*)name
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger
codec:(NSObject<FlutterMessageCodec>*)codec {
return [[FlutterBasicMessageChannel alloc] initWithName:name
binaryMessenger:messenger
codec:codec];
}
- (instancetype)initWithName:(NSString*)name
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger
codec:(NSObject<FlutterMessageCodec>*)codec {
self = [self initWithName:name binaryMessenger:messenger codec:codec taskQueue:nil];
return self;
}
- (instancetype)initWithName:(NSString*)name
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger
codec:(NSObject<FlutterMessageCodec>*)codec
taskQueue:(NSObject<FlutterTaskQueue>*)taskQueue {
self = [super init];
NSAssert(self, @"Super init cannot be nil");
_name = [name copy];
_messenger = messenger;
_codec = codec;
_taskQueue = taskQueue;
return self;
}
- (void)sendMessage:(id)message {
[_messenger sendOnChannel:_name message:[_codec encode:message]];
}
- (void)sendMessage:(id)message reply:(FlutterReply)callback {
FlutterBinaryReply reply = ^(NSData* data) {
if (callback) {
callback([_codec decode:data]);
}
};
[_messenger sendOnChannel:_name message:[_codec encode:message] binaryReply:reply];
}
- (void)setMessageHandler:(FlutterMessageHandler)handler {
if (!handler) {
if (_connection > 0) {
[_messenger cleanUpConnection:_connection];
_connection = 0;
} else {
[_messenger setMessageHandlerOnChannel:_name binaryMessageHandler:nil];
}
return;
}
// Grab reference to avoid retain on self.
// `self` might be released before the block, so the block needs to retain the codec to
// make sure it is not released with `self`
NSObject<FlutterMessageCodec>* codec = _codec;
FlutterBinaryMessageHandler messageHandler = ^(NSData* message, FlutterBinaryReply callback) {
handler([codec decode:message], ^(id reply) {
callback([codec encode:reply]);
});
};
_connection = SetMessageHandler(_messenger, _name, messageHandler, _taskQueue);
}
+ (void)resizeChannelWithName:(NSString*)name
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger
size:(NSInteger)newSize {
ResizeChannelBuffer(messenger, name, newSize);
}
- (void)resizeChannelBuffer:(NSInteger)newSize {
ResizeChannelBuffer(_messenger, _name, newSize);
}
+ (void)setWarnsOnOverflow:(BOOL)warns
forChannelWithName:(NSString*)name
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger {
SetWarnsOnOverflow(messenger, name, warns);
}
- (void)setWarnsOnOverflow:(BOOL)warns {
SetWarnsOnOverflow(_messenger, _name, warns);
}
@end
#pragma mark - Method channel
////////////////////////////////////////////////////////////////////////////////
@implementation FlutterError
+ (instancetype)errorWithCode:(NSString*)code message:(NSString*)message details:(id)details {
return [[FlutterError alloc] initWithCode:code message:message details:details];
}
- (instancetype)initWithCode:(NSString*)code message:(NSString*)message details:(id)details {
NSAssert(code, @"Code cannot be nil");
self = [super init];
NSAssert(self, @"Super init cannot be nil");
_code = [code copy];
_message = [message copy];
_details = details;
return self;
}
- (BOOL)isEqual:(id)object {
if (self == object) {
return YES;
}
if (![object isKindOfClass:[FlutterError class]]) {
return NO;
}
FlutterError* other = (FlutterError*)object;
return [self.code isEqual:other.code] &&
((!self.message && !other.message) || [self.message isEqual:other.message]) &&
((!self.details && !other.details) || [self.details isEqual:other.details]);
}
- (NSUInteger)hash {
return [self.code hash] ^ [self.message hash] ^ [self.details hash];
}
@end
////////////////////////////////////////////////////////////////////////////////
@implementation FlutterMethodCall
+ (instancetype)methodCallWithMethodName:(NSString*)method arguments:(id)arguments {
return [[FlutterMethodCall alloc] initWithMethodName:method arguments:arguments];
}
- (instancetype)initWithMethodName:(NSString*)method arguments:(id)arguments {
NSAssert(method, @"Method name cannot be nil");
self = [super init];
NSAssert(self, @"Super init cannot be nil");
_method = [method copy];
_arguments = arguments;
return self;
}
- (BOOL)isEqual:(id)object {
if (self == object) {
return YES;
}
if (![object isKindOfClass:[FlutterMethodCall class]]) {
return NO;
}
FlutterMethodCall* other = (FlutterMethodCall*)object;
return [self.method isEqual:[other method]] &&
((!self.arguments && !other.arguments) || [self.arguments isEqual:other.arguments]);
}
- (NSUInteger)hash {
return [self.method hash] ^ [self.arguments hash];
}
@end
NSObject const* FlutterMethodNotImplemented = [[NSObject alloc] init];
////////////////////////////////////////////////////////////////////////////////
@implementation FlutterMethodChannel {
NSObject<FlutterBinaryMessenger>* _messenger;
NSString* _name;
NSObject<FlutterMethodCodec>* _codec;
FlutterBinaryMessengerConnection _connection;
NSObject<FlutterTaskQueue>* _taskQueue;
}
+ (instancetype)methodChannelWithName:(NSString*)name
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger {
NSObject<FlutterMethodCodec>* codec = [FlutterStandardMethodCodec sharedInstance];
return [FlutterMethodChannel methodChannelWithName:name binaryMessenger:messenger codec:codec];
}
+ (instancetype)methodChannelWithName:(NSString*)name
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger
codec:(NSObject<FlutterMethodCodec>*)codec {
return [[FlutterMethodChannel alloc] initWithName:name binaryMessenger:messenger codec:codec];
}
- (instancetype)initWithName:(NSString*)name
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger
codec:(NSObject<FlutterMethodCodec>*)codec {
self = [self initWithName:name binaryMessenger:messenger codec:codec taskQueue:nil];
return self;
}
- (instancetype)initWithName:(NSString*)name
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger
codec:(NSObject<FlutterMethodCodec>*)codec
taskQueue:(NSObject<FlutterTaskQueue>*)taskQueue {
self = [super init];
NSAssert(self, @"Super init cannot be nil");
_name = [name copy];
_messenger = messenger;
_codec = codec;
_taskQueue = taskQueue;
return self;
}
- (void)invokeMethod:(NSString*)method arguments:(id)arguments {
FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:method
arguments:arguments];
NSData* message = [_codec encodeMethodCall:methodCall];
[_messenger sendOnChannel:_name message:message];
}
- (void)invokeMethod:(NSString*)method arguments:(id)arguments result:(FlutterResult)callback {
FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:method
arguments:arguments];
NSData* message = [_codec encodeMethodCall:methodCall];
FlutterBinaryReply reply = ^(NSData* data) {
if (callback) {
callback((data == nil) ? FlutterMethodNotImplemented : [_codec decodeEnvelope:data]);
}
};
[_messenger sendOnChannel:_name message:message binaryReply:reply];
}
- (void)setMethodCallHandler:(FlutterMethodCallHandler)handler {
if (!handler) {
if (_connection > 0) {
[_messenger cleanUpConnection:_connection];
_connection = 0;
} else {
[_messenger setMessageHandlerOnChannel:_name binaryMessageHandler:nil];
}
return;
}
// Make sure the block captures the codec, not self.
// `self` might be released before the block, so the block needs to retain the codec to
// make sure it is not released with `self`
NSObject<FlutterMethodCodec>* codec = _codec;
FlutterBinaryMessageHandler messageHandler = ^(NSData* message, FlutterBinaryReply callback) {
FlutterMethodCall* call = [codec decodeMethodCall:message];
handler(call, ^(id result) {
if (result == FlutterMethodNotImplemented) {
callback(nil);
} else if ([result isKindOfClass:[FlutterError class]]) {
callback([codec encodeErrorEnvelope:(FlutterError*)result]);
} else {
callback([codec encodeSuccessEnvelope:result]);
}
});
};
_connection = SetMessageHandler(_messenger, _name, messageHandler, _taskQueue);
}
- (void)resizeChannelBuffer:(NSInteger)newSize {
ResizeChannelBuffer(_messenger, _name, newSize);
}
@end
#pragma mark - Event channel
NSObject const* FlutterEndOfEventStream = [[NSObject alloc] init];
////////////////////////////////////////////////////////////////////////////////
@implementation FlutterEventChannel {
NSObject<FlutterBinaryMessenger>* _messenger;
NSString* _name;
NSObject<FlutterMethodCodec>* _codec;
NSObject<FlutterTaskQueue>* _taskQueue;
FlutterBinaryMessengerConnection _connection;
}
+ (instancetype)eventChannelWithName:(NSString*)name
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger {
NSObject<FlutterMethodCodec>* codec = [FlutterStandardMethodCodec sharedInstance];
return [FlutterEventChannel eventChannelWithName:name binaryMessenger:messenger codec:codec];
}
+ (instancetype)eventChannelWithName:(NSString*)name
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger
codec:(NSObject<FlutterMethodCodec>*)codec {
return [[FlutterEventChannel alloc] initWithName:name binaryMessenger:messenger codec:codec];
}
- (instancetype)initWithName:(NSString*)name
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger
codec:(NSObject<FlutterMethodCodec>*)codec {
return [self initWithName:name binaryMessenger:messenger codec:codec taskQueue:nil];
}
- (instancetype)initWithName:(NSString*)name
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger
codec:(NSObject<FlutterMethodCodec>*)codec
taskQueue:(NSObject<FlutterTaskQueue>* _Nullable)taskQueue {
self = [super init];
NSAssert(self, @"Super init cannot be nil");
_name = [name copy];
_messenger = messenger;
_codec = codec;
_taskQueue = taskQueue;
return self;
}
static FlutterBinaryMessengerConnection SetStreamHandlerMessageHandlerOnChannel(
NSObject<FlutterStreamHandler>* handler,
NSString* name,
NSObject<FlutterBinaryMessenger>* messenger,
NSObject<FlutterMethodCodec>* codec,
NSObject<FlutterTaskQueue>* taskQueue) {
__block FlutterEventSink currentSink = nil;
FlutterBinaryMessageHandler messageHandler = ^(NSData* message, FlutterBinaryReply callback) {
FlutterMethodCall* call = [codec decodeMethodCall:message];
if ([call.method isEqual:@"listen"]) {
if (currentSink) {
FlutterError* error = [handler onCancelWithArguments:nil];
if (error) {
NSLog(@"Failed to cancel existing stream: %@. %@ (%@)", error.code, error.message,
error.details);
}
}
currentSink = ^(id event) {
if (event == FlutterEndOfEventStream) {
[messenger sendOnChannel:name message:nil];
} else if ([event isKindOfClass:[FlutterError class]]) {
[messenger sendOnChannel:name message:[codec encodeErrorEnvelope:(FlutterError*)event]];
} else {
[messenger sendOnChannel:name message:[codec encodeSuccessEnvelope:event]];
}
};
FlutterError* error = [handler onListenWithArguments:call.arguments eventSink:currentSink];
if (error) {
callback([codec encodeErrorEnvelope:error]);
} else {
callback([codec encodeSuccessEnvelope:nil]);
}
} else if ([call.method isEqual:@"cancel"]) {
if (!currentSink) {
callback(
[codec encodeErrorEnvelope:[FlutterError errorWithCode:@"error"
message:@"No active stream to cancel"
details:nil]]);
return;
}
currentSink = nil;
FlutterError* error = [handler onCancelWithArguments:call.arguments];
if (error) {
callback([codec encodeErrorEnvelope:error]);
} else {
callback([codec encodeSuccessEnvelope:nil]);
}
} else {
callback(nil);
}
};
return SetMessageHandler(messenger, name, messageHandler, taskQueue);
}
- (void)setStreamHandler:(NSObject<FlutterStreamHandler>*)handler {
if (!handler) {
[_messenger cleanUpConnection:_connection];
_connection = 0;
return;
}
_connection =
SetStreamHandlerMessageHandlerOnChannel(handler, _name, _messenger, _codec, _taskQueue);
}
@end
| engine/shell/platform/darwin/common/framework/Source/FlutterChannels.mm/0 | {
"file_path": "engine/shell/platform/darwin/common/framework/Source/FlutterChannels.mm",
"repo_id": "engine",
"token_count": 6512
} | 314 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_GRAPHICS_FLUTTERDARWINCONTEXTMETALIMPELLER_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_GRAPHICS_FLUTTERDARWINCONTEXTMETALIMPELLER_H_
#import <CoreVideo/CVMetalTextureCache.h>
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
#include "flutter/fml/concurrent_message_loop.h"
#include "flutter/fml/platform/darwin/cf_utils.h"
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterTexture.h"
#import "flutter/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.h"
#include "impeller/renderer/backend/metal/context_mtl.h"
NS_ASSUME_NONNULL_BEGIN
/**
* Provides skia GrContexts that are shared between iOS and macOS embeddings.
*/
@interface FlutterDarwinContextMetalImpeller : NSObject
/**
* Initializes a FlutterDarwinContextMetalImpeller.
*/
- (instancetype)init:(const std::shared_ptr<const fml::SyncSwitch>&)is_gpu_disabled_sync_switch;
/**
* Creates an external texture with the specified ID and contents.
*/
- (FlutterDarwinExternalTextureMetal*)
createExternalTextureWithIdentifier:(int64_t)textureID
texture:(NSObject<FlutterTexture>*)texture;
/**
* Impeller context.
*/
@property(nonatomic, readonly) std::shared_ptr<impeller::ContextMTL> context;
/*
* Texture cache for external textures.
*/
@property(nonatomic, readonly) fml::CFRef<CVMetalTextureCacheRef> textureCache;
@end
NS_ASSUME_NONNULL_END
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_GRAPHICS_FLUTTERDARWINCONTEXTMETALIMPELLER_H_
| engine/shell/platform/darwin/graphics/FlutterDarwinContextMetalImpeller.h/0 | {
"file_path": "engine/shell/platform/darwin/graphics/FlutterDarwinContextMetalImpeller.h",
"repo_id": "engine",
"token_count": 609
} | 315 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERPLUGINAPPLIFECYCLEDELEGATE_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERPLUGINAPPLIFECYCLEDELEGATE_H_
#import "FlutterPlugin.h"
NS_ASSUME_NONNULL_BEGIN
/**
* Propagates `UIAppDelegate` callbacks to registered plugins.
*/
FLUTTER_DARWIN_EXPORT
@interface FlutterPluginAppLifeCycleDelegate : NSObject <UNUserNotificationCenterDelegate>
/**
* Registers `delegate` to receive life cycle callbacks via this FlutterPluginAppLifeCycleDelegate
* as long as it is alive.
*
* `delegate` will only be referenced weakly.
*/
- (void)addDelegate:(NSObject<FlutterApplicationLifeCycleDelegate>*)delegate;
/**
* Calls all plugins registered for `UIApplicationDelegate` callbacks.
*
* @return `NO` if any plugin vetos application launch.
*/
- (BOOL)application:(UIApplication*)application
didFinishLaunchingWithOptions:(NSDictionary*)launchOptions;
/**
* Calls all plugins registered for `UIApplicationDelegate` callbacks.
*
* @return `NO` if any plugin vetos application launch.
*/
- (BOOL)application:(UIApplication*)application
willFinishLaunchingWithOptions:(NSDictionary*)launchOptions;
/**
* Called if this plugin has been registered for `UIApplicationDelegate` callbacks.
*/
- (void)application:(UIApplication*)application
didRegisterUserNotificationSettings:(UIUserNotificationSettings*)notificationSettings
API_DEPRECATED(
"See -[UIApplicationDelegate application:didRegisterUserNotificationSettings:] deprecation",
ios(8.0, 10.0));
/**
* Calls all plugins registered for `UIApplicationDelegate` callbacks.
*/
- (void)application:(UIApplication*)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken;
/**
* Calls all plugins registered for `UIApplicationDelegate` callbacks.
*/
- (void)application:(UIApplication*)application
didFailToRegisterForRemoteNotificationsWithError:(NSError*)error;
/**
* Calls all plugins registered for `UIApplicationDelegate` callbacks.
*/
- (void)application:(UIApplication*)application
didReceiveRemoteNotification:(NSDictionary*)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler;
/**
* Calls all plugins registered for `UIApplicationDelegate` callbacks.
*/
- (void)application:(UIApplication*)application
didReceiveLocalNotification:(UILocalNotification*)notification
API_DEPRECATED(
"See -[UIApplicationDelegate application:didReceiveLocalNotification:] deprecation",
ios(4.0, 10.0));
/**
* Calls all plugins registered for `UIApplicationDelegate` callbacks in order of registration until
* some plugin handles the request.
*
* @return `YES` if any plugin handles the request.
*/
- (BOOL)application:(UIApplication*)application
openURL:(NSURL*)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey, id>*)options;
/**
* Calls all plugins registered for `UIApplicationDelegate` callbacks in order of registration until
* some plugin handles the request.
*
* @return `YES` if any plugin handles the request.
*/
- (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)url;
/**
* Calls all plugins registered for `UIApplicationDelegate` callbacks in order of registration until
* some plugin handles the request.
*
* @return `YES` if any plugin handles the request.
*/
- (BOOL)application:(UIApplication*)application
openURL:(NSURL*)url
sourceApplication:(NSString*)sourceApplication
annotation:(id)annotation;
/**
* Calls all plugins registered for `UIApplicationDelegate` callbacks.
*/
- (void)application:(UIApplication*)application
performActionForShortcutItem:(UIApplicationShortcutItem*)shortcutItem
completionHandler:(void (^)(BOOL succeeded))completionHandler
API_AVAILABLE(ios(9.0));
/**
* Calls all plugins registered for `UIApplicationDelegate` callbacks in order of registration until
* some plugin handles the request.
*
* @return `YES` if any plugin handles the request.
*/
- (BOOL)application:(UIApplication*)application
handleEventsForBackgroundURLSession:(nonnull NSString*)identifier
completionHandler:(nonnull void (^)(void))completionHandler;
/**
* Calls all plugins registered for `UIApplicationDelegate` callbacks in order of registration until
* some plugin handles the request.
*
* @returns `YES` if any plugin handles the request.
*/
- (BOOL)application:(UIApplication*)application
performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler;
/**
* Calls all plugins registered for `UIApplicationDelegate` callbacks in order of registration until
* some plugin handles the request.
*
* @return `YES` if any plugin handles the request.
*/
- (BOOL)application:(UIApplication*)application
continueUserActivity:(NSUserActivity*)userActivity
restorationHandler:(void (^)(NSArray*))restorationHandler;
@end
NS_ASSUME_NONNULL_END
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERPLUGINAPPLIFECYCLEDELEGATE_H_
| engine/shell/platform/darwin/ios/framework/Headers/FlutterPluginAppLifeCycleDelegate.h/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Headers/FlutterPluginAppLifeCycleDelegate.h",
"repo_id": "engine",
"token_count": 1670
} | 316 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#define FML_USED_ON_EMBEDDER
#import "FlutterDartVMServicePublisher.h"
#if FLUTTER_RELEASE
@implementation FlutterDartVMServicePublisher
- (instancetype)initWithEnableVMServicePublication:(BOOL)enableVMServicePublication {
return [super init];
}
@end
#else // FLUTTER_RELEASE
#import <TargetConditionals.h>
// NSNetService works fine on physical devices before iOS 13.2.
// However, it doesn't expose the services to regular mDNS
// queries on the Simulator or on iOS 13.2+ devices.
//
// When debugging issues with this implementation, the following is helpful:
//
// 1) Running `dns-sd -Z _dartVmService`. This is a built-in macOS tool that
// can find advertized observatories using this method. If dns-sd can't find
// it, then the VM service is not getting advertised over any network
// interface that the host machine has access to.
// 2) The Python zeroconf package. The dns-sd tool can sometimes see things
// that aren't advertizing over a network interface - for example, simulators
// using NSNetService has been observed using dns-sd, but doesn't show up in
// the Python package (which is a high quality socket based implementation).
// If that happens, this code should be tweaked such that it shows up in both
// dns-sd's output and Python zeroconf's detection.
// 3) The Dart multicast_dns package, which is what Flutter uses to find the
// port and auth code. If the advertizement shows up in dns-sd and Python
// zeroconf but not multicast_dns, then it is a bug in multicast_dns.
#include <dns_sd.h>
#include <net/if.h>
#include "flutter/fml/logging.h"
#include "flutter/fml/memory/weak_ptr.h"
#include "flutter/fml/message_loop.h"
#include "flutter/fml/platform/darwin/scoped_nsobject.h"
#include "flutter/runtime/dart_service_isolate.h"
@protocol FlutterDartVMServicePublisherDelegate
- (void)publishServiceProtocolPort:(NSURL*)uri;
- (void)stopService;
@end
@interface FlutterDartVMServicePublisher ()
+ (NSData*)createTxtData:(NSURL*)url;
@property(readonly, class) NSString* serviceName;
@property(readonly) fml::scoped_nsobject<NSObject<FlutterDartVMServicePublisherDelegate>> delegate;
@property(nonatomic, readwrite) NSURL* url;
@property(readonly) BOOL enableVMServicePublication;
@end
@interface DartVMServiceDNSServiceDelegate : NSObject <FlutterDartVMServicePublisherDelegate>
@end
@implementation DartVMServiceDNSServiceDelegate {
DNSServiceRef _dnsServiceRef;
DNSServiceRef _legacyDnsServiceRef;
}
- (void)stopService {
if (_dnsServiceRef) {
DNSServiceRefDeallocate(_dnsServiceRef);
_dnsServiceRef = NULL;
}
if (_legacyDnsServiceRef) {
DNSServiceRefDeallocate(_legacyDnsServiceRef);
_legacyDnsServiceRef = NULL;
}
}
- (void)publishServiceProtocolPort:(NSURL*)url {
// TODO(vashworth): Remove once done debugging https://github.com/flutter/flutter/issues/129836
FML_LOG(INFO) << "Publish Service Protocol Port";
DNSServiceFlags flags = kDNSServiceFlagsDefault;
#if TARGET_IPHONE_SIMULATOR
// Simulator needs to use local loopback explicitly to work.
uint32_t interfaceIndex = if_nametoindex("lo0");
#else // TARGET_IPHONE_SIMULATOR
// Physical devices need to request all interfaces.
uint32_t interfaceIndex = 0;
#endif // TARGET_IPHONE_SIMULATOR
const char* registrationType = "_dartVmService._tcp";
const char* legacyRegistrationType = "_dartobservatory._tcp";
const char* domain = "local."; // default domain
uint16_t port = [[url port] unsignedShortValue];
NSData* txtData = [FlutterDartVMServicePublisher createTxtData:url];
int err = DNSServiceRegister(&_dnsServiceRef, flags, interfaceIndex,
FlutterDartVMServicePublisher.serviceName.UTF8String,
registrationType, domain, NULL, htons(port), txtData.length,
txtData.bytes, RegistrationCallback, NULL);
if (err == 0) {
DNSServiceSetDispatchQueue(_dnsServiceRef, dispatch_get_main_queue());
return;
}
// TODO(bkonyi): remove once flutter_tools no longer looks for the legacy registration type.
// See https://github.com/dart-lang/sdk/issues/50233
//
// Try to fallback on the legacy registration type.
err = DNSServiceRegister(&_legacyDnsServiceRef, flags, interfaceIndex,
FlutterDartVMServicePublisher.serviceName.UTF8String,
legacyRegistrationType, domain, NULL, htons(port), txtData.length,
txtData.bytes, RegistrationCallback, NULL);
if (err == 0) {
DNSServiceSetDispatchQueue(_legacyDnsServiceRef, dispatch_get_main_queue());
return;
}
FML_LOG(ERROR) << "Failed to register Dart VM Service port with mDNS with error " << err << ".";
if (@available(iOS 14.0, *)) {
FML_LOG(ERROR) << "On iOS 14+, local network broadcast in apps need to be declared in "
<< "the app's Info.plist. Debug and profile Flutter apps and modules host "
<< "VM services on the local network to support debugging features such "
<< "as hot reload and DevTools. To make your Flutter app or module "
<< "attachable and debuggable, add a '" << registrationType << "' value "
<< "to the 'NSBonjourServices' key in your Info.plist for the Debug/"
<< "Profile configurations. " << "For more information, see "
<< "https://flutter.dev/docs/development/add-to-app/ios/"
"project-setup#local-network-privacy-permissions";
}
}
static void DNSSD_API RegistrationCallback(DNSServiceRef sdRef,
DNSServiceFlags flags,
DNSServiceErrorType errorCode,
const char* name,
const char* regType,
const char* domain,
void* context) {
if (errorCode == kDNSServiceErr_NoError) {
FML_DLOG(INFO) << "FlutterDartVMServicePublisher is ready!";
} else if (errorCode == kDNSServiceErr_PolicyDenied) {
FML_LOG(ERROR)
<< "Could not register as server for FlutterDartVMServicePublisher, permission "
<< "denied. Check your 'Local Network' permissions for this app in the Privacy section of "
<< "the system Settings.";
} else {
FML_LOG(ERROR) << "Could not register as server for FlutterDartVMServicePublisher. Check your "
"network settings and relaunch the application.";
}
}
@end
@implementation FlutterDartVMServicePublisher {
flutter::DartServiceIsolate::CallbackHandle _callbackHandle;
std::unique_ptr<fml::WeakPtrFactory<FlutterDartVMServicePublisher>> _weakFactory;
}
- (instancetype)initWithEnableVMServicePublication:(BOOL)enableVMServicePublication {
self = [super init];
NSAssert(self, @"Super must not return null on init.");
_delegate.reset([[DartVMServiceDNSServiceDelegate alloc] init]);
_enableVMServicePublication = enableVMServicePublication;
_weakFactory = std::make_unique<fml::WeakPtrFactory<FlutterDartVMServicePublisher>>(self);
fml::MessageLoop::EnsureInitializedForCurrentThread();
_callbackHandle = flutter::DartServiceIsolate::AddServerStatusCallback(
[weak = _weakFactory->GetWeakPtr(),
runner = fml::MessageLoop::GetCurrent().GetTaskRunner()](const std::string& uri) {
if (!uri.empty()) {
runner->PostTask([weak, uri]() {
// uri comes in as something like 'http://127.0.0.1:XXXXX/' where XXXXX is the port
// number.
if (weak) {
NSURL* url = [[[NSURL alloc]
initWithString:[NSString stringWithUTF8String:uri.c_str()]] autorelease];
weak.get().url = url;
if (weak.get().enableVMServicePublication) {
[[weak.get() delegate] publishServiceProtocolPort:url];
}
}
});
}
});
return self;
}
+ (NSString*)serviceName {
return NSBundle.mainBundle.bundleIdentifier;
}
+ (NSData*)createTxtData:(NSURL*)url {
// Check to see if there's an authentication code. If there is, we'll provide
// it as a txt record so flutter tools can establish a connection.
NSString* path = [[url path] substringFromIndex:MIN(1, [[url path] length])];
NSData* pathData = [path dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary<NSString*, NSData*>* txtDict = @{
@"authCode" : pathData,
};
return [NSNetService dataFromTXTRecordDictionary:txtDict];
}
- (void)dealloc {
// It will be destroyed and invalidate its weak pointers
// before any other members are destroyed.
_weakFactory.reset();
[_delegate stopService];
[_url release];
flutter::DartServiceIsolate::RemoveServerStatusCallback(_callbackHandle);
[super dealloc];
}
@end
#endif // FLUTTER_RELEASE
| engine/shell/platform/darwin/ios/framework/Source/FlutterDartVMServicePublisher.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterDartVMServicePublisher.mm",
"repo_id": "engine",
"token_count": 3507
} | 317 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERKEYSECONDARYRESPONDER_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERKEYSECONDARYRESPONDER_H_
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h"
/**
* An interface for a responder that can process a key event and synchronously
* decide whether to handle the event.
*
* To use this class, add it to a |FlutterKeyboardManager| with
* |addSecondaryResponder|.
*/
@protocol FlutterKeySecondaryResponder
/**
* Informs the receiver that the user has interacted with a key.
*
* The return value indicates whether it has handled the given event.
*
* Default implementation returns NO.
*/
@required
- (BOOL)handlePress:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4));
@end
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERKEYSECONDARYRESPONDER_H_
| engine/shell/platform/darwin/ios/framework/Source/FlutterKeySecondaryResponder.h/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterKeySecondaryResponder.h",
"repo_id": "engine",
"token_count": 363
} | 318 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterPluginAppLifeCycleDelegate.h"
#include "flutter/fml/logging.h"
#include "flutter/fml/paths.h"
#include "flutter/lib/ui/plugins/callback_cache.h"
#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterCallbackCache_Internal.h"
static const char* kCallbackCacheSubDir = "Library/Caches/";
static const SEL kSelectorsHandledByPlugins[] = {
@selector(application:didReceiveRemoteNotification:fetchCompletionHandler:),
@selector(application:performFetchWithCompletionHandler:)};
@interface FlutterPluginAppLifeCycleDelegate ()
- (void)handleDidEnterBackground:(NSNotification*)notification
NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in app extensions");
- (void)handleWillEnterForeground:(NSNotification*)notification
NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in app extensions");
- (void)handleWillResignActive:(NSNotification*)notification
NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in app extensions");
- (void)handleDidBecomeActive:(NSNotification*)notification
NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in app extensions");
- (void)handleWillTerminate:(NSNotification*)notification
NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in app extensions");
@end
@implementation FlutterPluginAppLifeCycleDelegate {
NSMutableArray* _notificationUnsubscribers;
UIBackgroundTaskIdentifier _debugBackgroundTask;
// Weak references to registered plugins.
NSPointerArray* _delegates;
}
- (void)addObserverFor:(NSString*)name selector:(SEL)selector {
[[NSNotificationCenter defaultCenter] addObserver:self selector:selector name:name object:nil];
__block NSObject* blockSelf = self;
dispatch_block_t unsubscribe = ^{
[[NSNotificationCenter defaultCenter] removeObserver:blockSelf name:name object:nil];
};
[_notificationUnsubscribers addObject:[[unsubscribe copy] autorelease]];
}
- (instancetype)init {
if (self = [super init]) {
_notificationUnsubscribers = [[NSMutableArray alloc] init];
std::string cachePath = fml::paths::JoinPaths({getenv("HOME"), kCallbackCacheSubDir});
[FlutterCallbackCache setCachePath:[NSString stringWithUTF8String:cachePath.c_str()]];
#if not APPLICATION_EXTENSION_API_ONLY
[self addObserverFor:UIApplicationDidEnterBackgroundNotification
selector:@selector(handleDidEnterBackground:)];
[self addObserverFor:UIApplicationWillEnterForegroundNotification
selector:@selector(handleWillEnterForeground:)];
[self addObserverFor:UIApplicationWillResignActiveNotification
selector:@selector(handleWillResignActive:)];
[self addObserverFor:UIApplicationDidBecomeActiveNotification
selector:@selector(handleDidBecomeActive:)];
[self addObserverFor:UIApplicationWillTerminateNotification
selector:@selector(handleWillTerminate:)];
#endif
_delegates = [[NSPointerArray weakObjectsPointerArray] retain];
_debugBackgroundTask = UIBackgroundTaskInvalid;
}
return self;
}
- (void)dealloc {
for (dispatch_block_t unsubscribe in _notificationUnsubscribers) {
unsubscribe();
}
[_notificationUnsubscribers release];
[_delegates release];
[super dealloc];
}
static BOOL IsPowerOfTwo(NSUInteger x) {
return x != 0 && (x & (x - 1)) == 0;
}
- (BOOL)isSelectorAddedDynamically:(SEL)selector {
for (const SEL& aSelector : kSelectorsHandledByPlugins) {
if (selector == aSelector) {
return YES;
}
}
return NO;
}
- (BOOL)hasPluginThatRespondsToSelector:(SEL)selector {
for (NSObject<FlutterApplicationLifeCycleDelegate>* delegate in [_delegates allObjects]) {
if (!delegate) {
continue;
}
if ([delegate respondsToSelector:selector]) {
return YES;
}
}
return NO;
}
- (void)addDelegate:(NSObject<FlutterApplicationLifeCycleDelegate>*)delegate {
[_delegates addPointer:(__bridge void*)delegate];
if (IsPowerOfTwo([_delegates count])) {
[_delegates compact];
}
}
- (BOOL)application:(UIApplication*)application
didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
for (NSObject<FlutterApplicationLifeCycleDelegate>* delegate in [_delegates allObjects]) {
if (!delegate) {
continue;
}
if ([delegate respondsToSelector:_cmd]) {
if (![delegate application:application didFinishLaunchingWithOptions:launchOptions]) {
return NO;
}
}
}
return YES;
}
- (BOOL)application:(UIApplication*)application
willFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
flutter::DartCallbackCache::LoadCacheFromDisk();
for (NSObject<FlutterApplicationLifeCycleDelegate>* delegate in [_delegates allObjects]) {
if (!delegate) {
continue;
}
if ([delegate respondsToSelector:_cmd]) {
if (![delegate application:application willFinishLaunchingWithOptions:launchOptions]) {
return NO;
}
}
}
return YES;
}
- (void)handleDidEnterBackground:(NSNotification*)notification
NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in app extensions") {
UIApplication* application = [UIApplication sharedApplication];
#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG
// The following keeps the Flutter session alive when the device screen locks
// in debug mode. It allows continued use of features like hot reload and
// taking screenshots once the device unlocks again.
//
// Note the name is not an identifier and multiple instances can exist.
_debugBackgroundTask = [application
beginBackgroundTaskWithName:@"Flutter debug task"
expirationHandler:^{
if (_debugBackgroundTask != UIBackgroundTaskInvalid) {
[application endBackgroundTask:_debugBackgroundTask];
_debugBackgroundTask = UIBackgroundTaskInvalid;
}
FML_LOG(WARNING)
<< "\nThe OS has terminated the Flutter debug connection for being "
"inactive in the background for too long.\n\n"
"There are no errors with your Flutter application.\n\n"
"To reconnect, launch your application again via 'flutter run'";
}];
#endif // FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG
for (NSObject<FlutterApplicationLifeCycleDelegate>* delegate in _delegates) {
if (!delegate) {
continue;
}
if ([delegate respondsToSelector:@selector(applicationDidEnterBackground:)]) {
[delegate applicationDidEnterBackground:application];
}
}
}
- (void)handleWillEnterForeground:(NSNotification*)notification
NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in app extensions") {
UIApplication* application = [UIApplication sharedApplication];
#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG
if (_debugBackgroundTask != UIBackgroundTaskInvalid) {
[application endBackgroundTask:_debugBackgroundTask];
_debugBackgroundTask = UIBackgroundTaskInvalid;
}
#endif // FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG
for (NSObject<FlutterApplicationLifeCycleDelegate>* delegate in _delegates) {
if (!delegate) {
continue;
}
if ([delegate respondsToSelector:@selector(applicationWillEnterForeground:)]) {
[delegate applicationWillEnterForeground:application];
}
}
}
- (void)handleWillResignActive:(NSNotification*)notification
NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in app extensions") {
UIApplication* application = [UIApplication sharedApplication];
for (NSObject<FlutterApplicationLifeCycleDelegate>* delegate in _delegates) {
if (!delegate) {
continue;
}
if ([delegate respondsToSelector:@selector(applicationWillResignActive:)]) {
[delegate applicationWillResignActive:application];
}
}
}
- (void)handleDidBecomeActive:(NSNotification*)notification
NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in app extensions") {
UIApplication* application = [UIApplication sharedApplication];
for (NSObject<FlutterApplicationLifeCycleDelegate>* delegate in _delegates) {
if (!delegate) {
continue;
}
if ([delegate respondsToSelector:@selector(applicationDidBecomeActive:)]) {
[delegate applicationDidBecomeActive:application];
}
}
}
- (void)handleWillTerminate:(NSNotification*)notification
NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in app extensions") {
UIApplication* application = [UIApplication sharedApplication];
for (NSObject<FlutterApplicationLifeCycleDelegate>* delegate in _delegates) {
if (!delegate) {
continue;
}
if ([delegate respondsToSelector:@selector(applicationWillTerminate:)]) {
[delegate applicationWillTerminate:application];
}
}
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
- (void)application:(UIApplication*)application
didRegisterUserNotificationSettings:(UIUserNotificationSettings*)notificationSettings {
for (NSObject<FlutterApplicationLifeCycleDelegate>* delegate in _delegates) {
if (!delegate) {
continue;
}
if ([delegate respondsToSelector:_cmd]) {
[delegate application:application didRegisterUserNotificationSettings:notificationSettings];
}
}
}
#pragma GCC diagnostic pop
- (void)application:(UIApplication*)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
for (NSObject<FlutterApplicationLifeCycleDelegate>* delegate in _delegates) {
if (!delegate) {
continue;
}
if ([delegate respondsToSelector:_cmd]) {
[delegate application:application
didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
}
}
- (void)application:(UIApplication*)application
didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
for (NSObject<FlutterApplicationLifeCycleDelegate>* delegate in _delegates) {
if (!delegate) {
continue;
}
if ([delegate respondsToSelector:_cmd]) {
[delegate application:application didFailToRegisterForRemoteNotificationsWithError:error];
}
}
}
- (void)application:(UIApplication*)application
didReceiveRemoteNotification:(NSDictionary*)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
for (NSObject<FlutterApplicationLifeCycleDelegate>* delegate in _delegates) {
if (!delegate) {
continue;
}
if ([delegate respondsToSelector:_cmd]) {
if ([delegate application:application
didReceiveRemoteNotification:userInfo
fetchCompletionHandler:completionHandler]) {
return;
}
}
}
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
- (void)application:(UIApplication*)application
didReceiveLocalNotification:(UILocalNotification*)notification {
for (NSObject<FlutterApplicationLifeCycleDelegate>* delegate in _delegates) {
if (!delegate) {
continue;
}
if ([delegate respondsToSelector:_cmd]) {
[delegate application:application didReceiveLocalNotification:notification];
}
}
}
#pragma GCC diagnostic pop
- (void)userNotificationCenter:(UNUserNotificationCenter*)center
willPresentNotification:(UNNotification*)notification
withCompletionHandler:
(void (^)(UNNotificationPresentationOptions options))completionHandler {
for (NSObject<FlutterApplicationLifeCycleDelegate>* delegate in _delegates) {
if ([delegate respondsToSelector:_cmd]) {
[delegate userNotificationCenter:center
willPresentNotification:notification
withCompletionHandler:completionHandler];
}
}
}
- (void)userNotificationCenter:(UNUserNotificationCenter*)center
didReceiveNotificationResponse:(UNNotificationResponse*)response
withCompletionHandler:(void (^)(void))completionHandler {
for (id<FlutterApplicationLifeCycleDelegate> delegate in _delegates) {
if ([delegate respondsToSelector:_cmd]) {
[delegate userNotificationCenter:center
didReceiveNotificationResponse:response
withCompletionHandler:completionHandler];
}
}
}
- (BOOL)application:(UIApplication*)application
openURL:(NSURL*)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey, id>*)options {
for (NSObject<FlutterApplicationLifeCycleDelegate>* delegate in _delegates) {
if (!delegate) {
continue;
}
if ([delegate respondsToSelector:_cmd]) {
if ([delegate application:application openURL:url options:options]) {
return YES;
}
}
}
return NO;
}
- (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)url {
for (NSObject<FlutterApplicationLifeCycleDelegate>* delegate in _delegates) {
if (!delegate) {
continue;
}
if ([delegate respondsToSelector:_cmd]) {
if ([delegate application:application handleOpenURL:url]) {
return YES;
}
}
}
return NO;
}
- (BOOL)application:(UIApplication*)application
openURL:(NSURL*)url
sourceApplication:(NSString*)sourceApplication
annotation:(id)annotation {
for (NSObject<FlutterApplicationLifeCycleDelegate>* delegate in _delegates) {
if (!delegate) {
continue;
}
if ([delegate respondsToSelector:_cmd]) {
if ([delegate application:application
openURL:url
sourceApplication:sourceApplication
annotation:annotation]) {
return YES;
}
}
}
return NO;
}
- (void)application:(UIApplication*)application
performActionForShortcutItem:(UIApplicationShortcutItem*)shortcutItem
completionHandler:(void (^)(BOOL succeeded))completionHandler {
for (NSObject<FlutterApplicationLifeCycleDelegate>* delegate in _delegates) {
if (!delegate) {
continue;
}
if ([delegate respondsToSelector:_cmd]) {
if ([delegate application:application
performActionForShortcutItem:shortcutItem
completionHandler:completionHandler]) {
return;
}
}
}
}
- (BOOL)application:(UIApplication*)application
handleEventsForBackgroundURLSession:(nonnull NSString*)identifier
completionHandler:(nonnull void (^)())completionHandler {
for (NSObject<FlutterApplicationLifeCycleDelegate>* delegate in _delegates) {
if (!delegate) {
continue;
}
if ([delegate respondsToSelector:_cmd]) {
if ([delegate application:application
handleEventsForBackgroundURLSession:identifier
completionHandler:completionHandler]) {
return YES;
}
}
}
return NO;
}
- (BOOL)application:(UIApplication*)application
performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
for (NSObject<FlutterApplicationLifeCycleDelegate>* delegate in _delegates) {
if (!delegate) {
continue;
}
if ([delegate respondsToSelector:_cmd]) {
if ([delegate application:application performFetchWithCompletionHandler:completionHandler]) {
return YES;
}
}
}
return NO;
}
- (BOOL)application:(UIApplication*)application
continueUserActivity:(NSUserActivity*)userActivity
restorationHandler:(void (^)(NSArray*))restorationHandler {
for (NSObject<FlutterApplicationLifeCycleDelegate>* delegate in _delegates) {
if (!delegate) {
continue;
}
if ([delegate respondsToSelector:_cmd]) {
if ([delegate application:application
continueUserActivity:userActivity
restorationHandler:restorationHandler]) {
return YES;
}
}
}
return NO;
}
@end
| engine/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegate.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegate.mm",
"repo_id": "engine",
"token_count": 5780
} | 319 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextureRegistryRelay.h"
#include "flutter/fml/logging.h"
@implementation FlutterTextureRegistryRelay : NSObject
#pragma mark - FlutterTextureRegistry
- (instancetype)initWithParent:(NSObject<FlutterTextureRegistry>*)parent {
if (self = [super init]) {
_parent = parent;
}
return self;
}
- (int64_t)registerTexture:(NSObject<FlutterTexture>*)texture {
if (!self.parent) {
FML_LOG(WARNING) << "Using on an empty registry.";
return 0;
}
return [self.parent registerTexture:texture];
}
- (void)textureFrameAvailable:(int64_t)textureId {
if (!self.parent) {
FML_LOG(WARNING) << "Using on an empty registry.";
}
return [self.parent textureFrameAvailable:textureId];
}
- (void)unregisterTexture:(int64_t)textureId {
if (!self.parent) {
FML_LOG(WARNING) << "Using on an empty registry.";
}
return [self.parent unregisterTexture:textureId];
}
@end
| engine/shell/platform/darwin/ios/framework/Source/FlutterTextureRegistryRelay.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterTextureRegistryRelay.mm",
"repo_id": "engine",
"token_count": 378
} | 320 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <XCTest/XCTest.h>
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h"
FLUTTER_ASSERT_ARC
@interface FakeDelegate : NSObject <FlutterViewEngineDelegate>
@property(nonatomic) BOOL callbackCalled;
@property(nonatomic, assign) BOOL isUsingImpeller;
@end
@implementation FakeDelegate {
std::shared_ptr<flutter::FlutterPlatformViewsController> _platformViewsController;
}
- (instancetype)init {
_callbackCalled = NO;
_platformViewsController = std::shared_ptr<flutter::FlutterPlatformViewsController>(nullptr);
return self;
}
- (flutter::Rasterizer::Screenshot)takeScreenshot:(flutter::Rasterizer::ScreenshotType)type
asBase64Encoded:(BOOL)base64Encode {
return {};
}
- (std::shared_ptr<flutter::FlutterPlatformViewsController>&)platformViewsController {
return _platformViewsController;
}
- (void)flutterViewAccessibilityDidCall {
_callbackCalled = YES;
}
@end
@interface FlutterViewTest : XCTestCase
@end
@implementation FlutterViewTest
- (void)testFlutterViewEnableSemanticsWhenIsAccessibilityElementIsCalled {
FakeDelegate* delegate = [[FakeDelegate alloc] init];
FlutterView* view = [[FlutterView alloc] initWithDelegate:delegate opaque:NO enableWideGamut:NO];
delegate.callbackCalled = NO;
XCTAssertFalse(view.isAccessibilityElement);
XCTAssertTrue(delegate.callbackCalled);
}
- (void)testFlutterViewBackgroundColorIsNotNil {
FakeDelegate* delegate = [[FakeDelegate alloc] init];
FlutterView* view = [[FlutterView alloc] initWithDelegate:delegate opaque:NO enableWideGamut:NO];
XCTAssertNotNil(view.backgroundColor);
}
- (void)testIgnoreWideColorWithoutImpeller {
FakeDelegate* delegate = [[FakeDelegate alloc] init];
delegate.isUsingImpeller = NO;
FlutterView* view = [[FlutterView alloc] initWithDelegate:delegate opaque:NO enableWideGamut:YES];
[view layoutSubviews];
XCTAssertTrue([view.layer isKindOfClass:NSClassFromString(@"CAMetalLayer")]);
CAMetalLayer* layer = (CAMetalLayer*)view.layer;
XCTAssertEqual(layer.pixelFormat, MTLPixelFormatBGRA8Unorm);
}
- (void)testLayerScalesMatchScreenAfterLayoutSubviews {
FakeDelegate* delegate = [[FakeDelegate alloc] init];
FlutterView* view = [[FlutterView alloc] initWithDelegate:delegate opaque:NO enableWideGamut:NO];
view.layer.contentsScale = CGFloat(-99.0);
view.layer.rasterizationScale = CGFloat(-99.0);
UIScreen* screen = [view screen];
XCTAssertNotEqual(view.layer.contentsScale, screen.scale);
XCTAssertNotEqual(view.layer.rasterizationScale, screen.scale);
[view layoutSubviews];
XCTAssertEqual(view.layer.contentsScale, screen.scale);
XCTAssertEqual(view.layer.rasterizationScale, screen.scale);
}
@end
| engine/shell/platform/darwin/ios/framework/Source/FlutterViewTest.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterViewTest.mm",
"repo_id": "engine",
"token_count": 1031
} | 321 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_TEXT_ENTRY_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_TEXT_ENTRY_H_
/**
* An implementation of `UITextInput` used for text fields that do not currently
* have input focus.
*
* This class is used by `TextInputSemanticsObject`.
*/
@interface FlutterInactiveTextInput : UIView <UITextInput>
@property(nonatomic, copy) NSString* text;
@property(nonatomic, copy, readonly) NSMutableString* markedText;
@property(copy) UITextRange* selectedTextRange;
@property(nonatomic, strong, readonly) UITextRange* markedTextRange;
@property(nonatomic, copy) NSDictionary<NSAttributedStringKey, id>* markedTextStyle;
@property(nonatomic, assign) id<UITextInputDelegate> inputDelegate;
@end
/**
* An implementation of `SemanticsObject` specialized for expressing text
* fields.
*
* Delegates to `FlutterTextInputView` when the object corresponds to a text
* field that currently owns input focus. Delegates to
* `FlutterInactiveTextInput` otherwise.
*/
@interface TextInputSemanticsObject : SemanticsObject <UITextInput>
@end
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_TEXT_ENTRY_H_
| engine/shell/platform/darwin/ios/framework/Source/accessibility_text_entry.h/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/accessibility_text_entry.h",
"repo_id": "engine",
"token_count": 444
} | 322 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/ios/ios_context_metal_impeller.h"
#include "flutter/impeller/entity/mtl/entity_shaders.h"
#import "flutter/shell/platform/darwin/ios/ios_external_texture_metal.h"
namespace flutter {
IOSContextMetalImpeller::IOSContextMetalImpeller(
const std::shared_ptr<const fml::SyncSwitch>& is_gpu_disabled_sync_switch)
: IOSContext(MsaaSampleCount::kFour),
darwin_context_metal_impeller_(fml::scoped_nsobject<FlutterDarwinContextMetalImpeller>{
[[FlutterDarwinContextMetalImpeller alloc] init:is_gpu_disabled_sync_switch]}) {}
IOSContextMetalImpeller::~IOSContextMetalImpeller() = default;
fml::scoped_nsobject<FlutterDarwinContextMetalSkia> IOSContextMetalImpeller::GetDarwinContext()
const {
return fml::scoped_nsobject<FlutterDarwinContextMetalSkia>{};
}
IOSRenderingBackend IOSContextMetalImpeller::GetBackend() const {
return IOSRenderingBackend::kImpeller;
}
sk_sp<GrDirectContext> IOSContextMetalImpeller::GetMainContext() const {
return nullptr;
}
sk_sp<GrDirectContext> IOSContextMetalImpeller::GetResourceContext() const {
return nullptr;
}
// |IOSContext|
sk_sp<GrDirectContext> IOSContextMetalImpeller::CreateResourceContext() {
return nullptr;
}
// |IOSContext|
std::shared_ptr<impeller::Context> IOSContextMetalImpeller::GetImpellerContext() const {
return darwin_context_metal_impeller_.get().context;
}
// |IOSContext|
std::unique_ptr<GLContextResult> IOSContextMetalImpeller::MakeCurrent() {
// This only makes sense for contexts that need to be bound to a specific thread.
return std::make_unique<GLContextDefaultResult>(true);
}
// |IOSContext|
std::unique_ptr<Texture> IOSContextMetalImpeller::CreateExternalTexture(
int64_t texture_id,
fml::scoped_nsobject<NSObject<FlutterTexture>> texture) {
return std::make_unique<IOSExternalTextureMetal>(
fml::scoped_nsobject<FlutterDarwinExternalTextureMetal>{
[[darwin_context_metal_impeller_ createExternalTextureWithIdentifier:texture_id
texture:texture] retain]});
}
} // namespace flutter
| engine/shell/platform/darwin/ios/ios_context_metal_impeller.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/ios_context_metal_impeller.mm",
"repo_id": "engine",
"token_count": 850
} | 323 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/ios/ios_surface_software.h"
#include <QuartzCore/CALayer.h>
#include <memory>
#include "flutter/fml/logging.h"
#include "flutter/fml/platform/darwin/cf_utils.h"
#include "flutter/fml/trace_event.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "third_party/skia/include/utils/mac/SkCGUtils.h"
namespace flutter {
IOSSurfaceSoftware::IOSSurfaceSoftware(const fml::scoped_nsobject<CALayer>& layer,
std::shared_ptr<IOSContext> context)
: IOSSurface(std::move(context)), layer_(layer) {}
IOSSurfaceSoftware::~IOSSurfaceSoftware() = default;
bool IOSSurfaceSoftware::IsValid() const {
return layer_;
}
void IOSSurfaceSoftware::UpdateStorageSizeIfNecessary() {
// Nothing to do here. We don't need an external entity to tell us when our
// backing store needs to be updated. Instead, we let the frame tell us its
// size so we can update to match. This method was added to work around
// Android oddities.
}
std::unique_ptr<Surface> IOSSurfaceSoftware::CreateGPUSurface(GrDirectContext* gr_context) {
if (!IsValid()) {
return nullptr;
}
auto surface = std::make_unique<GPUSurfaceSoftware>(this, true /* render to surface */);
if (!surface->IsValid()) {
return nullptr;
}
return surface;
}
sk_sp<SkSurface> IOSSurfaceSoftware::AcquireBackingStore(const SkISize& size) {
TRACE_EVENT0("flutter", "IOSSurfaceSoftware::AcquireBackingStore");
if (!IsValid()) {
return nullptr;
}
if (sk_surface_ != nullptr &&
SkISize::Make(sk_surface_->width(), sk_surface_->height()) == size) {
// The old and new surface sizes are the same. Nothing to do here.
return sk_surface_;
}
SkImageInfo info = SkImageInfo::MakeN32(size.fWidth, size.fHeight, kPremul_SkAlphaType,
SkColorSpace::MakeSRGB());
sk_surface_ = SkSurfaces::Raster(info, nullptr);
return sk_surface_;
}
bool IOSSurfaceSoftware::PresentBackingStore(sk_sp<SkSurface> backing_store) {
TRACE_EVENT0("flutter", "IOSSurfaceSoftware::PresentBackingStore");
if (!IsValid() || backing_store == nullptr) {
return false;
}
SkPixmap pixmap;
if (!backing_store->peekPixels(&pixmap)) {
return false;
}
// Some basic sanity checking.
uint64_t expected_pixmap_data_size = pixmap.width() * pixmap.height() * 4;
const size_t pixmap_size = pixmap.computeByteSize();
if (expected_pixmap_data_size != pixmap_size) {
return false;
}
fml::CFRef<CGColorSpaceRef> colorspace(CGColorSpaceCreateDeviceRGB());
// Setup the data provider that gives CG a view into the pixmap.
fml::CFRef<CGDataProviderRef> pixmap_data_provider(CGDataProviderCreateWithData(
nullptr, // info
pixmap.addr32(), // data
pixmap_size, // size
nullptr // release callback
));
if (!pixmap_data_provider) {
return false;
}
// Create the CGImageRef representation on the pixmap.
fml::CFRef<CGImageRef> pixmap_image(CGImageCreate(pixmap.width(), // width
pixmap.height(), // height
8, // bits per component
32, // bits per pixel
pixmap.rowBytes(), // bytes per row
colorspace, // colorspace
kCGImageAlphaPremultipliedLast, // bitmap info
pixmap_data_provider, // data provider
nullptr, // decode array
false, // should interpolate
kCGRenderingIntentDefault // rendering intent
));
if (!pixmap_image) {
return false;
}
layer_.get().contents = reinterpret_cast<id>(static_cast<CGImageRef>(pixmap_image));
return true;
}
} // namespace flutter
| engine/shell/platform/darwin/ios/ios_surface_software.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/ios_surface_software.mm",
"repo_id": "engine",
"token_count": 2036
} | 324 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERPLUGINREGISTRARMACOS_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERPLUGINREGISTRARMACOS_H_
#import <Cocoa/Cocoa.h>
#import "FlutterBinaryMessenger.h"
#import "FlutterChannels.h"
#import "FlutterMacros.h"
#import "FlutterPlatformViews.h"
#import "FlutterPluginMacOS.h"
#import "FlutterTexture.h"
// TODO(stuartmorgan): Merge this file and FlutterPluginMacOS.h with the iOS FlutterPlugin.h,
// sharing all but the platform-specific methods.
/**
* The protocol for an object managing registration for a plugin. It provides access to application
* context, as allowing registering for callbacks for handling various conditions.
*
* Currently the macOS PluginRegistrar has very limited functionality, but is expected to expand
* over time to more closely match the functionality of FlutterPluginRegistrar.
*/
FLUTTER_DARWIN_EXPORT
@protocol FlutterPluginRegistrar <NSObject>
/**
* The binary messenger used for creating channels to communicate with the Flutter engine.
*/
@property(nonnull, readonly) id<FlutterBinaryMessenger> messenger;
/**
* Returns a `FlutterTextureRegistry` for registering textures
* provided by the plugin.
*/
@property(nonnull, readonly) id<FlutterTextureRegistry> textures;
/**
* The view displaying Flutter content.
*
* This property is provided for backwards compatibility for apps
* that assume a single view. This will eventually be replaced by
* a multi-view API variant.
*
* This method may return |nil|, for instance in a headless environment.
*/
@property(nullable, readonly) NSView* view;
/**
* Registers |delegate| to receive handleMethodCall:result: callbacks for the given |channel|.
*/
- (void)addMethodCallDelegate:(nonnull id<FlutterPlugin>)delegate
channel:(nonnull FlutterMethodChannel*)channel;
/**
* Registers the plugin as a receiver of `NSApplicationDelegate` calls.
*
* @param delegate The receiving object, such as the plugin's main class.
*/
- (void)addApplicationDelegate:(nonnull NSObject<FlutterAppLifecycleDelegate>*)delegate;
/**
* Registers a `FlutterPlatformViewFactory` for creation of platform views.
*
* Plugins expose `NSView` for embedding in Flutter apps by registering a view factory.
*
* @param factory The view factory that will be registered.
* @param factoryId A unique identifier for the factory, the Dart code of the Flutter app can use
* this identifier to request creation of a `NSView` by the registered factory.
*/
- (void)registerViewFactory:(nonnull NSObject<FlutterPlatformViewFactory>*)factory
withId:(nonnull NSString*)factoryId;
/**
* Publishes a value for external use of the plugin.
*
* Plugins may publish a single value, such as an instance of the
* plugin's main class, for situations where external control or
* interaction is needed.
*
* The published value will be available from the `FlutterPluginRegistry`.
* Repeated calls overwrite any previous publication.
*
* @param value The value to be published.
*/
- (void)publish:(nonnull NSObject*)value;
/**
* Returns the file name for the given asset.
* The returned file name can be used to access the asset in the application's main bundle.
*
* @param asset The name of the asset. The name can be hierarchical.
* @return the file name to be used for lookup in the main bundle.
*/
- (nonnull NSString*)lookupKeyForAsset:(nonnull NSString*)asset;
/**
* Returns the file name for the given asset which originates from the specified package.
* The returned file name can be used to access the asset in the application's main bundle.
*
*
* @param asset The name of the asset. The name can be hierarchical.
* @param package The name of the package from which the asset originates.
* @return the file name to be used for lookup in the main bundle.
*/
- (nonnull NSString*)lookupKeyForAsset:(nonnull NSString*)asset
fromPackage:(nonnull NSString*)package;
@end
/**
* A registry of Flutter macOS plugins.
*
* Plugins are identified by unique string keys, typically the name of the
* plugin's main class.
*
* Plugins typically need contextual information and the ability to register
* callbacks for various application events. To keep the API of the registry
* focused, these facilities are not provided directly by the registry, but by
* a `FlutterPluginRegistrar`, created by the registry in exchange for the unique
* key of the plugin.
*
* There is no implied connection between the registry and the registrar.
* Specifically, callbacks registered by the plugin via the registrar may be
* relayed directly to the underlying iOS application objects.
*/
@protocol FlutterPluginRegistry <NSObject>
/**
* Returns a registrar for registering a plugin.
*
* @param pluginKey The unique key identifying the plugin.
*/
- (nonnull id<FlutterPluginRegistrar>)registrarForPlugin:(nonnull NSString*)pluginKey;
/**
* Returns a value published by the specified plugin.
*
* @param pluginKey The unique key identifying the plugin.
* @return An object published by the plugin, if any. Will be `NSNull` if
* nothing has been published. Will be `nil` if the plugin has not been
* registered.
*/
- (nullable NSObject*)valuePublishedByPlugin:(nonnull NSString*)pluginKey;
@end
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERPLUGINREGISTRARMACOS_H_
| engine/shell/platform/darwin/macos/framework/Headers/FlutterPluginRegistrarMacOS.h/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Headers/FlutterPluginRegistrarMacOS.h",
"repo_id": "engine",
"token_count": 1597
} | 325 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponder.h"
#include <Carbon/Carbon.h>
#import <Foundation/Foundation.h>
#include "flutter/shell/platform/embedder/test_utils/key_codes.g.h"
#include "flutter/testing/autoreleasepool_test.h"
#include "flutter/testing/testing.h"
#include "third_party/googletest/googletest/include/gtest/gtest.h"
// FlutterBasicMessageChannel fake instance that records Flutter key event messages.
//
// When a sendMessage:reply: callback is specified, it is invoked with the value stored in the
// nextResponse property.
@interface FakeMessageChannel : FlutterBasicMessageChannel
@property(nonatomic, readonly) NSMutableArray<id>* messages;
@property(nonatomic) NSDictionary* nextResponse;
- (instancetype)init;
- (void)sendMessage:(id _Nullable)message;
- (void)sendMessage:(id _Nullable)message reply:(FlutterReply _Nullable)callback;
@end
@implementation FakeMessageChannel
- (instancetype)init {
self = [super init];
if (self != nil) {
_messages = [[NSMutableArray<id> alloc] init];
}
return self;
}
- (void)sendMessage:(id _Nullable)message {
[self sendMessage:message reply:nil];
}
- (void)sendMessage:(id _Nullable)message reply:(FlutterReply _Nullable)callback {
[_messages addObject:message];
if (callback) {
callback(_nextResponse);
}
}
@end
namespace flutter::testing {
namespace {
using flutter::testing::keycodes::kLogicalKeyQ;
NSEvent* CreateKeyEvent(NSEventType type,
NSEventModifierFlags modifierFlags,
NSString* characters,
NSString* charactersIgnoringModifiers,
BOOL isARepeat,
unsigned short keyCode) {
return [NSEvent keyEventWithType:type
location:NSZeroPoint
modifierFlags:modifierFlags
timestamp:0
windowNumber:0
context:nil
characters:characters
charactersIgnoringModifiers:charactersIgnoringModifiers
isARepeat:isARepeat
keyCode:keyCode];
}
} // namespace
using FlutterChannelKeyResponderTest = AutoreleasePoolTest;
TEST_F(FlutterChannelKeyResponderTest, BasicKeyEvent) {
__block NSMutableArray<NSNumber*>* responses = [[NSMutableArray<NSNumber*> alloc] init];
FakeMessageChannel* channel = [[FakeMessageChannel alloc] init];
FlutterChannelKeyResponder* responder =
[[FlutterChannelKeyResponder alloc] initWithChannel:channel];
// Initial empty modifiers.
//
// This can happen when user opens window while modifier key is pressed and then releases the
// modifier. No events should be sent, but the callback should still be called.
// Regression test for https://github.com/flutter/flutter/issues/87339.
channel.nextResponse = @{@"handled" : @YES};
[responder handleEvent:CreateKeyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", NO, 60)
callback:^(BOOL handled) {
[responses addObject:@(handled)];
}];
EXPECT_EQ([channel.messages count], 0u);
ASSERT_EQ([responses count], 1u);
EXPECT_EQ([responses[0] boolValue], YES);
[responses removeAllObjects];
// Key down
channel.nextResponse = @{@"handled" : @YES};
[responder handleEvent:CreateKeyEvent(NSEventTypeKeyDown, 0x100, @"a", @"a", NO, 0)
callback:^(BOOL handled) {
[responses addObject:@(handled)];
}];
ASSERT_EQ([channel.messages count], 1u);
EXPECT_STREQ([[channel.messages lastObject][@"keymap"] UTF8String], "macos");
EXPECT_STREQ([[channel.messages lastObject][@"type"] UTF8String], "keydown");
EXPECT_EQ([[channel.messages lastObject][@"keyCode"] intValue], 0);
EXPECT_EQ([[channel.messages lastObject][@"modifiers"] intValue], 0x0);
EXPECT_STREQ([[channel.messages lastObject][@"characters"] UTF8String], "a");
EXPECT_STREQ([[channel.messages lastObject][@"charactersIgnoringModifiers"] UTF8String], "a");
ASSERT_EQ([responses count], 1u);
EXPECT_EQ([[responses lastObject] boolValue], YES);
[channel.messages removeAllObjects];
[responses removeAllObjects];
// Key up
channel.nextResponse = @{@"handled" : @NO};
[responder handleEvent:CreateKeyEvent(NSEventTypeKeyUp, 0x100, @"a", @"a", NO, 0)
callback:^(BOOL handled) {
[responses addObject:@(handled)];
}];
ASSERT_EQ([channel.messages count], 1u);
EXPECT_STREQ([[channel.messages lastObject][@"keymap"] UTF8String], "macos");
EXPECT_STREQ([[channel.messages lastObject][@"type"] UTF8String], "keyup");
EXPECT_EQ([[channel.messages lastObject][@"keyCode"] intValue], 0);
EXPECT_EQ([[channel.messages lastObject][@"modifiers"] intValue], 0);
EXPECT_STREQ([[channel.messages lastObject][@"characters"] UTF8String], "a");
EXPECT_STREQ([[channel.messages lastObject][@"charactersIgnoringModifiers"] UTF8String], "a");
ASSERT_EQ([responses count], 1u);
EXPECT_EQ([[responses lastObject] boolValue], NO);
[channel.messages removeAllObjects];
[responses removeAllObjects];
// LShift down
channel.nextResponse = @{@"handled" : @YES};
[responder handleEvent:CreateKeyEvent(NSEventTypeFlagsChanged, 0x20102, @"", @"", NO, 56)
callback:^(BOOL handled) {
[responses addObject:@(handled)];
}];
ASSERT_EQ([channel.messages count], 1u);
EXPECT_STREQ([[channel.messages lastObject][@"keymap"] UTF8String], "macos");
EXPECT_STREQ([[channel.messages lastObject][@"type"] UTF8String], "keydown");
EXPECT_EQ([[channel.messages lastObject][@"keyCode"] intValue], 56);
EXPECT_EQ([[channel.messages lastObject][@"modifiers"] intValue], 0x20002);
ASSERT_EQ([responses count], 1u);
EXPECT_EQ([[responses lastObject] boolValue], YES);
[channel.messages removeAllObjects];
[responses removeAllObjects];
// RShift down
channel.nextResponse = @{@"handled" : @NO};
[responder handleEvent:CreateKeyEvent(NSEventTypeFlagsChanged, 0x20006, @"", @"", NO, 60)
callback:^(BOOL handled) {
[responses addObject:@(handled)];
}];
ASSERT_EQ([channel.messages count], 1u);
EXPECT_STREQ([[channel.messages lastObject][@"keymap"] UTF8String], "macos");
EXPECT_STREQ([[channel.messages lastObject][@"type"] UTF8String], "keydown");
EXPECT_EQ([[channel.messages lastObject][@"keyCode"] intValue], 60);
EXPECT_EQ([[channel.messages lastObject][@"modifiers"] intValue], 0x20006);
ASSERT_EQ([responses count], 1u);
EXPECT_EQ([[responses lastObject] boolValue], NO);
[channel.messages removeAllObjects];
[responses removeAllObjects];
// LShift up
channel.nextResponse = @{@"handled" : @NO};
[responder handleEvent:CreateKeyEvent(NSEventTypeFlagsChanged, 0x20104, @"", @"", NO, 56)
callback:^(BOOL handled) {
[responses addObject:@(handled)];
}];
ASSERT_EQ([channel.messages count], 1u);
EXPECT_STREQ([[channel.messages lastObject][@"keymap"] UTF8String], "macos");
EXPECT_STREQ([[channel.messages lastObject][@"type"] UTF8String], "keyup");
EXPECT_EQ([[channel.messages lastObject][@"keyCode"] intValue], 56);
EXPECT_EQ([[channel.messages lastObject][@"modifiers"] intValue], 0x20004);
ASSERT_EQ([responses count], 1u);
EXPECT_EQ([[responses lastObject] boolValue], NO);
[channel.messages removeAllObjects];
[responses removeAllObjects];
// RShift up
channel.nextResponse = @{@"handled" : @NO};
[responder handleEvent:CreateKeyEvent(NSEventTypeFlagsChanged, 0, @"", @"", NO, 60)
callback:^(BOOL handled) {
[responses addObject:@(handled)];
}];
ASSERT_EQ([channel.messages count], 1u);
EXPECT_STREQ([[channel.messages lastObject][@"keymap"] UTF8String], "macos");
EXPECT_STREQ([[channel.messages lastObject][@"type"] UTF8String], "keyup");
EXPECT_EQ([[channel.messages lastObject][@"keyCode"] intValue], 60);
EXPECT_EQ([[channel.messages lastObject][@"modifiers"] intValue], 0);
ASSERT_EQ([responses count], 1u);
EXPECT_EQ([[responses lastObject] boolValue], NO);
[channel.messages removeAllObjects];
[responses removeAllObjects];
// RShift up again, should be ignored and not produce a keydown event, but the
// callback should be called.
channel.nextResponse = @{@"handled" : @NO};
[responder handleEvent:CreateKeyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", NO, 60)
callback:^(BOOL handled) {
[responses addObject:@(handled)];
}];
EXPECT_EQ([channel.messages count], 0u);
ASSERT_EQ([responses count], 1u);
EXPECT_EQ([responses[0] boolValue], YES);
}
TEST_F(FlutterChannelKeyResponderTest, EmptyResponseIsTakenAsHandled) {
__block NSMutableArray<NSNumber*>* responses = [[NSMutableArray<NSNumber*> alloc] init];
FakeMessageChannel* channel = [[FakeMessageChannel alloc] init];
FlutterChannelKeyResponder* responder =
[[FlutterChannelKeyResponder alloc] initWithChannel:channel];
channel.nextResponse = nil;
[responder handleEvent:CreateKeyEvent(NSEventTypeKeyDown, 0x100, @"a", @"a", NO, 0)
callback:^(BOOL handled) {
[responses addObject:@(handled)];
}];
ASSERT_EQ([channel.messages count], 1u);
EXPECT_STREQ([[channel.messages lastObject][@"keymap"] UTF8String], "macos");
EXPECT_STREQ([[channel.messages lastObject][@"type"] UTF8String], "keydown");
EXPECT_EQ([[channel.messages lastObject][@"keyCode"] intValue], 0);
EXPECT_EQ([[channel.messages lastObject][@"modifiers"] intValue], 0);
EXPECT_STREQ([[channel.messages lastObject][@"characters"] UTF8String], "a");
EXPECT_STREQ([[channel.messages lastObject][@"charactersIgnoringModifiers"] UTF8String], "a");
ASSERT_EQ([responses count], 1u);
EXPECT_EQ([[responses lastObject] boolValue], YES);
}
TEST_F(FlutterChannelKeyResponderTest, FollowsLayoutMap) {
__block NSMutableArray<NSNumber*>* responses = [[NSMutableArray<NSNumber*> alloc] init];
FakeMessageChannel* channel = [[FakeMessageChannel alloc] init];
FlutterChannelKeyResponder* responder =
[[FlutterChannelKeyResponder alloc] initWithChannel:channel];
NSMutableDictionary<NSNumber*, NSNumber*>* layoutMap =
[NSMutableDictionary<NSNumber*, NSNumber*> dictionary];
responder.layoutMap = layoutMap;
// French layout
layoutMap[@(kVK_ANSI_A)] = @(kLogicalKeyQ);
channel.nextResponse = @{@"handled" : @YES};
[responder handleEvent:CreateKeyEvent(NSEventTypeKeyDown, kVK_ANSI_A, @"q", @"q", NO, 0)
callback:^(BOOL handled) {
[responses addObject:@(handled)];
}];
ASSERT_EQ([channel.messages count], 1u);
EXPECT_STREQ([[channel.messages lastObject][@"keymap"] UTF8String], "macos");
EXPECT_STREQ([[channel.messages lastObject][@"type"] UTF8String], "keydown");
EXPECT_EQ([[channel.messages lastObject][@"keyCode"] intValue], 0);
EXPECT_EQ([[channel.messages lastObject][@"modifiers"] intValue], 0x0);
EXPECT_STREQ([[channel.messages lastObject][@"characters"] UTF8String], "q");
EXPECT_STREQ([[channel.messages lastObject][@"charactersIgnoringModifiers"] UTF8String], "q");
EXPECT_EQ([channel.messages lastObject][@"specifiedLogicalKey"], @(kLogicalKeyQ));
ASSERT_EQ([responses count], 1u);
EXPECT_EQ([[responses lastObject] boolValue], YES);
[channel.messages removeAllObjects];
[responses removeAllObjects];
}
} // namespace flutter::testing
| engine/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponderTest.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponderTest.mm",
"repo_id": "engine",
"token_count": 4595
} | 326 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERENGINE_INTERNAL_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERENGINE_INTERNAL_H_
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h"
#import <Cocoa/Cocoa.h>
#include <memory>
#include "flutter/shell/platform/common/app_lifecycle_state.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMac.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterCompositor.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewController.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderer.h"
NS_ASSUME_NONNULL_BEGIN
#pragma mark - Typedefs
typedef void (^FlutterTerminationCallback)(id _Nullable sender);
#pragma mark - Enumerations
/**
* An enum for defining the different request types allowed when requesting an
* application exit.
*
* Must match the entries in the `AppExitType` enum in the Dart code.
*/
typedef NS_ENUM(NSInteger, FlutterAppExitType) {
kFlutterAppExitTypeCancelable = 0,
kFlutterAppExitTypeRequired = 1,
};
/**
* An enum for defining the different responses the framework can give to an
* application exit request from the engine.
*
* Must match the entries in the `AppExitResponse` enum in the Dart code.
*/
typedef NS_ENUM(NSInteger, FlutterAppExitResponse) {
kFlutterAppExitResponseCancel = 0,
kFlutterAppExitResponseExit = 1,
};
#pragma mark - FlutterEngineTerminationHandler
/**
* A handler interface for handling application termination that the
* FlutterAppDelegate can use to coordinate an application exit by sending
* messages through the platform channel managed by the engine.
*/
@interface FlutterEngineTerminationHandler : NSObject
@property(nonatomic, readonly) BOOL shouldTerminate;
@property(nonatomic, readwrite) BOOL acceptingRequests;
- (instancetype)initWithEngine:(FlutterEngine*)engine
terminator:(nullable FlutterTerminationCallback)terminator;
- (void)handleRequestAppExitMethodCall:(NSDictionary<NSString*, id>*)data
result:(FlutterResult)result;
- (void)requestApplicationTermination:(NSApplication*)sender
exitType:(FlutterAppExitType)type
result:(nullable FlutterResult)result;
@end
/**
* An NSPasteboard wrapper object to allow for substitution of a fake in unit tests.
*/
@interface FlutterPasteboard : NSObject
- (NSInteger)clearContents;
- (NSString*)stringForType:(NSPasteboardType)dataType;
- (BOOL)setString:(NSString*)string forType:(NSPasteboardType)dataType;
@end
@interface FlutterEngine ()
/**
* True if the engine is currently running.
*/
@property(nonatomic, readonly) BOOL running;
/**
* Provides the renderer config needed to initialize the engine and also handles external
* texture management.
*/
@property(nonatomic, readonly, nullable) FlutterRenderer* renderer;
/**
* Function pointers for interacting with the embedder.h API.
*/
@property(nonatomic) FlutterEngineProcTable& embedderAPI;
/**
* True if the semantics is enabled. The Flutter framework starts sending
* semantics update through the embedder as soon as it is set to YES.
*/
@property(nonatomic) BOOL semanticsEnabled;
/**
* The executable name for the current process.
*/
@property(nonatomic, readonly, nonnull) NSString* executableName;
/**
* This just returns the NSPasteboard so that it can be mocked in the tests.
*/
@property(nonatomic, nonnull) FlutterPasteboard* pasteboard;
/**
* The command line arguments array for the engine.
*/
@property(nonatomic, readonly) std::vector<std::string> switches;
/**
* Provides the |FlutterEngineTerminationHandler| to be used for this engine.
*/
@property(nonatomic, readonly) FlutterEngineTerminationHandler* terminationHandler;
/**
* Attach a view controller to the engine as its default controller.
*
* Practically, since FlutterEngine can only be attached with one controller,
* the given controller, if successfully attached, will always have the default
* view ID kFlutterImplicitViewId.
*
* The engine holds a weak reference to the attached view controller.
*
* If the given view controller is already attached to an engine, this call
* throws an assertion.
*/
- (void)addViewController:(FlutterViewController*)viewController;
/**
* Notify the engine that a view for the given view controller has been loaded.
*/
- (void)viewControllerViewDidLoad:(FlutterViewController*)viewController;
/**
* Dissociate the given view controller from this engine.
*
* If the view controller is not associated with this engine, this call throws an
* assertion.
*
* Practically, since FlutterEngine can only be attached with one controller for
* now, the given controller must be the current view controller.
*/
- (void)removeViewController:(FlutterViewController*)viewController;
/**
* The |FlutterViewController| associated with the given view ID, if any.
*/
- (nullable FlutterViewController*)viewControllerForId:(FlutterViewId)viewId;
/**
* Informs the engine that the specified view controller's window metrics have changed.
*/
- (void)updateWindowMetricsForViewController:(FlutterViewController*)viewController;
/**
* Dispatches the given pointer event data to engine.
*/
- (void)sendPointerEvent:(const FlutterPointerEvent&)event;
/**
* Dispatches the given pointer event data to engine.
*/
- (void)sendKeyEvent:(const FlutterKeyEvent&)event
callback:(nullable FlutterKeyEventCallback)callback
userData:(nullable void*)userData;
/**
* Registers an external texture with the given id. Returns YES on success.
*/
- (BOOL)registerTextureWithID:(int64_t)textureId;
/**
* Marks texture with the given id as available. Returns YES on success.
*/
- (BOOL)markTextureFrameAvailable:(int64_t)textureID;
/**
* Unregisters an external texture with the given id. Returns YES on success.
*/
- (BOOL)unregisterTextureWithID:(int64_t)textureID;
- (nonnull FlutterPlatformViewController*)platformViewController;
/**
* Handles changes to the application state, sending them to the framework.
*
* @param state One of the lifecycle constants in app_lifecycle_state.h,
* corresponding to the Dart enum AppLifecycleState.
*/
- (void)setApplicationState:(flutter::AppLifecycleState)state;
// Accessibility API.
/**
* Dispatches semantics action back to the framework. The semantics must be enabled by calling
* the updateSemanticsEnabled before dispatching semantics actions.
*/
- (void)dispatchSemanticsAction:(FlutterSemanticsAction)action
toTarget:(uint16_t)target
withData:(fml::MallocMapping)data;
/**
* Handles accessibility events.
*/
- (void)handleAccessibilityEvent:(NSDictionary<NSString*, id>*)annotatedEvent;
/**
* Announces accessibility messages.
*/
- (void)announceAccessibilityMessage:(NSString*)message
withPriority:(NSAccessibilityPriorityLevel)priority;
/**
* Returns an array of screen objects representing all of the screens available on the system.
*/
- (NSArray<NSScreen*>*)screens;
@end
@interface FlutterEngine (Tests)
- (nonnull FlutterThreadSynchronizer*)testThreadSynchronizer;
@end
NS_ASSUME_NONNULL_END
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERENGINE_INTERNAL_H_
| engine/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h",
"repo_id": "engine",
"token_count": 2350
} | 327 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMutatorView.h"
#include "third_party/googletest/googletest/include/gtest/gtest.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/NSView+ClipsToBounds.h"
@interface FlutterMutatorView (Private)
@property(readonly, nonatomic, nonnull) NSMutableArray<NSView*>* pathClipViews;
@property(readonly, nonatomic, nullable) NSView* platformViewContainer;
@end
static constexpr float kMaxErr = 1e-10;
namespace {
void ApplyFlutterLayer(FlutterMutatorView* view,
FlutterSize size,
const std::vector<FlutterPlatformViewMutation>& mutations) {
flutter::PlatformViewLayer layer(0, // identifier
mutations,
// Offset is ignored by mutator view, the bounding rect is
// determined by width and transform.
FlutterPoint{0, 0}, // offset
size);
[view applyFlutterLayer:&layer];
}
// Expect that each element within two CATransform3Ds is within an error bound.
//
// In order to avoid architecture-specific floating point differences we don't check for exact
// equality using, for example, CATransform3DEqualToTransform.
void ExpectTransform3DEqual(const CATransform3D& t, const CATransform3D& u) {
EXPECT_NEAR(t.m11, u.m11, kMaxErr);
EXPECT_NEAR(t.m12, u.m12, kMaxErr);
EXPECT_NEAR(t.m13, u.m13, kMaxErr);
EXPECT_NEAR(t.m14, u.m14, kMaxErr);
EXPECT_NEAR(t.m21, u.m21, kMaxErr);
EXPECT_NEAR(t.m22, u.m22, kMaxErr);
EXPECT_NEAR(t.m23, u.m23, kMaxErr);
EXPECT_NEAR(t.m24, u.m24, kMaxErr);
EXPECT_NEAR(t.m31, u.m31, kMaxErr);
EXPECT_NEAR(t.m32, u.m32, kMaxErr);
EXPECT_NEAR(t.m33, u.m33, kMaxErr);
EXPECT_NEAR(t.m34, u.m34, kMaxErr);
EXPECT_NEAR(t.m41, u.m41, kMaxErr);
EXPECT_NEAR(t.m42, u.m42, kMaxErr);
EXPECT_NEAR(t.m43, u.m43, kMaxErr);
EXPECT_NEAR(t.m44, u.m44, kMaxErr);
}
} // namespace
TEST(FlutterMutatorViewTest, BasicFrameIsCorrect) {
NSView* platformView = [[NSView alloc] init];
FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView];
EXPECT_EQ(mutatorView.platformView, platformView);
std::vector<FlutterPlatformViewMutation> mutations{
{
.type = kFlutterPlatformViewMutationTypeTransformation,
.transformation =
FlutterTransformation{
.scaleX = 1,
.transX = 100,
.scaleY = 1,
.transY = 50,
},
},
};
ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations);
EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(100, 50, 30, 20)));
EXPECT_TRUE(CGRectEqualToRect(platformView.frame, CGRectMake(0, 0, 30, 20)));
EXPECT_EQ(mutatorView.pathClipViews.count, 0ull);
EXPECT_NE(mutatorView.platformViewContainer, nil);
}
TEST(FlutterMutatorViewTest, ClipsToBounds) {
NSView* platformView = [[NSView alloc] init];
FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView];
EXPECT_TRUE(mutatorView.clipsToBounds);
}
TEST(FlutterMutatorViewTest, TransformedFrameIsCorrect) {
NSView* platformView = [[NSView alloc] init];
FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView];
NSView* mutatorViewParent = [[NSView alloc] init];
mutatorViewParent.wantsLayer = YES;
mutatorViewParent.layer.contentsScale = 2.0;
[mutatorViewParent addSubview:mutatorView];
std::vector<FlutterPlatformViewMutation> mutations{
{
.type = kFlutterPlatformViewMutationTypeTransformation,
.transformation =
FlutterTransformation{
.scaleX = 2,
.scaleY = 2,
},
},
{
.type = kFlutterPlatformViewMutationTypeTransformation,
.transformation =
FlutterTransformation{
.scaleX = 1,
.transX = 100,
.scaleY = 1,
.transY = 50,
},
},
{
.type = kFlutterPlatformViewMutationTypeTransformation,
.transformation =
FlutterTransformation{
.scaleX = 1.5,
.transX = -7.5,
.scaleY = 1.5,
.transY = -5,
},
},
};
// PlatformView size form engine comes in physical pixels
ApplyFlutterLayer(mutatorView, FlutterSize{30 * 2, 20 * 2}, mutations);
EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(92.5, 45, 45, 30)));
EXPECT_TRUE(CGRectEqualToRect(platformView.frame, CGRectMake(0, 0, 30, 20)));
ExpectTransform3DEqual(mutatorView.platformViewContainer.layer.sublayerTransform,
CATransform3DMakeScale(1.5, 1.5, 1));
}
TEST(FlutterMutatorViewTest, FrameWithLooseClipIsCorrect) {
NSView* platformView = [[NSView alloc] init];
FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView];
EXPECT_EQ(mutatorView.platformView, platformView);
std::vector<FlutterPlatformViewMutation> mutations{
{
.type = kFlutterPlatformViewMutationTypeClipRect,
.clip_rect = FlutterRect{80, 40, 200, 100},
},
{
.type = kFlutterPlatformViewMutationTypeTransformation,
.transformation =
FlutterTransformation{
.scaleX = 1,
.transX = 100,
.scaleY = 1,
.transY = 50,
},
},
};
ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations);
EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(100, 50, 30, 20)));
EXPECT_TRUE(CGRectEqualToRect(platformView.frame, CGRectMake(0, 0, 30, 20)));
}
TEST(FlutterMutatorViewTest, FrameWithTightClipIsCorrect) {
NSView* platformView = [[NSView alloc] init];
FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView];
EXPECT_EQ(mutatorView.platformView, platformView);
std::vector<FlutterPlatformViewMutation> mutations{
{
.type = kFlutterPlatformViewMutationTypeClipRect,
.clip_rect = FlutterRect{80, 40, 200, 100},
},
{
.type = kFlutterPlatformViewMutationTypeClipRect,
.clip_rect = FlutterRect{110, 55, 120, 65},
},
{
.type = kFlutterPlatformViewMutationTypeTransformation,
.transformation =
FlutterTransformation{
.scaleX = 1,
.transX = 100,
.scaleY = 1,
.transY = 50,
},
},
};
ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations);
EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(110, 55, 10, 10)));
EXPECT_TRUE(
CGRectEqualToRect(mutatorView.subviews.firstObject.frame, CGRectMake(-10, -5, 30, 20)));
EXPECT_TRUE(CGRectEqualToRect(platformView.frame, CGRectMake(0, 0, 30, 20)));
}
TEST(FlutterMutatorViewTest, FrameWithTightClipAndTransformIsCorrect) {
NSView* platformView = [[NSView alloc] init];
FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView];
NSView* mutatorViewParent = [[NSView alloc] init];
mutatorViewParent.wantsLayer = YES;
mutatorViewParent.layer.contentsScale = 2.0;
[mutatorViewParent addSubview:mutatorView];
std::vector<FlutterPlatformViewMutation> mutations{
{
.type = kFlutterPlatformViewMutationTypeTransformation,
.transformation =
FlutterTransformation{
.scaleX = 2,
.scaleY = 2,
},
},
{
.type = kFlutterPlatformViewMutationTypeClipRect,
.clip_rect = FlutterRect{80, 40, 200, 100},
},
{
.type = kFlutterPlatformViewMutationTypeClipRect,
.clip_rect = FlutterRect{110, 55, 120, 65},
},
{
.type = kFlutterPlatformViewMutationTypeTransformation,
.transformation =
FlutterTransformation{
.scaleX = 1,
.transX = 100,
.scaleY = 1,
.transY = 50,
},
},
{
.type = kFlutterPlatformViewMutationTypeTransformation,
.transformation =
FlutterTransformation{
.scaleX = 1.5,
.transX = -7.5,
.scaleY = 1.5,
.transY = -5,
},
},
};
ApplyFlutterLayer(mutatorView, FlutterSize{30 * 2, 20 * 2}, mutations);
EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(110, 55, 10, 10)));
EXPECT_TRUE(
CGRectEqualToRect(mutatorView.subviews.firstObject.frame, CGRectMake(-17.5, -10, 45, 30)));
EXPECT_TRUE(CGRectEqualToRect(platformView.frame, CGRectMake(0, 0, 30, 20)));
}
// Rounded rectangle without hitting the corner
TEST(FlutterMutatorViewTest, RoundRectClipsToSimpleRectangle) {
NSView* platformView = [[NSView alloc] init];
FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView];
std::vector<FlutterPlatformViewMutation> mutations{
{
.type = kFlutterPlatformViewMutationTypeClipRoundedRect,
.clip_rounded_rect =
FlutterRoundedRect{
.rect = FlutterRect{110, 30, 120, 90},
.upper_left_corner_radius = FlutterSize{10, 10},
.upper_right_corner_radius = FlutterSize{10, 10},
.lower_right_corner_radius = FlutterSize{10, 10},
.lower_left_corner_radius = FlutterSize{10, 10},
},
},
{
.type = kFlutterPlatformViewMutationTypeTransformation,
.transformation =
FlutterTransformation{
.scaleX = 1,
.transX = 100,
.scaleY = 1,
.transY = 50,
},
},
};
ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations);
EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(110, 50, 10, 20)));
EXPECT_TRUE(
CGRectEqualToRect(mutatorView.subviews.firstObject.frame, CGRectMake(-10, 0, 30, 20)));
EXPECT_TRUE(CGRectEqualToRect(platformView.frame, CGRectMake(0, 0, 30, 20)));
EXPECT_EQ(mutatorView.pathClipViews.count, 0ul);
}
// Ensure that the mutator view, clip views, and container all use a flipped y axis. The transforms
// sent from the framework assume this, and so aside from the consistency with every other embedder,
// we can avoid a lot of extra math.
TEST(FlutterMutatorViewTest, ViewsSetIsFlipped) {
NSView* platformView = [[NSView alloc] init];
FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView];
std::vector<FlutterPlatformViewMutation> mutations{
{
.type = kFlutterPlatformViewMutationTypeClipRoundedRect,
.clip_rounded_rect =
FlutterRoundedRect{
.rect = FlutterRect{110, 60, 150, 150},
.upper_left_corner_radius = FlutterSize{10, 10},
.upper_right_corner_radius = FlutterSize{10, 10},
.lower_right_corner_radius = FlutterSize{10, 10},
.lower_left_corner_radius = FlutterSize{10, 10},
},
},
{
.type = kFlutterPlatformViewMutationTypeTransformation,
.transformation =
FlutterTransformation{
.scaleX = 1,
.transX = 100,
.scaleY = 1,
.transY = 50,
},
},
};
ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations);
EXPECT_TRUE(mutatorView.isFlipped);
ASSERT_EQ(mutatorView.pathClipViews.count, 1ul);
EXPECT_TRUE(mutatorView.pathClipViews.firstObject.isFlipped);
EXPECT_TRUE(mutatorView.platformViewContainer.isFlipped);
}
TEST(FlutterMutatorViewTest, RectsClipsToPathWhenRotated) {
NSView* platformView = [[NSView alloc] init];
FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView];
std::vector<FlutterPlatformViewMutation> mutations{
{
.type = kFlutterPlatformViewMutationTypeTransformation,
// Roation M_PI / 8
.transformation =
FlutterTransformation{
.scaleX = 0.9238795325112867,
.skewX = -0.3826834323650898,
.skewY = 0.3826834323650898,
.scaleY = 0.9238795325112867,
},
},
{
.type = kFlutterPlatformViewMutationTypeClipRect,
.clip_rect = FlutterRect{110, 60, 150, 150},
},
{
.type = kFlutterPlatformViewMutationTypeTransformation,
.transformation =
FlutterTransformation{
.scaleX = 1,
.transX = 100,
.scaleY = 1,
.transY = 50,
},
},
};
ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations);
EXPECT_EQ(mutatorView.pathClipViews.count, 1ul);
EXPECT_NEAR(mutatorView.platformViewContainer.frame.size.width, 35.370054622640396, kMaxErr);
EXPECT_NEAR(mutatorView.platformViewContainer.frame.size.height, 29.958093621178421, kMaxErr);
}
TEST(FlutterMutatorViewTest, RoundRectClipsToPath) {
NSView* platformView = [[NSView alloc] init];
FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView];
std::vector<FlutterPlatformViewMutation> mutations{
{
.type = kFlutterPlatformViewMutationTypeClipRoundedRect,
.clip_rounded_rect =
FlutterRoundedRect{
.rect = FlutterRect{110, 60, 150, 150},
.upper_left_corner_radius = FlutterSize{10, 10},
.upper_right_corner_radius = FlutterSize{10, 10},
.lower_right_corner_radius = FlutterSize{10, 10},
.lower_left_corner_radius = FlutterSize{10, 10},
},
},
{
.type = kFlutterPlatformViewMutationTypeTransformation,
.transformation =
FlutterTransformation{
.scaleX = 1,
.transX = 100,
.scaleY = 1,
.transY = 50,
},
},
};
ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations);
EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(110, 60, 20, 10)));
EXPECT_TRUE(
CGRectEqualToRect(mutatorView.subviews.firstObject.frame, CGRectMake(-10, -10, 30, 20)));
EXPECT_TRUE(CGRectEqualToRect(platformView.frame, CGRectMake(0, 0, 30, 20)));
EXPECT_EQ(mutatorView.pathClipViews.count, 1ul);
ExpectTransform3DEqual(mutatorView.pathClipViews.firstObject.layer.mask.transform,
CATransform3DMakeTranslation(-100, -50, 0));
}
TEST(FlutterMutatorViewTest, PathClipViewsAreAddedAndRemoved) {
NSView* platformView = [[NSView alloc] init];
FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView];
std::vector<FlutterPlatformViewMutation> mutations{
{
.type = kFlutterPlatformViewMutationTypeTransformation,
.transformation =
FlutterTransformation{
.scaleX = 1,
.transX = 100,
.scaleY = 1,
.transY = 50,
},
},
};
ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations);
EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(100, 50, 30, 20)));
EXPECT_EQ(mutatorView.pathClipViews.count, 0ull);
std::vector<FlutterPlatformViewMutation> mutations2{
{
.type = kFlutterPlatformViewMutationTypeClipRoundedRect,
.clip_rounded_rect =
FlutterRoundedRect{
.rect = FlutterRect{110, 60, 150, 150},
.upper_left_corner_radius = FlutterSize{10, 10},
.upper_right_corner_radius = FlutterSize{10, 10},
.lower_right_corner_radius = FlutterSize{10, 10},
.lower_left_corner_radius = FlutterSize{10, 10},
},
},
{
.type = kFlutterPlatformViewMutationTypeTransformation,
.transformation =
FlutterTransformation{
.scaleX = 1,
.transX = 100,
.scaleY = 1,
.transY = 50,
},
},
};
ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations2);
EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(110, 60, 20, 10)));
EXPECT_TRUE(
CGRectEqualToRect(mutatorView.subviews.firstObject.frame, CGRectMake(-10, -10, 30, 20)));
EXPECT_TRUE(CGRectEqualToRect(platformView.frame, CGRectMake(0, 0, 30, 20)));
EXPECT_EQ(mutatorView.pathClipViews.count, 1ul);
EXPECT_EQ(platformView.superview, mutatorView.platformViewContainer);
EXPECT_EQ(mutatorView.platformViewContainer.superview, mutatorView.pathClipViews[0]);
EXPECT_EQ(mutatorView.pathClipViews[0].superview, mutatorView);
std::vector<FlutterPlatformViewMutation> mutations3{
{
.type = kFlutterPlatformViewMutationTypeClipRoundedRect,
.clip_rounded_rect =
FlutterRoundedRect{
.rect = FlutterRect{110, 55, 150, 150},
.upper_left_corner_radius = FlutterSize{10, 10},
.upper_right_corner_radius = FlutterSize{10, 10},
.lower_right_corner_radius = FlutterSize{10, 10},
.lower_left_corner_radius = FlutterSize{10, 10},
},
},
{
.type = kFlutterPlatformViewMutationTypeClipRoundedRect,
.clip_rounded_rect =
FlutterRoundedRect{
.rect = FlutterRect{30, 30, 120, 65},
.upper_left_corner_radius = FlutterSize{10, 10},
.upper_right_corner_radius = FlutterSize{10, 10},
.lower_right_corner_radius = FlutterSize{10, 10},
.lower_left_corner_radius = FlutterSize{10, 10},
},
},
{
.type = kFlutterPlatformViewMutationTypeTransformation,
.transformation =
FlutterTransformation{
.scaleX = 1,
.transX = 100,
.scaleY = 1,
.transY = 50,
},
},
};
ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations3);
EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(110, 55, 10, 10)));
EXPECT_TRUE(
CGRectEqualToRect(mutatorView.subviews.firstObject.frame, CGRectMake(-10, -5, 30, 20)));
EXPECT_EQ(mutatorView.pathClipViews.count, 2ul);
EXPECT_EQ(platformView.superview, mutatorView.platformViewContainer);
EXPECT_EQ(mutatorView.platformViewContainer.superview, mutatorView.pathClipViews[1]);
EXPECT_EQ(mutatorView.pathClipViews[1].superview, mutatorView.pathClipViews[0]);
EXPECT_EQ(mutatorView.pathClipViews[0].superview, mutatorView);
ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations2);
EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(110, 60, 20, 10)));
EXPECT_TRUE(
CGRectEqualToRect(mutatorView.subviews.firstObject.frame, CGRectMake(-10, -10, 30, 20)));
EXPECT_TRUE(CGRectEqualToRect(platformView.frame, CGRectMake(0, 0, 30, 20)));
EXPECT_EQ(mutatorView.pathClipViews.count, 1ul);
EXPECT_EQ(platformView.superview, mutatorView.platformViewContainer);
EXPECT_EQ(mutatorView.platformViewContainer.superview, mutatorView.pathClipViews[0]);
EXPECT_EQ(mutatorView.pathClipViews[0].superview, mutatorView);
ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations);
EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(100, 50, 30, 20)));
EXPECT_EQ(mutatorView.pathClipViews.count, 0ull);
}
| engine/shell/platform/darwin/macos/framework/Source/FlutterMutatorViewTest.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterMutatorViewTest.mm",
"repo_id": "engine",
"token_count": 9487
} | 328 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/NSView+ClipsToBounds.h"
#import <OCMock/OCMock.h>
#import "flutter/testing/testing.h"
@interface FlutterTextField (Testing)
- (void)setPlatformNode:(flutter::FlutterTextPlatformNode*)node;
@end
@interface FlutterTextFieldMock : FlutterTextField
@property(nonatomic, nullable, copy) NSString* lastUpdatedString;
@property(nonatomic) NSRange lastUpdatedSelection;
@end
@implementation FlutterTextFieldMock
- (void)updateString:(NSString*)string withSelection:(NSRange)selection {
_lastUpdatedString = string;
_lastUpdatedSelection = selection;
}
@end
@interface NSTextInputContext (Private)
// This is a private method.
- (BOOL)isActive;
@end
@interface TextInputTestViewController : FlutterViewController
@end
@implementation TextInputTestViewController
- (nonnull FlutterView*)createFlutterViewWithMTLDevice:(id<MTLDevice>)device
commandQueue:(id<MTLCommandQueue>)commandQueue {
return OCMClassMock([NSView class]);
}
@end
@interface FlutterInputPluginTestObjc : NSObject
- (bool)testEmptyCompositionRange;
- (bool)testClearClientDuringComposing;
@end
@implementation FlutterInputPluginTestObjc
- (bool)testEmptyCompositionRange {
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
NSDictionary* setClientConfig = @{
@"inputAction" : @"action",
@"inputType" : @{@"name" : @"inputName"},
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]]
result:^(id){
}];
FlutterMethodCall* call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditingState"
arguments:@{
@"text" : @"Text",
@"selectionBase" : @(0),
@"selectionExtent" : @(0),
@"composingBase" : @(-1),
@"composingExtent" : @(-1),
}];
[plugin handleMethodCall:call
result:^(id){
}];
// Verify editing state was set.
NSDictionary* editingState = [plugin editingState];
EXPECT_STREQ([editingState[@"text"] UTF8String], "Text");
EXPECT_STREQ([editingState[@"selectionAffinity"] UTF8String], "TextAffinity.upstream");
EXPECT_FALSE([editingState[@"selectionIsDirectional"] boolValue]);
EXPECT_EQ([editingState[@"selectionBase"] intValue], 0);
EXPECT_EQ([editingState[@"selectionExtent"] intValue], 0);
EXPECT_EQ([editingState[@"composingBase"] intValue], -1);
EXPECT_EQ([editingState[@"composingExtent"] intValue], -1);
return true;
}
- (bool)testSetMarkedTextWithSelectionChange {
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
NSDictionary* setClientConfig = @{
@"inputAction" : @"action",
@"inputType" : @{@"name" : @"inputName"},
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]]
result:^(id){
}];
FlutterMethodCall* call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditingState"
arguments:@{
@"text" : @"Text",
@"selectionBase" : @(4),
@"selectionExtent" : @(4),
@"composingBase" : @(-1),
@"composingExtent" : @(-1),
}];
[plugin handleMethodCall:call
result:^(id){
}];
[plugin setMarkedText:@"marked"
selectedRange:NSMakeRange(1, 0)
replacementRange:NSMakeRange(NSNotFound, 0)];
NSDictionary* expectedState = @{
@"selectionBase" : @(5),
@"selectionExtent" : @(5),
@"selectionAffinity" : @"TextAffinity.upstream",
@"selectionIsDirectional" : @(NO),
@"composingBase" : @(4),
@"composingExtent" : @(10),
@"text" : @"Textmarked",
};
NSData* updateCall = [[FlutterJSONMethodCodec sharedInstance]
encodeMethodCall:[FlutterMethodCall
methodCallWithMethodName:@"TextInputClient.updateEditingState"
arguments:@[ @(1), expectedState ]]];
OCMExpect( // NOLINT(google-objc-avoid-throwing-exception)
[binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]);
@try {
OCMVerify( // NOLINT(google-objc-avoid-throwing-exception)
[binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]);
} @catch (...) {
return false;
}
return true;
}
- (bool)testSetMarkedTextWithReplacementRange {
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
NSDictionary* setClientConfig = @{
@"inputAction" : @"action",
@"inputType" : @{@"name" : @"inputName"},
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]]
result:^(id){
}];
FlutterMethodCall* call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditingState"
arguments:@{
@"text" : @"1234",
@"selectionBase" : @(3),
@"selectionExtent" : @(3),
@"composingBase" : @(-1),
@"composingExtent" : @(-1),
}];
[plugin handleMethodCall:call
result:^(id){
}];
[plugin setMarkedText:@"marked"
selectedRange:NSMakeRange(1, 0)
replacementRange:NSMakeRange(1, 2)];
NSDictionary* expectedState = @{
@"selectionBase" : @(2),
@"selectionExtent" : @(2),
@"selectionAffinity" : @"TextAffinity.upstream",
@"selectionIsDirectional" : @(NO),
@"composingBase" : @(1),
@"composingExtent" : @(7),
@"text" : @"1marked4",
};
NSData* updateCall = [[FlutterJSONMethodCodec sharedInstance]
encodeMethodCall:[FlutterMethodCall
methodCallWithMethodName:@"TextInputClient.updateEditingState"
arguments:@[ @(1), expectedState ]]];
OCMExpect( // NOLINT(google-objc-avoid-throwing-exception)
[binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]);
@try {
OCMVerify( // NOLINT(google-objc-avoid-throwing-exception)
[binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]);
} @catch (...) {
return false;
}
return true;
}
- (bool)testComposingRegionRemovedByFramework {
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
NSDictionary* setClientConfig = @{
@"inputAction" : @"action",
@"inputType" : @{@"name" : @"inputName"},
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]]
result:^(id){
}];
FlutterMethodCall* call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditingState"
arguments:@{
@"text" : @"Text",
@"selectionBase" : @(4),
@"selectionExtent" : @(4),
@"composingBase" : @(2),
@"composingExtent" : @(4),
}];
[plugin handleMethodCall:call
result:^(id){
}];
// Update with the composing region removed.
call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditingState"
arguments:@{
@"text" : @"Te",
@"selectionBase" : @(2),
@"selectionExtent" : @(2),
@"composingBase" : @(-1),
@"composingExtent" : @(-1),
}];
[plugin handleMethodCall:call
result:^(id){
}];
// Verify editing state was set.
NSDictionary* editingState = [plugin editingState];
EXPECT_STREQ([editingState[@"text"] UTF8String], "Te");
EXPECT_STREQ([editingState[@"selectionAffinity"] UTF8String], "TextAffinity.upstream");
EXPECT_FALSE([editingState[@"selectionIsDirectional"] boolValue]);
EXPECT_EQ([editingState[@"selectionBase"] intValue], 2);
EXPECT_EQ([editingState[@"selectionExtent"] intValue], 2);
EXPECT_EQ([editingState[@"composingBase"] intValue], -1);
EXPECT_EQ([editingState[@"composingExtent"] intValue], -1);
return true;
}
- (bool)testClearClientDuringComposing {
// Set up FlutterTextInputPlugin.
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
// Set input client 1.
NSDictionary* setClientConfig = @{
@"inputAction" : @"action",
@"inputType" : @{@"name" : @"inputName"},
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]]
result:^(id){
}];
// Set editing state with an active composing range.
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditingState"
arguments:@{
@"text" : @"Text",
@"selectionBase" : @(0),
@"selectionExtent" : @(0),
@"composingBase" : @(0),
@"composingExtent" : @(1),
}]
result:^(id){
}];
// Verify composing range is (0, 1).
NSDictionary* editingState = [plugin editingState];
EXPECT_EQ([editingState[@"composingBase"] intValue], 0);
EXPECT_EQ([editingState[@"composingExtent"] intValue], 1);
// Clear input client.
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.clearClient"
arguments:@[]]
result:^(id){
}];
// Verify composing range is collapsed.
editingState = [plugin editingState];
EXPECT_EQ([editingState[@"composingBase"] intValue], [editingState[@"composingExtent"] intValue]);
return true;
}
- (bool)testAutocompleteDisabledWhenAutofillNotSet {
// Set up FlutterTextInputPlugin.
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
// Set input client 1.
NSDictionary* setClientConfig = @{
@"inputAction" : @"action",
@"inputType" : @{@"name" : @"inputName"},
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]]
result:^(id){
}];
// Verify autocomplete is disabled.
EXPECT_FALSE([plugin isAutomaticTextCompletionEnabled]);
return true;
}
- (bool)testAutocompleteEnabledWhenAutofillSet {
// Set up FlutterTextInputPlugin.
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
// Set input client 1.
NSDictionary* setClientConfig = @{
@"inputAction" : @"action",
@"inputType" : @{@"name" : @"inputName"},
@"autofill" : @{
@"uniqueIdentifier" : @"field1",
@"hints" : @[ @"name" ],
@"editingValue" : @{@"text" : @""},
}
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]]
result:^(id){
}];
// Verify autocomplete is enabled.
EXPECT_TRUE([plugin isAutomaticTextCompletionEnabled]);
// Verify content type is nil for unsupported content types.
if (@available(macOS 11.0, *)) {
EXPECT_EQ([plugin contentType], nil);
}
return true;
}
- (bool)testAutocompleteEnabledWhenAutofillSetNoHint {
// Set up FlutterTextInputPlugin.
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
// Set input client 1.
NSDictionary* setClientConfig = @{
@"inputAction" : @"action",
@"inputType" : @{@"name" : @"inputName"},
@"autofill" : @{
@"uniqueIdentifier" : @"field1",
@"hints" : @[],
@"editingValue" : @{@"text" : @""},
}
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]]
result:^(id){
}];
// Verify autocomplete is enabled.
EXPECT_TRUE([plugin isAutomaticTextCompletionEnabled]);
return true;
}
- (bool)testAutocompleteDisabledWhenObscureTextSet {
// Set up FlutterTextInputPlugin.
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
// Set input client 1.
NSDictionary* setClientConfig = @{
@"inputAction" : @"action",
@"inputType" : @{@"name" : @"inputName"},
@"obscureText" : @YES,
@"autofill" : @{
@"uniqueIdentifier" : @"field1",
@"editingValue" : @{@"text" : @""},
}
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]]
result:^(id){
}];
// Verify autocomplete is disabled.
EXPECT_FALSE([plugin isAutomaticTextCompletionEnabled]);
return true;
}
- (bool)testAutocompleteDisabledWhenPasswordAutofillSet {
// Set up FlutterTextInputPlugin.
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
// Set input client 1.
NSDictionary* setClientConfig = @{
@"inputAction" : @"action",
@"inputType" : @{@"name" : @"inputName"},
@"autofill" : @{
@"uniqueIdentifier" : @"field1",
@"hints" : @[ @"password" ],
@"editingValue" : @{@"text" : @""},
}
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]]
result:^(id){
}];
// Verify autocomplete is disabled.
EXPECT_FALSE([plugin isAutomaticTextCompletionEnabled]);
// Verify content type is password.
if (@available(macOS 11.0, *)) {
EXPECT_EQ([plugin contentType], NSTextContentTypePassword);
}
return true;
}
- (bool)testAutocompleteDisabledWhenAutofillGroupIncludesPassword {
// Set up FlutterTextInputPlugin.
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
// Set input client 1.
NSDictionary* setClientConfig = @{
@"inputAction" : @"action",
@"inputType" : @{@"name" : @"inputName"},
@"fields" : @[
@{
@"inputAction" : @"action",
@"inputType" : @{@"name" : @"inputName"},
@"autofill" : @{
@"uniqueIdentifier" : @"field1",
@"hints" : @[ @"password" ],
@"editingValue" : @{@"text" : @""},
}
},
@{
@"inputAction" : @"action",
@"inputType" : @{@"name" : @"inputName"},
@"autofill" : @{
@"uniqueIdentifier" : @"field2",
@"hints" : @[ @"name" ],
@"editingValue" : @{@"text" : @""},
}
}
]
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]]
result:^(id){
}];
// Verify autocomplete is disabled.
EXPECT_FALSE([plugin isAutomaticTextCompletionEnabled]);
return true;
}
- (bool)testContentTypeWhenAutofillTypeIsUsername {
// Set up FlutterTextInputPlugin.
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
// Set input client 1.
NSDictionary* setClientConfig = @{
@"inputAction" : @"action",
@"inputType" : @{@"name" : @"inputName"},
@"autofill" : @{
@"uniqueIdentifier" : @"field1",
@"hints" : @[ @"name" ],
@"editingValue" : @{@"text" : @""},
}
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]]
result:^(id){
}];
// Verify autocomplete is disabled.
EXPECT_FALSE([plugin isAutomaticTextCompletionEnabled]);
// Verify content type is username.
if (@available(macOS 11.0, *)) {
EXPECT_EQ([plugin contentType], NSTextContentTypeUsername);
}
return true;
}
- (bool)testContentTypeWhenAutofillTypeIsOneTimeCode {
// Set up FlutterTextInputPlugin.
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
// Set input client 1.
NSDictionary* setClientConfig = @{
@"inputAction" : @"action",
@"inputType" : @{@"name" : @"inputName"},
@"autofill" : @{
@"uniqueIdentifier" : @"field1",
@"hints" : @[ @"oneTimeCode" ],
@"editingValue" : @{@"text" : @""},
}
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]]
result:^(id){
}];
// Verify autocomplete is disabled.
EXPECT_FALSE([plugin isAutomaticTextCompletionEnabled]);
// Verify content type is username.
if (@available(macOS 11.0, *)) {
EXPECT_EQ([plugin contentType], NSTextContentTypeOneTimeCode);
}
return true;
}
- (bool)testFirstRectForCharacterRange {
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* controllerMock =
[[TextInputTestViewController alloc] initWithEngine:engineMock nibName:nil bundle:nil];
[controllerMock loadView];
id viewMock = controllerMock.flutterView;
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[viewMock bounds])
.andReturn(NSMakeRect(0, 0, 200, 200));
id windowMock = OCMClassMock([NSWindow class]);
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[viewMock window])
.andReturn(windowMock);
OCMExpect( // NOLINT(google-objc-avoid-throwing-exception)
[viewMock convertRect:NSMakeRect(28, 10, 2, 19) toView:nil])
.andReturn(NSMakeRect(28, 10, 2, 19));
OCMExpect( // NOLINT(google-objc-avoid-throwing-exception)
[windowMock convertRectToScreen:NSMakeRect(28, 10, 2, 19)])
.andReturn(NSMakeRect(38, 20, 2, 19));
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:controllerMock];
FlutterMethodCall* call = [FlutterMethodCall
methodCallWithMethodName:@"TextInput.setEditableSizeAndTransform"
arguments:@{
@"height" : @(20.0),
@"transform" : @[
@(1.0), @(0.0), @(0.0), @(0.0), @(0.0), @(1.0), @(0.0), @(0.0), @(0.0),
@(0.0), @(1.0), @(0.0), @(20.0), @(10.0), @(0.0), @(1.0)
],
@"width" : @(400.0),
}];
[plugin handleMethodCall:call
result:^(id){
}];
call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setCaretRect"
arguments:@{
@"height" : @(19.0),
@"width" : @(2.0),
@"x" : @(8.0),
@"y" : @(0.0),
}];
[plugin handleMethodCall:call
result:^(id){
}];
NSRect rect = [plugin firstRectForCharacterRange:NSMakeRange(0, 0) actualRange:nullptr];
@try {
OCMVerify( // NOLINT(google-objc-avoid-throwing-exception)
[windowMock convertRectToScreen:NSMakeRect(28, 10, 2, 19)]);
} @catch (...) {
return false;
}
return NSEqualRects(rect, NSMakeRect(38, 20, 2, 19));
}
- (bool)testFirstRectForCharacterRangeAtInfinity {
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* controllerMock =
[[TextInputTestViewController alloc] initWithEngine:engineMock nibName:nil bundle:nil];
[controllerMock loadView];
id viewMock = controllerMock.flutterView;
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[viewMock bounds])
.andReturn(NSMakeRect(0, 0, 200, 200));
id windowMock = OCMClassMock([NSWindow class]);
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[viewMock window])
.andReturn(windowMock);
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:controllerMock];
FlutterMethodCall* call = [FlutterMethodCall
methodCallWithMethodName:@"TextInput.setEditableSizeAndTransform"
arguments:@{
@"height" : @(20.0),
// Projects all points to infinity.
@"transform" : @[
@(1.0), @(0.0), @(0.0), @(0.0), @(0.0), @(1.0), @(0.0), @(0.0), @(0.0),
@(0.0), @(1.0), @(0.0), @(20.0), @(10.0), @(0.0), @(0.0)
],
@"width" : @(400.0),
}];
[plugin handleMethodCall:call
result:^(id){
}];
call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setCaretRect"
arguments:@{
@"height" : @(19.0),
@"width" : @(2.0),
@"x" : @(8.0),
@"y" : @(0.0),
}];
[plugin handleMethodCall:call
result:^(id){
}];
NSRect rect = [plugin firstRectForCharacterRange:NSMakeRange(0, 0) actualRange:nullptr];
return NSEqualRects(rect, CGRectZero);
}
- (bool)testFirstRectForCharacterRangeWithEsotericAffineTransform {
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* controllerMock =
[[TextInputTestViewController alloc] initWithEngine:engineMock nibName:nil bundle:nil];
[controllerMock loadView];
id viewMock = controllerMock.flutterView;
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[viewMock bounds])
.andReturn(NSMakeRect(0, 0, 200, 200));
id windowMock = OCMClassMock([NSWindow class]);
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[viewMock window])
.andReturn(windowMock);
OCMExpect( // NOLINT(google-objc-avoid-throwing-exception)
[viewMock convertRect:NSMakeRect(-18, 6, 3, 3) toView:nil])
.andReturn(NSMakeRect(-18, 6, 3, 3));
OCMExpect( // NOLINT(google-objc-avoid-throwing-exception)
[windowMock convertRectToScreen:NSMakeRect(-18, 6, 3, 3)])
.andReturn(NSMakeRect(-18, 6, 3, 3));
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:controllerMock];
FlutterMethodCall* call = [FlutterMethodCall
methodCallWithMethodName:@"TextInput.setEditableSizeAndTransform"
arguments:@{
@"height" : @(20.0),
// This matrix can be generated by running this dart code snippet:
// Matrix4.identity()..scale(3.0)..rotateZ(math.pi/2)..translate(1.0, 2.0,
// 3.0);
@"transform" : @[
@(0.0), @(3.0), @(0.0), @(0.0), @(-3.0), @(0.0), @(0.0), @(0.0), @(0.0),
@(0.0), @(3.0), @(0.0), @(-6.0), @(3.0), @(9.0), @(1.0)
],
@"width" : @(400.0),
}];
[plugin handleMethodCall:call
result:^(id){
}];
call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setCaretRect"
arguments:@{
@"height" : @(1.0),
@"width" : @(1.0),
@"x" : @(1.0),
@"y" : @(3.0),
}];
[plugin handleMethodCall:call
result:^(id){
}];
NSRect rect = [plugin firstRectForCharacterRange:NSMakeRange(0, 0) actualRange:nullptr];
@try {
OCMVerify( // NOLINT(google-objc-avoid-throwing-exception)
[windowMock convertRectToScreen:NSMakeRect(-18, 6, 3, 3)]);
} @catch (...) {
return false;
}
return NSEqualRects(rect, NSMakeRect(-18, 6, 3, 3));
}
- (bool)testSetEditingStateWithTextEditingDelta {
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
NSDictionary* setClientConfig = @{
@"inputAction" : @"action",
@"enableDeltaModel" : @"true",
@"inputType" : @{@"name" : @"inputName"},
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]]
result:^(id){
}];
FlutterMethodCall* call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditingState"
arguments:@{
@"text" : @"Text",
@"selectionBase" : @(0),
@"selectionExtent" : @(0),
@"composingBase" : @(-1),
@"composingExtent" : @(-1),
}];
[plugin handleMethodCall:call
result:^(id){
}];
// Verify editing state was set.
NSDictionary* editingState = [plugin editingState];
EXPECT_STREQ([editingState[@"text"] UTF8String], "Text");
EXPECT_STREQ([editingState[@"selectionAffinity"] UTF8String], "TextAffinity.upstream");
EXPECT_FALSE([editingState[@"selectionIsDirectional"] boolValue]);
EXPECT_EQ([editingState[@"selectionBase"] intValue], 0);
EXPECT_EQ([editingState[@"selectionExtent"] intValue], 0);
EXPECT_EQ([editingState[@"composingBase"] intValue], -1);
EXPECT_EQ([editingState[@"composingExtent"] intValue], -1);
return true;
}
- (bool)testOperationsThatTriggerDelta {
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
NSDictionary* setClientConfig = @{
@"inputAction" : @"action",
@"enableDeltaModel" : @"true",
@"inputType" : @{@"name" : @"inputName"},
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]]
result:^(id){
}];
[plugin insertText:@"text to insert"];
NSDictionary* deltaToFramework = @{
@"oldText" : @"",
@"deltaText" : @"text to insert",
@"deltaStart" : @(0),
@"deltaEnd" : @(0),
@"selectionBase" : @(14),
@"selectionExtent" : @(14),
@"selectionAffinity" : @"TextAffinity.upstream",
@"selectionIsDirectional" : @(false),
@"composingBase" : @(-1),
@"composingExtent" : @(-1),
};
NSDictionary* expectedState = @{
@"deltas" : @[ deltaToFramework ],
};
NSData* updateCall = [[FlutterJSONMethodCodec sharedInstance]
encodeMethodCall:[FlutterMethodCall
methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas"
arguments:@[ @(1), expectedState ]]];
@try {
OCMVerify( // NOLINT(google-objc-avoid-throwing-exception)
[binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]);
} @catch (...) {
return false;
}
[plugin setMarkedText:@"marked text" selectedRange:NSMakeRange(0, 1)];
deltaToFramework = @{
@"oldText" : @"text to insert",
@"deltaText" : @"marked text",
@"deltaStart" : @(14),
@"deltaEnd" : @(14),
@"selectionBase" : @(14),
@"selectionExtent" : @(15),
@"selectionAffinity" : @"TextAffinity.upstream",
@"selectionIsDirectional" : @(false),
@"composingBase" : @(14),
@"composingExtent" : @(25),
};
expectedState = @{
@"deltas" : @[ deltaToFramework ],
};
updateCall = [[FlutterJSONMethodCodec sharedInstance]
encodeMethodCall:[FlutterMethodCall
methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas"
arguments:@[ @(1), expectedState ]]];
@try {
OCMVerify( // NOLINT(google-objc-avoid-throwing-exception)
[binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]);
} @catch (...) {
return false;
}
[plugin unmarkText];
deltaToFramework = @{
@"oldText" : @"text to insertmarked text",
@"deltaText" : @"",
@"deltaStart" : @(-1),
@"deltaEnd" : @(-1),
@"selectionBase" : @(25),
@"selectionExtent" : @(25),
@"selectionAffinity" : @"TextAffinity.upstream",
@"selectionIsDirectional" : @(false),
@"composingBase" : @(-1),
@"composingExtent" : @(-1),
};
expectedState = @{
@"deltas" : @[ deltaToFramework ],
};
updateCall = [[FlutterJSONMethodCodec sharedInstance]
encodeMethodCall:[FlutterMethodCall
methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas"
arguments:@[ @(1), expectedState ]]];
@try {
OCMVerify( // NOLINT(google-objc-avoid-throwing-exception)
[binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]);
} @catch (...) {
return false;
}
return true;
}
- (bool)testComposingWithDelta {
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
NSDictionary* setClientConfig = @{
@"inputAction" : @"action",
@"enableDeltaModel" : @"true",
@"inputType" : @{@"name" : @"inputName"},
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]]
result:^(id){
}];
[plugin setMarkedText:@"m" selectedRange:NSMakeRange(0, 1)];
NSDictionary* deltaToFramework = @{
@"oldText" : @"",
@"deltaText" : @"m",
@"deltaStart" : @(0),
@"deltaEnd" : @(0),
@"selectionBase" : @(0),
@"selectionExtent" : @(1),
@"selectionAffinity" : @"TextAffinity.upstream",
@"selectionIsDirectional" : @(false),
@"composingBase" : @(0),
@"composingExtent" : @(1),
};
NSDictionary* expectedState = @{
@"deltas" : @[ deltaToFramework ],
};
NSData* updateCall = [[FlutterJSONMethodCodec sharedInstance]
encodeMethodCall:[FlutterMethodCall
methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas"
arguments:@[ @(1), expectedState ]]];
@try {
OCMVerify( // NOLINT(google-objc-avoid-throwing-exception)
[binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]);
} @catch (...) {
return false;
}
[plugin setMarkedText:@"ma" selectedRange:NSMakeRange(0, 1)];
deltaToFramework = @{
@"oldText" : @"m",
@"deltaText" : @"ma",
@"deltaStart" : @(0),
@"deltaEnd" : @(1),
@"selectionBase" : @(0),
@"selectionExtent" : @(1),
@"selectionAffinity" : @"TextAffinity.upstream",
@"selectionIsDirectional" : @(false),
@"composingBase" : @(0),
@"composingExtent" : @(2),
};
expectedState = @{
@"deltas" : @[ deltaToFramework ],
};
updateCall = [[FlutterJSONMethodCodec sharedInstance]
encodeMethodCall:[FlutterMethodCall
methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas"
arguments:@[ @(1), expectedState ]]];
@try {
OCMVerify( // NOLINT(google-objc-avoid-throwing-exception)
[binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]);
} @catch (...) {
return false;
}
[plugin setMarkedText:@"mar" selectedRange:NSMakeRange(0, 1)];
deltaToFramework = @{
@"oldText" : @"ma",
@"deltaText" : @"mar",
@"deltaStart" : @(0),
@"deltaEnd" : @(2),
@"selectionBase" : @(0),
@"selectionExtent" : @(1),
@"selectionAffinity" : @"TextAffinity.upstream",
@"selectionIsDirectional" : @(false),
@"composingBase" : @(0),
@"composingExtent" : @(3),
};
expectedState = @{
@"deltas" : @[ deltaToFramework ],
};
updateCall = [[FlutterJSONMethodCodec sharedInstance]
encodeMethodCall:[FlutterMethodCall
methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas"
arguments:@[ @(1), expectedState ]]];
@try {
OCMVerify( // NOLINT(google-objc-avoid-throwing-exception)
[binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]);
} @catch (...) {
return false;
}
[plugin setMarkedText:@"mark" selectedRange:NSMakeRange(0, 1)];
deltaToFramework = @{
@"oldText" : @"mar",
@"deltaText" : @"mark",
@"deltaStart" : @(0),
@"deltaEnd" : @(3),
@"selectionBase" : @(0),
@"selectionExtent" : @(1),
@"selectionAffinity" : @"TextAffinity.upstream",
@"selectionIsDirectional" : @(false),
@"composingBase" : @(0),
@"composingExtent" : @(4),
};
expectedState = @{
@"deltas" : @[ deltaToFramework ],
};
updateCall = [[FlutterJSONMethodCodec sharedInstance]
encodeMethodCall:[FlutterMethodCall
methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas"
arguments:@[ @(1), expectedState ]]];
@try {
OCMVerify( // NOLINT(google-objc-avoid-throwing-exception)
[binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]);
} @catch (...) {
return false;
}
[plugin setMarkedText:@"marke" selectedRange:NSMakeRange(0, 1)];
deltaToFramework = @{
@"oldText" : @"mark",
@"deltaText" : @"marke",
@"deltaStart" : @(0),
@"deltaEnd" : @(4),
@"selectionBase" : @(0),
@"selectionExtent" : @(1),
@"selectionAffinity" : @"TextAffinity.upstream",
@"selectionIsDirectional" : @(false),
@"composingBase" : @(0),
@"composingExtent" : @(5),
};
expectedState = @{
@"deltas" : @[ deltaToFramework ],
};
updateCall = [[FlutterJSONMethodCodec sharedInstance]
encodeMethodCall:[FlutterMethodCall
methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas"
arguments:@[ @(1), expectedState ]]];
@try {
OCMVerify( // NOLINT(google-objc-avoid-throwing-exception)
[binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]);
} @catch (...) {
return false;
}
[plugin setMarkedText:@"marked" selectedRange:NSMakeRange(0, 1)];
deltaToFramework = @{
@"oldText" : @"marke",
@"deltaText" : @"marked",
@"deltaStart" : @(0),
@"deltaEnd" : @(5),
@"selectionBase" : @(0),
@"selectionExtent" : @(1),
@"selectionAffinity" : @"TextAffinity.upstream",
@"selectionIsDirectional" : @(false),
@"composingBase" : @(0),
@"composingExtent" : @(6),
};
expectedState = @{
@"deltas" : @[ deltaToFramework ],
};
updateCall = [[FlutterJSONMethodCodec sharedInstance]
encodeMethodCall:[FlutterMethodCall
methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas"
arguments:@[ @(1), expectedState ]]];
@try {
OCMVerify( // NOLINT(google-objc-avoid-throwing-exception)
[binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]);
} @catch (...) {
return false;
}
[plugin unmarkText];
deltaToFramework = @{
@"oldText" : @"marked",
@"deltaText" : @"",
@"deltaStart" : @(-1),
@"deltaEnd" : @(-1),
@"selectionBase" : @(6),
@"selectionExtent" : @(6),
@"selectionAffinity" : @"TextAffinity.upstream",
@"selectionIsDirectional" : @(false),
@"composingBase" : @(-1),
@"composingExtent" : @(-1),
};
expectedState = @{
@"deltas" : @[ deltaToFramework ],
};
updateCall = [[FlutterJSONMethodCodec sharedInstance]
encodeMethodCall:[FlutterMethodCall
methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas"
arguments:@[ @(1), expectedState ]]];
@try {
OCMVerify( // NOLINT(google-objc-avoid-throwing-exception)
[binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]);
} @catch (...) {
return false;
}
return true;
}
- (bool)testComposingWithDeltasWhenSelectionIsActive {
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
NSDictionary* setClientConfig = @{
@"inputAction" : @"action",
@"enableDeltaModel" : @"true",
@"inputType" : @{@"name" : @"inputName"},
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]]
result:^(id){
}];
FlutterMethodCall* call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditingState"
arguments:@{
@"text" : @"Text",
@"selectionBase" : @(0),
@"selectionExtent" : @(4),
@"composingBase" : @(-1),
@"composingExtent" : @(-1),
}];
[plugin handleMethodCall:call
result:^(id){
}];
[plugin setMarkedText:@"~"
selectedRange:NSMakeRange(1, 0)
replacementRange:NSMakeRange(NSNotFound, 0)];
NSDictionary* deltaToFramework = @{
@"oldText" : @"Text",
@"deltaText" : @"~",
@"deltaStart" : @(0),
@"deltaEnd" : @(4),
@"selectionBase" : @(1),
@"selectionExtent" : @(1),
@"selectionAffinity" : @"TextAffinity.upstream",
@"selectionIsDirectional" : @(false),
@"composingBase" : @(0),
@"composingExtent" : @(1),
};
NSDictionary* expectedState = @{
@"deltas" : @[ deltaToFramework ],
};
NSData* updateCall = [[FlutterJSONMethodCodec sharedInstance]
encodeMethodCall:[FlutterMethodCall
methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas"
arguments:@[ @(1), expectedState ]]];
@try {
OCMVerify( // NOLINT(google-objc-avoid-throwing-exception)
[binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]);
} @catch (...) {
return false;
}
return true;
}
- (bool)testPerformKeyEquivalent {
__block NSEvent* eventBeingDispatchedByKeyboardManager = nil;
FlutterViewController* viewControllerMock = OCMClassMock([FlutterViewController class]);
OCMStub([viewControllerMock isDispatchingKeyEvent:[OCMArg any]])
.andDo(^(NSInvocation* invocation) {
NSEvent* event;
[invocation getArgument:(void*)&event atIndex:2];
BOOL result = event == eventBeingDispatchedByKeyboardManager;
[invocation setReturnValue:&result];
});
NSEvent* event = [NSEvent keyEventWithType:NSEventTypeKeyDown
location:NSZeroPoint
modifierFlags:0x100
timestamp:0
windowNumber:0
context:nil
characters:@""
charactersIgnoringModifiers:@""
isARepeat:NO
keyCode:0x50];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewControllerMock];
OCMExpect([viewControllerMock keyDown:event]);
// Require that event is handled (returns YES)
if (![plugin performKeyEquivalent:event]) {
return false;
};
@try {
OCMVerify( // NOLINT(google-objc-avoid-throwing-exception)
[viewControllerMock keyDown:event]);
} @catch (...) {
return false;
}
// performKeyEquivalent must not forward event if it is being
// dispatched by keyboard manager
eventBeingDispatchedByKeyboardManager = event;
OCMReject([viewControllerMock keyDown:event]);
@try {
// Require that event is not handled (returns NO) and not
// forwarded to controller
if ([plugin performKeyEquivalent:event]) {
return false;
};
} @catch (...) {
return false;
}
return true;
}
- (bool)handleArrowKeyWhenImePopoverIsActive {
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:FlutterKeyEvent {}
callback:nil
userData:nil]);
NSTextInputContext* textInputContext = OCMClassMock([NSTextInputContext class]);
OCMStub([textInputContext handleEvent:[OCMArg any]]).andReturn(YES);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
plugin.textInputContext = textInputContext;
NSDictionary* setClientConfig = @{
@"inputAction" : @"action",
@"enableDeltaModel" : @"true",
@"inputType" : @{@"name" : @"inputName"},
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]]
result:^(id){
}];
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.show"
arguments:@[]]
result:^(id){
}];
// Set marked text, simulate active IME popover.
[plugin setMarkedText:@"m"
selectedRange:NSMakeRange(0, 1)
replacementRange:NSMakeRange(NSNotFound, 0)];
// Right arrow key. This, unlike the key below should be handled by the plugin.
NSEvent* event = [NSEvent keyEventWithType:NSEventTypeKeyDown
location:NSZeroPoint
modifierFlags:0xa00100
timestamp:0
windowNumber:0
context:nil
characters:@"\uF702"
charactersIgnoringModifiers:@"\uF702"
isARepeat:NO
keyCode:0x4];
// Plugin should mark the event as key equivalent.
[plugin performKeyEquivalent:event];
if ([plugin handleKeyEvent:event] != true) {
return false;
}
// CTRL+H (delete backwards)
event = [NSEvent keyEventWithType:NSEventTypeKeyDown
location:NSZeroPoint
modifierFlags:0x40101
timestamp:0
windowNumber:0
context:nil
characters:@"\uF702"
charactersIgnoringModifiers:@"\uF702"
isARepeat:NO
keyCode:0x4];
// Plugin should mark the event as key equivalent.
[plugin performKeyEquivalent:event];
if ([plugin handleKeyEvent:event] != false) {
return false;
}
return true;
}
- (bool)unhandledKeyEquivalent {
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
NSDictionary* setClientConfig = @{
@"inputAction" : @"action",
@"enableDeltaModel" : @"true",
@"inputType" : @{@"name" : @"inputName"},
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]]
result:^(id){
}];
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.show"
arguments:@[]]
result:^(id){
}];
// CTRL+H (delete backwards)
NSEvent* event = [NSEvent keyEventWithType:NSEventTypeKeyDown
location:NSZeroPoint
modifierFlags:0x40101
timestamp:0
windowNumber:0
context:nil
characters:@""
charactersIgnoringModifiers:@"h"
isARepeat:NO
keyCode:0x4];
// Plugin should mark the event as key equivalent.
[plugin performKeyEquivalent:event];
// Simulate KeyboardManager sending unhandled event to plugin. This must return
// true because it is a known editing command.
if ([plugin handleKeyEvent:event] != true) {
return false;
}
// CMD+W
event = [NSEvent keyEventWithType:NSEventTypeKeyDown
location:NSZeroPoint
modifierFlags:0x100108
timestamp:0
windowNumber:0
context:nil
characters:@"w"
charactersIgnoringModifiers:@"w"
isARepeat:NO
keyCode:0x13];
// Plugin should mark the event as key equivalent.
[plugin performKeyEquivalent:event];
// This is not a valid editing command, plugin must return false so that
// KeyboardManager sends the event to next responder.
if ([plugin handleKeyEvent:event] != false) {
return false;
}
return true;
}
- (bool)testInsertNewLine {
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:FlutterKeyEvent {}
callback:nil
userData:nil]);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
NSDictionary* setClientConfig = @{
@"inputType" : @{@"name" : @"TextInputType.multiline"},
@"inputAction" : @"TextInputAction.newline",
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]]
result:^(id){
}];
FlutterMethodCall* call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditingState"
arguments:@{
@"text" : @"Text",
@"selectionBase" : @(4),
@"selectionExtent" : @(4),
@"composingBase" : @(-1),
@"composingExtent" : @(-1),
}];
[plugin handleMethodCall:call
result:^(id){
}];
// Verify editing state was set.
NSDictionary* editingState = [plugin editingState];
EXPECT_STREQ([editingState[@"text"] UTF8String], "Text");
EXPECT_STREQ([editingState[@"selectionAffinity"] UTF8String], "TextAffinity.upstream");
EXPECT_FALSE([editingState[@"selectionIsDirectional"] boolValue]);
EXPECT_EQ([editingState[@"selectionBase"] intValue], 4);
EXPECT_EQ([editingState[@"selectionExtent"] intValue], 4);
EXPECT_EQ([editingState[@"composingBase"] intValue], -1);
EXPECT_EQ([editingState[@"composingExtent"] intValue], -1);
[plugin doCommandBySelector:@selector(insertNewline:)];
// Verify editing state was set.
editingState = [plugin editingState];
EXPECT_STREQ([editingState[@"text"] UTF8String], "Text\n");
EXPECT_STREQ([editingState[@"selectionAffinity"] UTF8String], "TextAffinity.upstream");
EXPECT_FALSE([editingState[@"selectionIsDirectional"] boolValue]);
EXPECT_EQ([editingState[@"selectionBase"] intValue], 5);
EXPECT_EQ([editingState[@"selectionExtent"] intValue], 5);
EXPECT_EQ([editingState[@"composingBase"] intValue], -1);
EXPECT_EQ([editingState[@"composingExtent"] intValue], -1);
return true;
}
- (bool)testSendActionDoNotInsertNewLine {
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:FlutterKeyEvent {}
callback:nil
userData:nil]);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
NSDictionary* setClientConfig = @{
@"inputType" : @{@"name" : @"TextInputType.multiline"},
@"inputAction" : @"TextInputAction.send",
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]]
result:^(id){
}];
FlutterMethodCall* call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditingState"
arguments:@{
@"text" : @"Text",
@"selectionBase" : @(4),
@"selectionExtent" : @(4),
@"composingBase" : @(-1),
@"composingExtent" : @(-1),
}];
NSDictionary* expectedState = @{
@"selectionBase" : @(4),
@"selectionExtent" : @(4),
@"selectionAffinity" : @"TextAffinity.upstream",
@"selectionIsDirectional" : @(NO),
@"composingBase" : @(-1),
@"composingExtent" : @(-1),
@"text" : @"Text",
};
NSData* updateCall = [[FlutterJSONMethodCodec sharedInstance]
encodeMethodCall:[FlutterMethodCall
methodCallWithMethodName:@"TextInputClient.updateEditingState"
arguments:@[ @(1), expectedState ]]];
OCMExpect( // NOLINT(google-objc-avoid-throwing-exception)
[binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]);
[plugin handleMethodCall:call
result:^(id){
}];
[plugin doCommandBySelector:@selector(insertNewline:)];
NSData* performActionCall = [[FlutterJSONMethodCodec sharedInstance]
encodeMethodCall:[FlutterMethodCall
methodCallWithMethodName:@"TextInputClient.performAction"
arguments:@[ @(1), @"TextInputAction.send" ]]];
// Input action should be notified.
@try {
OCMVerify( // NOLINT(google-objc-avoid-throwing-exception)
[binaryMessengerMock sendOnChannel:@"flutter/textinput" message:performActionCall]);
} @catch (...) {
return false;
}
NSDictionary* updatedState = @{
@"selectionBase" : @(5),
@"selectionExtent" : @(5),
@"selectionAffinity" : @"TextAffinity.upstream",
@"selectionIsDirectional" : @(NO),
@"composingBase" : @(-1),
@"composingExtent" : @(-1),
@"text" : @"Text\n",
};
updateCall = [[FlutterJSONMethodCodec sharedInstance]
encodeMethodCall:[FlutterMethodCall
methodCallWithMethodName:@"TextInputClient.updateEditingState"
arguments:@[ @(1), updatedState ]]];
// Verify that editing state was not be updated.
@try {
OCMVerify( // NOLINT(google-objc-avoid-throwing-exception)
[binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]);
return false;
} @catch (...) {
// Expected.
}
return true;
}
- (bool)testLocalTextAndSelectionUpdateAfterDelta {
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
NSDictionary* setClientConfig = @{
@"inputAction" : @"action",
@"enableDeltaModel" : @"true",
@"inputType" : @{@"name" : @"inputName"},
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]]
result:^(id){
}];
[plugin insertText:@"text to insert"];
NSDictionary* deltaToFramework = @{
@"oldText" : @"",
@"deltaText" : @"text to insert",
@"deltaStart" : @(0),
@"deltaEnd" : @(0),
@"selectionBase" : @(14),
@"selectionExtent" : @(14),
@"selectionAffinity" : @"TextAffinity.upstream",
@"selectionIsDirectional" : @(false),
@"composingBase" : @(-1),
@"composingExtent" : @(-1),
};
NSDictionary* expectedState = @{
@"deltas" : @[ deltaToFramework ],
};
NSData* updateCall = [[FlutterJSONMethodCodec sharedInstance]
encodeMethodCall:[FlutterMethodCall
methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas"
arguments:@[ @(1), expectedState ]]];
@try {
OCMVerify( // NOLINT(google-objc-avoid-throwing-exception)
[binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]);
} @catch (...) {
return false;
}
bool localTextAndSelectionUpdated = [plugin.string isEqualToString:@"text to insert"] &&
NSEqualRanges(plugin.selectedRange, NSMakeRange(14, 0));
return localTextAndSelectionUpdated;
}
- (bool)testSelectorsAreForwardedToFramework {
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
NSDictionary* setClientConfig = @{
@"inputAction" : @"action",
@"enableDeltaModel" : @"true",
@"inputType" : @{@"name" : @"inputName"},
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]]
result:^(id){
}];
// Can't run CFRunLoop in default mode because it causes crashes from scheduled
// sources from other tests.
NSString* runLoopMode = @"FlutterTestRunLoopMode";
plugin.customRunLoopMode = runLoopMode;
// Ensure both selectors are grouped in one platform channel call.
[plugin doCommandBySelector:@selector(moveUp:)];
[plugin doCommandBySelector:@selector(moveRightAndModifySelection:)];
__block bool done = false;
CFRunLoopPerformBlock(CFRunLoopGetMain(), (__bridge CFStringRef)runLoopMode, ^{
done = true;
});
while (!done) {
// Each invocation will handle one source.
CFRunLoopRunInMode((__bridge CFStringRef)runLoopMode, 0, true);
}
NSData* performSelectorCall = [[FlutterJSONMethodCodec sharedInstance]
encodeMethodCall:[FlutterMethodCall
methodCallWithMethodName:@"TextInputClient.performSelectors"
arguments:@[
@(1), @[ @"moveUp:", @"moveRightAndModifySelection:" ]
]]];
@try {
OCMVerify( // NOLINT(google-objc-avoid-throwing-exception)
[binaryMessengerMock sendOnChannel:@"flutter/textinput" message:performSelectorCall]);
} @catch (...) {
return false;
}
return true;
}
@end
namespace flutter::testing {
namespace {
// Allocates and returns an engine configured for the text fixture resource configuration.
FlutterEngine* CreateTestEngine() {
NSString* fixtures = @(testing::GetFixturesPath());
FlutterDartProject* project = [[FlutterDartProject alloc]
initWithAssetsPath:fixtures
ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
return [[FlutterEngine alloc] initWithName:@"test" project:project allowHeadlessExecution:true];
}
} // namespace
TEST(FlutterTextInputPluginTest, TestEmptyCompositionRange) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testEmptyCompositionRange]);
}
TEST(FlutterTextInputPluginTest, TestSetMarkedTextWithSelectionChange) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testSetMarkedTextWithSelectionChange]);
}
TEST(FlutterTextInputPluginTest, TestSetMarkedTextWithReplacementRange) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testSetMarkedTextWithReplacementRange]);
}
TEST(FlutterTextInputPluginTest, TestComposingRegionRemovedByFramework) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testComposingRegionRemovedByFramework]);
}
TEST(FlutterTextInputPluginTest, TestClearClientDuringComposing) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testClearClientDuringComposing]);
}
TEST(FlutterTextInputPluginTest, TestAutocompleteDisabledWhenAutofillNotSet) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testAutocompleteDisabledWhenAutofillNotSet]);
}
TEST(FlutterTextInputPluginTest, TestAutocompleteEnabledWhenAutofillSet) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testAutocompleteEnabledWhenAutofillSet]);
}
TEST(FlutterTextInputPluginTest, TestAutocompleteEnabledWhenAutofillSetNoHint) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testAutocompleteEnabledWhenAutofillSetNoHint]);
}
TEST(FlutterTextInputPluginTest, TestAutocompleteDisabledWhenObscureTextSet) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testAutocompleteDisabledWhenObscureTextSet]);
}
TEST(FlutterTextInputPluginTest, TestAutocompleteDisabledWhenPasswordAutofillSet) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testAutocompleteDisabledWhenPasswordAutofillSet]);
}
TEST(FlutterTextInputPluginTest, TestAutocompleteDisabledWhenAutofillGroupIncludesPassword) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc]
testAutocompleteDisabledWhenAutofillGroupIncludesPassword]);
}
TEST(FlutterTextInputPluginTest, TestFirstRectForCharacterRange) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testFirstRectForCharacterRange]);
}
TEST(FlutterTextInputPluginTest, TestFirstRectForCharacterRangeAtInfinity) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testFirstRectForCharacterRangeAtInfinity]);
}
TEST(FlutterTextInputPluginTest, TestFirstRectForCharacterRangeWithEsotericAffineTransform) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc]
testFirstRectForCharacterRangeWithEsotericAffineTransform]);
}
TEST(FlutterTextInputPluginTest, TestSetEditingStateWithTextEditingDelta) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testSetEditingStateWithTextEditingDelta]);
}
TEST(FlutterTextInputPluginTest, TestOperationsThatTriggerDelta) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testOperationsThatTriggerDelta]);
}
TEST(FlutterTextInputPluginTest, TestComposingWithDelta) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testComposingWithDelta]);
}
TEST(FlutterTextInputPluginTest, testComposingWithDeltasWhenSelectionIsActive) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testComposingWithDeltasWhenSelectionIsActive]);
}
TEST(FlutterTextInputPluginTest, TestLocalTextAndSelectionUpdateAfterDelta) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testLocalTextAndSelectionUpdateAfterDelta]);
}
TEST(FlutterTextInputPluginTest, TestPerformKeyEquivalent) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testPerformKeyEquivalent]);
}
TEST(FlutterTextInputPluginTest, HandleArrowKeyWhenImePopoverIsActive) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] handleArrowKeyWhenImePopoverIsActive]);
}
TEST(FlutterTextInputPluginTest, UnhandledKeyEquivalent) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] unhandledKeyEquivalent]);
}
TEST(FlutterTextInputPluginTest, TestSelectorsAreForwardedToFramework) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testSelectorsAreForwardedToFramework]);
}
TEST(FlutterTextInputPluginTest, TestInsertNewLine) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testInsertNewLine]);
}
TEST(FlutterTextInputPluginTest, TestSendActionDoNotInsertNewLine) {
ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testSendActionDoNotInsertNewLine]);
}
TEST(FlutterTextInputPluginTest, CanWorkWithFlutterTextField) {
FlutterEngine* engine = CreateTestEngine();
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
nibName:nil
bundle:nil];
[viewController loadView];
// Create a NSWindow so that the native text field can become first responder.
NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600)
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO];
window.contentView = viewController.view;
engine.semanticsEnabled = YES;
auto bridge = viewController.accessibilityBridge.lock();
FlutterPlatformNodeDelegateMac delegate(bridge, viewController);
ui::AXTree tree;
ui::AXNode ax_node(&tree, nullptr, 0, 0);
ui::AXNodeData node_data;
node_data.SetValue("initial text");
ax_node.SetData(node_data);
delegate.Init(viewController.accessibilityBridge, &ax_node);
{
FlutterTextPlatformNode text_platform_node(&delegate, viewController);
FlutterTextFieldMock* mockTextField =
[[FlutterTextFieldMock alloc] initWithPlatformNode:&text_platform_node
fieldEditor:viewController.textInputPlugin];
[viewController.view addSubview:mockTextField];
[mockTextField startEditing];
NSDictionary* setClientConfig = @{
@"inputAction" : @"action",
@"inputType" : @{@"name" : @"inputName"},
};
FlutterMethodCall* methodCall =
[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
arguments:@[ @(1), setClientConfig ]];
FlutterResult result = ^(id result) {
};
[viewController.textInputPlugin handleMethodCall:methodCall result:result];
NSDictionary* arguments = @{
@"text" : @"new text",
@"selectionBase" : @(1),
@"selectionExtent" : @(2),
@"composingBase" : @(-1),
@"composingExtent" : @(-1),
};
methodCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditingState"
arguments:arguments];
[viewController.textInputPlugin handleMethodCall:methodCall result:result];
EXPECT_EQ([mockTextField.lastUpdatedString isEqualToString:@"new text"], YES);
EXPECT_EQ(NSEqualRanges(mockTextField.lastUpdatedSelection, NSMakeRange(1, 1)), YES);
// This blocks the FlutterTextFieldMock, which is held onto by the main event
// loop, from crashing.
[mockTextField setPlatformNode:nil];
}
// This verifies that clearing the platform node works.
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
}
TEST(FlutterTextInputPluginTest, CanNotBecomeResponderIfNoViewController) {
FlutterEngine* engine = CreateTestEngine();
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
nibName:nil
bundle:nil];
[viewController loadView];
// Creates a NSWindow so that the native text field can become first responder.
NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600)
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO];
window.contentView = viewController.view;
engine.semanticsEnabled = YES;
auto bridge = viewController.accessibilityBridge.lock();
FlutterPlatformNodeDelegateMac delegate(bridge, viewController);
ui::AXTree tree;
ui::AXNode ax_node(&tree, nullptr, 0, 0);
ui::AXNodeData node_data;
node_data.SetValue("initial text");
ax_node.SetData(node_data);
delegate.Init(viewController.accessibilityBridge, &ax_node);
FlutterTextPlatformNode text_platform_node(&delegate, viewController);
FlutterTextField* textField = text_platform_node.GetNativeViewAccessible();
EXPECT_EQ([textField becomeFirstResponder], YES);
// Removes view controller.
[engine setViewController:nil];
FlutterTextPlatformNode text_platform_node_no_controller(&delegate, nil);
textField = text_platform_node_no_controller.GetNativeViewAccessible();
EXPECT_EQ([textField becomeFirstResponder], NO);
}
TEST(FlutterTextInputPluginTest, IsAddedAndRemovedFromViewHierarchy) {
FlutterEngine* engine = CreateTestEngine();
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
nibName:nil
bundle:nil];
[viewController loadView];
NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600)
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO];
window.contentView = viewController.view;
ASSERT_EQ(viewController.textInputPlugin.superview, nil);
ASSERT_FALSE(window.firstResponder == viewController.textInputPlugin);
[viewController.textInputPlugin
handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.show" arguments:@[]]
result:^(id){
}];
ASSERT_EQ(viewController.textInputPlugin.superview, viewController.view);
ASSERT_TRUE(window.firstResponder == viewController.textInputPlugin);
[viewController.textInputPlugin
handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.hide" arguments:@[]]
result:^(id){
}];
ASSERT_EQ(viewController.textInputPlugin.superview, nil);
ASSERT_FALSE(window.firstResponder == viewController.textInputPlugin);
}
TEST(FlutterTextInputPluginTest, FirstResponderIsCorrect) {
FlutterEngine* engine = CreateTestEngine();
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
nibName:nil
bundle:nil];
[viewController loadView];
NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600)
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO];
window.contentView = viewController.view;
ASSERT_TRUE(viewController.flutterView.acceptsFirstResponder);
[window makeFirstResponder:viewController.flutterView];
[viewController.textInputPlugin
handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.show" arguments:@[]]
result:^(id){
}];
ASSERT_TRUE(window.firstResponder == viewController.textInputPlugin);
ASSERT_FALSE(viewController.flutterView.acceptsFirstResponder);
[viewController.textInputPlugin
handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.hide" arguments:@[]]
result:^(id){
}];
ASSERT_TRUE(viewController.flutterView.acceptsFirstResponder);
ASSERT_TRUE(window.firstResponder == viewController.flutterView);
}
TEST(FlutterTextInputPluginTest, HasZeroSizeAndClipsToBounds) {
id engineMock = flutter::testing::CreateMockFlutterEngine(@"");
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
FlutterTextInputPlugin* plugin =
[[FlutterTextInputPlugin alloc] initWithViewController:viewController];
ASSERT_TRUE(NSIsEmptyRect(plugin.frame));
ASSERT_TRUE(plugin.clipsToBounds);
}
} // namespace flutter::testing
| engine/shell/platform/darwin/macos/framework/Source/FlutterTextInputPluginTest.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterTextInputPluginTest.mm",
"repo_id": "engine",
"token_count": 42520
} | 329 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterView.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManager.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterThreadSynchronizer.h"
#import <QuartzCore/QuartzCore.h>
@interface FlutterView () <FlutterSurfaceManagerDelegate> {
int64_t _viewId;
__weak id<FlutterViewDelegate> _viewDelegate;
FlutterThreadSynchronizer* _threadSynchronizer;
FlutterSurfaceManager* _surfaceManager;
}
@end
@implementation FlutterView
- (instancetype)initWithMTLDevice:(id<MTLDevice>)device
commandQueue:(id<MTLCommandQueue>)commandQueue
delegate:(id<FlutterViewDelegate>)delegate
threadSynchronizer:(FlutterThreadSynchronizer*)threadSynchronizer
viewId:(int64_t)viewId {
self = [super initWithFrame:NSZeroRect];
if (self) {
[self setWantsLayer:YES];
[self setBackgroundColor:[NSColor blackColor]];
[self setLayerContentsRedrawPolicy:NSViewLayerContentsRedrawDuringViewResize];
_viewId = viewId;
_viewDelegate = delegate;
_threadSynchronizer = threadSynchronizer;
_surfaceManager = [[FlutterSurfaceManager alloc] initWithDevice:device
commandQueue:commandQueue
layer:self.layer
delegate:self];
}
return self;
}
- (void)onPresent:(CGSize)frameSize withBlock:(dispatch_block_t)block {
[_threadSynchronizer performCommitForView:_viewId size:frameSize notify:block];
}
- (FlutterSurfaceManager*)surfaceManager {
return _surfaceManager;
}
- (void)reshaped {
CGSize scaledSize = [self convertSizeToBacking:self.bounds.size];
[_threadSynchronizer beginResizeForView:_viewId
size:scaledSize
notify:^{
[_viewDelegate viewDidReshape:self];
}];
}
- (void)setBackgroundColor:(NSColor*)color {
self.layer.backgroundColor = color.CGColor;
}
#pragma mark - NSView overrides
- (void)setFrameSize:(NSSize)newSize {
[super setFrameSize:newSize];
[self reshaped];
}
/**
* Declares that the view uses a flipped coordinate system, consistent with Flutter conventions.
*/
- (BOOL)isFlipped {
return YES;
}
- (BOOL)isOpaque {
return YES;
}
/**
* Declares that the initial mouse-down when the view is not in focus will send an event to the
* view.
*/
- (BOOL)acceptsFirstMouse:(NSEvent*)event {
return YES;
}
- (BOOL)acceptsFirstResponder {
// This is to ensure that FlutterView does not take first responder status from TextInputPlugin
// on mouse clicks.
return [_viewDelegate viewShouldAcceptFirstResponder:self];
}
- (void)cursorUpdate:(NSEvent*)event {
// When adding/removing views AppKit will schedule call to current hit-test view
// cursorUpdate: at the end of frame to determine possible cursor change. If
// the view doesn't implement cursorUpdate: AppKit will set the default (arrow) cursor
// instead. This would replace the cursor set by FlutterMouseCursorPlugin.
// Empty cursorUpdate: implementation prevents this behavior.
// https://github.com/flutter/flutter/issues/111425
}
- (void)viewDidChangeBackingProperties {
[super viewDidChangeBackingProperties];
// Force redraw
[_viewDelegate viewDidReshape:self];
}
- (BOOL)layer:(CALayer*)layer
shouldInheritContentsScale:(CGFloat)newScale
fromWindow:(NSWindow*)window {
return YES;
}
#pragma mark - NSAccessibility overrides
- (BOOL)isAccessibilityElement {
return YES;
}
- (NSAccessibilityRole)accessibilityRole {
return NSAccessibilityGroupRole;
}
- (NSString*)accessibilityLabel {
// TODO(chunhtai): Provides a way to let developer customize the accessibility
// label.
// https://github.com/flutter/flutter/issues/75446
NSString* applicationName =
[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
if (!applicationName) {
applicationName = [NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleName"];
}
return applicationName;
}
@end
| engine/shell/platform/darwin/macos/framework/Source/FlutterView.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterView.mm",
"repo_id": "engine",
"token_count": 1721
} | 330 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Cocoa/Cocoa.h>
#import <Foundation/Foundation.h>
#import "flutter/shell/platform/darwin/macos/framework/Source/TestFlutterPlatformView.h"
@implementation TestFlutterPlatformView
- (instancetype)initWithFrame:(CGRect)frame arguments:(nullable NSDictionary*)args {
self = [super initWithFrame:frame];
_args = args;
return self;
}
@end
@implementation TestFlutterPlatformViewFactory
- (NSView*)createWithViewIdentifier:(int64_t)viewId arguments:(nullable id)args {
return [[TestFlutterPlatformView alloc] initWithFrame:CGRectZero arguments:args];
}
- (NSObject<FlutterMessageCodec>*)createArgsCodec {
return [FlutterStandardMessageCodec sharedInstance];
}
@end
| engine/shell/platform/darwin/macos/framework/Source/TestFlutterPlatformView.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/TestFlutterPlatformView.mm",
"repo_id": "engine",
"token_count": 267
} | 331 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/embedder/embedder_external_texture_resolver.h"
#include <memory>
#include <utility>
namespace flutter {
#ifdef SHELL_ENABLE_GL
EmbedderExternalTextureResolver::EmbedderExternalTextureResolver(
EmbedderExternalTextureGL::ExternalTextureCallback gl_callback)
: gl_callback_(std::move(gl_callback)) {}
#endif
#ifdef SHELL_ENABLE_METAL
EmbedderExternalTextureResolver::EmbedderExternalTextureResolver(
EmbedderExternalTextureMetal::ExternalTextureCallback metal_callback)
: metal_callback_(std::move(metal_callback)) {}
#endif
std::unique_ptr<Texture>
EmbedderExternalTextureResolver::ResolveExternalTexture(int64_t texture_id) {
#ifdef SHELL_ENABLE_GL
if (gl_callback_) {
return std::make_unique<EmbedderExternalTextureGL>(texture_id,
gl_callback_);
}
#endif
#ifdef SHELL_ENABLE_METAL
if (metal_callback_) {
return std::make_unique<EmbedderExternalTextureMetal>(texture_id,
metal_callback_);
}
#endif
return nullptr;
}
bool EmbedderExternalTextureResolver::SupportsExternalTextures() {
#ifdef SHELL_ENABLE_GL
if (gl_callback_) {
return true;
}
#endif
#ifdef SHELL_ENABLE_METAL
if (metal_callback_) {
return true;
}
#endif
return false;
}
} // namespace flutter
| engine/shell/platform/embedder/embedder_external_texture_resolver.cc/0 | {
"file_path": "engine/shell/platform/embedder/embedder_external_texture_resolver.cc",
"repo_id": "engine",
"token_count": 592
} | 332 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/embedder/embedder_render_target_impeller.h"
#include "flutter/fml/logging.h"
#include "flutter/impeller/renderer/render_target.h"
namespace flutter {
EmbedderRenderTargetImpeller::EmbedderRenderTargetImpeller(
FlutterBackingStore backing_store,
std::shared_ptr<impeller::AiksContext> aiks_context,
std::unique_ptr<impeller::RenderTarget> impeller_target,
fml::closure on_release,
fml::closure framebuffer_destruction_callback)
: EmbedderRenderTarget(backing_store, std::move(on_release)),
aiks_context_(std::move(aiks_context)),
impeller_target_(std::move(impeller_target)),
framebuffer_destruction_callback_(
std::move(framebuffer_destruction_callback)) {
FML_DCHECK(aiks_context_);
FML_DCHECK(impeller_target_);
}
EmbedderRenderTargetImpeller::~EmbedderRenderTargetImpeller() {
if (framebuffer_destruction_callback_) {
framebuffer_destruction_callback_();
}
}
sk_sp<SkSurface> EmbedderRenderTargetImpeller::GetSkiaSurface() const {
return nullptr;
}
impeller::RenderTarget* EmbedderRenderTargetImpeller::GetImpellerRenderTarget()
const {
return impeller_target_.get();
}
std::shared_ptr<impeller::AiksContext>
EmbedderRenderTargetImpeller::GetAiksContext() const {
return aiks_context_;
}
SkISize EmbedderRenderTargetImpeller::GetRenderTargetSize() const {
auto size = impeller_target_->GetRenderTargetSize();
return SkISize::Make(size.width, size.height);
}
} // namespace flutter
| engine/shell/platform/embedder/embedder_render_target_impeller.cc/0 | {
"file_path": "engine/shell/platform/embedder/embedder_render_target_impeller.cc",
"repo_id": "engine",
"token_count": 594
} | 333 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include <utility>
#include "flutter/shell/platform/embedder/embedder_surface_metal_impeller.h"
#include "flutter/fml/logging.h"
#include "flutter/fml/synchronization/sync_switch.h"
#include "flutter/shell/gpu/gpu_surface_metal_delegate.h"
#include "flutter/shell/gpu/gpu_surface_metal_impeller.h"
#import "flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalImpeller.h"
#include "impeller/entity/mtl/entity_shaders.h"
#include "impeller/entity/mtl/framebuffer_blend_shaders.h"
#include "impeller/entity/mtl/modern_shaders.h"
#include "impeller/renderer/backend/metal/context_mtl.h"
#if IMPELLER_ENABLE_3D
#include "impeller/scene/shaders/mtl/scene_shaders.h" // nogncheck
#endif // IMPELLER_ENABLE_3D
FLUTTER_ASSERT_NOT_ARC
namespace flutter {
EmbedderSurfaceMetalImpeller::EmbedderSurfaceMetalImpeller(
GPUMTLDeviceHandle device,
GPUMTLCommandQueueHandle command_queue,
MetalDispatchTable metal_dispatch_table,
std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder)
: GPUSurfaceMetalDelegate(MTLRenderTargetType::kMTLTexture),
metal_dispatch_table_(std::move(metal_dispatch_table)),
external_view_embedder_(std::move(external_view_embedder)) {
std::vector<std::shared_ptr<fml::Mapping>> shader_mappings = {
std::make_shared<fml::NonOwnedMapping>(impeller_entity_shaders_data,
impeller_entity_shaders_length),
#if IMPELLER_ENABLE_3D
std::make_shared<fml::NonOwnedMapping>(impeller_scene_shaders_data,
impeller_scene_shaders_length),
#endif // IMPELLER_ENABLE_3D
std::make_shared<fml::NonOwnedMapping>(impeller_modern_shaders_data,
impeller_modern_shaders_length),
std::make_shared<fml::NonOwnedMapping>(impeller_framebuffer_blend_shaders_data,
impeller_framebuffer_blend_shaders_length),
};
context_ = impeller::ContextMTL::Create(
(id<MTLDevice>)device, // device
(id<MTLCommandQueue>)command_queue, // command_queue
shader_mappings, // shader_libraries_data
std::make_shared<fml::SyncSwitch>(false), // is_gpu_disabled_sync_switch
"Impeller Library" // library_label
);
FML_LOG(IMPORTANT) << "Using the Impeller rendering backend (Metal).";
valid_ = !!context_;
}
EmbedderSurfaceMetalImpeller::~EmbedderSurfaceMetalImpeller() = default;
bool EmbedderSurfaceMetalImpeller::IsValid() const {
return valid_;
}
std::unique_ptr<Surface> EmbedderSurfaceMetalImpeller::CreateGPUSurface()
IMPELLER_CA_METAL_LAYER_AVAILABLE {
if (!IsValid()) {
return nullptr;
}
const bool render_to_surface = !external_view_embedder_;
auto surface = std::make_unique<GPUSurfaceMetalImpeller>(this, context_, render_to_surface);
if (!surface->IsValid()) {
return nullptr;
}
return surface;
}
std::shared_ptr<impeller::Context> EmbedderSurfaceMetalImpeller::CreateImpellerContext() const {
return context_;
}
GPUCAMetalLayerHandle EmbedderSurfaceMetalImpeller::GetCAMetalLayer(
const SkISize& frame_info) const {
FML_CHECK(false) << "Only rendering to MTLTexture is supported.";
return nullptr;
}
bool EmbedderSurfaceMetalImpeller::PresentDrawable(GrMTLHandle drawable) const {
FML_CHECK(false) << "Only rendering to MTLTexture is supported.";
return false;
}
GPUMTLTextureInfo EmbedderSurfaceMetalImpeller::GetMTLTexture(const SkISize& frame_info) const {
return metal_dispatch_table_.get_texture(frame_info);
}
bool EmbedderSurfaceMetalImpeller::PresentTexture(GPUMTLTextureInfo texture) const {
return metal_dispatch_table_.present(texture);
}
} // namespace flutter
| engine/shell/platform/embedder/embedder_surface_metal_impeller.mm/0 | {
"file_path": "engine/shell/platform/embedder/embedder_surface_metal_impeller.mm",
"repo_id": "engine",
"token_count": 1660
} | 334 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/embedder/pixel_formats.h"
#include "flutter/shell/platform/embedder/embedder.h"
#include "third_party/skia/include/core/SkColorSpace.h"
#include "third_party/skia/include/core/SkColorType.h"
#include "third_party/skia/include/core/SkImageInfo.h"
std::optional<SkColorType> getSkColorType(FlutterSoftwarePixelFormat pixfmt) {
switch (pixfmt) {
case kFlutterSoftwarePixelFormatGray8:
return kGray_8_SkColorType;
case kFlutterSoftwarePixelFormatRGB565:
return kRGB_565_SkColorType;
case kFlutterSoftwarePixelFormatRGBA4444:
return kARGB_4444_SkColorType;
case kFlutterSoftwarePixelFormatRGBA8888:
return kRGBA_8888_SkColorType;
case kFlutterSoftwarePixelFormatRGBX8888:
return kRGB_888x_SkColorType;
case kFlutterSoftwarePixelFormatBGRA8888:
return kBGRA_8888_SkColorType;
case kFlutterSoftwarePixelFormatNative32:
return kN32_SkColorType;
default:
FML_LOG(ERROR) << "Invalid software rendering pixel format";
return std::nullopt;
}
}
std::optional<SkColorInfo> getSkColorInfo(FlutterSoftwarePixelFormat pixfmt) {
auto ct = getSkColorType(pixfmt);
if (!ct) {
return std::nullopt;
}
auto at = SkColorTypeIsAlwaysOpaque(*ct) ? kOpaque_SkAlphaType
: kPremul_SkAlphaType;
return SkColorInfo(*ct, at, SkColorSpace::MakeSRGB());
}
| engine/shell/platform/embedder/pixel_formats.cc/0 | {
"file_path": "engine/shell/platform/embedder/pixel_formats.cc",
"repo_id": "engine",
"token_count": 609
} | 335 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_H_
#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_H_
#include <map>
#include <memory>
#include "flutter/fml/macros.h"
#include "flutter/shell/platform/embedder/tests/embedder_test_context.h"
#include "flutter/testing/testing.h"
#include "flutter/testing/thread_test.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
class EmbedderTest : public ThreadTest {
public:
EmbedderTest();
std::string GetFixturesDirectory() const;
EmbedderTestContext& GetEmbedderContext(EmbedderTestContextType type);
private:
std::map<EmbedderTestContextType, std::unique_ptr<EmbedderTestContext>>
embedder_contexts_;
FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTest);
};
class EmbedderTestMultiBackend
: public EmbedderTest,
public ::testing::WithParamInterface<EmbedderTestContextType> {};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_H_
| engine/shell/platform/embedder/tests/embedder_test.h/0 | {
"file_path": "engine/shell/platform/embedder/tests/embedder_test.h",
"repo_id": "engine",
"token_count": 430
} | 336 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_GL_H_
#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_GL_H_
#include "flutter/shell/platform/embedder/tests/embedder_test_context.h"
#include "flutter/testing/test_gl_surface.h"
namespace flutter {
namespace testing {
class EmbedderTestContextGL : public EmbedderTestContext {
public:
using GLGetFBOCallback = std::function<void(FlutterFrameInfo frame_info)>;
using GLPopulateExistingDamageCallback =
std::function<void(intptr_t id, FlutterDamage* existing_damage)>;
using GLPresentCallback =
std::function<void(FlutterPresentInfo present_info)>;
explicit EmbedderTestContextGL(std::string assets_path = "");
~EmbedderTestContextGL() override;
size_t GetSurfacePresentCount() const override;
// |EmbedderTestContext|
EmbedderTestContextType GetContextType() const override;
//----------------------------------------------------------------------------
/// @brief Sets a callback that will be invoked (on the raster task
/// runner) when the engine asks the embedder for a new FBO ID at
/// the updated size.
///
/// @attention The callback will be invoked on the raster task runner. The
/// callback can be set on the tests host thread.
///
/// @param[in] callback The callback to set. The previous callback will be
/// un-registered.
///
void SetGLGetFBOCallback(GLGetFBOCallback callback);
void SetGLPopulateExistingDamageCallback(
GLPopulateExistingDamageCallback callback);
uint32_t GetWindowFBOId() const;
//----------------------------------------------------------------------------
/// @brief Sets a callback that will be invoked (on the raster task
/// runner) when the engine presents an fbo that was given by the
/// embedder.
///
/// @attention The callback will be invoked on the raster task runner. The
/// callback can be set on the tests host thread.
///
/// @param[in] callback The callback to set. The previous callback will be
/// un-registered.
///
void SetGLPresentCallback(GLPresentCallback callback);
void GLPopulateExistingDamage(const intptr_t id,
FlutterDamage* existing_damage);
protected:
virtual void SetupCompositor() override;
private:
// This allows the builder to access the hooks.
friend class EmbedderConfigBuilder;
std::unique_ptr<TestGLSurface> gl_surface_;
size_t gl_surface_present_count_ = 0;
std::mutex gl_callback_mutex_;
GLGetFBOCallback gl_get_fbo_callback_;
GLPresentCallback gl_present_callback_;
GLPopulateExistingDamageCallback gl_populate_existing_damage_callback_;
void SetupSurface(SkISize surface_size) override;
bool GLMakeCurrent();
bool GLClearCurrent();
bool GLPresent(FlutterPresentInfo present_info);
uint32_t GLGetFramebuffer(FlutterFrameInfo frame_info);
bool GLMakeResourceCurrent();
void* GLGetProcAddress(const char* name);
FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestContextGL);
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_GL_H_
| engine/shell/platform/embedder/tests/embedder_test_context_gl.h/0 | {
"file_path": "engine/shell/platform/embedder/tests/embedder_test_context_gl.h",
"repo_id": "engine",
"token_count": 1159
} | 337 |
dart:fuchsia
===========
These are the Dart bindings for the Fuchsia application model.
| engine/shell/platform/fuchsia/dart-pkg/fuchsia/README.md/0 | {
"file_path": "engine/shell/platform/fuchsia/dart-pkg/fuchsia/README.md",
"repo_id": "engine",
"token_count": 25
} | 338 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
library zircon;
// uncomment the next line for local testing.
// import 'package:zircon_ffi/zircon_ffi.dart';
import 'dart:convert' show utf8;
import 'dart:ffi';
import 'dart:io';
import 'dart:nativewrappers';
import 'dart:typed_data';
import 'dart:zircon_ffi';
part 'src/handle.dart';
part 'src/handle_disposition.dart';
part 'src/handle_waiter.dart';
part 'src/init.dart';
part 'src/system.dart';
part 'src/zd_channel.dart';
part 'src/zd_handle.dart';
| engine/shell/platform/fuchsia/dart-pkg/zircon/lib/zircon.dart/0 | {
"file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon/lib/zircon.dart",
"repo_id": "engine",
"token_count": 232
} | 339 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_BASIC_TYPES_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_BASIC_TYPES_H_
#include "macros.h"
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct zircon_dart_byte_array_t {
uint8_t* data;
uint32_t length;
} zircon_dart_byte_array_t;
ZIRCON_FFI_EXPORT zircon_dart_byte_array_t* zircon_dart_byte_array_create(
uint32_t size);
ZIRCON_FFI_EXPORT void zircon_dart_byte_array_set_value(
zircon_dart_byte_array_t* arr,
uint32_t index,
uint8_t value);
ZIRCON_FFI_EXPORT void zircon_dart_byte_array_free(
zircon_dart_byte_array_t* arr);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_BASIC_TYPES_H_
| engine/shell/platform/fuchsia/dart-pkg/zircon_ffi/basic_types.h/0 | {
"file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon_ffi/basic_types.h",
"repo_id": "engine",
"token_count": 441
} | 340 |
# Dart Application Runner
Implements the `fuchsia::component::runner::ComponentRunner` FIDL interface to
launch and run Dart applications that don't use Flutter. | engine/shell/platform/fuchsia/dart_runner/README.md/0 | {
"file_path": "engine/shell/platform/fuchsia/dart_runner/README.md",
"repo_id": "engine",
"token_count": 40
} | 341 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//flutter/tools/fuchsia/gn-sdk/src/fidl_library.gni")
fidl_library("dart_test") {
library_name = "dart.test"
sources = [ "echo.fidl" ]
}
| engine/shell/platform/fuchsia/dart_runner/fidl/BUILD.gn/0 | {
"file_path": "engine/shell/platform/fuchsia/dart_runner/fidl/BUILD.gn",
"repo_id": "engine",
"token_count": 112
} | 342 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//flutter/tools/fuchsia/dart/dart_component.gni")
import("//flutter/tools/fuchsia/fuchsia_archive.gni")
import("//flutter/tools/fuchsia/gn-sdk/src/fidl_library.gni")
group("tests") {
testonly = true
deps = [ ":dart-aot-runner-integration-test" ]
}
executable("dart-aot-runner-integration-test-bin") {
testonly = true
output_name = "dart-aot-runner-integration-test"
sources = [ "dart-aot-runner-integration-test.cc" ]
# This is needed for //flutter/third_party/googletest for linking zircon
# symbols.
libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ]
deps = [
"${fuchsia_sdk}/fidl/fuchsia.logger",
"${fuchsia_sdk}/fidl/fuchsia.tracing.provider",
"${fuchsia_sdk}/pkg/async",
"${fuchsia_sdk}/pkg/async-loop-testing",
"${fuchsia_sdk}/pkg/fidl_cpp",
"${fuchsia_sdk}/pkg/sys_component_cpp_testing",
"${fuchsia_sdk}/pkg/zx",
"../dart_echo_server:aot_echo_package",
"//flutter/fml",
"//flutter/shell/platform/fuchsia/dart_runner/fidl:dart_test",
"//flutter/third_party/googletest:gtest",
"//flutter/third_party/googletest:gtest_main",
]
}
fuchsia_test_archive("dart-aot-runner-integration-test") {
deps = [ ":dart-aot-runner-integration-test-bin" ]
binary = "$target_name"
cml_file = rebase_path("meta/$target_name.cml")
}
| engine/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_aot_runner/BUILD.gn/0 | {
"file_path": "engine/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_aot_runner/BUILD.gn",
"repo_id": "engine",
"token_count": 638
} | 343 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This entry point is never invoked. Its purpose is to allow the vmservice's
// Dart code to built with dart_aot_app.
void main(List<String> args) {}
| engine/shell/platform/fuchsia/dart_runner/vmservice/empty.dart/0 | {
"file_path": "engine/shell/platform/fuchsia/dart_runner/vmservice/empty.dart",
"repo_id": "engine",
"token_count": 87
} | 344 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_ENGINE_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_ENGINE_H_
#include <optional>
#include <fuchsia/intl/cpp/fidl.h>
#include <fuchsia/io/cpp/fidl.h>
#include <fuchsia/memorypressure/cpp/fidl.h>
#include <fuchsia/ui/composition/cpp/fidl.h>
#include <fuchsia/ui/views/cpp/fidl.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/sys/cpp/service_directory.h>
#include "flutter/flow/embedded_views.h"
#include "flutter/flow/surface.h"
#include "flutter/fml/macros.h"
#include "flutter/shell/common/shell.h"
#include "flutter/shell/common/thread_host.h"
#include "flutter/shell/platform/fuchsia/flutter/accessibility_bridge.h"
#include "external_view_embedder.h"
#include "flatland_connection.h"
#include "flutter_runner_product_configuration.h"
#include "isolate_configurator.h"
#include "surface_producer.h"
namespace flutter_runner {
namespace testing {
class EngineTest;
}
// Represents an instance of running Flutter engine along with the threads
// that host the same.
class Engine final : public fuchsia::memorypressure::Watcher {
public:
class Delegate {
public:
virtual void OnEngineTerminate(const Engine* holder) = 0;
};
static flutter::ThreadHost CreateThreadHost(
const std::string& name_prefix,
const std::shared_ptr<sys::ServiceDirectory>& runner_services = nullptr);
Engine(Delegate& delegate,
std::string thread_label,
std::shared_ptr<sys::ServiceDirectory> svc,
std::shared_ptr<sys::ServiceDirectory> runner_services,
flutter::Settings settings,
fuchsia::ui::views::ViewCreationToken view_creation_token,
std::pair<fuchsia::ui::views::ViewRefControl,
fuchsia::ui::views::ViewRef> view_ref_pair,
UniqueFDIONS fdio_ns,
fidl::InterfaceRequest<fuchsia::io::Directory> directory_request,
FlutterRunnerProductConfiguration product_config,
const std::vector<std::string>& dart_entrypoint_args);
~Engine();
// Returns the Dart return code for the root isolate if one is present. This
// call is thread safe and synchronous. This call must be made infrequently.
std::optional<uint32_t> GetEngineReturnCode() const;
#if !defined(DART_PRODUCT)
void WriteProfileToTrace() const;
#endif // !defined(DART_PRODUCT)
private:
void Initialize(
std::pair<fuchsia::ui::views::ViewRefControl, fuchsia::ui::views::ViewRef>
view_ref_pair,
std::shared_ptr<sys::ServiceDirectory> svc,
std::shared_ptr<sys::ServiceDirectory> runner_services,
flutter::Settings settings,
UniqueFDIONS fdio_ns,
fidl::InterfaceRequest<fuchsia::io::Directory> directory_request,
FlutterRunnerProductConfiguration product_config,
const std::vector<std::string>& dart_entrypoint_args);
static void WarmupSkps(
fml::BasicTaskRunner* concurrent_task_runner,
fml::BasicTaskRunner* raster_task_runner,
std::shared_ptr<SurfaceProducer> surface_producer,
SkISize size,
std::shared_ptr<flutter::AssetManager> asset_manager,
std::optional<const std::vector<std::string>> skp_names,
std::optional<std::function<void(uint32_t)>> completion_callback,
bool synchronous = false);
void OnMainIsolateStart();
void OnMainIsolateShutdown();
void Terminate();
void DebugWireframeSettingsChanged(bool enabled);
void CreateView(int64_t view_id,
ViewCallback on_view_created,
ViewCreatedCallback on_view_bound,
bool hit_testable,
bool focusable);
void UpdateView(int64_t view_id,
SkRect occlusion_hint,
bool hit_testable,
bool focusable);
void DestroyView(int64_t view_id, ViewIdCallback on_view_unbound);
// |fuchsia::memorypressure::Watcher|
void OnLevelChanged(fuchsia::memorypressure::Level level,
fuchsia::memorypressure::Watcher::OnLevelChangedCallback
callback) override;
std::shared_ptr<flutter::ExternalViewEmbedder> GetExternalViewEmbedder();
std::unique_ptr<flutter::Surface> CreateSurface();
Delegate& delegate_;
const std::string thread_label_;
flutter::ThreadHost thread_host_;
fuchsia::ui::views::ViewCreationToken view_creation_token_;
std::shared_ptr<FlatlandConnection>
flatland_connection_; // Must come before surface_producer_
std::shared_ptr<SurfaceProducer> surface_producer_;
std::shared_ptr<ExternalViewEmbedder> view_embedder_;
std::unique_ptr<IsolateConfigurator> isolate_configurator_;
std::unique_ptr<flutter::Shell> shell_;
std::unique_ptr<AccessibilityBridge> accessibility_bridge_;
fuchsia::intl::PropertyProviderPtr intl_property_provider_;
fuchsia::memorypressure::ProviderPtr memory_pressure_provider_;
fidl::Binding<fuchsia::memorypressure::Watcher>
memory_pressure_watcher_binding_;
// We need to track the latest memory pressure level to determine
// the direction of change when a new level is provided.
fuchsia::memorypressure::Level latest_memory_pressure_level_;
bool intercept_all_input_ = false;
fml::WeakPtrFactory<Engine> weak_factory_;
friend class testing::EngineTest;
FML_DISALLOW_COPY_AND_ASSIGN(Engine);
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_ENGINE_H_
| engine/shell/platform/fuchsia/flutter/engine.h/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/engine.h",
"repo_id": "engine",
"token_count": 2070
} | 345 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "isolate_configurator.h"
#include "dart-pkg/fuchsia/sdk_ext/fuchsia.h"
#include "dart-pkg/zircon/sdk_ext/handle.h"
#include "third_party/dart/runtime/include/dart_api.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_state.h"
#include "third_party/tonic/logging/dart_error.h"
namespace flutter_runner {
IsolateConfigurator::IsolateConfigurator(UniqueFDIONS fdio_ns,
zx::channel directory_request,
zx::eventpair view_ref)
: fdio_ns_(std::move(fdio_ns)),
directory_request_(std::move(directory_request)),
view_ref_(std::move(view_ref)) {}
IsolateConfigurator::~IsolateConfigurator() = default;
bool IsolateConfigurator::ConfigureCurrentIsolate() {
if (used_) {
return false;
}
used_ = true;
BindFuchsia();
BindZircon();
BindDartIO();
// This is now owned by the Dart bindings. So relinquish our ownership of the
// handle.
(void)fdio_ns_.release();
return true;
}
void IsolateConfigurator::BindFuchsia() {
fuchsia::dart::Initialize(std::move(directory_request_),
std::move(view_ref_));
}
void IsolateConfigurator::BindZircon() {
// Tell dart:zircon about the FDIO namespace configured for this instance.
Dart_Handle zircon_lib = Dart_LookupLibrary(tonic::ToDart("dart:zircon"));
FML_CHECK(!tonic::CheckAndHandleError(zircon_lib));
Dart_Handle namespace_type = Dart_GetNonNullableType(
zircon_lib, tonic::ToDart("_Namespace"), 0, nullptr);
FML_CHECK(!tonic::CheckAndHandleError(namespace_type));
Dart_Handle result =
Dart_SetField(namespace_type, //
tonic::ToDart("_namespace"), //
tonic::ToDart(reinterpret_cast<intptr_t>(fdio_ns_.get())));
FML_CHECK(!tonic::CheckAndHandleError(result));
}
void IsolateConfigurator::BindDartIO() {
// Grab the dart:io lib.
Dart_Handle io_lib = Dart_LookupLibrary(tonic::ToDart("dart:io"));
FML_CHECK(!tonic::CheckAndHandleError(io_lib));
// Disable dart:io exit()
Dart_Handle embedder_config_type = Dart_GetNonNullableType(
io_lib, tonic::ToDart("_EmbedderConfig"), 0, nullptr);
FML_CHECK(!tonic::CheckAndHandleError(embedder_config_type));
Dart_Handle result = Dart_SetField(embedder_config_type,
tonic::ToDart("_mayExit"), Dart_False());
FML_CHECK(!tonic::CheckAndHandleError(result));
// Tell dart:io about the FDIO namespace configured for this instance.
Dart_Handle namespace_type =
Dart_GetNonNullableType(io_lib, tonic::ToDart("_Namespace"), 0, nullptr);
FML_CHECK(!tonic::CheckAndHandleError(namespace_type));
Dart_Handle namespace_args[] = {
Dart_NewInteger(reinterpret_cast<intptr_t>(fdio_ns_.get())), //
};
result = Dart_Invoke(namespace_type, tonic::ToDart("_setupNamespace"), 1,
namespace_args);
FML_CHECK(!tonic::CheckAndHandleError(result));
}
} // namespace flutter_runner
| engine/shell/platform/fuchsia/flutter/isolate_configurator.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/isolate_configurator.cc",
"repo_id": "engine",
"token_count": 1309
} | 346 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_RUNNER_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_RUNNER_H_
#include <memory>
#include <unordered_map>
#include <fuchsia/component/runner/cpp/fidl.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/sys/cpp/component_context.h>
#include <lib/trace-engine/instrumentation.h>
#include <lib/trace/observer.h>
#include "component_v2.h"
#include "flutter/fml/macros.h"
#include "fml/memory/ref_ptr.h"
#include "fml/task_runner.h"
#include "lib/fidl/cpp/binding_set.h"
#include "runtime/dart/utils/vmservice_object.h"
namespace flutter_runner {
/// Publishes the CF v2 runner service.
///
/// Each component will be run on a separate thread dedicated to that component.
///
/// TODO(fxb/50694): Add unit tests for CF v2.
class Runner final
: public fuchsia::component::runner::ComponentRunner /* CF v2 */ {
public:
// Does not take ownership of context.
Runner(fml::RefPtr<fml::TaskRunner> task_runner,
sys::ComponentContext* context);
~Runner();
private:
// CF v2 lifecycle methods.
// |fuchsia::component::runner::ComponentRunner|
void Start(
fuchsia::component::runner::ComponentStartInfo start_info,
fidl::InterfaceRequest<fuchsia::component::runner::ComponentController>
controller) override;
/// Registers a new CF v2 component with this runner, binding the component
/// to this runner.
void RegisterComponentV2(
fidl::InterfaceRequest<fuchsia::component::runner::ComponentRunner>
request);
/// Callback that should be fired when a registered CF v2 component is
/// terminated.
void OnComponentV2Terminate(const ComponentV2* component);
void SetupICU();
#if !defined(DART_PRODUCT)
void SetupTraceObserver();
#endif // !defined(DART_PRODUCT)
// Called from SetupICU, for testing only. Returns false on error.
static bool SetupICUInternal();
// Called from SetupICU, for testing only. Returns false on error.
static bool SetupTZDataInternal();
#if defined(FRIEND_TEST)
FRIEND_TEST(RunnerTZDataTest, LoadsWithTZDataPresent);
FRIEND_TEST(RunnerTZDataTest, LoadsWithoutTZDataPresent);
#endif // defined(FRIEND_TEST)
fml::RefPtr<fml::TaskRunner> task_runner_;
sys::ComponentContext* context_;
// CF v2 component state.
/// The components that are currently bound to this runner.
fidl::BindingSet<fuchsia::component::runner::ComponentRunner>
active_components_v2_bindings_;
/// The components that are currently actively running on threads.
std::unordered_map<const ComponentV2*, ActiveComponentV2>
active_components_v2_;
#if !defined(DART_PRODUCT)
// The connection between the Dart VM service and The Hub.
std::unique_ptr<dart_utils::VMServiceObject> vmservice_object_;
std::unique_ptr<trace::TraceObserver> trace_observer_;
trace_prolonged_context_t* prolonged_context_;
#endif // !defined(DART_PRODUCT)
FML_DISALLOW_COPY_AND_ASSIGN(Runner);
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_RUNNER_H_
| engine/shell/platform/fuchsia/flutter/runner.h/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/runner.h",
"repo_id": "engine",
"token_count": 1101
} | 347 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_FOCUSER_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_FOCUSER_H_
#include <fuchsia/ui/views/cpp/fidl.h>
#include <fuchsia/ui/views/cpp/fidl_test_base.h>
#include <string>
#include "flutter/fml/logging.h"
using Focuser = fuchsia::ui::views::Focuser;
namespace flutter_runner::testing {
class FakeFocuser : public fuchsia::ui::views::testing::Focuser_TestBase {
public:
bool request_focus_called() const { return request_focus_called_; }
void fail_request_focus(bool fail_request = true) {
fail_request_focus_ = fail_request;
}
private:
void RequestFocus(fuchsia::ui::views::ViewRef view_ref,
RequestFocusCallback callback) override {
request_focus_called_ = true;
auto result =
fail_request_focus_
? fuchsia::ui::views::Focuser_RequestFocus_Result::WithErr(
fuchsia::ui::views::Error::DENIED)
: fuchsia::ui::views::Focuser_RequestFocus_Result::WithResponse(
fuchsia::ui::views::Focuser_RequestFocus_Response());
callback(std::move(result));
}
void NotImplemented_(const std::string& name) {
FML_LOG(FATAL) << "flutter_runner::Testing::FakeFocuser does not implement "
<< name;
}
bool request_focus_called_ = false;
bool fail_request_focus_ = false;
};
} // namespace flutter_runner::testing
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_FOCUSER_H_
| engine/shell/platform/fuchsia/flutter/tests/fakes/focuser.h/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/fakes/focuser.h",
"repo_id": "engine",
"token_count": 679
} | 348 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//flutter/tools/fuchsia/dart/dart_library.gni")
import("//flutter/tools/fuchsia/flutter/flutter_component.gni")
import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni")
import("//flutter/tools/fuchsia/gn-sdk/src/package.gni")
dart_library("lib") {
package_name = "child-view"
sources = [ "child_view.dart" ]
}
flutter_component("component") {
main_package = "child-view"
component_name = "child-view"
main_dart = "child_view.dart"
manifest = rebase_path("meta/child-view.cml")
deps = [ ":lib" ]
}
fuchsia_package("package") {
package_name = "child-view"
deps = [ ":component" ]
}
| engine/shell/platform/fuchsia/flutter/tests/integration/embedder/child-view/BUILD.gn/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/embedder/child-view/BUILD.gn",
"repo_id": "engine",
"token_count": 293
} | 349 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <fuchsia/accessibility/semantics/cpp/fidl.h>
#include <fuchsia/buildinfo/cpp/fidl.h>
#include <fuchsia/component/cpp/fidl.h>
#include <fuchsia/fonts/cpp/fidl.h>
#include <fuchsia/intl/cpp/fidl.h>
#include <fuchsia/kernel/cpp/fidl.h>
#include <fuchsia/memorypressure/cpp/fidl.h>
#include <fuchsia/metrics/cpp/fidl.h>
#include <fuchsia/net/interfaces/cpp/fidl.h>
#include <fuchsia/sysmem/cpp/fidl.h>
#include <fuchsia/tracing/provider/cpp/fidl.h>
#include <fuchsia/ui/app/cpp/fidl.h>
#include <fuchsia/ui/display/singleton/cpp/fidl.h>
#include <fuchsia/ui/input/cpp/fidl.h>
#include <fuchsia/ui/test/input/cpp/fidl.h>
#include <fuchsia/ui/test/scene/cpp/fidl.h>
#include <fuchsia/web/cpp/fidl.h>
#include <lib/async-loop/testing/cpp/real_loop.h>
#include <lib/async/cpp/task.h>
#include <lib/fidl/cpp/binding_set.h>
#include <lib/sys/component/cpp/testing/realm_builder.h>
#include <lib/sys/component/cpp/testing/realm_builder_types.h>
#include <lib/sys/cpp/component_context.h>
#include <lib/zx/clock.h>
#include <lib/zx/time.h>
#include <zircon/status.h>
#include <zircon/types.h>
#include <zircon/utc.h>
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <memory>
#include <type_traits>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include "flutter/fml/logging.h"
#include "flutter/shell/platform/fuchsia/flutter/tests/integration/utils/portable_ui_test.h"
// This test exercises the touch input dispatch path from Input Pipeline to a
// Scenic client. It is a multi-component test, and carefully avoids sleeping or
// polling for component coordination.
// - It runs real Scene Manager and Scenic components.
// - It uses a fake display controller; the physical device is unused.
//
// Components involved
// - This test program
// - Scene Manager
// - Scenic
// - Child view, a Scenic client
//
// Touch dispatch path
// - Test program's injection -> Input Pipeline -> Scenic -> Child view
//
// Setup sequence
// - The test sets up this view hierarchy:
// - Top level scene, owned by Scene Manager.
// - Child view, owned by the ui client.
// - The test waits for a Scenic event that verifies the child has UI content in
// the scene graph.
// - The test injects input into Input Pipeline, emulating a display's touch
// report.
// - Input Pipeline dispatches the touch event to Scenic, which in turn
// dispatches it to the child.
// - The child receives the touch event and reports back to the test over a
// custom test-only FIDL.
// - Test waits for the child to report a touch; when the test receives the
// report, the test quits
// successfully.
//
// This test uses the realm_builder library to construct the topology of
// components and routes services between them. For v2 components, every test
// driver component sits as a child of test_manager in the topology. Thus, the
// topology of a test driver component such as this one looks like this:
//
// test_manager
// |
// touch-input-test.cml (this component)
//
// With the usage of the realm_builder library, we construct a realm during
// runtime and then extend the topology to look like:
//
// test_manager
// |
// touch-input-test.cml (this component)
// |
// <created realm root>
// / \
// scenic input-pipeline
//
// For more information about testing v2 components and realm_builder,
// visit the following links:
//
// Testing: https://fuchsia.dev/fuchsia-src/concepts/testing/v2
// Realm Builder:
// https://fuchsia.dev/fuchsia-src/development/components/v2/realm_builder
namespace touch_input_test::testing {
namespace {
// Types imported for the realm_builder library.
using component_testing::ChildRef;
using component_testing::ConfigValue;
using component_testing::DirectoryContents;
using component_testing::LocalComponentImpl;
using component_testing::ParentRef;
using component_testing::Protocol;
using component_testing::Realm;
using component_testing::RealmRoot;
using component_testing::Route;
using fuchsia_test_utils::PortableUITest;
using RealmBuilder = component_testing::RealmBuilder;
// Max timeout in failure cases.
// Set this as low as you can that still works across all test platforms.
constexpr zx::duration kTimeout = zx::min(1);
constexpr auto kTestUIStackUrl =
"fuchsia-pkg://fuchsia.com/flatland-scene-manager-test-ui-stack#meta/"
"test-ui-stack.cm";
constexpr auto kMockTouchInputListener = "touch_input_listener";
constexpr auto kMockTouchInputListenerRef = ChildRef{kMockTouchInputListener};
constexpr auto kTouchInputView = "touch-input-view";
constexpr auto kTouchInputViewRef = ChildRef{kTouchInputView};
constexpr auto kTouchInputViewUrl =
"fuchsia-pkg://fuchsia.com/touch-input-view#meta/touch-input-view.cm";
constexpr auto kEmbeddingFlutterView = "embedding-flutter-view";
constexpr auto kEmbeddingFlutterViewRef = ChildRef{kEmbeddingFlutterView};
constexpr auto kEmbeddingFlutterViewUrl =
"fuchsia-pkg://fuchsia.com/embedding-flutter-view#meta/"
"embedding-flutter-view.cm";
bool CompareDouble(double f0, double f1, double epsilon) {
return std::abs(f0 - f1) <= epsilon;
}
// This component implements the TouchInput protocol
// and the interface for a RealmBuilder LocalComponentImpl. A LocalComponentImpl
// is a component that is implemented here in the test, as opposed to
// elsewhere in the system. When it's inserted to the realm, it will act
// like a proper component. This is accomplished, in part, because the
// realm_builder library creates the necessary plumbing. It creates a manifest
// for the component and routes all capabilities to and from it.
// LocalComponentImpl:
// https://fuchsia.dev/fuchsia-src/development/testing/components/realm_builder#mock-components
class TouchInputListenerServer
: public fuchsia::ui::test::input::TouchInputListener,
public LocalComponentImpl {
public:
explicit TouchInputListenerServer(async_dispatcher_t* dispatcher)
: dispatcher_(dispatcher) {}
// |fuchsia::ui::test::input::TouchInputListener|
void ReportTouchInput(
fuchsia::ui::test::input::TouchInputListenerReportTouchInputRequest
request) override {
FML_LOG(INFO) << "Received ReportTouchInput event";
events_received_.push_back(std::move(request));
}
// |LocalComponentImpl::OnStart|
// When the component framework requests for this component to start, this
// method will be invoked by the realm_builder library.
void OnStart() override {
FML_LOG(INFO) << "Starting TouchInputListenerServer";
// When this component starts, add a binding to the
// protocol to this component's outgoing directory.
ASSERT_EQ(ZX_OK, outgoing()->AddPublicService(
fidl::InterfaceRequestHandler<
fuchsia::ui::test::input::TouchInputListener>(
[this](auto request) {
bindings_.AddBinding(this, std::move(request),
dispatcher_);
})));
}
const std::vector<
fuchsia::ui::test::input::TouchInputListenerReportTouchInputRequest>&
events_received() {
return events_received_;
}
private:
async_dispatcher_t* dispatcher_ = nullptr;
fidl::BindingSet<fuchsia::ui::test::input::TouchInputListener> bindings_;
std::vector<
fuchsia::ui::test::input::TouchInputListenerReportTouchInputRequest>
events_received_;
};
class FlutterTapTestBase : public PortableUITest, public ::testing::Test {
protected:
~FlutterTapTestBase() override {
FML_CHECK(touch_injection_request_count() > 0)
<< "Injection expected but didn't happen.";
}
void SetUp() override {
PortableUITest::SetUp();
// Post a "just in case" quit task, if the test hangs.
async::PostDelayedTask(
dispatcher(),
[] {
FML_LOG(FATAL)
<< "\n\n>> Test did not complete in time, terminating. <<\n\n";
},
kTimeout);
// Get the display information using the
// |fuchsia.ui.display.singleton.Info|.
FML_LOG(INFO)
<< "Waiting for display info from fuchsia.ui.display.singleton.Info";
std::optional<bool> display_metrics_obtained;
fuchsia::ui::display::singleton::InfoPtr display_info =
realm_root()
->component()
.Connect<fuchsia::ui::display::singleton::Info>();
display_info->GetMetrics([this, &display_metrics_obtained](auto info) {
display_width_ = info.extent_in_px().width;
display_height_ = info.extent_in_px().height;
display_metrics_obtained = true;
});
RunLoopUntil([&display_metrics_obtained] {
return display_metrics_obtained.has_value();
});
// Register input injection device.
FML_LOG(INFO) << "Registering input injection device";
RegisterTouchScreen();
}
bool LastEventReceivedMatches(float expected_x,
float expected_y,
std::string component_name) {
const auto& events_received =
touch_input_listener_server_->events_received();
if (events_received.empty()) {
return false;
}
const auto& last_event = events_received.back();
auto pixel_scale = last_event.has_device_pixel_ratio()
? last_event.device_pixel_ratio()
: 1;
auto actual_x = pixel_scale * last_event.local_x();
auto actual_y = pixel_scale * last_event.local_y();
auto actual_component = last_event.component_name();
bool last_event_matches =
CompareDouble(actual_x, expected_x, pixel_scale) &&
CompareDouble(actual_y, expected_y, pixel_scale) &&
last_event.component_name() == component_name;
if (last_event_matches) {
FML_LOG(INFO) << "Received event for component " << component_name
<< " at (" << expected_x << ", " << expected_y << ")";
} else {
FML_LOG(WARNING) << "Expecting event for component " << component_name
<< " at (" << expected_x << ", " << expected_y << "). "
<< "Instead received event for component "
<< actual_component << " at (" << actual_x << ", "
<< actual_y << "), accounting for pixel scale of "
<< pixel_scale;
}
return last_event_matches;
}
// Guaranteed to be initialized after SetUp().
uint32_t display_width() const { return display_width_; }
uint32_t display_height() const { return display_height_; }
std::string GetTestUIStackUrl() override { return kTestUIStackUrl; };
TouchInputListenerServer* touch_input_listener_server_;
};
class FlutterTapTest : public FlutterTapTestBase {
private:
void ExtendRealm() override {
FML_LOG(INFO) << "Extending realm";
// Key part of service setup: have this test component vend the
// |TouchInputListener| service in the constructed realm.
auto touch_input_listener_server =
std::make_unique<TouchInputListenerServer>(dispatcher());
touch_input_listener_server_ = touch_input_listener_server.get();
realm_builder()->AddLocalChild(
kMockTouchInputListener, [touch_input_listener_server = std::move(
touch_input_listener_server)]() mutable {
return std::move(touch_input_listener_server);
});
// Add touch-input-view to the Realm
realm_builder()->AddChild(kTouchInputView, kTouchInputViewUrl,
component_testing::ChildOptions{
.environment = kFlutterRunnerEnvironment,
});
// Route the TouchInput protocol capability to the Dart component
realm_builder()->AddRoute(
Route{.capabilities = {Protocol{
fuchsia::ui::test::input::TouchInputListener::Name_}},
.source = kMockTouchInputListenerRef,
.targets = {kFlutterJitRunnerRef, kTouchInputViewRef}});
realm_builder()->AddRoute(
Route{.capabilities = {Protocol{fuchsia::ui::app::ViewProvider::Name_}},
.source = kTouchInputViewRef,
.targets = {ParentRef()}});
}
};
class FlutterEmbedTapTest : public FlutterTapTestBase {
protected:
void SetUp() override {
PortableUITest::SetUp(false);
// Post a "just in case" quit task, if the test hangs.
async::PostDelayedTask(
dispatcher(),
[] {
FML_LOG(FATAL)
<< "\n\n>> Test did not complete in time, terminating. <<\n\n";
},
kTimeout);
}
void LaunchClientWithEmbeddedView() {
BuildRealm();
// Get the display information using the
// |fuchsia.ui.display.singleton.Info|.
FML_LOG(INFO)
<< "Waiting for display info from fuchsia.ui.display.singleton.Info";
std::optional<bool> display_metrics_obtained;
fuchsia::ui::display::singleton::InfoPtr display_info =
realm_root()
->component()
.Connect<fuchsia::ui::display::singleton::Info>();
display_info->GetMetrics([this, &display_metrics_obtained](auto info) {
display_width_ = info.extent_in_px().width;
display_height_ = info.extent_in_px().height;
display_metrics_obtained = true;
});
RunLoopUntil([&display_metrics_obtained] {
return display_metrics_obtained.has_value();
});
// Register input injection device.
FML_LOG(INFO) << "Registering input injection device";
RegisterTouchScreen();
PortableUITest::LaunchClientWithEmbeddedView();
}
// Helper method to add a component argument
// This will be written into an args.csv file that can be parsed and read
// by embedding-flutter-view.dart
//
// Note: You must call this method before LaunchClientWithEmbeddedView()
// Realm Builder will not allow you to create a new directory / file in a
// realm that's already been built
void AddComponentArgument(std::string component_arg) {
auto config_directory_contents = DirectoryContents();
config_directory_contents.AddFile("args.csv", component_arg);
realm_builder()->RouteReadOnlyDirectory(
"config-data", {kEmbeddingFlutterViewRef},
std::move(config_directory_contents));
}
private:
void ExtendRealm() override {
FML_LOG(INFO) << "Extending realm";
// Key part of service setup: have this test component vend the
// |TouchInputListener| service in the constructed realm.
auto touch_input_listener_server =
std::make_unique<TouchInputListenerServer>(dispatcher());
touch_input_listener_server_ = touch_input_listener_server.get();
realm_builder()->AddLocalChild(
kMockTouchInputListener, [touch_input_listener_server = std::move(
touch_input_listener_server)]() mutable {
return std::move(touch_input_listener_server);
});
// Add touch-input-view to the Realm
realm_builder()->AddChild(kTouchInputView, kTouchInputViewUrl,
component_testing::ChildOptions{
.environment = kFlutterRunnerEnvironment,
});
// Add embedding-flutter-view to the Realm
// This component will embed touch-input-view as a child view
realm_builder()->AddChild(kEmbeddingFlutterView, kEmbeddingFlutterViewUrl,
component_testing::ChildOptions{
.environment = kFlutterRunnerEnvironment,
});
// Route the TouchInput protocol capability to the Dart component
realm_builder()->AddRoute(
Route{.capabilities = {Protocol{
fuchsia::ui::test::input::TouchInputListener::Name_}},
.source = kMockTouchInputListenerRef,
.targets = {kFlutterJitRunnerRef, kTouchInputViewRef,
kEmbeddingFlutterViewRef}});
realm_builder()->AddRoute(
Route{.capabilities = {Protocol{fuchsia::ui::app::ViewProvider::Name_}},
.source = kEmbeddingFlutterViewRef,
.targets = {ParentRef()}});
realm_builder()->AddRoute(
Route{.capabilities = {Protocol{fuchsia::ui::app::ViewProvider::Name_}},
.source = kTouchInputViewRef,
.targets = {kEmbeddingFlutterViewRef}});
}
};
TEST_F(FlutterTapTest, FlutterTap) {
// Launch client view, and wait until it's rendering to proceed with the test.
FML_LOG(INFO) << "Initializing scene";
LaunchClient();
FML_LOG(INFO) << "Client launched";
// touch-input-view logical coordinate space doesn't match the fake touch
// screen injector's coordinate space, which spans [-1000, 1000] on both axes.
// Scenic handles figuring out where in the coordinate space
// to inject a touch event (this is fixed to a display's bounds).
InjectTap(-500, -500);
// For a (-500 [x], -500 [y]) tap, we expect a touch event in the middle of
// the upper-left quadrant of the screen.
RunLoopUntil([this] {
return LastEventReceivedMatches(
/*expected_x=*/static_cast<float>(display_width() / 4.0f),
/*expected_y=*/static_cast<float>(display_height() / 4.0f),
/*component_name=*/"touch-input-view");
});
// There should be 1 injected tap
ASSERT_EQ(touch_injection_request_count(), 1);
}
TEST_F(FlutterEmbedTapTest, FlutterEmbedTap) {
// Launch view
FML_LOG(INFO) << "Initializing scene";
LaunchClientWithEmbeddedView();
FML_LOG(INFO) << "Client launched";
{
// Embedded child view takes up the center of the screen
// Expect a response from the child view if we inject a tap there
InjectTap(0, 0);
RunLoopUntil([this] {
return LastEventReceivedMatches(
/*expected_x=*/static_cast<float>(display_width() / 8.0f),
/*expected_y=*/static_cast<float>(display_height() / 8.0f),
/*component_name=*/"touch-input-view");
});
}
{
// Parent view takes up the rest of the screen
// Validate that parent can still receive taps
InjectTap(500, 500);
RunLoopUntil([this] {
return LastEventReceivedMatches(
/*expected_x=*/static_cast<float>(display_width() / (4.0f / 3.0f)),
/*expected_y=*/static_cast<float>(display_height() / (4.0f / 3.0f)),
/*component_name=*/"embedding-flutter-view");
});
}
// There should be 2 injected taps
ASSERT_EQ(touch_injection_request_count(), 2);
}
TEST_F(FlutterEmbedTapTest, FlutterEmbedOverlayEnabled) {
FML_LOG(INFO) << "Initializing scene";
AddComponentArgument("--showOverlay");
LaunchClientWithEmbeddedView();
FML_LOG(INFO) << "Client launched";
{
// The bottom-left corner of the overlay is at the center of the screen
// Expect the overlay / parent view to respond if we inject a tap there
// and not the embedded child view
InjectTap(0, 0);
RunLoopUntil([this] {
return LastEventReceivedMatches(
/*expected_x=*/static_cast<float>(display_width() / 2.0f),
/*expected_y=*/static_cast<float>(display_height() / 2.0f),
/*component_name=*/"embedding-flutter-view");
});
}
{
// The embedded child view is just outside of the bottom-left corner of the
// overlay
// Expect the embedded child view to still receive taps
InjectTap(-1, -1);
RunLoopUntil([this] {
return LastEventReceivedMatches(
/*expected_x=*/static_cast<float>(display_width() / 8.0f),
/*expected_y=*/static_cast<float>(display_height() / 8.0f),
/*component_name=*/"touch-input-view");
});
}
// There should be 2 injected taps
ASSERT_EQ(touch_injection_request_count(), 2);
}
} // namespace
} // namespace touch_input_test::testing
| engine/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-test.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-test.cc",
"repo_id": "engine",
"token_count": 7544
} | 350 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.