diff --git a/.github/workflows/build_test_check.yml b/.github/workflows/build_test_check.yml index c9d25d4..f346c27 100644 --- a/.github/workflows/build_test_check.yml +++ b/.github/workflows/build_test_check.yml @@ -21,7 +21,7 @@ jobs: strategy: matrix: - projects: [ TwoPaneLayout, WindowState ] + projects: [ TwoPaneLayout, WindowState, ComposeTesting ] fail-fast: false steps: diff --git a/.github/workflows/publish_composetesting_ado.yml b/.github/workflows/publish_composetesting_ado.yml new file mode 100644 index 0000000..2b73928 --- /dev/null +++ b/.github/workflows/publish_composetesting_ado.yml @@ -0,0 +1,77 @@ +# This workflow will build a Java project with Gradle +# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle + +name: publish-ComposeTesting-ado +# This workflow builds and publishes in ADO the ComposeTesting Compose artifact. + +on: + push: + tags: + - 'composetesting*' + + workflow_dispatch: + inputs: + name: + description: 'Triggers publication to ADO - ComposeTesting Compose' + home: + description: 'location' + required: false + +jobs: + publish-ComposeTesting-ADO: + runs-on: ubuntu-latest + defaults: + run: + working-directory: ./ComposeTesting + + steps: + - uses: actions/checkout@v2 + + - name: Set up JDK 11 + uses: actions/setup-java@v1 + with: + java-version: 11 + + - name: Cache Gradle packages + uses: actions/cache@v2 + with: + path: ~/.gradle/caches + key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }} + restore-keys: ${{ runner.os }}-gradle + + # Base64 decodes and pipes the GPG key content into the secret file + - name: Prepare environment + env: + SIGNING_SECRET_KEY: ${{ secrets.SIGNING_SECRET_KEY }} + SIGNING_SECRET_FILE: ${{ secrets.SIGNING_SECRET_FILE }} + run: | + git fetch --unshallow + sudo bash -c "echo '$SIGNING_SECRET_KEY' | base64 -d > '$SIGNING_SECRET_FILE'" + - name: Grant execute permission for gradlew + run: chmod +x gradlew + + - name: clean + run: ./gradlew :library:clean --info + + # Builds the release artifacts of the library + - name: Release build + run: ./gradlew :library:assembleRelease + + # Generates other artifacts + - name: Source jar + run: ./gradlew :library:androidSourcesJar + + # Generates docs artifact + - name: Docs jar + run: ./gradlew :library:dokkaHtmlJar + + # Runs upload to ADO + - name: Publish to ADO + run: ./gradlew :library:publishSurfaceDuoComposePublicationToADORepository --max-workers 1 + env: + ADO_URL: ${{ secrets.ADO_URL }} + ADO_USER: ${{ secrets.ADO_USER }} + ADO_PASSWD: ${{ secrets.ADO_PASSWD }} + SIGNING_KEY_ID: ${{ secrets.SIGNING_KEY_ID }} + SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }} + SIGNING_SECRET_FILE: ${{ secrets.SIGNING_SECRET_FILE }} \ No newline at end of file diff --git a/.github/workflows/publish_composetesting_mavencentral.yml b/.github/workflows/publish_composetesting_mavencentral.yml new file mode 100644 index 0000000..550916b --- /dev/null +++ b/.github/workflows/publish_composetesting_mavencentral.yml @@ -0,0 +1,77 @@ +# This workflow will build a Java project with Gradle +# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle + +name: publish-ComposeTesting-mavencentral +# This workflow builds and publishes in Maven Central the ComposeTesting artifact. +# The final publishing step has to be done manually in Sonatype site. + +on: + push: + tags: + - 'composetesting*' + + workflow_dispatch: + inputs: + name: + description: 'Triggers publication to MavenCentral - ComposeTesting' + home: + description: 'location' + required: false + +jobs: + publish-ComposeTesting-MavenCentral: + runs-on: ubuntu-latest + defaults: + run: + working-directory: ./ComposeTesting + + steps: + - uses: actions/checkout@v2 + + - name: Set up JDK 11 + uses: actions/setup-java@v1 + with: + java-version: 11 + + - name: Cache Gradle packages + uses: actions/cache@v2 + with: + path: ~/.gradle/caches + key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }} + restore-keys: ${{ runner.os }}-gradle + + # Base64 decodes and pipes the GPG key content into the secret file + - name: Prepare environment + env: + SIGNING_SECRET_KEY: ${{ secrets.SIGNING_SECRET_KEY }} + SIGNING_SECRET_FILE: ${{ secrets.SIGNING_SECRET_FILE }} + run: | + git fetch --unshallow + sudo bash -c "echo '$SIGNING_SECRET_KEY' | base64 -d > '$SIGNING_SECRET_FILE'" + - name: Grant execute permission for gradlew + run: chmod +x gradlew + + - name: clean + run: ./gradlew :library:clean + + # Builds the release artifacts of the library + - name: Release build + run: ./gradlew :library:assembleRelease + + # Generates other artifacts + - name: Source jar + run: ./gradlew :library:androidSourcesJar + + # Generates docs artifact + - name: Docs jar + run: ./gradlew :library:dokkaHtmlJar + + # Runs upload to MavenCentral (final release step will be manually done in Sonatype site) + - name: Publish to MavenCentral + run: ./gradlew :library:publishSurfaceDuoComposePublicationToMavencentralRepository --max-workers 1 + env: + MAVEN_USER: ${{ secrets.MAVEN_USER }} + MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }} + SIGNING_KEY_ID: ${{ secrets.SIGNING_KEY_ID }} + SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }} + SIGNING_SECRET_FILE: ${{ secrets.SIGNING_SECRET_FILE }} \ No newline at end of file diff --git a/ComposeTesting/.gitignore b/ComposeTesting/.gitignore new file mode 100644 index 0000000..8ef8ef6 --- /dev/null +++ b/ComposeTesting/.gitignore @@ -0,0 +1,45 @@ +### Android template +# Built application files +*.apk +*.ap_ +*.aab + +# Files for the ART/Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ +release/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# IntelliJ +*.iml +.idea/ + +# Keystore files +# Uncomment the following lines if you do not want to check your keystore files in. +#*.jks +#*.keystore \ No newline at end of file diff --git a/ComposeTesting/README.md b/ComposeTesting/README.md new file mode 100644 index 0000000..5353936 --- /dev/null +++ b/ComposeTesting/README.md @@ -0,0 +1,195 @@ +# ComposeTesting - Surface Duo Compose SDK + +**ComposeTesting** provides some helper functions that help you easily test your application on the dual-screen, foldable and large screen devices, by simulating the foldingFeatures(fold/hinge), device gestures, screenshot comparing and zooming. + +## Add to your project + +1. Make sure you have **mavenCentral()** repository in your top level **build.gradle** or **settings.gradle** file: + + ```gradle + repositories { + google() + mavenCentral() + } + ``` + +2. Add dependencies to the module-level **build.gradle** file (current version may be different from what's shown here). + + ```gradle + implementation "com.microsoft.device.dualscreen.testing:testing-compose:1.0.0-alpha01" + ``` + +3. Also ensure the compileSdkVersion and targetSdkVersion are set to API 31 or newer in the module-level build.gradle file. + + ```gradle + android { + compileSdkVersion 31 + + defaultConfig { + targetSdkVersion 31 + } + ... + } + ``` + +4. Access the testing functions from **ComposeTesting** to test your application. Please refer to the [sample](https://github.com/microsoft/surface-duo-compose-sdk/tree/main/ComposeTesting/sample) for more details. + +## API reference + + +### FoldingFeature Helper + +These functions can be used in foldable UI tests to simulate the present of vertical and +horizontal foldingFeatures(folds/hinges). The foldingFeatures are simulated using TestWindowLayoutInfo, using the Google [Jetpack WindowManager Testing](https://developer.android.com/reference/androidx/window/testing/layout/package-summary) library. + +```kotlin +fun createWindowLayoutInfoPublisherRule(): TestRule +``` + +Return WindowLayoutInfoPublisherRule which allows you to simulate the different foldingFeature by pushing through different WindowLayoutInfo values. + +```kotlin +fun TestRule.simulateVerticalFoldingFeature( + composeTestRule: AndroidComposeTestRule, A>, + center: Int = -1, + size: Int = 0, + state: FoldingFeature.State = FoldingFeature.State.HALF_OPENED +) +``` + +Simulate a vertical foldingFeature in a Compose test + +```kotlin +fun TestRule.simulateHorizontalFoldingFeature( + composeTestRule: AndroidComposeTestRule, A>, + center: Int = -1, + size: Int = 0, + state: FoldingFeature.State = FoldingFeature.State.HALF_OPENED +) +``` + +Simulate a horizontal foldingFeature in a Compose test + +```kotlin +fun TestRule.simulateFoldingFeature( + composeTestRule: AndroidComposeTestRule, A>, + center: Int, + size: Int, + state: FoldingFeature.State, + orientation: FoldingFeature.Orientation, +) +``` + +Simulate a foldingFeature with the given properties in a Compose test + +### Swipe Helper + +These functions can be used in dual-screen UI tests to simulate swipe gestures that affect +app display. The swipes are simulated using UiDevice, and the coordinates are calculated based +on the display width/height of the testing device. They can be used only on dual-screen devices, not foldable devices or large screen devices. + +```kotlin +fun UiDevice.spanFromStart() +``` + +Span app from the top/left pane + +```kotlin +fun UiDevice.spanFromEnd() +``` + +Span app from the bottom/right pane + +```kotlin +fun UiDevice.unspanToStart() +``` + +Unspan app to the top/left pane + +```kotlin +fun UiDevice.unspanToEnd() +``` + +Unspan app to bottom/right pane + +```kotlin +fun UiDevice.switchToStart() +``` + +Switch app from bottom/right pane to top/left pane + +```kotlin +fun UiDevice.switchToEnd() +``` + +Switch app from top/left pane to bottom/right pane + +```kotlin +fun UiDevice.closeStart() +``` + +Close app from top/left pane + +```kotlin +fun UiDevice.closeEnd() +``` + +Close app from bottom/right pane + +### String Helper + +These functions can be used for string operations in UI tests to simplify testing code. + +```kotlin +fun AndroidComposeTestRule, A>.getString(@StringRes id: Int): String +``` + +Get resource string inside Compose test with resource id + +```kotlin +fun AndroidComposeTestRule, A>.getString(@StringRes id: Int, vararg formatArgs: Any): String +``` + +Get resource string inside Compose test with resource id and arguments + +### Zoom Helper + +These functions can be used to perform zooming gestures during Compose UI tests. + +```kotlin +fun TouchInjectionScope.zoomIn(pinchMillis: Long = PINCH_MILLIS) +``` + +Performs a zoom in gesture (swipes start towards center then move outwards) + +```kotlin +fun TouchInjectionScope.zoomOut(pinchMillis: Long = PINCH_MILLIS) +``` + +Performs a zoom out gesture (swipes start towards center then move outwards) + +## Contributing + +This project welcomes contributions and suggestions. Most contributions require you to agree to a +Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us +the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. + +When you submit a pull request, a CLA bot will automatically determine whether you need to provide +a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions +provided by the bot. You will only need to do this once across all repos using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or +contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. + +## License + +Copyright (c) Microsoft Corporation. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/ComposeTesting/build.gradle b/ComposeTesting/build.gradle new file mode 100644 index 0000000..f959f95 --- /dev/null +++ b/ComposeTesting/build.gradle @@ -0,0 +1,41 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. +buildscript { + apply from: 'dependencies.gradle' + + repositories { + google() + mavenCentral() + } + + dependencies { + classpath config.gradlePlugin + classpath config.kotlinGradlePlugin + classpath dokkaDependencies.dokkaGradlePlugin + } +} + +allprojects { + repositories { + google() + mavenCentral() + } + apply from: "$rootDir/ktlint.gradle" +} + +task clean(type: Delete) { + delete rootProject.buildDir +} + +// Used to get the value of a local property or if not found the value that could +// be stored in the repo settings as a token. +String getPropertyValue(String property) { + def localPropertyFound = project.hasProperty(property) + def envProperty = System.getenv(property) + if (localPropertyFound) { + return project.getProperties().get(property) + } else if (envProperty != null) { + return envProperty + } else { + return "NO_VALUE" + } +} \ No newline at end of file diff --git a/ComposeTesting/dependencies.gradle b/ComposeTesting/dependencies.gradle new file mode 100644 index 0000000..4ff39ed --- /dev/null +++ b/ComposeTesting/dependencies.gradle @@ -0,0 +1,99 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + +ext { + + //---- Important ------------------- + // We have to update following versionName and versionCode groups in order to + // publish correctly a new version of each of our libraries. + // e.g. ComposeTesting library, you could have as a current version + // 1.0.0-beta1, if you want to publish a new version you will have to increase in one the + //composeTestingVersionCode and to bump the composeTestingVersionName. + + // ComposeTesting library version code: + // If you want to publish a new version, bump in one (1) the specific line(s) + composeTestingVersionCode = 1 + + // ComposeTesting library version name: + // If you want to publish a new version, bump the specific line + composeTestingVersionName = '1.0.0-alpha01' + + // ---------------------------------- + + gradlePluginVersion = '7.1.0' + kotlinVersion = "1.6.10" + compileSdkVersion = 31 + targetSdkVersion = compileSdkVersion + minSdkVersion = 23 + dokkaVersion = "1.6.0" + + config = [ + gradlePlugin : "com.android.tools.build:gradle:$gradlePluginVersion", + kotlinGradlePlugin : "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion", + testInstrumentationRunner: "androidx.test.runner.AndroidJUnitRunner" + ] + + kotlinDependencies = [ + kotlinStdlib: "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion" + ] + + dokkaDependencies = [ + dokkaGradlePlugin: "org.jetbrains.dokka:dokka-gradle-plugin:$dokkaVersion" + ] + + // AndroidX dependencies + appCompatVersion = '1.4.1' + ktxCoreVersion = '1.7.0' + androidxDependencies = [ + appCompat : "androidx.appcompat:appcompat:$appCompatVersion", + ktxCore : "androidx.core:core-ktx:$ktxCoreVersion", + ] + + // Compose dependencies + composeVersion = "1.1.0-rc03" + activityComposeVersion = "1.4.0" + navigationComposeVersion = "2.4.0" + composeDependencies = [ + composeMaterial : "androidx.compose.material:material:$composeVersion", + composeRuntime : "androidx.compose.runtime:runtime-livedata:$composeVersion", + composeUI : "androidx.compose.ui:ui:$composeVersion", + composeUITooling : "androidx.compose.ui:ui-tooling:$composeVersion", + activityCompose : "androidx.activity:activity-compose:$activityComposeVersion", + navigationCompose : "androidx.navigation:navigation-compose:$navigationComposeVersion" + ] + + // Testing versions + windowVersion = "1.0.0" + androidxTestVersion = "1.3.0" + uiAutomatorVersion = "2.2.0" + espressoVersion = "3.4.0" + junitVersion = "4.12" + mockitoVersion = "4.1.0" + testDependencies = [ + androidxTestCore : "androidx.test:core:$androidxTestVersion", + androidxTestRules : "androidx.test:rules:$androidxTestVersion", + androidxTestRunner : "androidx.test:runner:$androidxTestVersion", + composeUITest : "androidx.compose.ui:ui-test:$composeVersion", + composeJunit : "androidx.compose.ui:ui-test-junit4:$composeVersion", + composeUITestManifest : "androidx.compose.ui:ui-test-manifest:$composeVersion", + uiAutomator : "androidx.test.uiautomator:uiautomator:$uiAutomatorVersion", + windowTest : "androidx.window:window-testing:$windowVersion", + espressoCore : "androidx.test.espresso:espresso-core:$espressoVersion", + androidJunit : "junit:junit:$junitVersion", + mockitoCore : "org.mockito:mockito-core:$mockitoVersion", + ] + + // Google dependencies + materialVersion = "1.5.0" + googleDependencies = [ + material: "com.google.android.material:material:$materialVersion" + ] + + // Microsoft dependencies + twoPaneLayoutVersion = "1.0.0-alpha10" + microsoftDependencies = [ + twoPaneLayout: "com.microsoft.device.dualscreen:twopanelayout:$twoPaneLayoutVersion", + ] +} diff --git a/ComposeTesting/gradle.properties b/ComposeTesting/gradle.properties new file mode 100644 index 0000000..cd0519b --- /dev/null +++ b/ComposeTesting/gradle.properties @@ -0,0 +1,23 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app"s APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true +# Kotlin code style for this project: "official" or "obsolete": +kotlin.code.style=official +# Enables namespacing of each library's R class so that its R class includes only the +# resources declared in the library itself and none from the library's dependencies, +# thereby reducing the size of the R class for that library +android.nonTransitiveRClass=true \ No newline at end of file diff --git a/ComposeTesting/gradle/wrapper/gradle-wrapper.jar b/ComposeTesting/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e708b1c Binary files /dev/null and b/ComposeTesting/gradle/wrapper/gradle-wrapper.jar differ diff --git a/ComposeTesting/gradle/wrapper/gradle-wrapper.properties b/ComposeTesting/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..4473512 --- /dev/null +++ b/ComposeTesting/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Fri Jan 28 10:29:08 PST 2022 +distributionBase=GRADLE_USER_HOME +distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-all.zip +distributionPath=wrapper/dists +zipStorePath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME diff --git a/ComposeTesting/gradlew b/ComposeTesting/gradlew new file mode 100755 index 0000000..4f906e0 --- /dev/null +++ b/ComposeTesting/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# 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 +# +# https://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. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/ComposeTesting/gradlew.bat b/ComposeTesting/gradlew.bat new file mode 100644 index 0000000..ac1b06f --- /dev/null +++ b/ComposeTesting/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/ComposeTesting/ktlint.gradle b/ComposeTesting/ktlint.gradle new file mode 100644 index 0000000..1ef63bf --- /dev/null +++ b/ComposeTesting/ktlint.gradle @@ -0,0 +1,33 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + +repositories { + mavenCentral() +} + +configurations { + ktlint +} + +dependencies { + ktlint "com.pinterest:ktlint:0.40.0" +} + +task ktlint(type: JavaExec, group: "verification") { + description = "Check Kotlin code style." + classpath = configurations.ktlint + mainClass.set("com.pinterest.ktlint.Main") + args "src/**/*.kt" + // to generate report in checkstyle format prepend following args: + // "--reporter=plain", "--reporter=checkstyle,output=${buildDir}/ktlint.xml" + // see https://github.com/pinterest/ktlint#usage for more +} + +task ktlintFormat(type: JavaExec, group: "formatting") { + description = "Fix Kotlin code style deviations." + classpath = configurations.ktlint + mainClass.set("com.pinterest.ktlint.Main") + args "-F", "src/**/*.kt" +} diff --git a/ComposeTesting/library/.gitignore b/ComposeTesting/library/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/ComposeTesting/library/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/ComposeTesting/library/build.gradle b/ComposeTesting/library/build.gradle new file mode 100644 index 0000000..76ff8ea --- /dev/null +++ b/ComposeTesting/library/build.gradle @@ -0,0 +1,66 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + +apply plugin: 'com.android.library' +apply plugin: 'kotlin-android' + +//Artifact publication data +ext { + PUBLISH_GROUP_ID = 'com.microsoft.device.dualscreen.testing' + PUBLISH_ARTIFACT_ID = 'testing-compose' + LIBRARY_DESCRIPTION = 'ComposeTesting library' + LIBRARY_VERSION = rootProject.ext.composeTestingVersionName +} +apply from: "${rootProject.projectDir}/publishing.gradle" + +android { + compileSdkVersion rootProject.ext.compileSdkVersion + + defaultConfig { + minSdkVersion rootProject.ext.minSdkVersion + targetSdkVersion rootProject.ext.targetSdkVersion + testInstrumentationRunner rootProject.ext.config.testInstrumentationRunner + vectorDrawables { + useSupportLibrary true + } + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + kotlinOptions { + jvmTarget = '1.8' + } + + buildFeatures { + compose true + } + + composeOptions { + kotlinCompilerExtensionVersion composeVersion + } + + packagingOptions { + resources { + excludes += ['META-INF/LGPL2.1', 'META-INF/AL2.0'] + } + } +} + +dependencies { + implementation testDependencies.composeJunit + implementation testDependencies.windowTest + implementation testDependencies.uiAutomator + implementation androidxDependencies.ktxCore +} diff --git a/ComposeTesting/library/consumer-rules.pro b/ComposeTesting/library/consumer-rules.pro new file mode 100644 index 0000000..e69de29 diff --git a/ComposeTesting/library/proguard-rules.pro b/ComposeTesting/library/proguard-rules.pro new file mode 100644 index 0000000..481bb43 --- /dev/null +++ b/ComposeTesting/library/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/ComposeTesting/library/src/main/AndroidManifest.xml b/ComposeTesting/library/src/main/AndroidManifest.xml new file mode 100644 index 0000000..3b57c8e --- /dev/null +++ b/ComposeTesting/library/src/main/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + \ No newline at end of file diff --git a/ComposeTesting/library/src/main/java/com/microsoft/device/dualscreen/testing/DeviceModel.kt b/ComposeTesting/library/src/main/java/com/microsoft/device/dualscreen/testing/DeviceModel.kt new file mode 100644 index 0000000..aeab10f --- /dev/null +++ b/ComposeTesting/library/src/main/java/com/microsoft/device/dualscreen/testing/DeviceModel.kt @@ -0,0 +1,112 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + +package com.microsoft.device.dualscreen.testing + +import android.util.Log +import android.view.Surface +import androidx.test.uiautomator.UiDevice + +/** + * DEVICE MODEL + * ----------------------------------------------------------------------------------------------- + * The DeviceModel class and related helper functions can be used in dualscreen UI tests to help + * calculate coordinates for simulated swipe gestures. Device properties are determined using + * UiDevice. + */ + +/** + * Enum class that can be used to represent various device models and extract coordinates that can be used for + * simulating gestures in UI tests + * + * For Microsoft Surface Duo devices, the coordinates are all from the dual portrait point of view, and dimensions + * were taken from here: https://docs.microsoft.com /dual-screen/android/surface-duo-dimensions + * + * @param paneWidth: width of device panes in pixels in dual portrait mode (assumed to have panes of equal size) + * @param paneHeight: height of device panes in pixels in dual portrait mode (assumed to have panes of equal size) + * @param foldWidth: width of device foldingFeature in pixels in dual portrait mode + * @param leftX: x-coordinate of the center of the left pane in dual portrait mode + * @param rightX: x-coordinate of the center of the right pane in dual portrait mode + * @param middleX: x-coordinate of the center of the device in dual portrait mode + * @param middleY: y-coordinate of the center of the device in dual portrait mode + * @param bottomY: y-coordinate of the bottom of the device in dual portrait mode + * @param spanSteps: number of move steps to take when executing a span gesture, where one step takes ~ 5ms + * @param unspanSteps: number of move steps to take when executing a unspan gesture, where one step takes ~ 5ms + * @param switchSteps: number of move steps to take when executing a switch gesture, where one step takes ~ 5ms + * @param closeSteps: number of move steps to take when executing a close gesture, where one step takes ~ 5ms + */ +enum class DeviceModel( + val paneWidth: Int, + val paneHeight: Int, + val foldWidth: Int, + val leftX: Int = paneWidth / 2, + val rightX: Int = leftX + paneWidth + foldWidth, + val middleX: Int = paneWidth + foldWidth / 2, + val middleY: Int = paneHeight / 2, + val bottomY: Int, + val spanSteps: Int = 400, + val unspanSteps: Int = 200, + val switchSteps: Int = 100, + val closeSteps: Int = 50, +) { + SurfaceDuo(paneWidth = 1350, paneHeight = 1800, foldWidth = 84, bottomY = 1780), + SurfaceDuo2(paneWidth = 1344, paneHeight = 1892, foldWidth = 66, bottomY = 1870), + Other(paneWidth = 0, paneHeight = 0, foldWidth = 0, bottomY = 0); + + override fun toString(): String { + return "$name [leftX: $leftX rightX: $rightX middleX: $middleX middleY: $middleY bottomY: $bottomY]" + } +} + +/** + * Checks whether a device is a Surface Duo model + */ +fun UiDevice.isSurfaceDuo(): Boolean { + val model = getDeviceModel() + return model == DeviceModel.SurfaceDuo || model == DeviceModel.SurfaceDuo2 +} + +/** + * Returns a pixel value of the hinge/fold size of a foldable or dual-screen device + */ +fun UiDevice.getFoldSize(): Int { + return getDeviceModel().foldWidth +} + +/** + * Returns the model of a device based on display width and height (in pixels) + */ +fun UiDevice.getDeviceModel(): DeviceModel { + Log.d( + "DeviceModel", + "w: $displayWidth h: $displayHeight rotation: $displayRotation" + ) + + return when (displayRotation) { + Surface.ROTATION_0, Surface.ROTATION_180 -> getModelFromPaneWidth(displayWidth) + Surface.ROTATION_90, Surface.ROTATION_270 -> getModelFromPaneWidth(displayHeight) + else -> throw Error("Unknown rotation state $displayRotation") + } +} + +/** + * Helper method to compare the pane width of a device to the pane widths of the defined device + * models + * + * @param paneWidth: pane width in pixels + */ +private fun UiDevice.getModelFromPaneWidth(paneWidth: Int): DeviceModel { + for (model in DeviceModel.values()) { + // pane width could be the width of a single pane, or the width of two panes + the width + // of the hinge + if (paneWidth == model.paneWidth || paneWidth == model.paneWidth * 2 + model.foldWidth) + return model + } + Log.d( + "DeviceModel", + "Unknown dualscreen device dimensions $displayWidth $displayHeight" + ) + return DeviceModel.Other +} diff --git a/ComposeTesting/library/src/main/java/com/microsoft/device/dualscreen/testing/FoldingFeatureHelper.kt b/ComposeTesting/library/src/main/java/com/microsoft/device/dualscreen/testing/FoldingFeatureHelper.kt new file mode 100644 index 0000000..0096e7d --- /dev/null +++ b/ComposeTesting/library/src/main/java/com/microsoft/device/dualscreen/testing/FoldingFeatureHelper.kt @@ -0,0 +1,151 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + +package com.microsoft.device.dualscreen.testing + +import androidx.activity.ComponentActivity +import androidx.compose.ui.test.junit4.AndroidComposeTestRule +import androidx.test.ext.junit.rules.ActivityScenarioRule +import androidx.window.layout.FoldingFeature +import androidx.window.testing.layout.FoldingFeature +import androidx.window.testing.layout.TestWindowLayoutInfo +import androidx.window.testing.layout.WindowLayoutInfoPublisherRule +import org.junit.rules.TestRule +import java.lang.ClassCastException + +/** + * FOLDINGFEATURE HELPER + * ----------------------------------------------------------------------------------------------- + * These functions can be used in foldable UI tests to simulate the present of vertical and + * horizontal foldingFeatures(folds/hinges). The foldingFeatures are simulated using TestWindowLayoutInfo. + */ + +/** + * Return WindowLayoutInfoPublisherRule which allows you to push through different WindowLayoutInfo + * values on demand from Window.testing to test + * + */ +fun createWindowLayoutInfoPublisherRule(): TestRule { + return WindowLayoutInfoPublisherRule() +} + +/** + * Simulate a vertical foldingFeature in a Compose test + * + * @param composeTestRule: Compose android test rule + * @param center: location of center of foldingFeature + * @param size: size of foldingFeature + * @param state: state of foldingFeature + */ +fun TestRule.simulateVerticalFoldingFeature( + composeTestRule: AndroidComposeTestRule, A>, + center: Int = -1, + size: Int = 0, + state: FoldingFeature.State = FoldingFeature.State.HALF_OPENED +) { + simulateVerticalFoldingFeature(composeTestRule.activityRule, center, size, state) +} + +/** + * Simulate a horizontal foldingFeature in a Compose test + * + * @param composeTestRule: Compose android test rule + * @param center: location of center of foldingFeature + * @param size: size of foldingFeature + * @param state: state of foldingFeature + */ +fun TestRule.simulateHorizontalFoldingFeature( + composeTestRule: AndroidComposeTestRule, A>, + center: Int = -1, + size: Int = 0, + state: FoldingFeature.State = FoldingFeature.State.HALF_OPENED +) { + simulateHorizontalFoldingFeature(composeTestRule.activityRule, center, size, state) +} + +/** + * Simulate a foldingFeature with the given properties in a Compose test + * + * @param composeTestRule: Compose android test rule + * @param center: location of center of foldingFeature + * @param size: size of foldingFeature + * @param state: state of foldingFeature + * @param orientation: orientation of foldingFeature + */ +fun TestRule.simulateFoldingFeature( + composeTestRule: AndroidComposeTestRule, A>, + center: Int, + size: Int, + state: FoldingFeature.State, + orientation: FoldingFeature.Orientation, +) { + simulateFoldingFeature(composeTestRule.activityRule, center, size, state, orientation) +} + +/** + * Simulate a vertical foldingFeature + * + * @param activityRule: test activity rule + * @param center: location of center of foldingFeature + * @param size: size of foldingFeature + * @param state: state of foldingFeature + */ +private fun TestRule.simulateVerticalFoldingFeature( + activityRule: ActivityScenarioRule, + center: Int = -1, + size: Int = 0, + state: FoldingFeature.State = FoldingFeature.State.HALF_OPENED +) { + simulateFoldingFeature(activityRule, center, size, state, FoldingFeature.Orientation.VERTICAL) +} + +/** + * Simulate a horizontal foldingFeature + * + * @param activityRule: test activity rule + * @param center: location of center of foldingFeature + * @param size: size of foldingFeature + * @param state: state of foldingFeature + */ +private fun TestRule.simulateHorizontalFoldingFeature( + activityRule: ActivityScenarioRule, + center: Int = -1, + size: Int = 0, + state: FoldingFeature.State = FoldingFeature.State.HALF_OPENED +) { + simulateFoldingFeature(activityRule, center, size, state, FoldingFeature.Orientation.HORIZONTAL) +} + +/** + * Simulate a foldingFeature with the given properties + * + * @param activityRule: test activity rule + * @param center: location of center of foldingFeature + * @param size: size of foldingFeature + * @param state: state of foldingFeature + * @param orientation: orientation of foldingFeature + */ +private fun TestRule.simulateFoldingFeature( + activityRule: ActivityScenarioRule, + center: Int, + size: Int, + state: FoldingFeature.State, + orientation: FoldingFeature.Orientation, +) { + this as? WindowLayoutInfoPublisherRule + ?: throw ClassCastException("Test rule is not of type WindowLayoutInfoPublisherRule") + + activityRule.scenario.onActivity { activity -> + val foldingFeature = FoldingFeature( + activity = activity, + center = center, + state = state, + size = size, + orientation = orientation + ) + val windowLayoutInfo = TestWindowLayoutInfo(listOf(foldingFeature)) + overrideWindowLayoutInfo(windowLayoutInfo) + } +} diff --git a/ComposeTesting/library/src/main/java/com/microsoft/device/dualscreen/testing/ScreenshotComparator.kt b/ComposeTesting/library/src/main/java/com/microsoft/device/dualscreen/testing/ScreenshotComparator.kt new file mode 100644 index 0000000..7b877df --- /dev/null +++ b/ComposeTesting/library/src/main/java/com/microsoft/device/dualscreen/testing/ScreenshotComparator.kt @@ -0,0 +1,140 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + +package com.microsoft.device.dualscreen.testing + +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.os.Build +import android.util.Log +import androidx.annotation.RequiresApi +import androidx.compose.ui.graphics.asAndroidBitmap +import androidx.compose.ui.test.SemanticsNodeInteraction +import androidx.compose.ui.test.captureToImage +import androidx.core.graphics.toColor +import androidx.test.platform.app.InstrumentationRegistry +import java.io.FileOutputStream +import kotlin.math.abs + +/** + * SCREENSHOT COMPARATOR + * ----------------------------------------------------------------------------------------------- + * These functions can be used to take, save, and compare screenshots of Composables in UI tests. + * + * Based on ScreenshotComparator.kt in the TestingCodelab project from the official Jetpack Compose codelab samples + * https://github.com/googlecodelabs/android-compose-codelabs/blob/main/TestingCodelab/app/src/androidTest/java/com/example/compose/rally/ScreenshotComparator.kt + */ + +/** + * Check whether a screenshot of the current node matches the reference image + * + * @param referenceAsset: name of reference image (must be stored in the androidTest/assets folder) + * @param node: Semantics Node to take screenshot of + */ +@RequiresApi(Build.VERSION_CODES.O) +fun assertScreenshotMatchesReference( + referenceAsset: String, + node: SemanticsNodeInteraction +) { + // Capture screenshot of composable + val bitmap = node.captureToImage().asAndroidBitmap() + + // Load reference screenshot from instrumentation test assets + val referenceBitmap = InstrumentationRegistry.getInstrumentation().context.resources.assets.open(referenceAsset) + .use { BitmapFactory.decodeStream(it) } + + // Compare bitmaps + assert(referenceBitmap.compare(bitmap)) +} + +/** + * Saves a screenshot of the current node to the device's internal storage - screenshots can be + * retrieved via adb tool + * + * @param filename: filename (including extension) of the screenshot + * @param node: Semantics Node to take screenshot of + */ +@RequiresApi(Build.VERSION_CODES.O) +fun saveScreenshotToDevice(filename: String, node: SemanticsNodeInteraction) { + // Capture screenshot of composable + val bmp = node.captureToImage().asAndroidBitmap() + + // Get path for saving file + val path = InstrumentationRegistry.getInstrumentation().targetContext.filesDir.canonicalPath + + // Compress bitmap and send to file + FileOutputStream("$path/$filename").use { out -> + bmp.compress(Bitmap.CompressFormat.PNG, 100, out) + } + + Log.d("Screenshot Comparator", "Saved screenshot to $path/$filename") +} + +/** + * Checks whether two bitmaps are the same based on the content and size + * + * @param other: Bitmap to compare to + * @return true if the bitmap size and content match, false otherwise + */ +@RequiresApi(Build.VERSION_CODES.O) +fun Bitmap.compare(other: Bitmap): Boolean { + if (this.width != other.width || this.height != other.height) { + return false + } + // Compare row by row to save memory on device + val row1 = IntArray(width) + val row2 = IntArray(width) + + for (column in 0 until height) { + // Read one row per bitmap and compare + this.getRow(row1, column) + other.getRow(row2, column) + if (!row1.contentEquals(row2)) { + throw AssertionError("Sizes match but bitmap content has differences") + } + } + return true +} + +/** + * Checks whether two colors (represented by integer values) are similar + * + * @param other: Color integer to compare to + * @return true if all color components are within 0.5% of the original, false otherwise + */ +@RequiresApi(Build.VERSION_CODES.O) +private fun Int.isSimilarColor(other: Int): Boolean { + // Convert ints to color values + val expectedColor = this.toColor() + val actualColor = other.toColor() + + // Compare individual color components + val expectedComponents = expectedColor.components + val actualComponents = actualColor.components + + // Check that color components have equal sizes + if (expectedComponents.size != actualComponents.size) { + return false + } + + // Check that each color component is similar (within +/- 0.5%) + val percentError = 0.005 + expectedComponents.forEachIndexed { index, comp -> + // Calculate the error allowance for the color component + val maxColorVal = expectedColor.colorSpace.getMaxValue(index) + val minColorVal = expectedColor.colorSpace.getMinValue(index) + val errorAllowance = percentError * (maxColorVal - minColorVal) + + // Compare color component values + if (abs(actualComponents[index] - comp) > errorAllowance) { + return false + } + } + return true +} + +private fun Bitmap.getRow(pixels: IntArray, column: Int) { + this.getPixels(pixels, 0, width, 0, column, width, 1) +} diff --git a/ComposeTesting/library/src/main/java/com/microsoft/device/dualscreen/testing/StringHelper.kt b/ComposeTesting/library/src/main/java/com/microsoft/device/dualscreen/testing/StringHelper.kt new file mode 100644 index 0000000..f209c20 --- /dev/null +++ b/ComposeTesting/library/src/main/java/com/microsoft/device/dualscreen/testing/StringHelper.kt @@ -0,0 +1,36 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + +package com.microsoft.device.dualscreen.testing + +import androidx.activity.ComponentActivity +import androidx.annotation.StringRes +import androidx.compose.ui.test.junit4.AndroidComposeTestRule +import androidx.test.ext.junit.rules.ActivityScenarioRule + +/** + * STRING HELPER + * ----------------------------------------------------------------------------------------------- + * These functions can be used for string operations in UI tests to simplify testing code. + */ + +/** + * Get resource string inside Compose test with resource id + * + * @param id: string resource id + */ +fun AndroidComposeTestRule, A>.getString(@StringRes id: Int): String { + return activity.getString(id) +} + +/** + * Get resource string inside Compose test with resource id and arguments + * + * @param id: string resource id + * @param formatArgs: arguments to string + */ +fun AndroidComposeTestRule, A>.getString(@StringRes id: Int, vararg formatArgs: Any): String { + return activity.getString(id, *formatArgs) +} diff --git a/ComposeTesting/library/src/main/java/com/microsoft/device/dualscreen/testing/SwipeHelper.kt b/ComposeTesting/library/src/main/java/com/microsoft/device/dualscreen/testing/SwipeHelper.kt new file mode 100644 index 0000000..79c13f0 --- /dev/null +++ b/ComposeTesting/library/src/main/java/com/microsoft/device/dualscreen/testing/SwipeHelper.kt @@ -0,0 +1,172 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + +package com.microsoft.device.dualscreen.testing + +import android.view.Surface +import androidx.test.uiautomator.UiDevice + +/** + * SWIPE HELPER + * ----------------------------------------------------------------------------------------------- + * These functions can be used in dualscreen UI tests to simulate swipe gestures that affect + * app display. The swipes are simulated using UiDevice, and the coordinates are calculated based + * on the display width/height of the testing device (see DeviceModel.kt). + * + * Available gestures: + * - span (display app in two panes) + * - unspan (display app in one pane) + * - close (close app) + * - switch (switch app from one pane to the other) + */ + +/** + * Helper method that sets up/cleans up a dualscreen swipe operation for automated testing + * (freezes rotation, retrieves device model, performs swipe, unfreezes rotation) + */ +private fun UiDevice.dualscreenSwipeWrapper(swipe: (DeviceModel) -> Boolean) { + freezeRotation() + + val model = getDeviceModel() + swipe(model) + + unfreezeRotation() +} + +/** + * Span app from the top/left pane + */ +fun UiDevice.spanFromStart() { + dualscreenSwipeWrapper { model -> + when (displayRotation) { + Surface.ROTATION_0, Surface.ROTATION_180 -> + swipe(model.leftX, model.bottomY, model.middleX, model.middleY, model.spanSteps) + Surface.ROTATION_270 -> + swipe(model.bottomY, model.leftX, model.middleY, model.middleX, model.spanSteps) + Surface.ROTATION_90 -> + swipe(model.bottomY, model.leftX, model.middleY, model.middleX, model.spanSteps) + else -> throw Error("Unknown rotation state $displayRotation") + } + } +} + +/** + * Span app from the bottom/right pane + */ +fun UiDevice.spanFromEnd() { + dualscreenSwipeWrapper { model -> + when (displayRotation) { + Surface.ROTATION_0, Surface.ROTATION_180 -> + swipe(model.rightX, model.bottomY, model.middleX, model.middleY, model.spanSteps) + Surface.ROTATION_270 -> + swipe(model.bottomY, model.rightX, model.middleY, model.middleX, model.spanSteps) + Surface.ROTATION_90 -> + swipe(model.bottomY, model.rightX, model.middleY, model.middleX, model.spanSteps) + else -> throw Error("Unknown rotation state $displayRotation") + } + } +} + +/** + * Unspan app to the top/left pane + */ +fun UiDevice.unspanToStart() { + dualscreenSwipeWrapper { model -> + when (displayRotation) { + Surface.ROTATION_0, Surface.ROTATION_180 -> + swipe(model.rightX, model.bottomY, model.leftX, model.middleY, model.unspanSteps) + Surface.ROTATION_270 -> + swipe(model.bottomY, model.rightX, model.middleY, model.leftX, model.unspanSteps) + Surface.ROTATION_90 -> + swipe(model.bottomY, model.rightX, model.middleY, model.leftX, model.unspanSteps) + else -> throw Error("Unknown rotation state $displayRotation") + } + } +} + +/** + * Unspan app to bottom/right pane + */ +fun UiDevice.unspanToEnd() { + dualscreenSwipeWrapper { model -> + when (displayRotation) { + Surface.ROTATION_0, Surface.ROTATION_180 -> + swipe(model.leftX, model.bottomY, model.rightX, model.middleY, model.unspanSteps) + Surface.ROTATION_270 -> + swipe(model.bottomY, model.leftX, model.middleY, model.rightX, model.unspanSteps) + Surface.ROTATION_90 -> + swipe(model.bottomY, model.leftX, model.middleY, model.rightX, model.unspanSteps) + else -> throw Error("Unknown rotation state $displayRotation") + } + } +} + +/** + * Switch app from bottom/right pane to top/left pane + */ +fun UiDevice.switchToStart() { + dualscreenSwipeWrapper { model -> + when (displayRotation) { + Surface.ROTATION_0, Surface.ROTATION_180 -> + swipe(model.rightX, model.bottomY, model.leftX, model.middleY, model.switchSteps) + Surface.ROTATION_270 -> + swipe(model.bottomY, model.rightX, model.middleY, model.leftX, model.switchSteps) + Surface.ROTATION_90 -> + swipe(model.bottomY, model.rightX, model.middleY, model.leftX, model.switchSteps) + else -> throw Error("Unknown rotation state $displayRotation") + } + } +} + +/** + * Switch app from top/left pane to bottom/right pane + */ +fun UiDevice.switchToEnd() { + dualscreenSwipeWrapper { model -> + when (displayRotation) { + Surface.ROTATION_0, Surface.ROTATION_180 -> + swipe(model.leftX, model.bottomY, model.rightX, model.middleY, model.switchSteps) + Surface.ROTATION_270 -> + swipe(model.bottomY, model.leftX, model.middleY, model.rightX, model.switchSteps) + Surface.ROTATION_90 -> + swipe(model.bottomY, model.leftX, model.middleY, model.rightX, model.switchSteps) + else -> throw Error("Unknown rotation state $displayRotation") + } + } +} + +/** + * Close app from top/left pane + */ +fun UiDevice.closeStart() { + dualscreenSwipeWrapper { model -> + when (displayRotation) { + Surface.ROTATION_0, Surface.ROTATION_180 -> + swipe(model.leftX, model.bottomY, model.leftX, model.middleY, model.closeSteps) + Surface.ROTATION_270 -> + swipe(model.bottomY, model.leftX, model.middleY, model.leftX, model.closeSteps) + Surface.ROTATION_90 -> + swipe(model.bottomY, model.leftX, model.middleY, model.leftX, model.closeSteps) + else -> throw Error("Unknown rotation state $displayRotation") + } + } +} + +/** + * Close app from bottom/right pane + */ +fun UiDevice.closeEnd() { + dualscreenSwipeWrapper { model -> + when (displayRotation) { + Surface.ROTATION_0, Surface.ROTATION_180 -> + swipe(model.rightX, model.bottomY, model.rightX, model.middleY, model.closeSteps) + Surface.ROTATION_270 -> + swipe(model.bottomY, model.rightX, model.middleY, model.rightX, model.closeSteps) + Surface.ROTATION_90 -> + swipe(model.bottomY, model.rightX, model.middleY, model.rightX, model.closeSteps) + else -> throw Error("Unknown rotation state $displayRotation") + } + } +} diff --git a/ComposeTesting/library/src/main/java/com/microsoft/device/dualscreen/testing/ZoomCoordinates.kt b/ComposeTesting/library/src/main/java/com/microsoft/device/dualscreen/testing/ZoomCoordinates.kt new file mode 100644 index 0000000..8ac94b0 --- /dev/null +++ b/ComposeTesting/library/src/main/java/com/microsoft/device/dualscreen/testing/ZoomCoordinates.kt @@ -0,0 +1,27 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + +package com.microsoft.device.dualscreen.testing + +import androidx.compose.ui.geometry.Offset + +/** + * Stores pinch start and end coordinates in order to simulate a zooming gesture + * + * @param leftOuter: outer value (closer to edge of screen/zero) for the left finger + * @param leftInner: inner value (closer to center of screen/max width) for the left finger + * @param rightOuter: outer value (closer to edge of screen/max width) for the right finger + * @param rightInner: inner value (closer to center of screen/zero) for the right finger + */ +data class ZoomCoordinates( + val leftOuter: Offset, + val leftInner: Offset, + val rightInner: Offset, + val rightOuter: Offset +) { + override fun toString(): String { + return "[LeftOuter: $leftOuter, LeftInner: $leftInner, RightInner: $rightInner, RightOuter: $rightOuter]" + } +} diff --git a/ComposeTesting/library/src/main/java/com/microsoft/device/dualscreen/testing/ZoomHelper.kt b/ComposeTesting/library/src/main/java/com/microsoft/device/dualscreen/testing/ZoomHelper.kt new file mode 100644 index 0000000..9cd6194 --- /dev/null +++ b/ComposeTesting/library/src/main/java/com/microsoft/device/dualscreen/testing/ZoomHelper.kt @@ -0,0 +1,58 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + +package com.microsoft.device.dualscreen.testing + +import android.util.Log +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.test.TouchInjectionScope +import androidx.compose.ui.test.pinch + +/** + * ZOOM HELPER + * ----------------------------------------------------------------------------------------------- + * These functions can be used to perform zooming gestures during Compose UI tests. + */ + +const val PINCH_MILLIS: Long = 500 + +/** + * Performs a zoom in gesture (swipes start towards center then move outwards) + * + * @param pinchMillis: number of milliseconds it takes to perform the pinch (default 500) + */ +fun TouchInjectionScope.zoomIn(pinchMillis: Long = PINCH_MILLIS) { + val coords = setupZoomCoords() + Log.d("ZoomHelper", "Zooming in: $coords") + pinch(coords.leftInner, coords.leftOuter, coords.rightInner, coords.rightOuter, pinchMillis) +} + +/** + * Performs a zoom out gesture (swipes start towards center then move outwards) + * + * @param pinchMillis: number of milliseconds it takes to perform the pinch (default 500) + */ +fun TouchInjectionScope.zoomOut(pinchMillis: Long = PINCH_MILLIS) { + val coords = setupZoomCoords() + Log.d("ZoomHelper", "Zooming out: $coords") + pinch(coords.leftOuter, coords.leftInner, coords.rightOuter, coords.rightInner, pinchMillis) +} + +/** + * Calculates starting and ending zoom coordinates based on GestureScope properties + */ +private fun TouchInjectionScope.setupZoomCoords(): ZoomCoordinates { + // Get height and width of node + val width = (right - left).toLong() + val height = (bottom - top).toLong() + + // Set up zoom coordinates offsets + return ZoomCoordinates( + leftOuter = Offset(left + width * 0.25f, top + height * 0.3f), + leftInner = Offset(left + width * 0.45f, top + height * 0.3f), + rightInner = Offset(left + width * 0.55f, height * 0.7f), + rightOuter = Offset(left + width * 0.75f, height * 0.7f), + ) +} diff --git a/ComposeTesting/publishing.gradle b/ComposeTesting/publishing.gradle new file mode 100644 index 0000000..fd3f823 --- /dev/null +++ b/ComposeTesting/publishing.gradle @@ -0,0 +1,128 @@ +apply plugin: 'maven-publish' +apply plugin: 'signing' +apply plugin: 'org.jetbrains.dokka' + +//Every module defines its own values +group = PUBLISH_GROUP_ID +version = LIBRARY_VERSION +description = LIBRARY_DESCRIPTION + +//Signing key-value pairs (used for the publication no matter the target (ADO or MavenCentral)) +ext["signing.keyId"] = getPropertyValue("SIGNING_KEY_ID") +ext["signing.password"] = getPropertyValue("SIGNING_PASSWORD") +ext["signing.secretKeyRingFile"] = getPropertyValue("SIGNING_SECRET_FILE") + +//Maven central key-value pairs +ext["mavenUser"] = getPropertyValue("MAVEN_USER") +ext["mavenPassword"] = getPropertyValue("MAVEN_PASSWORD") + +//ADO key-value pairs +ext["ado_url"] = getPropertyValue("ADO_URL") +ext["ado_user"] = getPropertyValue("ADO_USER") +ext["ado_passwd"] = getPropertyValue("ADO_PASSWD") + + +task androidSourcesJar(type: Jar) { + archiveClassifier.set('sources') + from android.sourceSets.main.java.srcDirs + from android.sourceSets.main.kotlin.srcDirs +} + +dokkaHtml.configure { + dokkaSourceSets { + named("main") { + noAndroidSdkLink.set(false) + } + } +} + +task dokkaHtmlJar(type: Jar, dependsOn: dokkaHtml) { + archiveClassifier.set('html-doc') + from dokkaHtml.outputDirectory +} + +publishing { + publications { + SurfaceDuoCompose(MavenPublication) { + //Define library main info. Each build.gradle library file define its own data. + groupId PUBLISH_GROUP_ID + artifactId PUBLISH_ARTIFACT_ID + version it.version + + //Set the artifact files + artifact("$buildDir/outputs/aar/${project.getName()}-release.aar") + artifact(androidSourcesJar) + artifact(dokkaHtmlJar) + + pom { + name = PUBLISH_ARTIFACT_ID + description = LIBRARY_DESCRIPTION + url = 'https://github.com/microsoft/surface-duo-compose-sdk' + licenses { + license { + name = 'MIT' + url = 'https://opensource.org/licenses/MIT' + } + } + developers { + developer { + id = 'MicrosoftSurfaceDuoDevX' + name = 'Microsoft Surface Duo DevX team' + email = 'surfaceduo-devx-libs@microsoft.com' + } + } + // Version control info + scm { + connection = 'scm:git:github.com/microsoft/surface-duo-compose-sdk.git' + developerConnection = 'scm:git:ssh://github.com/microsoft/surface-duo-compose-sdk.git' + url = 'https://github.com/microsoft/surface-duo-compose-sdk/tree/main' + } + // A slightly hacky fix so that your POM will include any transitive dependencies + // that your library builds upon + withXml { + def dependenciesNode = asNode().appendNode('dependencies') + project.configurations.implementation.allDependencies.each { + def dependencyNode = dependenciesNode.appendNode('dependency') + dependencyNode.appendNode('groupId', it.group) + dependencyNode.appendNode('artifactId', it.name) + dependencyNode.appendNode('version', it.version) + } + } + } + } + } + // Public: This is used to upload the artifact to the public repository. + //You can use it by doing: ./gradlew :module:publishSurfaceDuoComposePublicationToMavencentralRepository + //being :module the specific module you want to create the artifact from + repositories { + maven { + name = "MavenCentral" + def releasesRepoUrl = "https://oss.sonatype.org/service/local/staging/deploy/maven2/" + def snapshotsRepoUrl = "https://oss.sonatype.org/content/repositories/snapshots/" + url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl + credentials { + username mavenUser + password mavenPassword + } + } + } + + // Public/and for test purposes: This is used to upload the artifact to internal repository + // for testing purposes You can use it by doing: + // ./gradlew :module:publishSurfaceDuoSDKPublicationToADORepository + //being :module the specific module you want to create the artifact from + repositories { + maven { + name 'ADO' + url ado_url + credentials { + username ado_user + password ado_passwd + } + } + } +} + +signing { + sign publishing.publications +} \ No newline at end of file diff --git a/ComposeTesting/sample/.gitignore b/ComposeTesting/sample/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/ComposeTesting/sample/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/ComposeTesting/sample/build.gradle b/ComposeTesting/sample/build.gradle new file mode 100644 index 0000000..7244614 --- /dev/null +++ b/ComposeTesting/sample/build.gradle @@ -0,0 +1,78 @@ +/* + * + * * Copyright (c) Microsoft Corporation. All rights reserved. + * * Licensed under the MIT License. + * + */ + +apply plugin: 'com.android.application' +apply plugin: 'kotlin-android' + +android { + compileSdkVersion rootProject.ext.compileSdkVersion + + defaultConfig { + applicationId "com.microsoft.device.dualscreen.composetesting" + minSdkVersion rootProject.ext.minSdkVersion + targetSdkVersion rootProject.ext.targetSdkVersion + + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + vectorDrawables { + useSupportLibrary true + } + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + kotlinOptions { + jvmTarget = '1.8' + } + + buildFeatures { + compose true + } + + composeOptions { + kotlinCompilerExtensionVersion composeVersion + } + + packagingOptions { + resources { + excludes += ['META-INF/LGPL2.1', 'META-INF/AL2.0'] + } + } +} + +dependencies { + implementation project(path: ':library') + + implementation kotlinDependencies.kotlinStdlib + implementation androidxDependencies.ktxCore + implementation androidxDependencies.appCompat + + implementation composeDependencies.composeUI + implementation composeDependencies.composeMaterial + implementation composeDependencies.composeUITooling + implementation composeDependencies.activityCompose + + implementation googleDependencies.material + implementation microsoftDependencies.twoPaneLayout + + androidTestImplementation(testDependencies.androidxTestCore) + androidTestImplementation(testDependencies.androidxTestRules) + androidTestImplementation(testDependencies.androidxTestRunner) + androidTestImplementation(testDependencies.composeUITest) + androidTestImplementation(testDependencies.composeJunit) + androidTestImplementation(testDependencies.uiAutomator) + debugImplementation(testDependencies.composeUITestManifest) +} \ No newline at end of file diff --git a/ComposeTesting/sample/src/androidTest/java/com/microsoft/device/dualscreen/testing/FoldingFeatureHelperTest.kt b/ComposeTesting/sample/src/androidTest/java/com/microsoft/device/dualscreen/testing/FoldingFeatureHelperTest.kt new file mode 100644 index 0000000..a5f3163 --- /dev/null +++ b/ComposeTesting/sample/src/androidTest/java/com/microsoft/device/dualscreen/testing/FoldingFeatureHelperTest.kt @@ -0,0 +1,74 @@ +/* + * + * * Copyright (c) Microsoft Corporation. All rights reserved. + * * Licensed under the MIT License. + * + */ + +package com.microsoft.device.dualscreen.testing + +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import androidx.compose.ui.test.onNodeWithText +import com.microsoft.device.dualscreen.testing.ui.theme.ComposeTestingTheme +import org.junit.Rule +import org.junit.Test +import org.junit.rules.RuleChain +import org.junit.rules.TestRule + +class FoldingFeatureHelperTest { + private val composeTestRule = createAndroidComposeRule() + private val publisherRule = createWindowLayoutInfoPublisherRule() + + @get: Rule + val testRule: TestRule + + init { + testRule = RuleChain.outerRule(publisherRule).around(composeTestRule) + RuleChain.outerRule(composeTestRule) + } + + @Test + fun deviceOpenVertically_showsTwoPanes() { + composeTestRule.setContent { + ComposeTestingTheme { + ComposeTestingApp() + } + } + // Simulate vertical foldingFeature + publisherRule.simulateVerticalFoldingFeature(composeTestRule) + + // Assert both panes are being shown + composeTestRule.onNodeWithText(composeTestRule.getString(R.string.pane1_text)).assertIsDisplayed() + composeTestRule.onNodeWithText(composeTestRule.getString(R.string.pane2_text)).assertIsDisplayed() + } + + @Test + fun deviceOpenHorizontally_showsTwoPanes() { + composeTestRule.setContent { + ComposeTestingTheme { + ComposeTestingApp() + } + } + // Simulate vertical foldingFeature + publisherRule.simulateHorizontalFoldingFeature(composeTestRule) + + // Assert both panes are being shown + composeTestRule.onNodeWithText(composeTestRule.getString(R.string.pane1_text)).assertIsDisplayed() + composeTestRule.onNodeWithText(composeTestRule.getString(R.string.pane2_text)).assertIsDisplayed() + } + + @Test + fun deviceNotOpen_showsOnePane() { + composeTestRule.setContent { + ComposeTestingTheme { + ComposeTestingApp() + } + } + + // Assert the first is being shown + composeTestRule.onNodeWithText(composeTestRule.getString(R.string.pane1_text)).assertIsDisplayed() + // Assert the second is not being shown + composeTestRule.onNodeWithText(composeTestRule.getString(R.string.pane2_text)).assertDoesNotExist() + } +} diff --git a/ComposeTesting/sample/src/androidTest/java/com/microsoft/device/dualscreen/testing/SwipeHelperTest.kt b/ComposeTesting/sample/src/androidTest/java/com/microsoft/device/dualscreen/testing/SwipeHelperTest.kt new file mode 100644 index 0000000..4c076f7 --- /dev/null +++ b/ComposeTesting/sample/src/androidTest/java/com/microsoft/device/dualscreen/testing/SwipeHelperTest.kt @@ -0,0 +1,77 @@ +/* + * + * * Copyright (c) Microsoft Corporation. All rights reserved. + * * Licensed under the MIT License. + * + */ + +package com.microsoft.device.dualscreen.testing + +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import androidx.compose.ui.test.onNodeWithText +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.uiautomator.UiDevice +import com.microsoft.device.dualscreen.testing.ui.theme.ComposeTestingTheme +import org.junit.Rule +import org.junit.Test + +class SwipeHelperTest { + @get: Rule + val composeTestRule = createAndroidComposeRule() + private val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) + + @Test + fun span_showsTwoPanes() { + composeTestRule.setContent { + ComposeTestingTheme { + ComposeTestingApp() + } + } + + // Assert that only pane 1 is shown + composeTestRule.onNodeWithText(composeTestRule.getString(R.string.pane1_text)).assertIsDisplayed() + composeTestRule.onNodeWithText(composeTestRule.getString(R.string.pane2_text)).assertDoesNotExist() + + // Span the app from start + if (device.isSurfaceDuo()) { + device.spanFromStart() + } else { + return + } + + // Assert that both panes are now shown + composeTestRule.onNodeWithText(composeTestRule.getString(R.string.pane1_text)).assertIsDisplayed() + composeTestRule.onNodeWithText(composeTestRule.getString(R.string.pane2_text)).assertIsDisplayed() + } + + @Test + fun unspan_showsOnePane() { + composeTestRule.setContent { + ComposeTestingTheme { + ComposeTestingApp() + } + } + if (device.isSurfaceDuo()) { + // Span the app from start + device.spanFromStart() + } else { + return + } + + // Assert that both panes are shown + composeTestRule.onNodeWithText(composeTestRule.getString(R.string.pane1_text)).assertIsDisplayed() + composeTestRule.onNodeWithText(composeTestRule.getString(R.string.pane2_text)).assertIsDisplayed() + + // Unspan the app to the end + if (device.isSurfaceDuo()) { + device.unspanToEnd() + } else { + return + } + + // Assert that only pane 1 is now shown + composeTestRule.onNodeWithText(composeTestRule.getString(R.string.pane1_text)).assertIsDisplayed() + composeTestRule.onNodeWithText(composeTestRule.getString(R.string.pane2_text)).assertDoesNotExist() + } +} diff --git a/ComposeTesting/sample/src/main/AndroidManifest.xml b/ComposeTesting/sample/src/main/AndroidManifest.xml new file mode 100644 index 0000000..8701d29 --- /dev/null +++ b/ComposeTesting/sample/src/main/AndroidManifest.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ComposeTesting/sample/src/main/java/com/microsoft/device/dualscreen/testing/MainActivity.kt b/ComposeTesting/sample/src/main/java/com/microsoft/device/dualscreen/testing/MainActivity.kt new file mode 100644 index 0000000..4fc297d --- /dev/null +++ b/ComposeTesting/sample/src/main/java/com/microsoft/device/dualscreen/testing/MainActivity.kt @@ -0,0 +1,46 @@ +/* + * + * * Copyright (c) Microsoft Corporation. All rights reserved. + * * Licensed under the MIT License. + * + */ + +package com.microsoft.device.dualscreen.testing + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Surface +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.res.stringResource +import com.microsoft.device.dualscreen.testing.ui.theme.ComposeTestingTheme +import com.microsoft.device.dualscreen.twopanelayout.TwoPaneLayout + +class MainActivity : ComponentActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContent { + ComposeTestingTheme { + // A surface container using the 'background' color from the theme + Surface(color = MaterialTheme.colors.background) { + ComposeTestingApp() + } + } + } + } +} + +@Composable +fun ComposeTestingApp() { + TwoPaneLayout( + pane1 = { + Text(text = stringResource(R.string.pane1_text)) + }, + pane2 = { + Text(text = stringResource(R.string.pane2_text)) + } + ) +} diff --git a/ComposeTesting/sample/src/main/java/com/microsoft/device/dualscreen/testing/ui/theme/Color.kt b/ComposeTesting/sample/src/main/java/com/microsoft/device/dualscreen/testing/ui/theme/Color.kt new file mode 100644 index 0000000..3ba8aff --- /dev/null +++ b/ComposeTesting/sample/src/main/java/com/microsoft/device/dualscreen/testing/ui/theme/Color.kt @@ -0,0 +1,8 @@ +package com.microsoft.device.dualscreen.testing.ui.theme + +import androidx.compose.ui.graphics.Color + +val Purple200 = Color(0xFFBB86FC) +val Purple500 = Color(0xFF6200EE) +val Purple700 = Color(0xFF3700B3) +val Teal200 = Color(0xFF03DAC5) diff --git a/ComposeTesting/sample/src/main/java/com/microsoft/device/dualscreen/testing/ui/theme/Shape.kt b/ComposeTesting/sample/src/main/java/com/microsoft/device/dualscreen/testing/ui/theme/Shape.kt new file mode 100644 index 0000000..194743d --- /dev/null +++ b/ComposeTesting/sample/src/main/java/com/microsoft/device/dualscreen/testing/ui/theme/Shape.kt @@ -0,0 +1,11 @@ +package com.microsoft.device.dualscreen.testing.ui.theme + +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.Shapes +import androidx.compose.ui.unit.dp + +val Shapes = Shapes( + small = RoundedCornerShape(4.dp), + medium = RoundedCornerShape(4.dp), + large = RoundedCornerShape(0.dp) +) diff --git a/ComposeTesting/sample/src/main/java/com/microsoft/device/dualscreen/testing/ui/theme/Theme.kt b/ComposeTesting/sample/src/main/java/com/microsoft/device/dualscreen/testing/ui/theme/Theme.kt new file mode 100644 index 0000000..c2b9ce9 --- /dev/null +++ b/ComposeTesting/sample/src/main/java/com/microsoft/device/dualscreen/testing/ui/theme/Theme.kt @@ -0,0 +1,35 @@ +package com.microsoft.device.dualscreen.testing.ui.theme + +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material.MaterialTheme +import androidx.compose.material.darkColors +import androidx.compose.material.lightColors +import androidx.compose.runtime.Composable + +private val DarkColorPalette = darkColors( + primary = Purple200, + primaryVariant = Purple700, + secondary = Teal200 +) + +private val LightColorPalette = lightColors( + primary = Purple500, + primaryVariant = Purple700, + secondary = Teal200 +) + +@Composable +fun ComposeTestingTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable() () -> Unit) { + val colors = if (darkTheme) { + DarkColorPalette + } else { + LightColorPalette + } + + MaterialTheme( + colors = colors, + typography = Typography, + shapes = Shapes, + content = content + ) +} diff --git a/ComposeTesting/sample/src/main/java/com/microsoft/device/dualscreen/testing/ui/theme/Type.kt b/ComposeTesting/sample/src/main/java/com/microsoft/device/dualscreen/testing/ui/theme/Type.kt new file mode 100644 index 0000000..9db8dd7 --- /dev/null +++ b/ComposeTesting/sample/src/main/java/com/microsoft/device/dualscreen/testing/ui/theme/Type.kt @@ -0,0 +1,16 @@ +package com.microsoft.device.dualscreen.testing.ui.theme + +import androidx.compose.material.Typography +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.sp + +// Set of Material typography styles to start with +val Typography = Typography( + body1 = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Normal, + fontSize = 16.sp + ) +) diff --git a/ComposeTesting/sample/src/main/res/drawable-v24/ic_launcher_foreground.xml b/ComposeTesting/sample/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..2b068d1 --- /dev/null +++ b/ComposeTesting/sample/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/ComposeTesting/sample/src/main/res/drawable/ic_launcher_background.xml b/ComposeTesting/sample/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..07d5da9 --- /dev/null +++ b/ComposeTesting/sample/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ComposeTesting/sample/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/ComposeTesting/sample/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..eca70cf --- /dev/null +++ b/ComposeTesting/sample/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/ComposeTesting/sample/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/ComposeTesting/sample/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..eca70cf --- /dev/null +++ b/ComposeTesting/sample/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/ComposeTesting/sample/src/main/res/mipmap-hdpi/ic_launcher.webp b/ComposeTesting/sample/src/main/res/mipmap-hdpi/ic_launcher.webp new file mode 100644 index 0000000..c209e78 Binary files /dev/null and b/ComposeTesting/sample/src/main/res/mipmap-hdpi/ic_launcher.webp differ diff --git a/ComposeTesting/sample/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/ComposeTesting/sample/src/main/res/mipmap-hdpi/ic_launcher_round.webp new file mode 100644 index 0000000..b2dfe3d Binary files /dev/null and b/ComposeTesting/sample/src/main/res/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/ComposeTesting/sample/src/main/res/mipmap-mdpi/ic_launcher.webp b/ComposeTesting/sample/src/main/res/mipmap-mdpi/ic_launcher.webp new file mode 100644 index 0000000..4f0f1d6 Binary files /dev/null and b/ComposeTesting/sample/src/main/res/mipmap-mdpi/ic_launcher.webp differ diff --git a/ComposeTesting/sample/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/ComposeTesting/sample/src/main/res/mipmap-mdpi/ic_launcher_round.webp new file mode 100644 index 0000000..62b611d Binary files /dev/null and b/ComposeTesting/sample/src/main/res/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/ComposeTesting/sample/src/main/res/mipmap-xhdpi/ic_launcher.webp b/ComposeTesting/sample/src/main/res/mipmap-xhdpi/ic_launcher.webp new file mode 100644 index 0000000..948a307 Binary files /dev/null and b/ComposeTesting/sample/src/main/res/mipmap-xhdpi/ic_launcher.webp differ diff --git a/ComposeTesting/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/ComposeTesting/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..1b9a695 Binary files /dev/null and b/ComposeTesting/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/ComposeTesting/sample/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/ComposeTesting/sample/src/main/res/mipmap-xxhdpi/ic_launcher.webp new file mode 100644 index 0000000..28d4b77 Binary files /dev/null and b/ComposeTesting/sample/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/ComposeTesting/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/ComposeTesting/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..9287f50 Binary files /dev/null and b/ComposeTesting/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/ComposeTesting/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/ComposeTesting/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.webp new file mode 100644 index 0000000..aa7d642 Binary files /dev/null and b/ComposeTesting/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/ComposeTesting/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/ComposeTesting/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..9126ae3 Binary files /dev/null and b/ComposeTesting/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/ComposeTesting/sample/src/main/res/values-night/themes.xml b/ComposeTesting/sample/src/main/res/values-night/themes.xml new file mode 100644 index 0000000..5617f4a --- /dev/null +++ b/ComposeTesting/sample/src/main/res/values-night/themes.xml @@ -0,0 +1,16 @@ + + + + \ No newline at end of file diff --git a/ComposeTesting/sample/src/main/res/values/colors.xml b/ComposeTesting/sample/src/main/res/values/colors.xml new file mode 100644 index 0000000..f8c6127 --- /dev/null +++ b/ComposeTesting/sample/src/main/res/values/colors.xml @@ -0,0 +1,10 @@ + + + #FFBB86FC + #FF6200EE + #FF3700B3 + #FF03DAC5 + #FF018786 + #FF000000 + #FFFFFFFF + \ No newline at end of file diff --git a/ComposeTesting/sample/src/main/res/values/strings.xml b/ComposeTesting/sample/src/main/res/values/strings.xml new file mode 100644 index 0000000..90413e8 --- /dev/null +++ b/ComposeTesting/sample/src/main/res/values/strings.xml @@ -0,0 +1,5 @@ + + ComposeTestingSample + TwoPaneLayout: A UI component that helps you build two-pane layout for dual-screen, foldable, and large-screen devices. + WindowState: A utility component that helps you easily get details about the window state of dual-screen, foldable, and large-screen devices. + \ No newline at end of file diff --git a/ComposeTesting/sample/src/main/res/values/themes.xml b/ComposeTesting/sample/src/main/res/values/themes.xml new file mode 100644 index 0000000..0570269 --- /dev/null +++ b/ComposeTesting/sample/src/main/res/values/themes.xml @@ -0,0 +1,25 @@ + + + + + + +