Android views using hybrid composition e2e driver test (#61507)

This commit is contained in:
Emmanuel Garcia
2020-07-16 16:19:49 -07:00
committed by GitHub
parent b7b60a2d2c
commit 293a2bf8e8
23 changed files with 1529 additions and 0 deletions

View File

@@ -0,0 +1,58 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
compileSdkVersion 28
lintOptions {
disable 'InvalidPackage'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "io.flutter.integration.platformviews"
minSdkVersion 16
targetSdkVersion 28
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
}
flutter {
source '../..'
}

View File

@@ -0,0 +1,36 @@
<!-- Copyright 2014 The Flutter Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file. -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.integration.platformviews">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:name="io.flutter.app.FlutterApplication"
android:label="platform_views">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<meta-data
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true" />
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<meta-data
android:name="flutterEmbedding"
android:value="2" />
<!-- Hybrid composition -->
<meta-data
android:name="io.flutter.embedded_views_preview"
android:value="true" />
</application>
</manifest>

View File

@@ -0,0 +1,110 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.integration.platformviews;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import java.util.HashMap;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity implements MethodChannel.MethodCallHandler {
final static int STORAGE_PERMISSION_CODE = 1;
MethodChannel mMethodChannel;
// The method result to complete with the Android permission request result.
// This is null when not waiting for the Android permission request;
private MethodChannel.Result permissionResult;
private View getFlutterView() {
// TODO(egarciad): Set an unique ID in FlutterView, so it's easier to look it up.
ViewGroup root = (ViewGroup)findViewById(android.R.id.content);
return ((ViewGroup)root.getChildAt(0)).getChildAt(0);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void configureFlutterEngine(FlutterEngine flutterEngine) {
DartExecutor executor = flutterEngine.getDartExecutor();
flutterEngine
.getPlatformViewsController()
.getRegistry()
.registerViewFactory("simple_view", new SimpleViewFactory(executor));
mMethodChannel = new MethodChannel(executor, "android_views_integration");
mMethodChannel.setMethodCallHandler(this);
GeneratedPluginRegistrant.registerWith(flutterEngine);
}
@Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
switch(methodCall.method) {
case "getStoragePermission":
if (permissionResult != null) {
result.error("error", "already waiting for permissions", null);
return;
}
permissionResult = result;
getExternalStoragePermissions();
return;
case "synthesizeEvent":
synthesizeEvent(methodCall, result);
return;
}
result.notImplemented();
}
@SuppressWarnings("unchecked")
public void synthesizeEvent(MethodCall methodCall, MethodChannel.Result result) {
MotionEvent event = MotionEventCodec.decode((HashMap<String, Object>) methodCall.arguments());
getFlutterView().dispatchTouchEvent(event);
// TODO(egarciad): This can be cleaned up.
mMethodChannel.invokeMethod("onTouch", MotionEventCodec.encode(event));
result.success(null);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode != STORAGE_PERMISSION_CODE || permissionResult == null)
return;
boolean permisisonGranted = grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;
sendPermissionResult(permisisonGranted);
}
private void getExternalStoragePermissions() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
return;
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
sendPermissionResult(true);
return;
}
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
private void sendPermissionResult(boolean result) {
if (permissionResult == null)
return;
permissionResult.success(result);
permissionResult = null;
}
}

View File

@@ -0,0 +1,125 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.integration.platformviews;
import android.annotation.TargetApi;
import android.os.Build;
import android.view.MotionEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static android.view.MotionEvent.PointerCoords;
import static android.view.MotionEvent.PointerProperties;
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class MotionEventCodec {
public static HashMap<String, Object> encode(MotionEvent event) {
ArrayList<HashMap<String,Object>> pointerProperties = new ArrayList<>();
ArrayList<HashMap<String,Object>> pointerCoords = new ArrayList<>();
for (int i = 0; i < event.getPointerCount(); i++) {
MotionEvent.PointerProperties properties = new MotionEvent.PointerProperties();
event.getPointerProperties(i, properties);
pointerProperties.add(encodePointerProperties(properties));
MotionEvent.PointerCoords coords = new MotionEvent.PointerCoords();
event.getPointerCoords(i, coords);
pointerCoords.add(encodePointerCoords(coords));
}
HashMap<String, Object> eventMap = new HashMap<>();
eventMap.put("downTime", event.getDownTime());
eventMap.put("eventTime", event.getEventTime());
eventMap.put("action", event.getAction());
eventMap.put("pointerCount", event.getPointerCount());
eventMap.put("pointerProperties", pointerProperties);
eventMap.put("pointerCoords", pointerCoords);
eventMap.put("metaState", event.getMetaState());
eventMap.put("buttonState", event.getButtonState());
eventMap.put("xPrecision", event.getXPrecision());
eventMap.put("yPrecision", event.getYPrecision());
eventMap.put("deviceId", event.getDeviceId());
eventMap.put("edgeFlags", event.getEdgeFlags());
eventMap.put("source", event.getSource());
eventMap.put("flags", event.getFlags());
return eventMap;
}
private static HashMap<String, Object> encodePointerProperties(PointerProperties properties) {
HashMap<String, Object> map = new HashMap<>();
map.put("id", properties.id);
map.put("toolType", properties.toolType);
return map;
}
private static HashMap<String, Object> encodePointerCoords(PointerCoords coords) {
HashMap<String, Object> map = new HashMap<>();
map.put("orientation", coords.orientation);
map.put("pressure", coords.pressure);
map.put("size", coords.size);
map.put("toolMajor", coords.toolMajor);
map.put("toolMinor", coords.toolMinor);
map.put("touchMajor", coords.touchMajor);
map.put("touchMinor", coords.touchMinor);
map.put("x", coords.x);
map.put("y", coords.y);
return map;
}
@SuppressWarnings("unchecked")
public static MotionEvent decode(HashMap<String, Object> data) {
List<PointerProperties> pointerProperties = new ArrayList<>();
List<PointerCoords> pointerCoords = new ArrayList<>();
for (HashMap<String, Object> property : (List<HashMap<String, Object>>) data.get("pointerProperties")) {
pointerProperties.add(decodePointerProperties(property)) ;
}
for (HashMap<String, Object> coord : (List<HashMap<String, Object>>) data.get("pointerCoords")) {
pointerCoords.add(decodePointerCoords(coord)) ;
}
return MotionEvent.obtain(
(int) data.get("downTime"),
(int) data.get("eventTime"),
(int) data.get("action"),
(int) data.get("pointerCount"),
pointerProperties.toArray(new PointerProperties[pointerProperties.size()]),
pointerCoords.toArray(new PointerCoords[pointerCoords.size()]),
(int) data.get("metaState"),
(int) data.get("buttonState"),
(float) (double) data.get("xPrecision"),
(float) (double) data.get("yPrecision"),
(int) data.get("deviceId"),
(int) data.get("edgeFlags"),
(int) data.get("source"),
(int) data.get("flags")
);
}
private static PointerProperties decodePointerProperties(HashMap<String, Object> data) {
PointerProperties properties = new PointerProperties();
properties.id = (int) data.get("id");
properties.toolType = (int) data.get("toolType");
return properties;
}
private static PointerCoords decodePointerCoords(HashMap<String, Object> data) {
PointerCoords coords = new PointerCoords();
coords.orientation = (float) (double) data.get("orientation");
coords.pressure = (float) (double) data.get("pressure");
coords.size = (float) (double) data.get("size");
coords.toolMajor = (float) (double) data.get("toolMajor");
coords.toolMinor = (float) (double) data.get("toolMinor");
coords.touchMajor = (float) (double) data.get("touchMajor");
coords.touchMinor = (float) (double) data.get("touchMinor");
coords.x = (float) (double) data.get("x");
coords.y = (float) (double) data.get("y");
return coords;
}
}

View File

@@ -0,0 +1,99 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.integration.platformviews;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.PixelFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.platform.PlatformView;
public class SimplePlatformView implements PlatformView, MethodChannel.MethodCallHandler {
private final FrameLayout view;
private final MethodChannel methodChannel;
private final io.flutter.integration.platformviews.TouchPipe touchPipe;
SimplePlatformView(Context context, MethodChannel methodChannel) {
this.methodChannel = methodChannel;
this.methodChannel.setMethodCallHandler(this);
view = new FrameLayout(context) {
@Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}
};
view.setBackgroundColor(0xff0000ff);
touchPipe = new TouchPipe(this.methodChannel, view);
}
@Override
public View getView() {
return view;
}
@Override
public void dispose() {}
@Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
switch(methodCall.method) {
case "pipeTouchEvents":
touchPipe.enable();
result.success(null);
return;
case "stopTouchEvents":
touchPipe.disable();
result.success(null);
return;
case "showAndHideAlertDialog":
showAndHideAlertDialog(result);
return;
case "addChildViewAndWaitForClick":
addWindow(result);
return;
}
result.notImplemented();
}
private void showAndHideAlertDialog(MethodChannel.Result result) {
Context context = view.getContext();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
TextView textView = new TextView(context);
textView.setText("This alert dialog will close in 1 second");
builder.setView(textView);
final AlertDialog alertDialog = builder.show();
result.success(null);
view.postDelayed(new Runnable() {
@Override
public void run() {
alertDialog.hide();
}
}, 1000);
}
private void addWindow(final MethodChannel.Result result) {
Context context = view.getContext();
final Button button = new Button(context);
button.setText("This view was added to the Android view");
view.addView(button);
button.setOnClickListener(v -> {
view.removeView(button);
result.success(null);
});
}
}

View File

@@ -0,0 +1,27 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.integration.platformviews;
import android.content.Context;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.platform.PlatformView;
import io.flutter.plugin.platform.PlatformViewFactory;
public class SimpleViewFactory extends PlatformViewFactory {
final DartExecutor executor;
public SimpleViewFactory(DartExecutor executor) {
super(null);
this.executor = executor;
}
@Override
public PlatformView create(Context context, int id, Object params) {
MethodChannel methodChannel = new MethodChannel(executor, "simple_view/" + id);
return new SimplePlatformView(context, methodChannel);
}
}

View File

@@ -0,0 +1,45 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.integration.platformviews;
import android.annotation.TargetApi;
import android.os.Build;
import android.view.MotionEvent;
import android.view.View;
import io.flutter.plugin.common.MethodChannel;
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
class TouchPipe implements View.OnTouchListener {
private final MethodChannel mMethodChannel;
private final View mView;
private boolean mEnabled;
TouchPipe(MethodChannel methodChannel, View view) {
mMethodChannel = methodChannel;
mView = view;
}
public void enable() {
if (mEnabled)
return;
mEnabled = true;
mView.setOnTouchListener(this);
}
public void disable() {
if(!mEnabled)
return;
mEnabled = false;
mView.setOnTouchListener(null);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
mMethodChannel.invokeMethod("onTouch", MotionEventCodec.encode(event));
return false;
}
}

View File

@@ -0,0 +1,33 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0'
}
}
allprojects {
repositories {
google()
jcenter()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
delete rootProject.buildDir
}

View File

@@ -0,0 +1,4 @@
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
android.enableR8=true

View File

@@ -0,0 +1,6 @@
#Fri Jun 23 08:50:38 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-all.zip

View File

@@ -0,0 +1,15 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
include ':app'
def localPropertiesFile = new File(rootProject.projectDir, "local.properties")
def properties = new Properties()
assert localPropertiesFile.exists()
localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) }
def flutterSdkPath = properties.getProperty("flutter.sdk")
assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle"