SurfaceControlViewHost: Test touch obscuring behavior

Add some tests for various kinds of obscured touch behavior.

Bug: 213603716
Bug: 214239892
Test: SurfaceControlViewHostTests
Change-Id: Ic1c06a06cf9733b83434cd0cbb31e8f4794a001a
diff --git a/tests/framework/base/windowmanager/AndroidTest.xml b/tests/framework/base/windowmanager/AndroidTest.xml
index b38c81f..de6ba79 100644
--- a/tests/framework/base/windowmanager/AndroidTest.xml
+++ b/tests/framework/base/windowmanager/AndroidTest.xml
@@ -40,6 +40,7 @@
         <option name="test-file-name" value="CtsMockInputMethod.apk" />
         <option name="test-file-name" value="CtsDeviceServicesTestShareUidAppA.apk" />
         <option name="test-file-name" value="CtsDeviceServicesTestShareUidAppB.apk" />
+        <option name="test-file-name" value="CtsCrossProcessSurfaceControlViewHostTestService.apk" />
     </target_preparer>
     <!-- Some older apk cannot be installed as instant, so we force them full mode -->
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
diff --git a/tests/framework/base/windowmanager/scvhapp/Android.bp b/tests/framework/base/windowmanager/scvhapp/Android.bp
new file mode 100644
index 0000000..1d557fa
--- /dev/null
+++ b/tests/framework/base/windowmanager/scvhapp/Android.bp
@@ -0,0 +1,39 @@
+// Copyright (C) 2022 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test {
+    name: "CtsCrossProcessSurfaceControlViewHostTestService",
+    defaults: ["cts_support_defaults"],
+
+    srcs: [
+        "src/**/*.java",
+    ],
+
+    static_libs: [
+        "cts-wm-app-base",
+        "androidx.annotation_annotation",
+    ],
+
+    sdk_version: "test_current",
+
+    test_suites: [
+        "cts",
+        "general-tests",
+        "sts",
+    ],
+}
diff --git a/tests/framework/base/windowmanager/scvhapp/AndroidManifest.xml b/tests/framework/base/windowmanager/scvhapp/AndroidManifest.xml
new file mode 100644
index 0000000..71cb02e
--- /dev/null
+++ b/tests/framework/base/windowmanager/scvhapp/AndroidManifest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2022 The Android Open Source Project
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~      http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.server.wm.scvh">
+
+    <application>
+        <service
+            android:name="android.server.wm.scvh.CrossProcessSurfaceControlViewHostTestService"
+            android:exported="true" />
+    </application>
+
+</manifest>
diff --git a/tests/framework/base/windowmanager/scvhapp/src/android/server/wm/scvh/Components.java b/tests/framework/base/windowmanager/scvhapp/src/android/server/wm/scvh/Components.java
new file mode 100644
index 0000000..e753f87
--- /dev/null
+++ b/tests/framework/base/windowmanager/scvhapp/src/android/server/wm/scvh/Components.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.server.wm.scvh;
+
+import android.content.ComponentName;
+import android.server.wm.component.ComponentsBase;
+
+
+public class Components extends ComponentsBase {
+    public interface CrossProcessSurfaceControlViewHostTestService {
+        ComponentName COMPONENT = component("CrossProcessSurfaceControlViewHostTestService");
+    }
+
+    private static ComponentName component(String className) {
+        return component(Components.class, className);
+    }
+}
diff --git a/tests/framework/base/windowmanager/scvhapp/src/android/server/wm/scvh/CrossProcessSurfaceControlViewHostTestService.java b/tests/framework/base/windowmanager/scvhapp/src/android/server/wm/scvh/CrossProcessSurfaceControlViewHostTestService.java
new file mode 100644
index 0000000..c65f42b
--- /dev/null
+++ b/tests/framework/base/windowmanager/scvhapp/src/android/server/wm/scvh/CrossProcessSurfaceControlViewHostTestService.java
@@ -0,0 +1,164 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.server.wm.scvh;
+
+import static android.view.Display.DEFAULT_DISPLAY;
+
+import android.app.Service;
+import android.content.Context;
+import android.content.Intent;
+import android.graphics.PixelFormat;
+import android.hardware.display.DisplayManager;
+import android.os.Handler;
+import android.os.Binder;
+import android.os.IBinder;
+import android.os.Looper;
+import android.os.RemoteException;
+import android.server.wm.shared.ICrossProcessSurfaceControlViewHostTestService;
+import android.util.ArrayMap;
+import android.view.Display;
+import android.view.MotionEvent;
+import android.view.View;
+import android.view.ViewTreeObserver;
+import android.view.WindowManager;
+import android.view.SurfaceControlViewHost;
+
+import androidx.annotation.Nullable;
+
+import java.util.Collections;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.Map;
+
+
+public class CrossProcessSurfaceControlViewHostTestService extends Service {
+    private final ICrossProcessSurfaceControlViewHostTestService mBinder = new ServiceImpl();
+    private Handler mHandler;
+
+    class MotionRecordingView extends View {
+        boolean mGotEvent = false;
+        boolean mGotObscuredEvent = false;
+
+        MotionRecordingView(Context c) {
+            super(c);
+        }
+
+        public boolean onTouchEvent(MotionEvent e) {
+            super.onTouchEvent(e);
+            synchronized (this) {
+                mGotEvent = true;
+                if ((e.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
+                    mGotObscuredEvent = true;
+                }
+            }
+            return true;
+        }
+
+        boolean gotEvent() {
+            synchronized (this) {
+                return mGotEvent;
+            }
+        }
+
+        boolean gotObscuredTouch() {
+            synchronized (this) {
+                return mGotObscuredEvent;
+            }
+        }
+
+        void reset() {
+            synchronized (this) {
+                mGotEvent = false;
+                mGotObscuredEvent = false;
+            }
+        }
+    }
+    @Override
+    public void onCreate() {
+        mHandler = new Handler(Looper.getMainLooper());
+    }
+
+    @Nullable
+    @Override
+    public IBinder onBind(Intent intent) {
+        return mBinder.asBinder();
+    }
+
+    Display getDefaultDisplay() {
+        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
+        return wm.getDefaultDisplay();
+    }
+
+    SurfaceControlViewHost mSurfaceControlViewHost;
+    MotionRecordingView mView;
+
+    SurfaceControlViewHost.SurfacePackage createSurfacePackage(IBinder hostInputToken) {
+        mView = new MotionRecordingView(this);
+        mSurfaceControlViewHost = new SurfaceControlViewHost(this, getDefaultDisplay(), hostInputToken);
+        mSurfaceControlViewHost.setView(mView, 100, 100);
+        return mSurfaceControlViewHost.getSurfacePackage();
+    }
+
+    private class ServiceImpl extends ICrossProcessSurfaceControlViewHostTestService.Stub {
+        private final CrossProcessSurfaceControlViewHostTestService mService =
+            CrossProcessSurfaceControlViewHostTestService.this;
+
+        private void drainHandler() {
+            final CountDownLatch latch = new CountDownLatch(1);
+            mHandler.post(() -> {
+                latch.countDown();
+            });
+            try {
+                latch.await(1, TimeUnit.SECONDS);
+            } catch (Exception e) {
+            }
+        }
+
+        @Override
+        public SurfaceControlViewHost.SurfacePackage getSurfacePackage(IBinder hostInputToken) {
+            final CountDownLatch latch = new CountDownLatch(1);
+            mHandler.post(() -> {
+                createSurfacePackage(hostInputToken);
+                mView.getViewTreeObserver().registerFrameCommitCallback(latch::countDown);
+                mView.invalidate();
+            });
+            try {
+                latch.await(1, TimeUnit.SECONDS);
+            } catch (Exception e) {
+                return null;
+            }
+            return mSurfaceControlViewHost.getSurfacePackage();
+        }
+
+        @Override
+        public boolean getViewIsTouched() {
+            drainHandler();
+            return mView.gotEvent();
+        }
+
+        @Override
+        public boolean getViewIsTouchedAndObscured() {
+            return getViewIsTouched() && mView.gotObscuredTouch();
+        }
+
+        @Override
+        public void resetViewIsTouched() {
+            drainHandler();
+            mView.reset();
+        }
+    }
+}
diff --git a/tests/framework/base/windowmanager/shared/src/android/server/wm/shared/ICrossProcessSurfaceControlViewHostTestService.aidl b/tests/framework/base/windowmanager/shared/src/android/server/wm/shared/ICrossProcessSurfaceControlViewHostTestService.aidl
new file mode 100644
index 0000000..53d9910
--- /dev/null
+++ b/tests/framework/base/windowmanager/shared/src/android/server/wm/shared/ICrossProcessSurfaceControlViewHostTestService.aidl
@@ -0,0 +1,27 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.server.wm.shared;
+
+import android.os.IBinder;
+import android.view.SurfaceControlViewHost;
+
+interface ICrossProcessSurfaceControlViewHostTestService {
+    SurfaceControlViewHost.SurfacePackage getSurfacePackage(IBinder hostInputToken);
+    boolean getViewIsTouched();
+    boolean getViewIsTouchedAndObscured();
+    void resetViewIsTouched();
+}
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/SurfaceControlViewHostTests.java b/tests/framework/base/windowmanager/src/android/server/wm/SurfaceControlViewHostTests.java
index 567d058..55f6c34 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/SurfaceControlViewHostTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/SurfaceControlViewHostTests.java
@@ -28,8 +28,10 @@
 import android.app.Activity;
 import android.app.ActivityManager;
 import android.app.Instrumentation;
+import android.content.ComponentName;
 import android.content.Context;
 import android.content.pm.ActivityInfo;
+import android.content.Intent;
 import android.content.pm.ConfigurationInfo;
 import android.content.pm.FeatureInfo;
 import android.content.res.Configuration;
@@ -37,9 +39,11 @@
 import android.graphics.PixelFormat;
 import android.graphics.Rect;
 import android.graphics.Region;
+import android.os.Binder;
 import android.platform.test.annotations.Presubmit;
 import android.platform.test.annotations.RequiresDevice;
 import android.server.wm.ActivityManagerTestBase;
+import android.server.wm.scvh.Components;
 import android.util.ArrayMap;
 import android.view.Gravity;
 import android.view.MotionEvent;
@@ -53,6 +57,8 @@
 import android.widget.Button;
 import android.widget.FrameLayout;
 
+import android.server.wm.shared.ICrossProcessSurfaceControlViewHostTestService;
+
 import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.FlakyTest;
 import androidx.test.rule.ActivityTestRule;
@@ -61,8 +67,10 @@
 import com.android.compatibility.common.util.WidgetTestUtils;
 
 import org.junit.Before;
+import org.junit.After;
 import org.junit.Test;
 
+import java.util.Map;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicReference;
@@ -89,6 +97,14 @@
 
     private volatile boolean mClicked = false;
 
+    private SurfaceControlViewHost.SurfacePackage mRemoteSurfacePackage;
+
+    private final Map<String,
+        FutureConnection<ICrossProcessSurfaceControlViewHostTestService>> mConnections =
+            new ArrayMap<>();
+    private ICrossProcessSurfaceControlViewHostTestService mTestService = null;
+    private static final long TIMEOUT_MS = 3000L;
+
     /*
      * Configurable state to control how the surfaceCreated callback
      * will initialize the embedded view hierarchy.
@@ -104,17 +120,31 @@
         super.setUp();
         mClicked = false;
         mEmbeddedLayoutParams = null;
+        mRemoteSurfacePackage = null;
 
         mInstrumentation = InstrumentationRegistry.getInstrumentation();
         mActivity = mActivityRule.launchActivity(null);
         mInstrumentation.waitForIdleSync();
     }
 
+    @After
+    public void tearDown() throws Throwable {
+        for (FutureConnection<ICrossProcessSurfaceControlViewHostTestService> connection :
+                 mConnections.values()) {
+            mInstrumentation.getContext().unbindService(connection);
+        }
+        mConnections.clear();
+    }
+
     private void addSurfaceView(int width, int height) throws Throwable {
+        addSurfaceView(width, height, true);
+    }
+
+    private void addSurfaceView(int width, int height, boolean onTop) throws Throwable {
         mActivityRule.runOnUiThread(() -> {
             final FrameLayout content = new FrameLayout(mActivity);
             mSurfaceView = new SurfaceView(mActivity);
-            mSurfaceView.setZOrderOnTop(true);
+            mSurfaceView.setZOrderOnTop(onTop);
             content.addView(mSurfaceView, new FrameLayout.LayoutParams(
                 width, height, Gravity.LEFT | Gravity.TOP));
             mViewParent = content;
@@ -191,8 +221,18 @@
 
     @Override
     public void surfaceCreated(SurfaceHolder holder) {
-        addViewToSurfaceView(mSurfaceView, mEmbeddedView,
+        if (mTestService == null) {
+            addViewToSurfaceView(mSurfaceView, mEmbeddedView,
                 mEmbeddedViewWidth, mEmbeddedViewHeight);
+        } else if (mRemoteSurfacePackage == null) {
+            try {
+                mRemoteSurfacePackage = mTestService.getSurfacePackage(mSurfaceView.getHostToken());
+            } catch (Exception e) {
+            }
+            mSurfaceView.setChildSurfacePackage(mRemoteSurfacePackage);
+        } else {
+            mSurfaceView.setChildSurfacePackage(mRemoteSurfacePackage);
+        }
     }
 
     @Override
@@ -752,5 +792,87 @@
                              mSurfaceView.getResources().getConfiguration().orientation);
         });
     }
+
+    @Test
+    public void testEmbeddedViewReceivesInputOnBottom() throws Throwable {
+        mEmbeddedView = new Button(mActivity);
+        mEmbeddedView.setOnClickListener((View v) -> {
+            mClicked = true;
+        });
+
+        addSurfaceView(DEFAULT_SURFACE_VIEW_WIDTH, DEFAULT_SURFACE_VIEW_HEIGHT, false);
+        mInstrumentation.waitForIdleSync();
+        waitUntilEmbeddedViewDrawn();
+
+        // We should receive no input until we punch a hole
+        CtsTouchUtils.emulateTapOnViewCenter(mInstrumentation, mActivityRule, mSurfaceView);
+        mInstrumentation.waitForIdleSync();
+        assertFalse(mClicked);
+
+        mActivityRule.runOnUiThread(() -> {
+            mSurfaceView.getRootSurfaceControl().setTouchableRegion(new Region(0,0,1,1));
+        });
+        mInstrumentation.waitForIdleSync();
+
+        CtsTouchUtils.emulateTapOnViewCenter(mInstrumentation, mActivityRule, mSurfaceView);
+        mInstrumentation.waitForIdleSync();
+        assertTrue(mClicked);
+    }
+
+    private ICrossProcessSurfaceControlViewHostTestService getService() throws Exception {
+        return mConnections.computeIfAbsent("android.server.wm.scvh", this::connect).get(TIMEOUT_MS);
+    }
+
+    private static ComponentName repackage(String packageName, ComponentName baseComponent) {
+        return new ComponentName(packageName, baseComponent.getClassName());
+    }
+
+    private FutureConnection<ICrossProcessSurfaceControlViewHostTestService> connect(
+            String packageName) {
+        FutureConnection<ICrossProcessSurfaceControlViewHostTestService> connection =
+                new FutureConnection<>(
+                    ICrossProcessSurfaceControlViewHostTestService.Stub::asInterface);
+        Intent intent = new Intent();
+        intent.setComponent(repackage(packageName,
+            Components.CrossProcessSurfaceControlViewHostTestService.COMPONENT));
+        assertTrue(mInstrumentation.getContext().bindService(intent,
+            connection, Context.BIND_AUTO_CREATE));
+        return connection;
+    }
+
+    @Test
+    public void testHostInputTokenAllowsObscuredTouches() throws Throwable {
+        SurfaceControlViewHost.SurfacePackage p = null;
+
+        mTestService = getService();
+        assertTrue(mTestService != null);
+
+        addSurfaceView(DEFAULT_SURFACE_VIEW_WIDTH, DEFAULT_SURFACE_VIEW_HEIGHT, false);
+        mActivityRule.runOnUiThread(() -> {
+            mSurfaceView.getRootSurfaceControl().setTouchableRegion(new Region());
+        });
+        mInstrumentation.waitForIdleSync();
+        CtsTouchUtils.emulateTapOnViewCenter(mInstrumentation, mActivityRule, mSurfaceView);
+        mInstrumentation.waitForIdleSync();
+
+        assertTrue(mTestService.getViewIsTouchedAndObscured());
+    }
+
+    @Test
+    public void testNoHostInputTokenDisallowsObscuredTouches() throws Throwable {
+        mTestService = getService();
+        mRemoteSurfacePackage = mTestService.getSurfacePackage(new Binder());
+        assertTrue(mRemoteSurfacePackage != null);
+
+        addSurfaceView(DEFAULT_SURFACE_VIEW_WIDTH, DEFAULT_SURFACE_VIEW_HEIGHT, false);
+        mActivityRule.runOnUiThread(() -> {
+            mSurfaceView.getRootSurfaceControl().setTouchableRegion(new Region());
+        });
+        mInstrumentation.waitForIdleSync();
+        CtsTouchUtils.emulateTapOnViewCenter(mInstrumentation, mActivityRule, mSurfaceView);
+        mInstrumentation.waitForIdleSync();
+
+        assertFalse(mTestService.getViewIsTouched());
+    }
 }