Allow Hybrid Composition fallback for Android platform views (flutter/engine#35233)

This commit is contained in:
stuartmorgan
2022-09-12 12:23:49 -04:00
committed by GitHub
parent 218fb443b9
commit 3eb6e7f4c3
9 changed files with 418 additions and 213 deletions

View File

@@ -100,10 +100,20 @@ public class PlatformViewsChannel {
0,
0,
(int) createArgs.get("direction"),
PlatformViewCreationRequest.RequestedDisplayMode.HYBRID_ONLY,
additionalParams);
handler.createForPlatformViewLayer(request);
result.success(null);
} else {
final boolean hybridFallback =
createArgs.containsKey("hybridFallback")
&& (boolean) createArgs.get("hybridFallback");
final PlatformViewCreationRequest.RequestedDisplayMode displayMode =
hybridFallback
? PlatformViewCreationRequest.RequestedDisplayMode
.TEXTURE_WITH_HYBRID_FALLBACK
: PlatformViewCreationRequest.RequestedDisplayMode
.TEXTURE_WITH_VIRTUAL_FALLBACK;
final PlatformViewCreationRequest request =
new PlatformViewCreationRequest(
(int) createArgs.get("id"),
@@ -113,9 +123,19 @@ public class PlatformViewsChannel {
(double) createArgs.get("width"),
(double) createArgs.get("height"),
(int) createArgs.get("direction"),
displayMode,
additionalParams);
long textureId = handler.createForTextureLayer(request);
result.success(textureId);
if (textureId == PlatformViewsHandler.NON_TEXTURE_FALLBACK) {
if (!hybridFallback) {
throw new AssertionError(
"Platform view attempted to fall back to hybrid mode when not requested.");
}
// A fallback to hybrid mode is indicated with a null texture ID.
result.success(null);
} else {
result.success(textureId);
}
}
} catch (IllegalStateException exception) {
result.error("error", detailedExceptionString(exception), null);
@@ -266,6 +286,15 @@ public class PlatformViewsChannel {
* PlatformViewsChannel#setPlatformViewsHandler(PlatformViewsHandler)}.
*/
public interface PlatformViewsHandler {
/*
* The ID returned by {@code createForTextureLayer} to indicate that the requested texture mode
* was not available and the view creation fell back to {@code PlatformViewLayer} mode.
*
* This can only be returned if the {@link PlatformViewCreationRequest} sets
* {@code TEXTURE_WITH_HYBRID_FALLBACK} as the requested display mode.
*/
static final long NON_TEXTURE_FALLBACK = -2;
/**
* The Flutter application would like to display a new Android {@code View}, i.e., platform
* view.
@@ -336,6 +365,16 @@ public class PlatformViewsChannel {
/** Request sent from Flutter to create a new platform view. */
public static class PlatformViewCreationRequest {
/** Platform view display modes that can be requested at creation time. */
public enum RequestedDisplayMode {
/** Use Texture Layer if possible, falling back to Virtual Display if not. */
TEXTURE_WITH_VIRTUAL_FALLBACK,
/** Use Texture Layer if possible, falling back to Hybrid Composition if not. */
TEXTURE_WITH_HYBRID_FALLBACK,
/** Use Hybrid Composition in all cases. */
HYBRID_ONLY,
}
/** The ID of the platform view as seen by the Flutter side. */
public final int viewId;
@@ -362,6 +401,8 @@ public class PlatformViewsChannel {
*/
public final int direction;
public final RequestedDisplayMode displayMode;
/** Custom parameters that are unique to the desired platform view. */
@Nullable public final ByteBuffer params;
@@ -375,6 +416,29 @@ public class PlatformViewsChannel {
double logicalHeight,
int direction,
@Nullable ByteBuffer params) {
this(
viewId,
viewType,
logicalTop,
logicalLeft,
logicalWidth,
logicalHeight,
direction,
RequestedDisplayMode.TEXTURE_WITH_VIRTUAL_FALLBACK,
params);
}
/** Creates a request to construct a platform view with the given display mode. */
public PlatformViewCreationRequest(
int viewId,
@NonNull String viewType,
double logicalTop,
double logicalLeft,
double logicalWidth,
double logicalHeight,
int direction,
RequestedDisplayMode displayMode,
@Nullable ByteBuffer params) {
this.viewId = viewId;
this.viewType = viewType;
this.logicalTop = logicalTop;
@@ -382,6 +446,7 @@ public class PlatformViewsChannel {
this.logicalWidth = logicalWidth;
this.logicalHeight = logicalHeight;
this.direction = direction;
this.displayMode = displayMode;
this.params = params;
}
}

View File

@@ -159,51 +159,25 @@ public class PlatformViewsController implements PlatformViewsAccessibilityDelega
@NonNull PlatformViewsChannel.PlatformViewCreationRequest request) {
// API level 19 is required for `android.graphics.ImageReader`.
ensureValidAndroidVersion(19);
ensureValidRequest(request);
final int viewId = request.viewId;
if (!validateDirection(request.direction)) {
throw new IllegalStateException(
"Trying to create a view with unknown direction value: "
+ request.direction
+ "(view id: "
+ viewId
+ ")");
}
final PlatformView platformView = createPlatformView(request);
final PlatformViewFactory factory = registry.getFactory(request.viewType);
if (factory == null) {
throw new IllegalStateException(
"Trying to create a platform view of unregistered type: " + request.viewType);
}
Object createParams = null;
if (request.params != null) {
createParams = factory.getCreateArgsCodec().decodeMessage(request.params);
}
final PlatformView platformView = factory.create(context, viewId, createParams);
platformView.getView().setLayoutDirection(request.direction);
platformViews.put(viewId, platformView);
Log.i(TAG, "Using hybrid composition for platform view: " + viewId);
configureForHybridComposition(platformView, request);
// New code should be added to configureForHybridComposition, not here, unless it is
// not applicable to fallback from TLHC to HC.
}
@TargetApi(20)
@Override
public long createForTextureLayer(
@NonNull PlatformViewsChannel.PlatformViewCreationRequest request) {
ensureValidRequest(request);
final int viewId = request.viewId;
if (viewWrappers.get(viewId) != null) {
throw new IllegalStateException(
"Trying to create an already created platform view, view id: " + viewId);
}
if (!validateDirection(request.direction)) {
throw new IllegalStateException(
"Trying to create a view with unknown direction value: "
+ request.direction
+ "(view id: "
+ viewId
+ ")");
}
if (textureRegistry == null) {
throw new IllegalStateException(
"Texture registry is null. This means that platform views controller was detached, view id: "
@@ -214,153 +188,42 @@ public class PlatformViewsController implements PlatformViewsAccessibilityDelega
"Flutter view is null. This means the platform views controller doesn't have an attached view, view id: "
+ viewId);
}
final PlatformViewFactory viewFactory = registry.getFactory(request.viewType);
if (viewFactory == null) {
throw new IllegalStateException(
"Trying to create a platform view of unregistered type: " + request.viewType);
}
Object createParams = null;
if (request.params != null) {
createParams = viewFactory.getCreateArgsCodec().decodeMessage(request.params);
}
// The virtual display controller will change the embedded view context.
final Context embeddedViewContext = new MutableContextWrapper(context);
final PlatformView platformView =
viewFactory.create(embeddedViewContext, viewId, createParams);
platformViews.put(viewId, platformView);
final PlatformView platformView = createPlatformView(request);
final View embeddedView = platformView.getView();
if (embeddedView == null) {
throw new IllegalStateException(
"PlatformView#getView() returned null, but an Android view reference was expected.");
} else if (embeddedView.getParent() != null) {
if (embeddedView.getParent() != null) {
throw new IllegalStateException(
"The Android view returned from PlatformView#getView() was already added to a parent view.");
}
embeddedView.setLayoutDirection(request.direction);
// The newer Texture Layer Hybrid Composition mode isn't suppported if any of the
// following are true:
// - The embedded view contains any of the VIEW_TYPES_REQUIRE_VIRTUAL_DISPLAY view types.
// These views allow out-of-band graphics operations that aren't notified to the Android
// view hierarchy via callbacks such as ViewParent#onDescendantInvalidated().
// - The API level is <23, due to TLHC implementation API requirements.
final boolean supportsTextureLayerMode =
Build.VERSION.SDK_INT >= 23
&& !ViewUtils.hasChildViewOfType(
embeddedView, VIEW_TYPES_REQUIRE_VIRTUAL_DISPLAY);
final int physicalWidth = toPhysicalPixels(request.logicalWidth);
final int physicalHeight = toPhysicalPixels(request.logicalHeight);
// Case 1. Add the view to a virtual display if the embedded view contains any of the
// VIEW_TYPES_REQUIRE_VIRTUAL_DISPLAY view types.
// These views allow out-of-band graphics operations that aren't notified to the Android
// view hierarchy via callbacks such as ViewParent#onDescendantInvalidated().
// The virtual display is wired up to a GL texture that is composed by the Flutter engine.
// Also, use virtual display if the API level is 20, 21 or 22 since the Case 2. requires
// at least API level 23.
final boolean shouldUseVirtualDisplay =
ViewUtils.hasChildViewOfType(embeddedView, VIEW_TYPES_REQUIRE_VIRTUAL_DISPLAY)
|| Build.VERSION.SDK_INT < 23;
if (!usesSoftwareRendering && shouldUseVirtualDisplay) {
Log.i(TAG, "Hosting view in a virtual display for platform view: " + viewId);
// API level 20 is required to use VirtualDisplay#setSurface.
ensureValidAndroidVersion(20);
final TextureRegistry.SurfaceTextureEntry textureEntry =
textureRegistry.createSurfaceTexture();
final VirtualDisplayController vdController =
VirtualDisplayController.create(
context,
accessibilityEventsDelegate,
platformView,
textureEntry,
physicalWidth,
physicalHeight,
request.viewId,
createParams,
(view, hasFocus) -> {
if (hasFocus) {
platformViewsChannel.invokeViewFocused(request.viewId);
}
});
if (vdController == null) {
throw new IllegalStateException(
"Failed creating virtual display for a "
+ request.viewType
+ " with id: "
+ request.viewId);
// Fall back to Hybrid Composition or Virtual Display when necessary, depending on which
// fallback mode is requested.
if (!supportsTextureLayerMode) {
if (request.displayMode
== PlatformViewsChannel.PlatformViewCreationRequest.RequestedDisplayMode
.TEXTURE_WITH_HYBRID_FALLBACK) {
configureForHybridComposition(platformView, request);
return PlatformViewsChannel.PlatformViewsHandler.NON_TEXTURE_FALLBACK;
} else if (!usesSoftwareRendering) { // Virtual Display doesn't support software mode.
return configureForVirtualDisplay(platformView, request);
}
// If our FlutterEngine is already attached to a Flutter UI, provide that Android
// View to this new platform view.
if (flutterView != null) {
vdController.onFlutterViewAttached(flutterView);
}
vdControllers.put(request.viewId, vdController);
contextToEmbeddedView.put(embeddedView.getContext(), embeddedView);
return textureEntry.id();
// TODO(stuartmorgan): Consider throwing a specific exception here as a breaking change.
// For now, preserve the 3.0 behavior of falling through to Texture Layer mode even
// though it won't work correctly.
}
// Case 2. Attach the view to the Android view hierarchy and record their drawing
// operations, so they can be forwarded to a GL texture that is composed by the
// Flutter engine.
// API level 23 is required to use Surface#lockHardwareCanvas().
ensureValidAndroidVersion(23);
Log.i(TAG, "Hosting view in view hierarchy for platform view: " + viewId);
PlatformViewWrapper viewWrapper;
long txId;
if (usesSoftwareRendering) {
viewWrapper = new PlatformViewWrapper(context);
txId = -1;
} else {
final TextureRegistry.SurfaceTextureEntry textureEntry =
textureRegistry.createSurfaceTexture();
viewWrapper = new PlatformViewWrapper(context, textureEntry);
txId = textureEntry.id();
}
viewWrapper.setTouchProcessor(androidTouchProcessor);
viewWrapper.setBufferSize(physicalWidth, physicalHeight);
final FrameLayout.LayoutParams viewWrapperLayoutParams =
new FrameLayout.LayoutParams(physicalWidth, physicalHeight);
// Size and position the view wrapper.
final int physicalTop = toPhysicalPixels(request.logicalTop);
final int physicalLeft = toPhysicalPixels(request.logicalLeft);
viewWrapperLayoutParams.topMargin = physicalTop;
viewWrapperLayoutParams.leftMargin = physicalLeft;
viewWrapper.setLayoutParams(viewWrapperLayoutParams);
// Size the embedded view.
// This isn't needed when the virtual display is used because the virtual display itself
// is sized.
embeddedView.setLayoutParams(new FrameLayout.LayoutParams(physicalWidth, physicalHeight));
// Accessibility in the embedded view is initially disabled because if a Flutter app
// disabled accessibility in the first frame, the embedding won't receive an update to
// disable accessibility since the embedding never received an update to enable it.
// The AccessibilityBridge keeps track of the accessibility nodes, and handles the deltas
// when the framework sends a new a11y tree to the embedding.
// To prevent races, the framework populate the SemanticsNode after the platform view has
// been created.
embeddedView.setImportantForAccessibility(
View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
// Add the embedded view to the wrapper.
viewWrapper.addView(embeddedView);
// Listen for focus changed in any subview, so the framework is notified when the platform
// view is focused.
viewWrapper.setOnDescendantFocusChangeListener(
(v, hasFocus) -> {
if (hasFocus) {
platformViewsChannel.invokeViewFocused(viewId);
} else if (textInputPlugin != null) {
textInputPlugin.clearPlatformViewClient(viewId);
}
});
flutterView.addView(viewWrapper);
viewWrappers.append(viewId, viewWrapper);
return txId;
return configureForTextureLayerComposition(platformView, request);
}
@Override
@@ -598,6 +461,186 @@ public class PlatformViewsController implements PlatformViewsAccessibilityDelega
}
}
private void ensureValidRequest(
@NonNull PlatformViewsChannel.PlatformViewCreationRequest request) {
if (!validateDirection(request.direction)) {
throw new IllegalStateException(
"Trying to create a view with unknown direction value: "
+ request.direction
+ "(view id: "
+ request.viewId
+ ")");
}
}
// Creates a platform view based on `request`, performs configuration that's common to
// all display modes, and adds it to `platformViews`.
@TargetApi(19)
private PlatformView createPlatformView(
@NonNull PlatformViewsChannel.PlatformViewCreationRequest request) {
final PlatformViewFactory viewFactory = registry.getFactory(request.viewType);
if (viewFactory == null) {
throw new IllegalStateException(
"Trying to create a platform view of unregistered type: " + request.viewType);
}
Object createParams = null;
if (request.params != null) {
createParams = viewFactory.getCreateArgsCodec().decodeMessage(request.params);
}
// In some display modes, the context needs to be modified during display.
final Context mutableContext = new MutableContextWrapper(context);
final PlatformView platformView =
viewFactory.create(mutableContext, request.viewId, createParams);
// Configure the view to match the requested layout direction.
final View embeddedView = platformView.getView();
if (embeddedView == null) {
throw new IllegalStateException(
"PlatformView#getView() returned null, but an Android view reference was expected.");
}
embeddedView.setLayoutDirection(request.direction);
platformViews.put(request.viewId, platformView);
return platformView;
}
// Configures the view for Hybrid Composition mode.
private void configureForHybridComposition(
@NonNull PlatformView platformView,
@NonNull PlatformViewsChannel.PlatformViewCreationRequest request) {
Log.i(TAG, "Using hybrid composition for platform view: " + request.viewId);
}
// Configures the view for Virtual Display mode, returning the associated texture ID.
private long configureForVirtualDisplay(
@NonNull PlatformView platformView,
@NonNull PlatformViewsChannel.PlatformViewCreationRequest request) {
// This mode adds the view to a virtual display, which is is wired up to a GL texture that
// is composed by the Flutter engine.
// API level 20 is required to use VirtualDisplay#setSurface.
ensureValidAndroidVersion(20);
Log.i(TAG, "Hosting view in a virtual display for platform view: " + request.viewId);
final TextureRegistry.SurfaceTextureEntry textureEntry =
textureRegistry.createSurfaceTexture();
final int physicalWidth = toPhysicalPixels(request.logicalWidth);
final int physicalHeight = toPhysicalPixels(request.logicalHeight);
final VirtualDisplayController vdController =
VirtualDisplayController.create(
context,
accessibilityEventsDelegate,
platformView,
textureEntry,
physicalWidth,
physicalHeight,
request.viewId,
null,
(view, hasFocus) -> {
if (hasFocus) {
platformViewsChannel.invokeViewFocused(request.viewId);
}
});
if (vdController == null) {
throw new IllegalStateException(
"Failed creating virtual display for a "
+ request.viewType
+ " with id: "
+ request.viewId);
}
// If our FlutterEngine is already attached to a Flutter UI, provide that Android
// View to this new platform view.
if (flutterView != null) {
vdController.onFlutterViewAttached(flutterView);
}
// The embedded view doesn't need to be sized in Virtual Display mode because the
// virtual display itself is sized.
vdControllers.put(request.viewId, vdController);
final View embeddedView = platformView.getView();
contextToEmbeddedView.put(embeddedView.getContext(), embeddedView);
return textureEntry.id();
}
// Configures the view for Texture Layer Hybrid Composition mode, returning the associated
// texture ID.
@TargetApi(23)
private long configureForTextureLayerComposition(
@NonNull PlatformView platformView,
@NonNull PlatformViewsChannel.PlatformViewCreationRequest request) {
// This mode attaches the view to the Android view hierarchy and record its drawing
// operations, so they can be forwarded to a GL texture that is composed by the
// Flutter engine.
// API level 23 is required to use Surface#lockHardwareCanvas().
ensureValidAndroidVersion(23);
Log.i(TAG, "Hosting view in view hierarchy for platform view: " + request.viewId);
final int physicalWidth = toPhysicalPixels(request.logicalWidth);
final int physicalHeight = toPhysicalPixels(request.logicalHeight);
PlatformViewWrapper viewWrapper;
long textureId;
if (usesSoftwareRendering) {
viewWrapper = new PlatformViewWrapper(context);
textureId = -1;
} else {
final TextureRegistry.SurfaceTextureEntry textureEntry =
textureRegistry.createSurfaceTexture();
viewWrapper = new PlatformViewWrapper(context, textureEntry);
textureId = textureEntry.id();
}
viewWrapper.setTouchProcessor(androidTouchProcessor);
viewWrapper.setBufferSize(physicalWidth, physicalHeight);
final FrameLayout.LayoutParams viewWrapperLayoutParams =
new FrameLayout.LayoutParams(physicalWidth, physicalHeight);
// Size and position the view wrapper.
final int physicalTop = toPhysicalPixels(request.logicalTop);
final int physicalLeft = toPhysicalPixels(request.logicalLeft);
viewWrapperLayoutParams.topMargin = physicalTop;
viewWrapperLayoutParams.leftMargin = physicalLeft;
viewWrapper.setLayoutParams(viewWrapperLayoutParams);
// Size the embedded view.
final View embeddedView = platformView.getView();
embeddedView.setLayoutParams(new FrameLayout.LayoutParams(physicalWidth, physicalHeight));
// Accessibility in the embedded view is initially disabled because if a Flutter app
// disabled accessibility in the first frame, the embedding won't receive an update to
// disable accessibility since the embedding never received an update to enable it.
// The AccessibilityBridge keeps track of the accessibility nodes, and handles the deltas
// when the framework sends a new a11y tree to the embedding.
// To prevent races, the framework populate the SemanticsNode after the platform view has
// been created.
embeddedView.setImportantForAccessibility(
View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
// Add the embedded view to the wrapper.
viewWrapper.addView(embeddedView);
// Listen for focus changed in any subview, so the framework is notified when the platform
// view is focused.
viewWrapper.setOnDescendantFocusChangeListener(
(v, hasFocus) -> {
if (hasFocus) {
platformViewsChannel.invokeViewFocused(request.viewId);
} else if (textInputPlugin != null) {
textInputPlugin.clearPlatformViewClient(request.viewId);
}
});
flutterView.addView(viewWrapper);
viewWrappers.append(request.viewId, viewWrapper);
return textureId;
}
@Override
public void synchronizeToNativeViewHierarchy(boolean yes) {
synchronizeToNativeViewHierarchy = yes;

View File

@@ -84,10 +84,6 @@ class SingleViewPresentation extends Presentation {
// so when we create the platform view we can tell it its view id.
private int viewId;
// This is the creation parameters for the platform view, we keep it here
// so when we create the platform view we can tell it its view id.
private Object createParams;
// The root view for the presentation, it has 2 childs: container which contains the embedded
// view, and
// fakeWindowViewGroup which contains views that were added directly to the presentation's window
@@ -115,12 +111,10 @@ class SingleViewPresentation extends Presentation {
PlatformView view,
AccessibilityEventsDelegate accessibilityEventsDelegate,
int viewId,
Object createParams,
OnFocusChangeListener focusChangeListener) {
super(new ImmContext(outerContext), display);
this.accessibilityEventsDelegate = accessibilityEventsDelegate;
this.viewId = viewId;
this.createParams = createParams;
this.focusChangeListener = focusChangeListener;
this.outerContext = outerContext;
state = new PresentationState();

View File

@@ -114,7 +114,6 @@ class VirtualDisplayController {
view,
accessibilityEventsDelegate,
viewId,
createParams,
focusChangeListener);
presentation.show();
}

View File

@@ -14,6 +14,8 @@ _android_sources = [
"app/src/androidTest/java/dev/flutter/scenariosui/PlatformTextureUiTests.java",
"app/src/androidTest/java/dev/flutter/scenariosui/PlatformViewUiTests.java",
"app/src/androidTest/java/dev/flutter/scenariosui/PlatformViewWithSurfaceViewBadContextUiTest.java",
"app/src/androidTest/java/dev/flutter/scenariosui/PlatformViewWithSurfaceViewHybridFallbackUiTest.java",
"app/src/androidTest/java/dev/flutter/scenariosui/PlatformViewWithSurfaceViewHybridUiTest.java",
"app/src/androidTest/java/dev/flutter/scenariosui/PlatformViewWithSurfaceViewUiTest.java",
"app/src/androidTest/java/dev/flutter/scenariosui/PlatformViewWithTextureViewUiTest.java",
"app/src/androidTest/java/dev/flutter/scenariosui/ScreenshotUtil.java",

View File

@@ -0,0 +1,47 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package dev.flutter.scenariosui;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.test.filters.LargeTest;
import androidx.test.rule.ActivityTestRule;
import androidx.test.runner.AndroidJUnit4;
import dev.flutter.scenarios.PlatformViewsActivity;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
@LargeTest
public class PlatformViewWithSurfaceViewHybridFallbackUiTest {
Intent intent;
@Rule @NonNull
public ActivityTestRule<PlatformViewsActivity> activityRule =
new ActivityTestRule<>(
PlatformViewsActivity.class, /*initialTouchMode=*/ false, /*launchActivity=*/ false);
private static String goldName(String suffix) {
return "PlatformViewWithSurfaceViewHybridFallbackUiTest_" + suffix;
}
@Before
public void setUp() {
intent = new Intent(Intent.ACTION_MAIN);
// Request TLHC with fallback to HC.
intent.putExtra("use_android_view", false);
intent.putExtra("expect_android_view_fallback", true);
// Use a SurfaceView to trigger fallback.
intent.putExtra("view_type", PlatformViewsActivity.SURFACE_VIEW_PV);
}
@Test
public void testPlatformView() throws Exception {
intent.putExtra("scenario_name", "platform_view");
ScreenshotUtil.capture(activityRule.launchActivity(intent), goldName("testPlatformView"));
}
}

View File

@@ -0,0 +1,44 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package dev.flutter.scenariosui;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.test.filters.LargeTest;
import androidx.test.rule.ActivityTestRule;
import androidx.test.runner.AndroidJUnit4;
import dev.flutter.scenarios.PlatformViewsActivity;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
@LargeTest
public class PlatformViewWithSurfaceViewHybridUiTest {
Intent intent;
@Rule @NonNull
public ActivityTestRule<PlatformViewsActivity> activityRule =
new ActivityTestRule<>(
PlatformViewsActivity.class, /*initialTouchMode=*/ false, /*launchActivity=*/ false);
private static String goldName(String suffix) {
return "PlatformViewWithSurfaceViewHybridUiTest_" + suffix;
}
@Before
public void setUp() {
intent = new Intent(Intent.ACTION_MAIN);
intent.putExtra("use_android_view", true);
intent.putExtra("view_type", PlatformViewsActivity.SURFACE_VIEW_PV);
}
@Test
public void testPlatformView() throws Exception {
intent.putExtra("scenario_name", "platform_view");
ScreenshotUtil.capture(activityRule.launchActivity(intent), goldName("testPlatformView"));
}
}

View File

@@ -84,6 +84,9 @@ public abstract class TestActivity extends TestableFlutterActivity {
test.put("name", "animated_color_square");
}
test.put("use_android_view", launchIntent.getBooleanExtra("use_android_view", false));
test.put(
"expect_android_view_fallback",
launchIntent.getBooleanExtra("expect_android_view_fallback", false));
test.put("view_type", launchIntent.getStringExtra("view_type"));
getScenarioParams(test);
channel.invokeMethod("set_scenario", test);

View File

@@ -28,6 +28,13 @@ List<int> _to64(num value) {
return temp;
}
List<int> _encodeString(String value) {
return <int>[
value.length, // This won't work if we use multi-byte characters.
...utf8.encode(value),
];
}
/// A simple platform view.
class PlatformViewScenario extends Scenario
with _BasePlatformViewScenarioMixin {
@@ -739,13 +746,11 @@ class PlatformViewForTouchIOSScenario extends Scenario
const int valueMap = 13;
final Uint8List message = Uint8List.fromList(<int>[
valueString,
method.length,
...utf8.encode(method),
..._encodeString(method),
valueMap,
1,
valueString,
'id'.length,
...utf8.encode('id'),
..._encodeString('id'),
valueInt32,
..._to32(id),
]);
@@ -1107,12 +1112,12 @@ void addPlatformView(
return;
}
bool usesAndroidHybridComposition = false;
if (scenarioParams['use_android_view'] is bool) {
usesAndroidHybridComposition = scenarioParams['use_android_view'] as bool;
}
final bool usesAndroidHybridComposition = scenarioParams['use_android_view'] as bool? ?? false;
final bool expectAndroidHybridCompositionFallback =
scenarioParams['expect_android_view_fallback'] as bool? ?? false;
const int valueTrue = 1;
const int valueFalse = 2;
const int valueInt32 = 3;
const int valueFloat64 = 6;
const int valueString = 7;
@@ -1121,29 +1126,24 @@ void addPlatformView(
final Uint8List message = Uint8List.fromList(<int>[
valueString,
'create'.length, // this won't work if we use multi-byte characters.
...utf8.encode('create'),
..._encodeString('create'),
valueMap,
if (Platform.isIOS) 3, // 3 entries in map for iOS.
if (Platform.isAndroid && !usesAndroidHybridComposition)
6, // 6 entries in map for texture on Android.
7, // 7 entries in map for texture on Android.
if (Platform.isAndroid && usesAndroidHybridComposition)
5, // 5 entries in map for hybrid composition on Android.
valueString,
'id'.length,
...utf8.encode('id'),
..._encodeString('id'),
valueInt32,
..._to32(id),
valueString,
'viewType'.length,
...utf8.encode('viewType'),
..._encodeString('viewType'),
valueString,
viewType.length,
...utf8.encode(viewType),
..._encodeString(viewType),
if (Platform.isAndroid && !usesAndroidHybridComposition) ...<int>[
valueString,
'width'.length,
...utf8.encode('width'),
..._encodeString('width'),
// This is missing the 64-bit boundary alignment, making the entire
// message encoding fragile to changes before this point. Do not add new
// variable-length values such as strings before this point.
@@ -1152,33 +1152,31 @@ void addPlatformView(
valueFloat64,
..._to64(width),
valueString,
'height'.length,
...utf8.encode('height'),
..._encodeString('height'),
valueFloat64,
..._to64(height),
valueString,
'direction'.length,
...utf8.encode('direction'),
..._encodeString('direction'),
valueInt32,
..._to32(0), // LTR
valueString,
..._encodeString('hybridFallback'),
if (expectAndroidHybridCompositionFallback) valueTrue
else valueFalse,
],
if (Platform.isAndroid && usesAndroidHybridComposition) ...<int>[
valueString,
'hybrid'.length,
...utf8.encode('hybrid'),
..._encodeString('hybrid'),
valueTrue,
valueString,
'direction'.length,
...utf8.encode('direction'),
..._encodeString('direction'),
valueInt32,
..._to32(0), // LTR
],
valueString,
'params'.length,
...utf8.encode('params'),
..._encodeString('params'),
valueUint8List,
text.length,
...utf8.encode(text),
..._encodeString(text),
]);
dispatcher.sendPlatformMessage(
@@ -1189,11 +1187,17 @@ void addPlatformView(
if (response != null &&
Platform.isAndroid &&
!usesAndroidHybridComposition) {
// This is the texture ID.
assert(response.getUint8(0) == 0, 'expected envelope');
final int type = response.getUint8(1);
assert(type == 4, 'expected int64');
textureId = response.getInt64(2, Endian.host);
if (expectAndroidHybridCompositionFallback) {
// Fallback is indicated with a null return.
assert(type == 0, 'expected null');
textureId = -1;
} else {
// This is the texture ID.
assert(type == 4, 'expected int64');
textureId = response.getInt64(2, Endian.host);
}
} else {
// There no texture ID.
textureId = -1;
@@ -1215,8 +1219,12 @@ Future<void> addPlatformViewToSceneBuilder(
if (Platform.isIOS) {
sceneBuilder.addPlatformView(id, width: width, height: height);
} else if (Platform.isAndroid) {
final bool? usesAndroidHybridComposition = scenarioParams['use_android_view'] as bool?;
if (usesAndroidHybridComposition != null && usesAndroidHybridComposition) {
final bool expectAndroidHybridCompositionFallback =
scenarioParams['expect_android_view_fallback'] as bool? ?? false;
final bool usesAndroidHybridComposition =
(scenarioParams['use_android_view'] as bool? ?? false) ||
expectAndroidHybridCompositionFallback;
if (usesAndroidHybridComposition) {
sceneBuilder.addPlatformView(id, width: width, height: height);
} else if (textureId != -1) {
sceneBuilder.addTexture(textureId, width: width, height: height);