[automerger skipped] Merge "Merge the internal changes to aosp." into androidx-main am: 851a2483ee -s ours
am skip reason: Merged-In Ia6e9b6f3b9bf76612d6c7706db30b3a21e5727ca with SHA-1 257920afa3 is already in history
Original change: https://android-review.googlesource.com/c/platform/frameworks/support/+/2406440
Change-Id: I74d661123f75828d8a1fb330a4cb032b42e49b72
Signed-off-by: Automerger Merge Worker <[email protected]>
diff --git a/appcompat/appcompat-resources/api/api_lint.ignore b/appcompat/appcompat-resources/api/api_lint.ignore
index 0cfa261..dd0cf8d 100644
--- a/appcompat/appcompat-resources/api/api_lint.ignore
+++ b/appcompat/appcompat-resources/api/api_lint.ignore
@@ -17,6 +17,8 @@
Missing nullability on parameter `tint` in method `setTintList`
MissingNullability: androidx.appcompat.graphics.drawable.DrawableWrapperCompat#DrawableWrapperCompat(android.graphics.drawable.Drawable) parameter #0:
Missing nullability on parameter `drawable` in method `DrawableWrapperCompat`
+MissingNullability: androidx.appcompat.graphics.drawable.DrawableWrapperCompat#draw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `canvas` in method `draw`
MissingNullability: androidx.appcompat.graphics.drawable.DrawableWrapperCompat#getCurrent():
Missing nullability on method `getCurrent` return
MissingNullability: androidx.appcompat.graphics.drawable.DrawableWrapperCompat#getPadding(android.graphics.Rect) parameter #0:
diff --git a/appcompat/appcompat/api/api_lint.ignore b/appcompat/appcompat/api/api_lint.ignore
index ff1d34f..90541cfd 100644
--- a/appcompat/appcompat/api/api_lint.ignore
+++ b/appcompat/appcompat/api/api_lint.ignore
@@ -91,12 +91,8 @@
Invalid nullability on parameter `filters` in method `setFilters`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
InvalidNullabilityOverride: androidx.appcompat.widget.AppCompatToggleButton#setFilters(android.text.InputFilter[]) parameter #0:
Invalid nullability on parameter `filters` in method `setFilters`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
-InvalidNullabilityOverride: androidx.appcompat.widget.LinearLayoutCompat#onDraw(android.graphics.Canvas) parameter #0:
- Invalid nullability on parameter `canvas` in method `onDraw`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
InvalidNullabilityOverride: androidx.appcompat.widget.ListPopupWindow#getListView():
Invalid nullability on method `getListView` return. Overrides of unannotated super method cannot be Nullable.
-InvalidNullabilityOverride: androidx.appcompat.widget.SwitchCompat#draw(android.graphics.Canvas) parameter #0:
- Invalid nullability on parameter `c` in method `draw`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
InvalidNullabilityOverride: androidx.appcompat.widget.SwitchCompat#getCustomSelectionActionModeCallback():
Invalid nullability on method `getCustomSelectionActionModeCallback` return. Overrides of unannotated super method cannot be Nullable.
InvalidNullabilityOverride: androidx.appcompat.widget.SwitchCompat#setFilters(android.text.InputFilter[]) parameter #0:
@@ -555,6 +551,8 @@
Missing nullability on parameter `attrs` in method `createView`
MissingNullability: androidx.appcompat.graphics.drawable.DrawerArrowDrawable#DrawerArrowDrawable(android.content.Context) parameter #0:
Missing nullability on parameter `context` in method `DrawerArrowDrawable`
+MissingNullability: androidx.appcompat.graphics.drawable.DrawerArrowDrawable#draw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `canvas` in method `draw`
MissingNullability: androidx.appcompat.graphics.drawable.DrawerArrowDrawable#getPaint():
Missing nullability on method `getPaint` return
MissingNullability: androidx.appcompat.graphics.drawable.DrawerArrowDrawable#setColorFilter(android.graphics.ColorFilter) parameter #0:
@@ -727,6 +725,8 @@
Missing nullability on parameter `p` in method `generateLayoutParams`
MissingNullability: androidx.appcompat.widget.LinearLayoutCompat#getDividerDrawable():
Missing nullability on method `getDividerDrawable` return
+MissingNullability: androidx.appcompat.widget.LinearLayoutCompat#onDraw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `canvas` in method `onDraw`
MissingNullability: androidx.appcompat.widget.LinearLayoutCompat#onInitializeAccessibilityEvent(android.view.accessibility.AccessibilityEvent) parameter #0:
Missing nullability on parameter `event` in method `onInitializeAccessibilityEvent`
MissingNullability: androidx.appcompat.widget.LinearLayoutCompat#onInitializeAccessibilityNodeInfo(android.view.accessibility.AccessibilityNodeInfo) parameter #0:
@@ -797,6 +797,8 @@
Missing nullability on parameter `source` in method `onShareTargetSelected`
MissingNullability: androidx.appcompat.widget.ShareActionProvider.OnShareTargetSelectedListener#onShareTargetSelected(androidx.appcompat.widget.ShareActionProvider, android.content.Intent) parameter #1:
Missing nullability on parameter `intent` in method `onShareTargetSelected`
+MissingNullability: androidx.appcompat.widget.SwitchCompat#draw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `c` in method `draw`
MissingNullability: androidx.appcompat.widget.SwitchCompat#getTextOff():
Missing nullability on method `getTextOff` return
MissingNullability: androidx.appcompat.widget.SwitchCompat#getTextOn():
@@ -831,6 +833,8 @@
Missing nullability on parameter `thumb` in method `setThumbDrawable`
MissingNullability: androidx.appcompat.widget.SwitchCompat#setTrackDrawable(android.graphics.drawable.Drawable) parameter #0:
Missing nullability on parameter `track` in method `setTrackDrawable`
+MissingNullability: androidx.appcompat.widget.SwitchCompat#verifyDrawable(android.graphics.drawable.Drawable) parameter #0:
+ Missing nullability on parameter `who` in method `verifyDrawable`
MissingNullability: androidx.appcompat.widget.Toolbar#checkLayoutParams(android.view.ViewGroup.LayoutParams) parameter #0:
Missing nullability on parameter `p` in method `checkLayoutParams`
MissingNullability: androidx.appcompat.widget.Toolbar#generateDefaultLayoutParams():
diff --git a/appcompat/appcompat/src/androidTest/java/androidx/appcompat/app/LocalesActivityA.java b/appcompat/appcompat/src/androidTest/java/androidx/appcompat/app/LocalesActivityA.java
index 069c76c..5719451 100644
--- a/appcompat/appcompat/src/androidTest/java/androidx/appcompat/app/LocalesActivityA.java
+++ b/appcompat/appcompat/src/androidTest/java/androidx/appcompat/app/LocalesActivityA.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2022 The Android Open Source Project
+ * Copyright 2021 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.
@@ -20,4 +20,3 @@
* An activity for locales with a unique class name.
*/
public class LocalesActivityA extends LocalesUpdateActivity {}
-
diff --git a/appsearch/appsearch-local-storage/proguard-rules.pro b/appsearch/appsearch-local-storage/proguard-rules.pro
index 82c4b719..335e9e8 100644
--- a/appsearch/appsearch-local-storage/proguard-rules.pro
+++ b/appsearch/appsearch-local-storage/proguard-rules.pro
@@ -19,7 +19,7 @@
<fields>;
}
-keep class com.google.android.icing.BreakIteratorBatcher { *; }
--keepclassmembers public class com.google.android.icing.IcingSearchEngine {
+-keepclassmembers public class com.google.android.icing.IcingSearchEngineImpl {
private long nativePointer;
}
diff --git a/appsearch/appsearch-local-storage/src/androidTest/java/androidx/appsearch/localstorage/AppSearchImplTest.java b/appsearch/appsearch-local-storage/src/androidTest/java/androidx/appsearch/localstorage/AppSearchImplTest.java
index 4fef3f4..6adfa73 100644
--- a/appsearch/appsearch-local-storage/src/androidTest/java/androidx/appsearch/localstorage/AppSearchImplTest.java
+++ b/appsearch/appsearch-local-storage/src/androidTest/java/androidx/appsearch/localstorage/AppSearchImplTest.java
@@ -3326,7 +3326,10 @@
@Test
public void testRemoveByQuery_withJoinSpec_throwsException() {
Exception e = assertThrows(IllegalArgumentException.class,
- () -> mAppSearchImpl.removeByQuery("", "", "",
+ () -> mAppSearchImpl.removeByQuery(
+ /*packageName=*/"",
+ /*databaseName=*/"",
+ /*queryExpression=*/"",
new SearchSpec.Builder()
.setJoinSpec(new JoinSpec.Builder("childProp").build())
.build(),
diff --git a/appsearch/appsearch-platform-storage/lint-baseline.xml b/appsearch/appsearch-platform-storage/lint-baseline.xml
index e1f4abe..b61f0f5 100644
--- a/appsearch/appsearch-platform-storage/lint-baseline.xml
+++ b/appsearch/appsearch-platform-storage/lint-baseline.xml
@@ -19,94 +19,4 @@
file="src/main/java/androidx/appsearch/platformstorage/SearchSessionImpl.java"/>
</issue>
- <issue
- id="ClassVerificationFailure"
- message="This call references a method added in API level 33; however, the containing class androidx.appsearch.platformstorage.converter.GetSchemaResponseToPlatformConverter is reachable from earlier API levels and will fail run-time class verification."
- errorLine1=" platformResponse.getSchemaTypesNotDisplayedBySystem()) {"
- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
- <location
- file="src/main/java/androidx/appsearch/platformstorage/converter/GetSchemaResponseToPlatformConverter.java"/>
- </issue>
-
- <issue
- id="ClassVerificationFailure"
- message="This call references a method added in API level 33; however, the containing class androidx.appsearch.platformstorage.converter.GetSchemaResponseToPlatformConverter is reachable from earlier API levels and will fail run-time class verification."
- errorLine1=" platformResponse.getRequiredPermissionsForSchemaTypeVisibility().entrySet()) {"
- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
- <location
- file="src/main/java/androidx/appsearch/platformstorage/converter/GetSchemaResponseToPlatformConverter.java"/>
- </issue>
-
- <issue
- id="ClassVerificationFailure"
- message="This call references a method added in API level 33; however, the containing class androidx.appsearch.platformstorage.converter.GetSchemaResponseToPlatformConverter is reachable from earlier API levels and will fail run-time class verification."
- errorLine1=" platformResponse.getSchemaTypesVisibleToPackages();"
- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
- <location
- file="src/main/java/androidx/appsearch/platformstorage/converter/GetSchemaResponseToPlatformConverter.java"/>
- </issue>
-
- <issue
- id="ClassVerificationFailure"
- message="This call references a method added in API level 33; however, the containing class androidx.appsearch.platformstorage.GlobalSearchSessionImpl is reachable from earlier API levels and will fail run-time class verification."
- errorLine1=" mPlatformSession.getByDocumentId(packageName, databaseName,"
- errorLine2=" ~~~~~~~~~~~~~~~">
- <location
- file="src/main/java/androidx/appsearch/platformstorage/GlobalSearchSessionImpl.java"/>
- </issue>
-
- <issue
- id="ClassVerificationFailure"
- message="This call references a method added in API level 33; however, the containing class androidx.appsearch.platformstorage.GlobalSearchSessionImpl is reachable from earlier API levels and will fail run-time class verification."
- errorLine1=" mPlatformSession.getSchema("
- errorLine2=" ~~~~~~~~~">
- <location
- file="src/main/java/androidx/appsearch/platformstorage/GlobalSearchSessionImpl.java"/>
- </issue>
-
- <issue
- id="ClassVerificationFailure"
- message="This call references a method added in API level 33; however, the containing class androidx.appsearch.platformstorage.GlobalSearchSessionImpl is reachable from earlier API levels and will fail run-time class verification."
- errorLine1=" mPlatformSession.registerObserverCallback("
- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~">
- <location
- file="src/main/java/androidx/appsearch/platformstorage/GlobalSearchSessionImpl.java"/>
- </issue>
-
- <issue
- id="ClassVerificationFailure"
- message="This call references a method added in API level 33; however, the containing class androidx.appsearch.platformstorage.GlobalSearchSessionImpl is reachable from earlier API levels and will fail run-time class verification."
- errorLine1=" mPlatformSession.unregisterObserverCallback(targetPackageName, frameworkCallback);"
- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~">
- <location
- file="src/main/java/androidx/appsearch/platformstorage/GlobalSearchSessionImpl.java"/>
- </issue>
-
- <issue
- id="ClassVerificationFailure"
- message="This call references a method added in API level 33; however, the containing class androidx.appsearch.platformstorage.converter.SearchResultToPlatformConverter is reachable from earlier API levels and will fail run-time class verification."
- errorLine1=" platformMatchInfo.getSubmatchRange().getStart(),"
- errorLine2=" ~~~~~~~~~~~~~~~~">
- <location
- file="src/main/java/androidx/appsearch/platformstorage/converter/SearchResultToPlatformConverter.java"/>
- </issue>
-
- <issue
- id="ClassVerificationFailure"
- message="This call references a method added in API level 33; however, the containing class androidx.appsearch.platformstorage.converter.SearchResultToPlatformConverter is reachable from earlier API levels and will fail run-time class verification."
- errorLine1=" platformMatchInfo.getSubmatchRange().getEnd()));"
- errorLine2=" ~~~~~~~~~~~~~~~~">
- <location
- file="src/main/java/androidx/appsearch/platformstorage/converter/SearchResultToPlatformConverter.java"/>
- </issue>
-
- <issue
- id="ClassVerificationFailure"
- message="This call references a method added in API level 33; however, the containing class androidx.appsearch.platformstorage.converter.SetSchemaRequestToPlatformConverter is reachable from earlier API levels and will fail run-time class verification."
- errorLine1=" platformBuilder.addRequiredPermissionsForSchemaTypeVisibility("
- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
- <location
- file="src/main/java/androidx/appsearch/platformstorage/converter/SetSchemaRequestToPlatformConverter.java"/>
- </issue>
-
</issues>
diff --git a/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/FeaturesImpl.java b/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/FeaturesImpl.java
index 9e70974..0c28ff3 100644
--- a/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/FeaturesImpl.java
+++ b/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/FeaturesImpl.java
@@ -15,6 +15,9 @@
*/
package androidx.appsearch.platformstorage;
+import android.annotation.SuppressLint;
+import android.os.Build;
+
import androidx.annotation.NonNull;
import androidx.appsearch.app.Features;
import androidx.core.os.BuildCompat;
@@ -26,7 +29,8 @@
final class FeaturesImpl implements Features {
@Override
- // TODO(b/201316758): Remove once BuildCompat.isAtLeastT is removed
+ // TODO(b/265311462): Remove these two lines once BuildCompat.isAtLeastU() is removed
+ @SuppressLint("NewApi")
@BuildCompat.PrereleaseSdkCheck
public boolean isFeatureSupported(@NonNull String feature) {
switch (feature) {
@@ -40,10 +44,11 @@
case Features.GLOBAL_SEARCH_SESSION_REGISTER_OBSERVER_CALLBACK:
// fall through
case Features.SEARCH_RESULT_MATCH_INFO_SUBMATCH:
- // fall through
- return BuildCompat.isAtLeastT();
+ return Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU;
// Android U Features
+ case Features.JOIN_SPEC_AND_QUALIFIED_ID:
+ return BuildCompat.isAtLeastU();
case Features.SEARCH_SPEC_PROPERTY_WEIGHTS:
// TODO(b/203700301) : Update to reflect support in Android U+ once this feature is
// synced over into service-appsearch.
@@ -60,10 +65,6 @@
// TODO(b/261474063) : Update to reflect support in Android U+ once advanced
// ranking becomes available.
// fall through
- case Features.JOIN_SPEC_AND_QUALIFIED_ID:
- // TODO(b/256022027) : Update to reflect support in Android U+ once this feature is
- // synced over into service-appsearch.
- // fall through
case Features.VERBATIM_SEARCH:
// TODO(b/204333391) : Update to reflect support in Android U+ once this feature is
// synced over into service-appsearch.
diff --git a/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/GlobalSearchSessionImpl.java b/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/GlobalSearchSessionImpl.java
index 6ed63ee..1f10cef 100644
--- a/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/GlobalSearchSessionImpl.java
+++ b/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/GlobalSearchSessionImpl.java
@@ -16,8 +16,11 @@
package androidx.appsearch.platformstorage;
import android.annotation.SuppressLint;
+import android.app.appsearch.AppSearchResult;
+import android.app.appsearch.BatchResultCallback;
import android.os.Build;
+import androidx.annotation.DoNotInline;
import androidx.annotation.GuardedBy;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
@@ -52,9 +55,10 @@
import java.util.Map;
import java.util.concurrent.Executor;
+import java.util.function.Consumer;
/**
- * An implementation of {@link androidx.appsearch.app.GlobalSearchSession} which proxies to a
+ * An implementation of {@link GlobalSearchSession} which proxies to a
* platform {@link android.app.appsearch.GlobalSearchSession}.
*
* @hide
@@ -80,13 +84,12 @@
mFeatures = Preconditions.checkNotNull(features);
}
- @BuildCompat.PrereleaseSdkCheck
@NonNull
@Override
public ListenableFuture<AppSearchBatchResult<String, GenericDocument>> getByDocumentIdAsync(
@NonNull String packageName, @NonNull String databaseName,
@NonNull GetByDocumentIdRequest request) {
- if (!BuildCompat.isAtLeastT()) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
throw new UnsupportedOperationException(Features.GLOBAL_SEARCH_SESSION_GET_BY_ID
+ " is not supported on this AppSearch implementation.");
}
@@ -95,14 +98,16 @@
Preconditions.checkNotNull(request);
ResolvableFuture<AppSearchBatchResult<String, GenericDocument>> future =
ResolvableFuture.create();
- mPlatformSession.getByDocumentId(packageName, databaseName,
- RequestToPlatformConverter.toPlatformGetByDocumentIdRequest(request),
- mExecutor,
+ ApiHelperForT.getByDocumentId(mPlatformSession, packageName, databaseName,
+ RequestToPlatformConverter.toPlatformGetByDocumentIdRequest(request), mExecutor,
new BatchResultCallbackAdapter<>(
future, GenericDocumentToPlatformConverter::toJetpackGenericDocument));
return future;
}
+ // TODO(b/265311462): Remove these two lines once BuildCompat.isAtLeastU() is removed
+ @SuppressLint("NewApi")
+ @BuildCompat.PrereleaseSdkCheck
@Override
@NonNull
public SearchResults search(
@@ -131,6 +136,8 @@
return future;
}
+ // TODO(b/265311462): Remove BuildCompat.PrereleaseSdkCheck annotation once usage of
+ // BuildCompat.isAtLeastU() is removed.
@BuildCompat.PrereleaseSdkCheck
@NonNull
@Override
@@ -138,16 +145,13 @@
@NonNull String databaseName) {
// Superclass is annotated with @RequiresFeature, so we shouldn't get here on an
// unsupported build.
- if (!BuildCompat.isAtLeastT()) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
throw new UnsupportedOperationException(
Features.GLOBAL_SEARCH_SESSION_GET_SCHEMA
+ " is not supported on this AppSearch implementation.");
}
ResolvableFuture<GetSchemaResponse> future = ResolvableFuture.create();
- mPlatformSession.getSchema(
- packageName,
- databaseName,
- mExecutor,
+ ApiHelperForT.getSchema(mPlatformSession, packageName, databaseName, mExecutor,
result -> AppSearchResultToPlatformConverter.platformAppSearchResultToFuture(
result,
future,
@@ -161,9 +165,7 @@
return mFeatures;
}
- // TODO(b/193494000): Remove these two lines once BuildCompat.isAtLeastT() is removed.
- @SuppressLint("NewApi")
- @BuildCompat.PrereleaseSdkCheck
+ @RequiresApi(Build.VERSION_CODES.TIRAMISU)
@Override
public void registerObserverCallback(
@NonNull String targetPackageName,
@@ -176,7 +178,7 @@
Preconditions.checkNotNull(observer);
// Superclass is annotated with @RequiresFeature, so we shouldn't get here on an
// unsupported build.
- if (!BuildCompat.isAtLeastT()) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
throw new UnsupportedOperationException(
Features.GLOBAL_SEARCH_SESSION_REGISTER_OBSERVER_CALLBACK
+ " is not supported on this AppSearch implementation");
@@ -213,10 +215,8 @@
// Regardless of whether this stub was fresh or not, we have to register it again
// because the user might be supplying a different spec.
try {
- mPlatformSession.registerObserverCallback(
- targetPackageName,
- ObserverSpecToPlatformConverter.toPlatformObserverSpec(spec),
- executor,
+ ApiHelperForT.registerObserverCallback(mPlatformSession, targetPackageName,
+ ObserverSpecToPlatformConverter.toPlatformObserverSpec(spec), executor,
frameworkCallback);
} catch (android.app.appsearch.exceptions.AppSearchException e) {
throw new AppSearchException((int) e.getResultCode(), e.getMessage(), e.getCause());
@@ -229,8 +229,6 @@
}
}
- @SuppressLint("NewApi")
- @BuildCompat.PrereleaseSdkCheck
@Override
public void unregisterObserverCallback(
@NonNull String targetPackageName, @NonNull ObserverCallback observer)
@@ -239,7 +237,7 @@
Preconditions.checkNotNull(observer);
// Superclass is annotated with @RequiresFeature, so we shouldn't get here on an
// unsupported build.
- if (!BuildCompat.isAtLeastT()) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
throw new UnsupportedOperationException(
Features.GLOBAL_SEARCH_SESSION_REGISTER_OBSERVER_CALLBACK
+ " is not supported on this AppSearch implementation");
@@ -253,7 +251,8 @@
}
try {
- mPlatformSession.unregisterObserverCallback(targetPackageName, frameworkCallback);
+ ApiHelperForT.unregisterObserverCallback(mPlatformSession, targetPackageName,
+ frameworkCallback);
} catch (android.app.appsearch.exceptions.AppSearchException e) {
throw new AppSearchException((int) e.getResultCode(), e.getMessage(), e.getCause());
}
@@ -267,4 +266,43 @@
public void close() {
mPlatformSession.close();
}
+
+ @RequiresApi(Build.VERSION_CODES.TIRAMISU)
+ private static class ApiHelperForT {
+ private ApiHelperForT() {
+ // This class is not instantiable.
+ }
+
+ @DoNotInline
+ static void getByDocumentId(android.app.appsearch.GlobalSearchSession platformSession,
+ String packageName, String databaseName,
+ android.app.appsearch.GetByDocumentIdRequest request, Executor executor,
+ BatchResultCallback<String, android.app.appsearch.GenericDocument> callback) {
+ platformSession.getByDocumentId(packageName, databaseName, request, executor, callback);
+ }
+
+ @DoNotInline
+ static void getSchema(android.app.appsearch.GlobalSearchSession platformSessions,
+ String packageName, String databaseName, Executor executor,
+ Consumer<AppSearchResult<android.app.appsearch.GetSchemaResponse>> callback) {
+ platformSessions.getSchema(packageName, databaseName, executor, callback);
+ }
+
+ @DoNotInline
+ static void registerObserverCallback(
+ android.app.appsearch.GlobalSearchSession platformSession, String targetPackageName,
+ android.app.appsearch.observer.ObserverSpec spec, Executor executor,
+ android.app.appsearch.observer.ObserverCallback observer)
+ throws android.app.appsearch.exceptions.AppSearchException {
+ platformSession.registerObserverCallback(targetPackageName, spec, executor, observer);
+ }
+
+ @DoNotInline
+ static void unregisterObserverCallback(
+ android.app.appsearch.GlobalSearchSession platformSession, String targetPackageName,
+ android.app.appsearch.observer.ObserverCallback observer)
+ throws android.app.appsearch.exceptions.AppSearchException {
+ platformSession.unregisterObserverCallback(targetPackageName, observer);
+ }
+ }
}
diff --git a/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/SearchResultsImpl.java b/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/SearchResultsImpl.java
index 6fde6d6..1217bf6 100644
--- a/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/SearchResultsImpl.java
+++ b/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/SearchResultsImpl.java
@@ -58,13 +58,14 @@
mExecutor = Preconditions.checkNotNull(executor);
}
+ // TODO(b/265311462): Remove BuildCompat.PrereleaseSdkCheck annotation once usage of
+ // BuildCompat.isAtLeastU() is removed.
@SuppressLint("WrongConstant")
@Override
@NonNull
@BuildCompat.PrereleaseSdkCheck
public ListenableFuture<List<SearchResult>> getNextPageAsync() {
- // TODO(b/256022027): add isAtLeastU check after Android U.
- if (mSearchSpec.getJoinSpec() != null) {
+ if (!BuildCompat.isAtLeastU() && mSearchSpec.getJoinSpec() != null) {
throw new UnsupportedOperationException("Searching with a SearchSpec containing a "
+ "JoinSpec is not supported on this AppSearch implementation.");
}
diff --git a/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/SearchSessionImpl.java b/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/SearchSessionImpl.java
index a4621c2..e291819 100644
--- a/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/SearchSessionImpl.java
+++ b/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/SearchSessionImpl.java
@@ -15,6 +15,7 @@
*/
package androidx.appsearch.platformstorage;
+import android.annotation.SuppressLint;
import android.os.Build;
import androidx.annotation.NonNull;
@@ -76,9 +77,11 @@
mFeatures = Preconditions.checkNotNull(features);
}
+ // TODO(b/265311462): Remove these two lines once BuildCompat.isAtLeastU() is removed
+ @SuppressLint("NewApi")
+ @BuildCompat.PrereleaseSdkCheck
@Override
@NonNull
- @BuildCompat.PrereleaseSdkCheck
public ListenableFuture<SetSchemaResponse> setSchemaAsync(@NonNull SetSchemaRequest request) {
Preconditions.checkNotNull(request);
ResolvableFuture<SetSchemaResponse> future = ResolvableFuture.create();
@@ -93,9 +96,11 @@
return future;
}
+ // TODO(b/265311462): Remove BuildCompat.PrereleaseSdkCheck annotation once usage of
+ // BuildCompat.isAtLeastU() is removed.
+ @BuildCompat.PrereleaseSdkCheck
@Override
@NonNull
- @BuildCompat.PrereleaseSdkCheck
public ListenableFuture<GetSchemaResponse> getSchemaAsync() {
ResolvableFuture<GetSchemaResponse> future = ResolvableFuture.create();
mPlatformSession.getSchema(
@@ -146,6 +151,9 @@
return future;
}
+ // TODO(b/265311462): Remove BuildCompat.PrereleaseSdkCheck annotation once usage of
+ // BuildCompat.isAtLeastU() is removed.
+ @BuildCompat.PrereleaseSdkCheck
@Override
@NonNull
public SearchResults search(
@@ -195,9 +203,11 @@
return future;
}
+ // TODO(b/265311462): Remove BuildCompat.PrereleaseSdkCheck annotation once usage of
+ // BuildCompat.isAtLeastU() is removed.
+ @BuildCompat.PrereleaseSdkCheck
@Override
@NonNull
- @BuildCompat.PrereleaseSdkCheck
public ListenableFuture<Void> removeAsync(
@NonNull String queryExpression, @NonNull SearchSpec searchSpec) {
Preconditions.checkNotNull(queryExpression);
@@ -209,7 +219,8 @@
+ "JoinSpec was provided.");
}
- if (!BuildCompat.isAtLeastT() && !searchSpec.getFilterNamespaces().isEmpty()) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU
+ && !searchSpec.getFilterNamespaces().isEmpty()) {
// This is a patch for b/197361770, framework-appsearch in Android S will
// disable the given namespace filter if it is not empty and none of given namespaces
// exist.
diff --git a/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/converter/GetSchemaResponseToPlatformConverter.java b/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/converter/GetSchemaResponseToPlatformConverter.java
index b69caca..d38567c 100644
--- a/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/converter/GetSchemaResponseToPlatformConverter.java
+++ b/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/converter/GetSchemaResponseToPlatformConverter.java
@@ -18,6 +18,7 @@
import android.os.Build;
+import androidx.annotation.DoNotInline;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.annotation.RestrictTo;
@@ -43,13 +44,15 @@
* Translates a platform {@link android.app.appsearch.GetSchemaResponse} into a jetpack
* {@link GetSchemaResponse}.
*/
- @NonNull
+ // TODO(b/265311462): Remove BuildCompat.PrereleaseSdkCheck annotation once usage of
+ // BuildCompat.isAtLeastU() is removed.
@BuildCompat.PrereleaseSdkCheck
+ @NonNull
public static GetSchemaResponse toJetpackGetSchemaResponse(
@NonNull android.app.appsearch.GetSchemaResponse platformResponse) {
Preconditions.checkNotNull(platformResponse);
GetSchemaResponse.Builder jetpackBuilder;
- if (!BuildCompat.isAtLeastT()) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
// Android API level in S-v2 and lower won't have any supported feature.
jetpackBuilder = new GetSchemaResponse.Builder(/*getVisibilitySettingSupported=*/false);
} else {
@@ -60,17 +63,18 @@
jetpackBuilder.addSchema(SchemaToPlatformConverter.toJetpackSchema(platformSchema));
}
jetpackBuilder.setVersion(platformResponse.getVersion());
- if (BuildCompat.isAtLeastT()) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
// Convert schemas not displayed by system
for (String schemaTypeNotDisplayedBySystem :
- platformResponse.getSchemaTypesNotDisplayedBySystem()) {
+ ApiHelperForT.getSchemaTypesNotDisplayedBySystem(platformResponse)) {
jetpackBuilder.addSchemaTypeNotDisplayedBySystem(schemaTypeNotDisplayedBySystem);
}
// Convert schemas visible to packages
convertSchemasVisibleToPackages(platformResponse, jetpackBuilder);
// Convert schemas visible to permissions
for (Map.Entry<String, Set<Set<Integer>>> entry :
- platformResponse.getRequiredPermissionsForSchemaTypeVisibility().entrySet()) {
+ ApiHelperForT.getRequiredPermissionsForSchemaTypeVisibility(platformResponse)
+ .entrySet()) {
jetpackBuilder.setRequiredPermissionsForSchemaTypeVisibility(entry.getKey(),
entry.getValue());
}
@@ -90,7 +94,7 @@
// incorrectly returns {@code null} in some prerelease versions of Android T. Remove
// this workaround after the issue is fixed in T.
Map<String, Set<android.app.appsearch.PackageIdentifier>> schemaTypesVisibleToPackages =
- platformResponse.getSchemaTypesVisibleToPackages();
+ ApiHelperForT.getSchemaTypesVisibleToPackage(platformResponse);
if (schemaTypesVisibleToPackages != null) {
for (Map.Entry<String, Set<android.app.appsearch.PackageIdentifier>> entry
: schemaTypesVisibleToPackages.entrySet()) {
@@ -107,4 +111,30 @@
}
}
}
+
+ @RequiresApi(Build.VERSION_CODES.TIRAMISU)
+ private static class ApiHelperForT {
+ private ApiHelperForT() {
+ // This class is not instantiable.
+ }
+
+ @DoNotInline
+ static Set<String> getSchemaTypesNotDisplayedBySystem(
+ android.app.appsearch.GetSchemaResponse platformResponse) {
+ return platformResponse.getSchemaTypesNotDisplayedBySystem();
+ }
+
+ @DoNotInline
+ static Map<String, Set<android.app.appsearch.PackageIdentifier>>
+ getSchemaTypesVisibleToPackage(
+ android.app.appsearch.GetSchemaResponse platformResponse) {
+ return platformResponse.getSchemaTypesVisibleToPackages();
+ }
+
+ @DoNotInline
+ static Map<String, Set<Set<Integer>>> getRequiredPermissionsForSchemaTypeVisibility(
+ android.app.appsearch.GetSchemaResponse platformResponse) {
+ return platformResponse.getRequiredPermissionsForSchemaTypeVisibility();
+ }
+ }
}
diff --git a/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/converter/JoinSpecToPlatformConverter.java b/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/converter/JoinSpecToPlatformConverter.java
new file mode 100644
index 0000000..9696cec
--- /dev/null
+++ b/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/converter/JoinSpecToPlatformConverter.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright 2023 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 androidx.appsearch.platformstorage.converter;
+
+import android.annotation.SuppressLint;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.RequiresApi;
+import androidx.annotation.RestrictTo;
+import androidx.appsearch.app.JoinSpec;
+import androidx.core.os.BuildCompat;
+import androidx.core.util.Preconditions;
+
+/**
+ * Translates between Platform and Jetpack versions of {@link JoinSpec}.
+ */
+// TODO(b/265311462): Remove BuildCompat.PrereleaseSdkCheck annotation once
+// SearchSpecToPlatformConverter.toPlatformSearchSpec() removes it. Also, replace literal '34' with
+// Build.VERSION_CODES.UPSIDE_DOWN_CAKE once the SDK_INT is finalized.
[email protected]
+@RestrictTo(RestrictTo.Scope.LIBRARY)
+@RequiresApi(34)
+public class JoinSpecToPlatformConverter {
+ private JoinSpecToPlatformConverter() {}
+
+ /**
+ * Translates a Jetpack {@link JoinSpec} into a platform {@link android.app.appsearch.JoinSpec}.
+ */
+ @SuppressLint("WrongConstant")
+ @NonNull
+ public static android.app.appsearch.JoinSpec toPlatformJoinSpec(@NonNull JoinSpec jetpackSpec) {
+ Preconditions.checkNotNull(jetpackSpec);
+ return new android.app.appsearch.JoinSpec.Builder(jetpackSpec.getChildPropertyExpression())
+ .setNestedSearch(
+ jetpackSpec.getNestedQuery(),
+ SearchSpecToPlatformConverter.toPlatformSearchSpec(
+ jetpackSpec.getNestedSearchSpec()))
+ .setMaxJoinedResultCount(jetpackSpec.getMaxJoinedResultCount())
+ .setAggregationScoringStrategy(jetpackSpec.getAggregationScoringStrategy())
+ .build();
+ }
+}
diff --git a/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/converter/SchemaToPlatformConverter.java b/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/converter/SchemaToPlatformConverter.java
index eba43cf..5a8e34f 100644
--- a/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/converter/SchemaToPlatformConverter.java
+++ b/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/converter/SchemaToPlatformConverter.java
@@ -19,16 +19,18 @@
import android.annotation.SuppressLint;
import android.os.Build;
+import androidx.annotation.DoNotInline;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.annotation.RestrictTo;
import androidx.appsearch.app.AppSearchSchema;
+import androidx.core.os.BuildCompat;
import androidx.core.util.Preconditions;
import java.util.List;
/**
- * Translates a jetpack {@link androidx.appsearch.app.AppSearchSchema} into a platform
+ * Translates a jetpack {@link AppSearchSchema} into a platform
* {@link android.app.appsearch.AppSearchSchema}.
* @hide
*/
@@ -38,9 +40,12 @@
private SchemaToPlatformConverter() {}
/**
- * Translates a jetpack {@link androidx.appsearch.app.AppSearchSchema} into a platform
+ * Translates a jetpack {@link AppSearchSchema} into a platform
* {@link android.app.appsearch.AppSearchSchema}.
*/
+ // TODO(b/265311462): Remove BuildCompat.PrereleaseSdkCheck annotation once
+ // toPlatformProperty() doesn't have it either.
+ @BuildCompat.PrereleaseSdkCheck
@NonNull
public static android.app.appsearch.AppSearchSchema toPlatformSchema(
@NonNull AppSearchSchema jetpackSchema) {
@@ -58,8 +63,11 @@
/**
* Translates a platform {@link android.app.appsearch.AppSearchSchema} to a jetpack
- * {@link androidx.appsearch.app.AppSearchSchema}.
+ * {@link AppSearchSchema}.
*/
+ // TODO(b/265311462): Remove BuildCompat.PrereleaseSdkCheck annotation once usage of
+ // BuildCompat.isAtLeastU() is removed.
+ @BuildCompat.PrereleaseSdkCheck
@NonNull
public static AppSearchSchema toJetpackSchema(
@NonNull android.app.appsearch.AppSearchSchema platformSchema) {
@@ -78,6 +86,9 @@
// Most stringProperty.get calls cause WrongConstant lint errors because the methods are not
// defined as returning the same constants as the corresponding setter expects, but they do
@SuppressLint("WrongConstant")
+ // TODO(b/265311462): Remove BuildCompat.PrereleaseSdkCheck annotation once usage of
+ // BuildCompat.isAtLeastU() is removed.
+ @BuildCompat.PrereleaseSdkCheck
@NonNull
private static android.app.appsearch.AppSearchSchema.PropertyConfig toPlatformProperty(
@NonNull AppSearchSchema.PropertyConfig jetpackProperty) {
@@ -85,20 +96,24 @@
if (jetpackProperty instanceof AppSearchSchema.StringPropertyConfig) {
AppSearchSchema.StringPropertyConfig stringProperty =
(AppSearchSchema.StringPropertyConfig) jetpackProperty;
- // TODO(b/256022027): add isAtLeastU check to allow JOINABLE_VALUE_TYPE_QUALIFIED_ID
- // after Android U, and set joinable value type to PropertyConfig.
- if (stringProperty.getJoinableValueType()
- == AppSearchSchema.StringPropertyConfig.JOINABLE_VALUE_TYPE_QUALIFIED_ID) {
- throw new UnsupportedOperationException(
- "StringPropertyConfig.JOINABLE_VALUE_TYPE_QUALIFIED_ID is not supported on "
- + "this AppSearch implementation.");
- }
- return new android.app.appsearch.AppSearchSchema.StringPropertyConfig.Builder(
+ android.app.appsearch.AppSearchSchema.StringPropertyConfig.Builder platformBuilder =
+ new android.app.appsearch.AppSearchSchema.StringPropertyConfig.Builder(
stringProperty.getName())
.setCardinality(stringProperty.getCardinality())
.setIndexingType(stringProperty.getIndexingType())
- .setTokenizerType(stringProperty.getTokenizerType())
- .build();
+ .setTokenizerType(stringProperty.getTokenizerType());
+
+ if (stringProperty.getJoinableValueType()
+ == AppSearchSchema.StringPropertyConfig.JOINABLE_VALUE_TYPE_QUALIFIED_ID) {
+ if (!BuildCompat.isAtLeastU()) {
+ throw new UnsupportedOperationException(
+ "StringPropertyConfig.JOINABLE_VALUE_TYPE_QUALIFIED_ID is not supported"
+ + " on this AppSearch implementation.");
+ }
+ ApiHelperForU.setJoinableValueType(platformBuilder,
+ stringProperty.getJoinableValueType());
+ }
+ return platformBuilder.build();
} else if (jetpackProperty instanceof AppSearchSchema.LongPropertyConfig) {
AppSearchSchema.LongPropertyConfig longProperty =
(AppSearchSchema.LongPropertyConfig) jetpackProperty;
@@ -145,6 +160,9 @@
// Most stringProperty.get calls cause WrongConstant lint errors because the methods are not
// defined as returning the same constants as the corresponding setter expects, but they do
@SuppressLint("WrongConstant")
+ // TODO(b/265311462): Remove BuildCompat.PrereleaseSdkCheck annotation once usage of
+ // BuildCompat.isAtLeastU() is removed.
+ @BuildCompat.PrereleaseSdkCheck
@NonNull
private static AppSearchSchema.PropertyConfig toJetpackProperty(
@NonNull android.app.appsearch.AppSearchSchema.PropertyConfig platformProperty) {
@@ -153,11 +171,16 @@
instanceof android.app.appsearch.AppSearchSchema.StringPropertyConfig) {
android.app.appsearch.AppSearchSchema.StringPropertyConfig stringProperty =
(android.app.appsearch.AppSearchSchema.StringPropertyConfig) platformProperty;
- return new AppSearchSchema.StringPropertyConfig.Builder(stringProperty.getName())
- .setCardinality(stringProperty.getCardinality())
- .setIndexingType(stringProperty.getIndexingType())
- .setTokenizerType(stringProperty.getTokenizerType())
- .build();
+ AppSearchSchema.StringPropertyConfig.Builder jetpackBuilder =
+ new AppSearchSchema.StringPropertyConfig.Builder(stringProperty.getName())
+ .setCardinality(stringProperty.getCardinality())
+ .setIndexingType(stringProperty.getIndexingType())
+ .setTokenizerType(stringProperty.getTokenizerType());
+ if (BuildCompat.isAtLeastU()) {
+ jetpackBuilder.setJoinableValueType(
+ ApiHelperForU.getJoinableValueType(stringProperty));
+ }
+ return jetpackBuilder.build();
} else if (platformProperty
instanceof android.app.appsearch.AppSearchSchema.LongPropertyConfig) {
return new AppSearchSchema.LongPropertyConfig.Builder(platformProperty.getName())
@@ -194,4 +217,30 @@
+ ": " + platformProperty);
}
}
+
+ // TODO(b/265311462): Replace literal '34' with Build.VERSION_CODES.UPSIDE_DOWN_CAKE when the
+ // SDK_INT is finalized.
+ @RequiresApi(34)
+ private static class ApiHelperForU {
+ private ApiHelperForU() {
+ // This class is not instantiable.
+ }
+
+ @DoNotInline
+ static void setJoinableValueType(
+ android.app.appsearch.AppSearchSchema.StringPropertyConfig.Builder builder,
+ @AppSearchSchema.StringPropertyConfig.JoinableValueType int joinableValueType) {
+ builder.setJoinableValueType(joinableValueType);
+ }
+
+ // Most stringProperty.get calls cause WrongConstant lint errors because the methods are not
+ // defined as returning the same constants as the corresponding setter expects, but they do
+ @SuppressLint("WrongConstant")
+ @DoNotInline
+ @AppSearchSchema.StringPropertyConfig.JoinableValueType
+ static int getJoinableValueType(
+ android.app.appsearch.AppSearchSchema.StringPropertyConfig stringPropertyConfig) {
+ return stringPropertyConfig.getJoinableValueType();
+ }
+ }
}
diff --git a/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/converter/SearchResultToPlatformConverter.java b/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/converter/SearchResultToPlatformConverter.java
index 707234d..a36e9cf 100644
--- a/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/converter/SearchResultToPlatformConverter.java
+++ b/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/converter/SearchResultToPlatformConverter.java
@@ -18,6 +18,7 @@
import android.os.Build;
+import androidx.annotation.DoNotInline;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.annotation.RestrictTo;
@@ -38,6 +39,8 @@
private SearchResultToPlatformConverter() {}
/** Translates from Platform to Jetpack versions of {@link SearchResult}. */
+ // TODO(b/265311462): Remove BuildCompat.PrereleaseSdkCheck annotation once usage of
+ // BuildCompat.isAtLeastU() is removed.
@BuildCompat.PrereleaseSdkCheck
@NonNull
public static SearchResult toJetpackSearchResult(
@@ -55,10 +58,15 @@
SearchResult.MatchInfo jetpackMatchInfo = toJetpackMatchInfo(platformMatches.get(i));
builder.addMatchInfo(jetpackMatchInfo);
}
+ if (BuildCompat.isAtLeastU()) {
+ for (android.app.appsearch.SearchResult joinedResult :
+ ApiHelperForU.getJoinedResults(platformResult)) {
+ builder.addJoinedResult(toJetpackSearchResult(joinedResult));
+ }
+ }
return builder.build();
}
- @BuildCompat.PrereleaseSdkCheck
@NonNull
private static SearchResult.MatchInfo toJetpackMatchInfo(
@NonNull android.app.appsearch.SearchResult.MatchInfo platformMatchInfo) {
@@ -73,12 +81,46 @@
new SearchResult.MatchRange(
platformMatchInfo.getSnippetRange().getStart(),
platformMatchInfo.getSnippetRange().getEnd()));
- if (BuildCompat.isAtLeastT()) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
builder.setSubmatchRange(
new SearchResult.MatchRange(
- platformMatchInfo.getSubmatchRange().getStart(),
- platformMatchInfo.getSubmatchRange().getEnd()));
+ ApiHelperForT.getSubmatchRangeStart(platformMatchInfo),
+ ApiHelperForT.getSubmatchRangeEnd(platformMatchInfo)));
}
return builder.build();
}
+
+ @RequiresApi(Build.VERSION_CODES.TIRAMISU)
+ private static class ApiHelperForT {
+ private ApiHelperForT() {
+ // This class is not instantiable.
+ }
+
+ @DoNotInline
+ static int getSubmatchRangeStart(@NonNull
+ android.app.appsearch.SearchResult.MatchInfo platformMatchInfo) {
+ return platformMatchInfo.getSubmatchRange().getStart();
+ }
+
+ @DoNotInline
+ static int getSubmatchRangeEnd(@NonNull
+ android.app.appsearch.SearchResult.MatchInfo platformMatchInfo) {
+ return platformMatchInfo.getSubmatchRange().getEnd();
+ }
+ }
+
+ // TODO(b/265311462): Replace literal '34' with Build.VERSION_CODES.UPSIDE_DOWN_CAKE when the
+ // SDK_INT is finalized.
+ @RequiresApi(34)
+ private static class ApiHelperForU {
+ private ApiHelperForU() {
+ // This class is not instantiable.
+ }
+
+ @DoNotInline
+ static List<android.app.appsearch.SearchResult> getJoinedResults(@NonNull
+ android.app.appsearch.SearchResult result) {
+ return result.getJoinedResults();
+ }
+ }
}
diff --git a/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/converter/SearchSpecToPlatformConverter.java b/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/converter/SearchSpecToPlatformConverter.java
index 6fc1d0b..1b64b6f 100644
--- a/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/converter/SearchSpecToPlatformConverter.java
+++ b/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/converter/SearchSpecToPlatformConverter.java
@@ -19,11 +19,14 @@
import android.annotation.SuppressLint;
import android.os.Build;
+import androidx.annotation.DoNotInline;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.annotation.RestrictTo;
import androidx.appsearch.app.Features;
+import androidx.appsearch.app.JoinSpec;
import androidx.appsearch.app.SearchSpec;
+import androidx.core.os.BuildCompat;
import androidx.core.util.Preconditions;
import java.util.List;
@@ -44,6 +47,9 @@
// Most jetpackSearchSpec.get calls cause WrongConstant lint errors because the methods are not
// defined as returning the same constants as the corresponding setter expects, but they do
@SuppressLint("WrongConstant")
+ // TODO(b/265311462): Remove BuildCompat.PrereleaseSdkCheck annotation once usage of
+ // BuildCompat.isAtLeastU() is removed.
+ @BuildCompat.PrereleaseSdkCheck
@NonNull
public static android.app.appsearch.SearchSpec toPlatformSearchSpec(
@NonNull SearchSpec jetpackSearchSpec) {
@@ -87,6 +93,31 @@
"Property weights are not supported with this backend/Android API level "
+ "combination.");
}
+
+ if (jetpackSearchSpec.getJoinSpec() != null) {
+ if (!BuildCompat.isAtLeastU()) {
+ throw new UnsupportedOperationException("JoinSpec is not available on this "
+ + "AppSearch implementation.");
+ }
+ ApiHelperForU.setJoinSpec(platformBuilder, jetpackSearchSpec.getJoinSpec());
+ }
return platformBuilder.build();
}
+
+ // TODO(b/265311462): Remove BuildCompat.PrereleaseSdkCheck annotation once usage of
+ // BuildCompat.isAtLeastU() is removed. Also, replace literal '34' with
+ // Build.VERSION_CODES.UPSIDE_DOWN_CAKE once the SDK_INT is finalized.
+ @BuildCompat.PrereleaseSdkCheck
+ @RequiresApi(34)
+ private static class ApiHelperForU {
+ private ApiHelperForU() {
+ // This class is not instantiable.
+ }
+
+ @DoNotInline
+ static void setJoinSpec(@NonNull android.app.appsearch.SearchSpec.Builder builder,
+ JoinSpec jetpackJoinSpec) {
+ builder.setJoinSpec(JoinSpecToPlatformConverter.toPlatformJoinSpec(jetpackJoinSpec));
+ }
+ }
}
diff --git a/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/converter/SetSchemaRequestToPlatformConverter.java b/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/converter/SetSchemaRequestToPlatformConverter.java
index 6950427..4dec86b 100644
--- a/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/converter/SetSchemaRequestToPlatformConverter.java
+++ b/appsearch/appsearch-platform-storage/src/main/java/androidx/appsearch/platformstorage/converter/SetSchemaRequestToPlatformConverter.java
@@ -18,6 +18,7 @@
import android.os.Build;
+import androidx.annotation.DoNotInline;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.annotation.RestrictTo;
@@ -47,6 +48,8 @@
* Translates a jetpack {@link SetSchemaRequest} into a platform
* {@link android.app.appsearch.SetSchemaRequest}.
*/
+ // TODO(b/265311462): Remove BuildCompat.PrereleaseSdkCheck annotation once usage of
+ // BuildCompat.isAtLeastU() is removed.
@BuildCompat.PrereleaseSdkCheck
@NonNull
public static android.app.appsearch.SetSchemaRequest toPlatformSetSchemaRequest(
@@ -74,7 +77,7 @@
}
}
if (!jetpackRequest.getRequiredPermissionsForSchemaTypeVisibility().isEmpty()) {
- if (!BuildCompat.isAtLeastT()) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
throw new UnsupportedOperationException(
"Set required permissions for schema type visibility are not supported "
+ "with this backend/Android API level combination.");
@@ -82,7 +85,7 @@
for (Map.Entry<String, Set<Set<Integer>>> entry :
jetpackRequest.getRequiredPermissionsForSchemaTypeVisibility().entrySet()) {
for (Set<Integer> permissionGroup : entry.getValue()) {
- platformBuilder.addRequiredPermissionsForSchemaTypeVisibility(
+ ApiHelperForT.addRequiredPermissionsForSchemaTypeVisibility(platformBuilder,
entry.getKey(), permissionGroup);
}
}
@@ -163,4 +166,18 @@
}
return jetpackBuilder.build();
}
+
+ @RequiresApi(Build.VERSION_CODES.TIRAMISU)
+ private static class ApiHelperForT {
+ private ApiHelperForT() {
+ // This class is not instantiable.
+ }
+
+ @DoNotInline
+ static void addRequiredPermissionsForSchemaTypeVisibility(
+ android.app.appsearch.SetSchemaRequest.Builder platformBuilder,
+ String schemaType, Set<Integer> permissions) {
+ platformBuilder.addRequiredPermissionsForSchemaTypeVisibility(schemaType, permissions);
+ }
+ }
}
diff --git a/appsearch/appsearch/src/androidTest/java/androidx/appsearch/cts/app/AppSearchSchemaMigrationLocalCtsTest.java b/appsearch/appsearch/src/androidTest/java/androidx/appsearch/cts/app/AppSearchSchemaMigrationLocalCtsTest.java
index 75b3888..0d0ac6e 100644
--- a/appsearch/appsearch/src/androidTest/java/androidx/appsearch/cts/app/AppSearchSchemaMigrationLocalCtsTest.java
+++ b/appsearch/appsearch/src/androidTest/java/androidx/appsearch/cts/app/AppSearchSchemaMigrationLocalCtsTest.java
@@ -22,12 +22,10 @@
import androidx.appsearch.app.AppSearchSession;
import androidx.appsearch.localstorage.LocalStorage;
import androidx.test.core.app.ApplicationProvider;
-import androidx.test.filters.FlakyTest;
import com.google.common.util.concurrent.ListenableFuture;
-@FlakyTest(bugId = 242761389)
-public class AppSearchSchemaMigrationLocalCtsTest extends AppSearchSchemaMigrationCtsTestBase{
+public class AppSearchSchemaMigrationLocalCtsTest extends AppSearchSchemaMigrationCtsTestBase {
@Override
protected ListenableFuture<AppSearchSession> createSearchSessionAsync(@NonNull String dbName) {
Context context = ApplicationProvider.getApplicationContext();
diff --git a/appsearch/appsearch/src/androidTest/java/androidx/appsearch/cts/app/AppSearchSessionCtsTestBase.java b/appsearch/appsearch/src/androidTest/java/androidx/appsearch/cts/app/AppSearchSessionCtsTestBase.java
index fb31d2e..9212462 100644
--- a/appsearch/appsearch/src/androidTest/java/androidx/appsearch/cts/app/AppSearchSessionCtsTestBase.java
+++ b/appsearch/appsearch/src/androidTest/java/androidx/appsearch/cts/app/AppSearchSessionCtsTestBase.java
@@ -3971,7 +3971,7 @@
.isFeatureSupported(Features.JOIN_SPEC_AND_QUALIFIED_ID));
// A full example of how join might be used
- AppSearchSchema actionSchema = new AppSearchSchema.Builder("BookmarkAction")
+ AppSearchSchema actionSchema = new AppSearchSchema.Builder("ViewAction")
.addProperty(new StringPropertyConfig.Builder("entityId")
.setCardinality(PropertyConfig.CARDINALITY_OPTIONAL)
.setIndexingType(StringPropertyConfig.INDEXING_TYPE_EXACT_TERMS)
@@ -4015,18 +4015,29 @@
String qualifiedId = DocumentIdUtil.createQualifiedId(mContext.getPackageName(), DB_NAME_1,
"namespace", "id1");
- GenericDocument join = new GenericDocument.Builder<>("NS", "id3", "BookmarkAction")
+ GenericDocument viewAction1 = new GenericDocument.Builder<>("NS", "id3", "ViewAction")
+ .setScore(1)
.setPropertyString("entityId", qualifiedId)
- .setPropertyString("note", "Hi this is a joined doc").build();
+ .setPropertyString("note", "Viewed email on Monday").build();
+ GenericDocument viewAction2 = new GenericDocument.Builder<>("NS", "id4", "ViewAction")
+ .setScore(2)
+ .setPropertyString("entityId", qualifiedId)
+ .setPropertyString("note", "Viewed email on Tuesday").build();
checkIsBatchResultSuccess(mDb1.putAsync(
- new PutDocumentsRequest.Builder().addGenericDocuments(inEmail, inEmail2, join)
+ new PutDocumentsRequest.Builder().addGenericDocuments(inEmail, inEmail2,
+ viewAction1, viewAction2)
.build()));
- SearchSpec nestedSearchSpec = new SearchSpec.Builder().build();
+ SearchSpec nestedSearchSpec =
+ new SearchSpec.Builder()
+ .setRankingStrategy(SearchSpec.RANKING_STRATEGY_DOCUMENT_SCORE)
+ .setOrder(SearchSpec.ORDER_ASCENDING)
+ .build();
JoinSpec js = new JoinSpec.Builder("entityId")
.setNestedSearch("", nestedSearchSpec)
.setAggregationScoringStrategy(JoinSpec.AGGREGATION_SCORING_RESULT_COUNT)
+ .setMaxJoinedResultCount(1)
.build();
SearchResults searchResults = mDb1.search("body email", new SearchSpec.Builder()
@@ -4042,7 +4053,7 @@
assertThat(sr.get(0).getGenericDocument().getId()).isEqualTo("id1");
assertThat(sr.get(0).getJoinedResults()).hasSize(1);
- assertThat(sr.get(0).getJoinedResults().get(0).getGenericDocument()).isEqualTo(join);
+ assertThat(sr.get(0).getJoinedResults().get(0).getGenericDocument()).isEqualTo(viewAction1);
assertThat(sr.get(0).getRankingSignal()).isEqualTo(1.0);
assertThat(sr.get(1).getGenericDocument().getId()).isEqualTo("id2");
@@ -4051,22 +4062,20 @@
}
@Test
- public void testJoinWithoutSupport() throws Exception {
+ public void testJoin_unsupportedFeature_throwsException() throws Exception {
assumeFalse(mDb1.getFeatures().isFeatureSupported(Features.JOIN_SPEC_AND_QUALIFIED_ID));
SearchSpec nestedSearchSpec = new SearchSpec.Builder().build();
JoinSpec js = new JoinSpec.Builder("entityId").setNestedSearch("", nestedSearchSpec)
.build();
- SearchResults searchResults = mDb1.search("", new SearchSpec.Builder()
- .setJoinSpec(js)
- .setTermMatch(SearchSpec.TERM_MATCH_EXACT_ONLY)
- .build());
-
- Exception e = assertThrows(UnsupportedOperationException.class, () ->
- searchResults.getNextPageAsync().get());
- assertThat(e).isInstanceOf(UnsupportedOperationException.class);
- assertThat(e.getMessage()).isEqualTo("Searching with a SearchSpec containing a JoinSpec "
- + "is not supported on this AppSearch implementation.");
+ Exception e = assertThrows(UnsupportedOperationException.class, () -> mDb1.search(
+ /*queryExpression */ "",
+ new SearchSpec.Builder()
+ .setJoinSpec(js)
+ .setTermMatch(SearchSpec.TERM_MATCH_EXACT_ONLY)
+ .build()));
+ assertThat(e.getMessage()).isEqualTo("JoinSpec is not available on this AppSearch "
+ + "implementation.");
}
@Test
diff --git a/appsearch/appsearch/src/androidTest/java/androidx/appsearch/cts/app/SearchSpecCtsTest.java b/appsearch/appsearch/src/androidTest/java/androidx/appsearch/cts/app/SearchSpecCtsTest.java
index 6a2a8f8..281894b 100644
--- a/appsearch/appsearch/src/androidTest/java/androidx/appsearch/cts/app/SearchSpecCtsTest.java
+++ b/appsearch/appsearch/src/androidTest/java/androidx/appsearch/cts/app/SearchSpecCtsTest.java
@@ -452,12 +452,13 @@
assertThat(e.getMessage()).isEqualTo("Attempting to rank based on joined documents, but"
+ " no JoinSpec provided");
+ JoinSpec joinSpec = new JoinSpec.Builder("childProp")
+ .setAggregationScoringStrategy(
+ JoinSpec.AGGREGATION_SCORING_SUM_RANKING_SIGNAL)
+ .build();
e = assertThrows(IllegalStateException.class, () -> new SearchSpec.Builder()
.setRankingStrategy(SearchSpec.RANKING_STRATEGY_CREATION_TIMESTAMP)
- .setJoinSpec(new JoinSpec.Builder("childProp")
- .setAggregationScoringStrategy(
- JoinSpec.AGGREGATION_SCORING_SUM_RANKING_SIGNAL)
- .build())
+ .setJoinSpec(joinSpec)
.build());
assertThat(e.getMessage()).isEqualTo("Aggregate scoring strategy has been set in the "
+ "nested JoinSpec, but ranking strategy is not "
diff --git a/buildSrc/public/src/main/kotlin/androidx/build/SupportConfig.kt b/buildSrc/public/src/main/kotlin/androidx/build/SupportConfig.kt
index 51626cc..33a5655 100644
--- a/buildSrc/public/src/main/kotlin/androidx/build/SupportConfig.kt
+++ b/buildSrc/public/src/main/kotlin/androidx/build/SupportConfig.kt
@@ -33,7 +33,7 @@
* Either an integer value or a pre-release platform code, prefixed with "android-" (ex.
* "android-28" or "android-Q") as you would see within the SDK's platforms directory.
*/
- const val COMPILE_SDK_VERSION = "android-33-ext4"
+ const val COMPILE_SDK_VERSION = "android-UpsideDownCake"
/**
* The Android SDK version to use for targetSdkVersion meta-data.
diff --git a/busytown/impl/check_translations.sh b/busytown/impl/check_translations.sh
index 35501ad..0f9e440 100755
--- a/busytown/impl/check_translations.sh
+++ b/busytown/impl/check_translations.sh
@@ -20,6 +20,7 @@
find . \
\( \
-iname '*sample*' \
+ -o -iname '*demo*' \
-o -iname '*donottranslate*' \
-o -iname '*debug*' \
-o -iname '*test*' \
diff --git a/constraintlayout/constraintlayout/api/api_lint.ignore b/constraintlayout/constraintlayout/api/api_lint.ignore
index 1f05e12..422e6ca 100644
--- a/constraintlayout/constraintlayout/api/api_lint.ignore
+++ b/constraintlayout/constraintlayout/api/api_lint.ignore
@@ -217,24 +217,6 @@
Invalid nullability on parameter `target` in method `onNestedFling`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
InvalidNullabilityOverride: androidx.constraintlayout.motion.widget.MotionLayout#onNestedPreFling(android.view.View, float, float) parameter #0:
Invalid nullability on parameter `target` in method `onNestedPreFling`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
-InvalidNullabilityOverride: androidx.constraintlayout.utils.widget.ImageFilterButton#draw(android.graphics.Canvas) parameter #0:
- Invalid nullability on parameter `canvas` in method `draw`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
-InvalidNullabilityOverride: androidx.constraintlayout.utils.widget.ImageFilterView#draw(android.graphics.Canvas) parameter #0:
- Invalid nullability on parameter `canvas` in method `draw`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
-InvalidNullabilityOverride: androidx.constraintlayout.utils.widget.MockView#onDraw(android.graphics.Canvas) parameter #0:
- Invalid nullability on parameter `canvas` in method `onDraw`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
-InvalidNullabilityOverride: androidx.constraintlayout.utils.widget.MotionButton#draw(android.graphics.Canvas) parameter #0:
- Invalid nullability on parameter `canvas` in method `draw`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
-InvalidNullabilityOverride: androidx.constraintlayout.utils.widget.MotionLabel#onDraw(android.graphics.Canvas) parameter #0:
- Invalid nullability on parameter `canvas` in method `onDraw`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
-InvalidNullabilityOverride: androidx.constraintlayout.widget.ConstraintHelper#onDraw(android.graphics.Canvas) parameter #0:
- Invalid nullability on parameter `canvas` in method `onDraw`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
-InvalidNullabilityOverride: androidx.constraintlayout.widget.Guideline#draw(android.graphics.Canvas) parameter #0:
- Invalid nullability on parameter `canvas` in method `draw`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
-InvalidNullabilityOverride: androidx.constraintlayout.widget.Placeholder#onDraw(android.graphics.Canvas) parameter #0:
- Invalid nullability on parameter `canvas` in method `onDraw`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
-InvalidNullabilityOverride: androidx.constraintlayout.widget.ReactiveGuide#draw(android.graphics.Canvas) parameter #0:
- Invalid nullability on parameter `canvas` in method `draw`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
KotlinOperator: androidx.constraintlayout.motion.utils.ViewTimeCycle#get(float, long, android.view.View, androidx.constraintlayout.core.motion.utils.KeyCache):
@@ -349,6 +331,8 @@
Missing nullability on method `getSpans` return
MissingNullability: androidx.constraintlayout.helper.widget.Grid#init(android.util.AttributeSet) parameter #0:
Missing nullability on parameter `attrs` in method `init`
+MissingNullability: androidx.constraintlayout.helper.widget.Grid#onDraw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `canvas` in method `onDraw`
MissingNullability: androidx.constraintlayout.helper.widget.Grid#setColumnWeights(String) parameter #0:
Missing nullability on parameter `columnWeights` in method `setColumnWeights`
MissingNullability: androidx.constraintlayout.helper.widget.Grid#setRowWeights(String) parameter #0:
@@ -1089,6 +1073,8 @@
Missing nullability on parameter `context` in method `ImageFilterButton`
MissingNullability: androidx.constraintlayout.utils.widget.ImageFilterButton#ImageFilterButton(android.content.Context, android.util.AttributeSet, int) parameter #1:
Missing nullability on parameter `attrs` in method `ImageFilterButton`
+MissingNullability: androidx.constraintlayout.utils.widget.ImageFilterButton#draw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `canvas` in method `draw`
MissingNullability: androidx.constraintlayout.utils.widget.ImageFilterButton#setImageDrawable(android.graphics.drawable.Drawable) parameter #0:
Missing nullability on parameter `drawable` in method `setImageDrawable`
MissingNullability: androidx.constraintlayout.utils.widget.ImageFilterView#ImageFilterView(android.content.Context) parameter #0:
@@ -1101,6 +1087,8 @@
Missing nullability on parameter `context` in method `ImageFilterView`
MissingNullability: androidx.constraintlayout.utils.widget.ImageFilterView#ImageFilterView(android.content.Context, android.util.AttributeSet, int) parameter #1:
Missing nullability on parameter `attrs` in method `ImageFilterView`
+MissingNullability: androidx.constraintlayout.utils.widget.ImageFilterView#draw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `canvas` in method `draw`
MissingNullability: androidx.constraintlayout.utils.widget.ImageFilterView#setAltImageDrawable(android.graphics.drawable.Drawable) parameter #0:
Missing nullability on parameter `altDrawable` in method `setAltImageDrawable`
MissingNullability: androidx.constraintlayout.utils.widget.ImageFilterView#setImageDrawable(android.graphics.drawable.Drawable) parameter #0:
@@ -1117,6 +1105,8 @@
Missing nullability on parameter `attrs` in method `MockView`
MissingNullability: androidx.constraintlayout.utils.widget.MockView#mText:
Missing nullability on field `mText` in class `class androidx.constraintlayout.utils.widget.MockView`
+MissingNullability: androidx.constraintlayout.utils.widget.MockView#onDraw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `canvas` in method `onDraw`
MissingNullability: androidx.constraintlayout.utils.widget.MotionButton#MotionButton(android.content.Context) parameter #0:
Missing nullability on parameter `context` in method `MotionButton`
MissingNullability: androidx.constraintlayout.utils.widget.MotionButton#MotionButton(android.content.Context, android.util.AttributeSet) parameter #0:
@@ -1127,6 +1117,8 @@
Missing nullability on parameter `context` in method `MotionButton`
MissingNullability: androidx.constraintlayout.utils.widget.MotionButton#MotionButton(android.content.Context, android.util.AttributeSet, int) parameter #1:
Missing nullability on parameter `attrs` in method `MotionButton`
+MissingNullability: androidx.constraintlayout.utils.widget.MotionButton#draw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `canvas` in method `draw`
MissingNullability: androidx.constraintlayout.utils.widget.MotionLabel#MotionLabel(android.content.Context) parameter #0:
Missing nullability on parameter `context` in method `MotionLabel`
MissingNullability: androidx.constraintlayout.utils.widget.MotionLabel#MotionLabel(android.content.Context, android.util.AttributeSet) parameter #0:
@@ -1135,6 +1127,8 @@
Missing nullability on parameter `context` in method `MotionLabel`
MissingNullability: androidx.constraintlayout.utils.widget.MotionLabel#getTypeface():
Missing nullability on method `getTypeface` return
+MissingNullability: androidx.constraintlayout.utils.widget.MotionLabel#onDraw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `canvas` in method `onDraw`
MissingNullability: androidx.constraintlayout.utils.widget.MotionLabel#setText(CharSequence) parameter #0:
Missing nullability on parameter `text` in method `setText`
MissingNullability: androidx.constraintlayout.utils.widget.MotionLabel#setTypeface(android.graphics.Typeface) parameter #0:
@@ -1149,6 +1143,8 @@
Missing nullability on parameter `context` in method `MotionTelltales`
MissingNullability: androidx.constraintlayout.utils.widget.MotionTelltales#MotionTelltales(android.content.Context, android.util.AttributeSet, int) parameter #1:
Missing nullability on parameter `attrs` in method `MotionTelltales`
+MissingNullability: androidx.constraintlayout.utils.widget.MotionTelltales#onDraw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `canvas` in method `onDraw`
MissingNullability: androidx.constraintlayout.utils.widget.MotionTelltales#setText(CharSequence) parameter #0:
Missing nullability on parameter `text` in method `setText`
MissingNullability: androidx.constraintlayout.widget.Barrier#Barrier(android.content.Context) parameter #0:
@@ -1267,6 +1263,8 @@
Missing nullability on field `mReferenceTags` in class `class androidx.constraintlayout.widget.ConstraintHelper`
MissingNullability: androidx.constraintlayout.widget.ConstraintHelper#myContext:
Missing nullability on field `myContext` in class `class androidx.constraintlayout.widget.ConstraintHelper`
+MissingNullability: androidx.constraintlayout.widget.ConstraintHelper#onDraw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `canvas` in method `onDraw`
MissingNullability: androidx.constraintlayout.widget.ConstraintHelper#removeView(android.view.View) parameter #0:
Missing nullability on parameter `view` in method `removeView`
MissingNullability: androidx.constraintlayout.widget.ConstraintHelper#resolveRtl(androidx.constraintlayout.core.widgets.ConstraintWidget, boolean) parameter #0:
@@ -1713,6 +1711,8 @@
Missing nullability on parameter `context` in method `Guideline`
MissingNullability: androidx.constraintlayout.widget.Guideline#Guideline(android.content.Context, android.util.AttributeSet, int, int) parameter #1:
Missing nullability on parameter `attrs` in method `Guideline`
+MissingNullability: androidx.constraintlayout.widget.Guideline#draw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `canvas` in method `draw`
MissingNullability: androidx.constraintlayout.widget.Placeholder#Placeholder(android.content.Context) parameter #0:
Missing nullability on parameter `context` in method `Placeholder`
MissingNullability: androidx.constraintlayout.widget.Placeholder#Placeholder(android.content.Context, android.util.AttributeSet) parameter #0:
@@ -1729,6 +1729,8 @@
Missing nullability on parameter `attrs` in method `Placeholder`
MissingNullability: androidx.constraintlayout.widget.Placeholder#getContent():
Missing nullability on method `getContent` return
+MissingNullability: androidx.constraintlayout.widget.Placeholder#onDraw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `canvas` in method `onDraw`
MissingNullability: androidx.constraintlayout.widget.Placeholder#updatePostMeasure(androidx.constraintlayout.widget.ConstraintLayout) parameter #0:
Missing nullability on parameter `container` in method `updatePostMeasure`
MissingNullability: androidx.constraintlayout.widget.Placeholder#updatePreLayout(androidx.constraintlayout.widget.ConstraintLayout) parameter #0:
@@ -1747,6 +1749,8 @@
Missing nullability on parameter `context` in method `ReactiveGuide`
MissingNullability: androidx.constraintlayout.widget.ReactiveGuide#ReactiveGuide(android.content.Context, android.util.AttributeSet, int, int) parameter #1:
Missing nullability on parameter `attrs` in method `ReactiveGuide`
+MissingNullability: androidx.constraintlayout.widget.ReactiveGuide#draw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `canvas` in method `draw`
MissingNullability: androidx.constraintlayout.widget.SharedValues#addListener(int, androidx.constraintlayout.widget.SharedValues.SharedValuesListener) parameter #1:
Missing nullability on parameter `listener` in method `addListener`
MissingNullability: androidx.constraintlayout.widget.SharedValues#removeListener(androidx.constraintlayout.widget.SharedValues.SharedValuesListener) parameter #0:
diff --git a/coordinatorlayout/coordinatorlayout/api/api_lint.ignore b/coordinatorlayout/coordinatorlayout/api/api_lint.ignore
index f200680..06d3c6e 100644
--- a/coordinatorlayout/coordinatorlayout/api/api_lint.ignore
+++ b/coordinatorlayout/coordinatorlayout/api/api_lint.ignore
@@ -1,6 +1,4 @@
// Baseline format: 1.0
-InvalidNullabilityOverride: androidx.coordinatorlayout.widget.CoordinatorLayout#onDraw(android.graphics.Canvas) parameter #0:
- Invalid nullability on parameter `c` in method `onDraw`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
InvalidNullabilityOverride: androidx.coordinatorlayout.widget.CoordinatorLayout#onNestedPreScroll(android.view.View, int, int, int[]) parameter #0:
Invalid nullability on parameter `target` in method `onNestedPreScroll`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
InvalidNullabilityOverride: androidx.coordinatorlayout.widget.CoordinatorLayout#onNestedPreScroll(android.view.View, int, int, int[]) parameter #3:
@@ -35,6 +33,8 @@
Missing nullability on method `generateLayoutParams` return
MissingNullability: androidx.coordinatorlayout.widget.CoordinatorLayout#generateLayoutParams(android.view.ViewGroup.LayoutParams) parameter #0:
Missing nullability on parameter `p` in method `generateLayoutParams`
+MissingNullability: androidx.coordinatorlayout.widget.CoordinatorLayout#onDraw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `c` in method `onDraw`
MissingNullability: androidx.coordinatorlayout.widget.CoordinatorLayout#onInterceptTouchEvent(android.view.MotionEvent) parameter #0:
Missing nullability on parameter `ev` in method `onInterceptTouchEvent`
MissingNullability: androidx.coordinatorlayout.widget.CoordinatorLayout#onNestedFling(android.view.View, float, float, boolean) parameter #0:
diff --git a/coordinatorlayout/coordinatorlayout/lint-baseline.xml b/coordinatorlayout/coordinatorlayout/lint-baseline.xml
index eb4748e..b3144af 100644
--- a/coordinatorlayout/coordinatorlayout/lint-baseline.xml
+++ b/coordinatorlayout/coordinatorlayout/lint-baseline.xml
@@ -1,5 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
-<issues format="6" by="lint 7.4.0-alpha08" type="baseline" client="gradle" dependencies="false" name="AGP (7.4.0-alpha08)" variant="all" version="7.4.0-alpha08">
+<issues format="6" by="lint 8.0.0-alpha07" type="baseline" client="gradle" dependencies="false" name="AGP (8.0.0-alpha07)" variant="all" version="8.0.0-alpha07">
+
+ <issue
+ id="UnknownNullness"
+ message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
+ errorLine1=" protected boolean drawChild(Canvas canvas, View child, long drawingTime) {"
+ errorLine2=" ~~~~~~">
+ <location
+ file="src/main/java/androidx/coordinatorlayout/widget/CoordinatorLayout.java"/>
+ </issue>
<issue
id="UnknownNullness"
diff --git a/core/core-ktx/src/main/java/androidx/core/os/OutcomeReceiver.kt b/core/core-ktx/src/main/java/androidx/core/os/OutcomeReceiver.kt
index 74052a3..d6698aa 100644
--- a/core/core-ktx/src/main/java/androidx/core/os/OutcomeReceiver.kt
+++ b/core/core-ktx/src/main/java/androidx/core/os/OutcomeReceiver.kt
@@ -61,7 +61,7 @@
private class ContinuationOutcomeReceiver<R, E : Throwable>(
private val continuation: Continuation<R>
) : OutcomeReceiver<R, E>, AtomicBoolean(false) {
- override fun onResult(result: R & Any) {
+ override fun onResult(result: R) {
// Do not attempt to resume more than once, even if the caller of the returned
// OutcomeReceiver is buggy and tries anyway.
if (compareAndSet(false, true)) {
diff --git a/core/core/api/current.txt b/core/core/api/current.txt
index 3f5d92d..7e893ff 100644
--- a/core/core/api/current.txt
+++ b/core/core/api/current.txt
@@ -2009,6 +2009,26 @@
}
+package androidx.core.service.quicksettings {
+
+ public class PendingIntentActivityWrapper {
+ ctor public PendingIntentActivityWrapper(android.content.Context, int, android.content.Intent, int, boolean);
+ ctor public PendingIntentActivityWrapper(android.content.Context, int, android.content.Intent, int, android.os.Bundle?, boolean);
+ method public android.content.Context getContext();
+ method public int getFlags();
+ method public android.content.Intent getIntent();
+ method public android.os.Bundle getOptions();
+ method public android.app.PendingIntent? getPendingIntent();
+ method public int getRequestCode();
+ method public boolean isMutable();
+ }
+
+ public class TileServiceCompat {
+ method public static void startActivityAndCollapse(android.service.quicksettings.TileService, androidx.core.service.quicksettings.PendingIntentActivityWrapper);
+ }
+
+}
+
package androidx.core.telephony {
@RequiresApi(22) public class SubscriptionManagerCompat {
@@ -2149,6 +2169,66 @@
method public static boolean addLinks(android.text.Spannable, java.util.regex.Pattern, String?, String![]?, android.text.util.Linkify.MatchFilter?, android.text.util.Linkify.TransformFilter?);
}
+ public final class LocalePreferences {
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getCalendarType();
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getCalendarType(java.util.Locale);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getCalendarType(boolean);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getCalendarType(java.util.Locale, boolean);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getFirstDayOfWeek();
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getFirstDayOfWeek(java.util.Locale);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getFirstDayOfWeek(boolean);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getFirstDayOfWeek(java.util.Locale, boolean);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getHourCycle();
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getHourCycle(java.util.Locale);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getHourCycle(boolean);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getHourCycle(java.util.Locale, boolean);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getTemperatureUnit();
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getTemperatureUnit(java.util.Locale);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getTemperatureUnit(boolean);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getTemperatureUnit(java.util.Locale, boolean);
+ }
+
+ public static class LocalePreferences.CalendarType {
+ field public static final String CHINESE = "chinese";
+ field public static final String DANGI = "dangi";
+ field public static final String DEFAULT = "";
+ field public static final String GREGORIAN = "gregorian";
+ field public static final String HEBREW = "hebrew";
+ field public static final String INDIAN = "indian";
+ field public static final String ISLAMIC = "islamic";
+ field public static final String ISLAMIC_CIVIL = "islamic-civil";
+ field public static final String ISLAMIC_RGSA = "islamic-rgsa";
+ field public static final String ISLAMIC_TBLA = "islamic-tbla";
+ field public static final String ISLAMIC_UMALQURA = "islamic-umalqura";
+ field public static final String PERSIAN = "persian";
+ }
+
+ public static class LocalePreferences.FirstDayOfWeek {
+ field public static final String DEFAULT = "";
+ field public static final String FRIDAY = "fri";
+ field public static final String MONDAY = "mon";
+ field public static final String SATURDAY = "sat";
+ field public static final String SUNDAY = "sun";
+ field public static final String THURSDAY = "thu";
+ field public static final String TUESDAY = "tue";
+ field public static final String WEDNESDAY = "wed";
+ }
+
+ public static class LocalePreferences.HourCycle {
+ field public static final String DEFAULT = "";
+ field public static final String H11 = "h11";
+ field public static final String H12 = "h12";
+ field public static final String H23 = "h23";
+ field public static final String H24 = "h24";
+ }
+
+ public static class LocalePreferences.TemperatureUnit {
+ field public static final String CELSIUS = "celsius";
+ field public static final String DEFAULT = "";
+ field public static final String FAHRENHEIT = "fahrenheit";
+ field public static final String KELVIN = "kelvin";
+ }
+
}
package androidx.core.util {
@@ -2687,9 +2767,12 @@
method public void setSupportBackgroundTintMode(android.graphics.PorterDuff.Mode?);
}
- @Deprecated public final class VelocityTrackerCompat {
+ public final class VelocityTrackerCompat {
+ method public static float getAxisVelocity(android.view.VelocityTracker, int);
+ method public static float getAxisVelocity(android.view.VelocityTracker, int, int);
method @Deprecated public static float getXVelocity(android.view.VelocityTracker!, int);
method @Deprecated public static float getYVelocity(android.view.VelocityTracker!, int);
+ method public static boolean isAxisSupported(android.view.VelocityTracker, int);
}
public class ViewCompat {
@@ -3626,6 +3709,7 @@
}
public class AccessibilityWindowInfoCompat {
+ ctor public AccessibilityWindowInfoCompat();
method public androidx.core.view.accessibility.AccessibilityNodeInfoCompat? getAnchor();
method public void getBoundsInScreen(android.graphics.Rect);
method public androidx.core.view.accessibility.AccessibilityWindowInfoCompat? getChild(int);
diff --git a/core/core/api/public_plus_experimental_current.txt b/core/core/api/public_plus_experimental_current.txt
index 9df9106..75a2c81 100644
--- a/core/core/api/public_plus_experimental_current.txt
+++ b/core/core/api/public_plus_experimental_current.txt
@@ -2015,6 +2015,26 @@
}
+package androidx.core.service.quicksettings {
+
+ public class PendingIntentActivityWrapper {
+ ctor public PendingIntentActivityWrapper(android.content.Context, int, android.content.Intent, int, boolean);
+ ctor public PendingIntentActivityWrapper(android.content.Context, int, android.content.Intent, int, android.os.Bundle?, boolean);
+ method public android.content.Context getContext();
+ method public int getFlags();
+ method public android.content.Intent getIntent();
+ method public android.os.Bundle getOptions();
+ method public android.app.PendingIntent? getPendingIntent();
+ method public int getRequestCode();
+ method public boolean isMutable();
+ }
+
+ public class TileServiceCompat {
+ method public static void startActivityAndCollapse(android.service.quicksettings.TileService, androidx.core.service.quicksettings.PendingIntentActivityWrapper);
+ }
+
+}
+
package androidx.core.telephony {
@RequiresApi(22) public class SubscriptionManagerCompat {
@@ -2155,6 +2175,66 @@
method public static boolean addLinks(android.text.Spannable, java.util.regex.Pattern, String?, String![]?, android.text.util.Linkify.MatchFilter?, android.text.util.Linkify.TransformFilter?);
}
+ public final class LocalePreferences {
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getCalendarType();
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getCalendarType(java.util.Locale);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getCalendarType(boolean);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getCalendarType(java.util.Locale, boolean);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getFirstDayOfWeek();
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getFirstDayOfWeek(java.util.Locale);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getFirstDayOfWeek(boolean);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getFirstDayOfWeek(java.util.Locale, boolean);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getHourCycle();
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getHourCycle(java.util.Locale);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getHourCycle(boolean);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getHourCycle(java.util.Locale, boolean);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getTemperatureUnit();
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getTemperatureUnit(java.util.Locale);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getTemperatureUnit(boolean);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getTemperatureUnit(java.util.Locale, boolean);
+ }
+
+ public static class LocalePreferences.CalendarType {
+ field public static final String CHINESE = "chinese";
+ field public static final String DANGI = "dangi";
+ field public static final String DEFAULT = "";
+ field public static final String GREGORIAN = "gregorian";
+ field public static final String HEBREW = "hebrew";
+ field public static final String INDIAN = "indian";
+ field public static final String ISLAMIC = "islamic";
+ field public static final String ISLAMIC_CIVIL = "islamic-civil";
+ field public static final String ISLAMIC_RGSA = "islamic-rgsa";
+ field public static final String ISLAMIC_TBLA = "islamic-tbla";
+ field public static final String ISLAMIC_UMALQURA = "islamic-umalqura";
+ field public static final String PERSIAN = "persian";
+ }
+
+ public static class LocalePreferences.FirstDayOfWeek {
+ field public static final String DEFAULT = "";
+ field public static final String FRIDAY = "fri";
+ field public static final String MONDAY = "mon";
+ field public static final String SATURDAY = "sat";
+ field public static final String SUNDAY = "sun";
+ field public static final String THURSDAY = "thu";
+ field public static final String TUESDAY = "tue";
+ field public static final String WEDNESDAY = "wed";
+ }
+
+ public static class LocalePreferences.HourCycle {
+ field public static final String DEFAULT = "";
+ field public static final String H11 = "h11";
+ field public static final String H12 = "h12";
+ field public static final String H23 = "h23";
+ field public static final String H24 = "h24";
+ }
+
+ public static class LocalePreferences.TemperatureUnit {
+ field public static final String CELSIUS = "celsius";
+ field public static final String DEFAULT = "";
+ field public static final String FAHRENHEIT = "fahrenheit";
+ field public static final String KELVIN = "kelvin";
+ }
+
}
package androidx.core.util {
@@ -2693,9 +2773,12 @@
method public void setSupportBackgroundTintMode(android.graphics.PorterDuff.Mode?);
}
- @Deprecated public final class VelocityTrackerCompat {
+ public final class VelocityTrackerCompat {
+ method public static float getAxisVelocity(android.view.VelocityTracker, int);
+ method public static float getAxisVelocity(android.view.VelocityTracker, int, int);
method @Deprecated public static float getXVelocity(android.view.VelocityTracker!, int);
method @Deprecated public static float getYVelocity(android.view.VelocityTracker!, int);
+ method public static boolean isAxisSupported(android.view.VelocityTracker, int);
}
public class ViewCompat {
@@ -3632,6 +3715,7 @@
}
public class AccessibilityWindowInfoCompat {
+ ctor public AccessibilityWindowInfoCompat();
method public androidx.core.view.accessibility.AccessibilityNodeInfoCompat? getAnchor();
method public void getBoundsInScreen(android.graphics.Rect);
method public androidx.core.view.accessibility.AccessibilityWindowInfoCompat? getChild(int);
diff --git a/core/core/api/restricted_current.txt b/core/core/api/restricted_current.txt
index 51353767..0913d2e 100644
--- a/core/core/api/restricted_current.txt
+++ b/core/core/api/restricted_current.txt
@@ -2373,6 +2373,26 @@
}
+package androidx.core.service.quicksettings {
+
+ public class PendingIntentActivityWrapper {
+ ctor public PendingIntentActivityWrapper(android.content.Context, int, android.content.Intent, int, boolean);
+ ctor public PendingIntentActivityWrapper(android.content.Context, int, android.content.Intent, int, android.os.Bundle?, boolean);
+ method public android.content.Context getContext();
+ method public int getFlags();
+ method public android.content.Intent getIntent();
+ method public android.os.Bundle getOptions();
+ method public android.app.PendingIntent? getPendingIntent();
+ method public int getRequestCode();
+ method public boolean isMutable();
+ }
+
+ public class TileServiceCompat {
+ method public static void startActivityAndCollapse(android.service.quicksettings.TileService, androidx.core.service.quicksettings.PendingIntentActivityWrapper);
+ }
+
+}
+
package androidx.core.telephony {
@RequiresApi(22) public class SubscriptionManagerCompat {
@@ -2518,6 +2538,66 @@
@IntDef(flag=true, value={android.text.util.Linkify.WEB_URLS, android.text.util.Linkify.EMAIL_ADDRESSES, android.text.util.Linkify.PHONE_NUMBERS, android.text.util.Linkify.MAP_ADDRESSES, android.text.util.Linkify.ALL}) @RestrictTo(androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP_PREFIX) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) public static @interface LinkifyCompat.LinkifyMask {
}
+ public final class LocalePreferences {
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getCalendarType();
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getCalendarType(java.util.Locale);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getCalendarType(boolean);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getCalendarType(java.util.Locale, boolean);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getFirstDayOfWeek();
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getFirstDayOfWeek(java.util.Locale);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getFirstDayOfWeek(boolean);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getFirstDayOfWeek(java.util.Locale, boolean);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getHourCycle();
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getHourCycle(java.util.Locale);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getHourCycle(boolean);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getHourCycle(java.util.Locale, boolean);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getTemperatureUnit();
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getTemperatureUnit(java.util.Locale);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getTemperatureUnit(boolean);
+ method @RequiresApi(android.os.Build.VERSION_CODES.TIRAMISU) public static String getTemperatureUnit(java.util.Locale, boolean);
+ }
+
+ public static class LocalePreferences.CalendarType {
+ field public static final String CHINESE = "chinese";
+ field public static final String DANGI = "dangi";
+ field public static final String DEFAULT = "";
+ field public static final String GREGORIAN = "gregorian";
+ field public static final String HEBREW = "hebrew";
+ field public static final String INDIAN = "indian";
+ field public static final String ISLAMIC = "islamic";
+ field public static final String ISLAMIC_CIVIL = "islamic-civil";
+ field public static final String ISLAMIC_RGSA = "islamic-rgsa";
+ field public static final String ISLAMIC_TBLA = "islamic-tbla";
+ field public static final String ISLAMIC_UMALQURA = "islamic-umalqura";
+ field public static final String PERSIAN = "persian";
+ }
+
+ public static class LocalePreferences.FirstDayOfWeek {
+ field public static final String DEFAULT = "";
+ field public static final String FRIDAY = "fri";
+ field public static final String MONDAY = "mon";
+ field public static final String SATURDAY = "sat";
+ field public static final String SUNDAY = "sun";
+ field public static final String THURSDAY = "thu";
+ field public static final String TUESDAY = "tue";
+ field public static final String WEDNESDAY = "wed";
+ }
+
+ public static class LocalePreferences.HourCycle {
+ field public static final String DEFAULT = "";
+ field public static final String H11 = "h11";
+ field public static final String H12 = "h12";
+ field public static final String H23 = "h23";
+ field public static final String H24 = "h24";
+ }
+
+ public static class LocalePreferences.TemperatureUnit {
+ field public static final String CELSIUS = "celsius";
+ field public static final String DEFAULT = "";
+ field public static final String FAHRENHEIT = "fahrenheit";
+ field public static final String KELVIN = "kelvin";
+ }
+
}
package androidx.core.util {
@@ -3123,9 +3203,15 @@
method public void setSupportBackgroundTintMode(android.graphics.PorterDuff.Mode?);
}
- @Deprecated public final class VelocityTrackerCompat {
+ public final class VelocityTrackerCompat {
+ method public static float getAxisVelocity(android.view.VelocityTracker, @androidx.core.view.VelocityTrackerCompat.VelocityTrackableMotionEventAxis int);
+ method public static float getAxisVelocity(android.view.VelocityTracker, @androidx.core.view.VelocityTrackerCompat.VelocityTrackableMotionEventAxis int, int);
method @Deprecated public static float getXVelocity(android.view.VelocityTracker!, int);
method @Deprecated public static float getYVelocity(android.view.VelocityTracker!, int);
+ method public static boolean isAxisSupported(android.view.VelocityTracker, @androidx.core.view.VelocityTrackerCompat.VelocityTrackableMotionEventAxis int);
+ }
+
+ @IntDef({android.view.MotionEvent.AXIS_X, android.view.MotionEvent.AXIS_Y, android.view.MotionEvent.AXIS_SCROLL}) @RestrictTo(androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP_PREFIX) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) public static @interface VelocityTrackerCompat.VelocityTrackableMotionEventAxis {
}
public class ViewCompat {
@@ -4099,6 +4185,7 @@
}
public class AccessibilityWindowInfoCompat {
+ ctor public AccessibilityWindowInfoCompat();
method public androidx.core.view.accessibility.AccessibilityNodeInfoCompat? getAnchor();
method public void getBoundsInScreen(android.graphics.Rect);
method public androidx.core.view.accessibility.AccessibilityWindowInfoCompat? getChild(int);
diff --git a/core/core/lint-baseline.xml b/core/core/lint-baseline.xml
index 2949272..ca1c7c0 100644
--- a/core/core/lint-baseline.xml
+++ b/core/core/lint-baseline.xml
@@ -713,6 +713,15 @@
</issue>
<issue
+ id="Range"
+ message="Value must be ≥ 1 and ≤ 200 but `getSvid` can be 206"
+ errorLine1=" return mWrapped.getSvid(satelliteIndex);"
+ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
+ <location
+ file="src/main/java/androidx/core/location/GnssStatusWrapper.java"/>
+ </issue>
+
+ <issue
id="WrongConstant"
message="Must be one of: Callback.DISPATCH_MODE_STOP, Callback.DISPATCH_MODE_CONTINUE_ON_SUBTREE"
errorLine1=" super(compat.getDispatchMode());"
diff --git a/core/core/src/androidTest/java/androidx/core/content/ContextCompatTest.java b/core/core/src/androidTest/java/androidx/core/content/ContextCompatTest.java
index 85db291..9629356 100644
--- a/core/core/src/androidTest/java/androidx/core/content/ContextCompatTest.java
+++ b/core/core/src/androidTest/java/androidx/core/content/ContextCompatTest.java
@@ -86,6 +86,7 @@
import android.app.KeyguardManager;
import android.app.NotificationManager;
import android.app.SearchManager;
+import android.app.UiAutomation;
import android.app.UiModeManager;
import android.app.WallpaperManager;
import android.app.admin.DevicePolicyManager;
@@ -517,11 +518,15 @@
@Test
@SdkSuppress(minSdkVersion = 29, maxSdkVersion = 32)
public void testRegisterReceiverPermissionNotGrantedApi26() {
- InstrumentationRegistry
- .getInstrumentation().getUiAutomation().adoptShellPermissionIdentity();
- assertThrows(RuntimeException.class,
- () -> ContextCompat.registerReceiver(mContext,
- mTestReceiver, mTestFilter, ContextCompat.RECEIVER_NOT_EXPORTED));
+ UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
+ uiAutomation.adoptShellPermissionIdentity();
+ try {
+ assertThrows(RuntimeException.class,
+ () -> ContextCompat.registerReceiver(mContext,
+ mTestReceiver, mTestFilter, ContextCompat.RECEIVER_NOT_EXPORTED));
+ } finally {
+ uiAutomation.dropShellPermissionIdentity();
+ }
}
@Test
diff --git a/core/core/src/androidTest/java/androidx/core/service/quicksettings/TileServiceCompatTest.java b/core/core/src/androidTest/java/androidx/core/service/quicksettings/TileServiceCompatTest.java
new file mode 100644
index 0000000..a78f703
--- /dev/null
+++ b/core/core/src/androidTest/java/androidx/core/service/quicksettings/TileServiceCompatTest.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright 2023 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 androidx.core.service.quicksettings;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.service.quicksettings.TileService;
+
+import androidx.test.core.app.ApplicationProvider;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.filters.SdkSuppress;
+import androidx.test.filters.SmallTest;
+
+import org.junit.After;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * Unit test for {@link TileServiceCompat}.
+ */
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class TileServiceCompatTest {
+
+ private final Context mContext = ApplicationProvider.getApplicationContext();
+
+ @After
+ public void tearDown() {
+ TileServiceCompat.clearTileServiceWrapper();
+ }
+
+ @SdkSuppress(minSdkVersion = 34)
+ @Test
+ public void startActivityAndCollapse_usesPendingIntent() {
+ TileServiceCompat.TileServiceWrapper tileServiceWrapper =
+ mock(TileServiceCompat.TileServiceWrapper.class);
+ TileService tileService = mock(TileService.class);
+ int requestCode = 7465;
+ Intent intent = new Intent();
+ Bundle options = new Bundle();
+ PendingIntentActivityWrapper wrapper = new PendingIntentActivityWrapper(mContext,
+ requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT, options, /* isMutable = */
+ true);
+ TileServiceCompat.setTileServiceWrapper(tileServiceWrapper);
+
+ TileServiceCompat.startActivityAndCollapse(tileService, wrapper);
+
+ verify(tileServiceWrapper).startActivityAndCollapse(wrapper.getPendingIntent());
+ }
+
+ @SdkSuppress(minSdkVersion = 24, maxSdkVersion = 33)
+ @Test
+ public void startActivityAndCollapse_usesIntent() {
+ TileServiceCompat.TileServiceWrapper tileServiceWrapper =
+ mock(TileServiceCompat.TileServiceWrapper.class);
+ TileService tileService = mock(TileService.class);
+ int requestCode = 7465;
+ Intent intent = new Intent();
+ Bundle options = new Bundle();
+ PendingIntentActivityWrapper wrapper = new PendingIntentActivityWrapper(mContext,
+ requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT, options, /* isMutable = */
+ true);
+ TileServiceCompat.setTileServiceWrapper(tileServiceWrapper);
+
+ TileServiceCompat.startActivityAndCollapse(tileService, wrapper);
+
+ verify(tileServiceWrapper).startActivityAndCollapse(intent);
+ }
+}
diff --git a/core/core/src/androidTest/java/androidx/core/text/util/LocalePreferencesTest.java b/core/core/src/androidTest/java/androidx/core/text/util/LocalePreferencesTest.java
new file mode 100644
index 0000000..c59ae1f
--- /dev/null
+++ b/core/core/src/androidTest/java/androidx/core/text/util/LocalePreferencesTest.java
@@ -0,0 +1,337 @@
+/*
+ * 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 androidx.core.text.util;
+
+import static org.junit.Assert.assertEquals;
+
+import android.os.Build.VERSION_CODES;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.filters.SdkSuppress;
+import androidx.test.filters.SmallTest;
+
+import org.junit.After;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.Locale;
+
+@SmallTest
+@SdkSuppress(minSdkVersion = VERSION_CODES.TIRAMISU)
+@RunWith(AndroidJUnit4.class)
+public class LocalePreferencesTest {
+ private static Locale sLocale;
+
+ @BeforeClass
+ public static void setUpClass() throws Exception {
+ sLocale = Locale.getDefault(Locale.Category.FORMAT);
+ }
+
+ @After
+ public void tearDown() {
+ Locale.setDefault(sLocale);
+ }
+
+ // Hour cycle
+ @Test
+ public void getHourCycle_hasSubTags_resultIsH24() throws Exception {
+ Locale.setDefault(Locale.forLanguageTag("en-US-u-ca-chinese-hc-h24-mu-celsius-fw-wed"));
+
+ String result = LocalePreferences.getHourCycle();
+
+ assertEquals(LocalePreferences.HourCycle.H24, result);
+ }
+
+ @Test
+ public void getHourCycle_hasSubTagsWithoutHourCycleTag_resultIsH12() throws Exception {
+ Locale.setDefault(Locale.forLanguageTag("en-US-u-ca-chinese-mu-celsius-fw-wed"));
+
+ String result = LocalePreferences.getHourCycle();
+
+ assertEquals(LocalePreferences.HourCycle.H12, result);
+ }
+
+ @Test
+ public void getHourCycle_hasSubTagsAndDisableResolved_resultIsH24() throws Exception {
+ Locale.setDefault(Locale.forLanguageTag("en-US-u-ca-chinese-hc-h24-mu-celsius-fw-wed"));
+
+ String result = LocalePreferences.getHourCycle(false);
+
+ assertEquals(LocalePreferences.HourCycle.H24, result);
+ }
+
+ @Test
+ public void getHourCycle_hasSubTagsWithoutHourCycleTagAndDisableResolved_resultIsEmpty()
+ throws Exception {
+ Locale.setDefault(Locale.forLanguageTag("en-US-u-ca-chinese-mu-celsius-fw-wed"));
+
+ String result = LocalePreferences.getHourCycle(false);
+
+ assertEquals(LocalePreferences.HourCycle.DEFAULT, result);
+ }
+
+ @Test
+ public void getHourCycle_inputLocaleWithHourCycleTag_resultIsH12() throws Exception {
+ String result = LocalePreferences.getHourCycle(Locale.forLanguageTag("en-US-u-hc-h12"));
+
+ assertEquals(LocalePreferences.HourCycle.H12, result);
+ }
+
+ @Test
+ public void getHourCycle_inputLocaleWithoutHourCycleTag_resultIsH12() throws Exception {
+ String result = LocalePreferences.getHourCycle(Locale.forLanguageTag("en-US"));
+
+ assertEquals(LocalePreferences.HourCycle.H12, result);
+ }
+
+ @Test
+ public void getHourCycle_inputH23Locale_resultIsH23() throws Exception {
+ String result = LocalePreferences.getHourCycle(Locale.forLanguageTag("fr-FR"));
+
+ assertEquals(LocalePreferences.HourCycle.H23, result);
+ }
+
+ @Test
+ public void getHourCycle_inputH23LocaleWithHourCycleTag_resultIsH12() throws Exception {
+ String result = LocalePreferences.getHourCycle(Locale.forLanguageTag("fr-FR-u-hc-h12"));
+
+ assertEquals(LocalePreferences.HourCycle.H12, result);
+ }
+
+ @Test
+ public void getHourCycle_inputLocaleWithoutHourCycleTagAndDisableResolved_resultIsEmpty()
+ throws Exception {
+ String result = LocalePreferences.getHourCycle(Locale.forLanguageTag("en-US"), false);
+
+ assertEquals(LocalePreferences.HourCycle.DEFAULT, result);
+ }
+
+ @Test
+ public void getHourCycle_compareHasResolvedValueIsTrueAndWithoutResolvedValue_sameResult()
+ throws Exception {
+ Locale.setDefault(Locale.forLanguageTag("zh-TW-u-ca-chinese-hc-h24-mu-celsius-fw-wed"));
+
+ // Has Hour Cycle subtag
+ String resultWithoutResolvedValue = LocalePreferences.getHourCycle();
+ String resultResolvedIsTrue = LocalePreferences.getHourCycle(true);
+ assertEquals(resultWithoutResolvedValue, resultResolvedIsTrue);
+
+ // Does not have HourCycle subtag
+ Locale.setDefault(Locale.forLanguageTag("zh-TW-u-ca-chinese-mu-celsius-fw-wed"));
+
+ resultWithoutResolvedValue = LocalePreferences.getHourCycle();
+ resultResolvedIsTrue = LocalePreferences.getHourCycle(true);
+ assertEquals(resultWithoutResolvedValue, resultResolvedIsTrue);
+ }
+
+ // Calendar
+ @Test
+ public void getCalendarType_hasSubTags_resultIsChinese() throws Exception {
+ Locale.setDefault(Locale.forLanguageTag("en-US-u-ca-chinese-hc-h24-mu-celsius-fw-wed"));
+
+ String result = LocalePreferences.getCalendarType();
+
+ assertEquals(LocalePreferences.CalendarType.CHINESE, result);
+ }
+
+ @Test
+ public void getCalendarType_hasSubTagsWithoutCalendarTag_resultIsGregorian() throws Exception {
+ Locale.setDefault(Locale.forLanguageTag("en-US-u-hc-h24-mu-celsius-fw-wed"));
+
+ String result = LocalePreferences.getCalendarType();
+
+ assertEquals(LocalePreferences.CalendarType.GREGORIAN, result);
+ }
+
+ @Test
+ public void getCalendarType_hasSubTagsAndDisableResolved_resultIsChinese() throws Exception {
+ Locale.setDefault(Locale.forLanguageTag("en-US-u-ca-chinese-hc-h24-mu-celsius-fw-wed"));
+
+ String result = LocalePreferences.getCalendarType(false);
+
+ assertEquals(LocalePreferences.CalendarType.CHINESE, result);
+ }
+
+ @Test
+ public void getCalendarType_hasSubTagsWithoutCalendarTagAndDisableResolved_resultIsEmpty()
+ throws Exception {
+ Locale.setDefault(Locale.forLanguageTag("en-US-u-mu-celsius-fw-wed"));
+
+ String result = LocalePreferences.getCalendarType(false);
+
+ assertEquals(LocalePreferences.CalendarType.DEFAULT, result);
+ }
+
+ @Test
+ public void getCalendarType_inputLocaleWithCalendarTag_resultIsChinese() throws Exception {
+ String result =
+ LocalePreferences.getCalendarType(Locale.forLanguageTag("en-US-u-ca-chinese"));
+
+ assertEquals(LocalePreferences.CalendarType.CHINESE, result);
+ }
+
+ @Test
+ public void getCalendarType_inputLocaleWithoutCalendarTag_resultIsGregorian() throws Exception {
+ String result = LocalePreferences.getCalendarType(Locale.forLanguageTag("en-US"));
+
+ assertEquals(LocalePreferences.CalendarType.GREGORIAN, result);
+ }
+
+ @Test
+ public void getCalendarType_inputLocaleWithoutCalendarTagAndDisableResolved_resultIsEmpty()
+ throws Exception {
+ String result = LocalePreferences.getCalendarType(Locale.forLanguageTag("en-US"), false);
+
+ assertEquals(LocalePreferences.CalendarType.DEFAULT, result);
+ }
+
+ // Temperature unit
+ @Test
+ public void getTemperatureUnit_hasSubTags_resultIsCelsius() throws Exception {
+ Locale.setDefault(Locale.forLanguageTag("en-US-u-ca-chinese-hc-h24-mu-celsius-fw-wed"));
+
+ String result = LocalePreferences.getTemperatureUnit();
+
+ assertEquals(LocalePreferences.TemperatureUnit.CELSIUS, result);
+ }
+
+ @Test
+ public void getTemperatureUnit_hasSubTagsWithoutUnitTag_resultIsFahrenheit() throws Exception {
+ Locale.setDefault(Locale.forLanguageTag("en-US-u-hc-h24-fw-wed"));
+
+ String result = LocalePreferences.getTemperatureUnit();
+
+ assertEquals(LocalePreferences.TemperatureUnit.FAHRENHEIT, result);
+ }
+
+ @Test
+ public void getTemperatureUnit_hasSubTagsAndDisableResolved_resultIsCelsius() throws Exception {
+ Locale.setDefault(Locale.forLanguageTag("en-US-u-ca-chinese-hc-h24-mu-celsius-fw-wed"));
+
+ String result = LocalePreferences.getTemperatureUnit(false);
+
+ assertEquals(LocalePreferences.TemperatureUnit.CELSIUS, result);
+ }
+
+ @Test
+ public void getTemperatureUnit_hasSubTagsAndDisableResolved_resultIsFahrenheit()
+ throws Exception {
+ Locale.setDefault(Locale.forLanguageTag("zh-TW-u-ca-chinese-hc-h24-mu-fahrenhe-fw-wed"));
+
+ String result = LocalePreferences.getTemperatureUnit(false);
+
+ assertEquals(LocalePreferences.TemperatureUnit.FAHRENHEIT, result);
+ }
+
+ @Test
+ public void getTemperatureUnit_hasSubTagsWithoutUnitTagAndDisableResolved_resultIsEmpty()
+ throws Exception {
+ Locale.setDefault(Locale.forLanguageTag("en-US-u-fw-wed"));
+
+ String result = LocalePreferences.getTemperatureUnit(false);
+
+ assertEquals(LocalePreferences.TemperatureUnit.DEFAULT, result);
+ }
+
+ @Test
+ public void getTemperatureUnit_inputLocaleWithUnitTag_resultIsCelsius() throws Exception {
+ String result = LocalePreferences
+ .getTemperatureUnit(Locale.forLanguageTag("en-US-u-mu-celsius"));
+
+ assertEquals(LocalePreferences.TemperatureUnit.CELSIUS, result);
+ }
+
+ @Test
+ public void getTemperatureUnit_inputLocaleWithoutUnitTag_resultIsFahrenheit() throws Exception {
+ String result = LocalePreferences.getTemperatureUnit(Locale.forLanguageTag("en-US"));
+
+ assertEquals(LocalePreferences.TemperatureUnit.FAHRENHEIT, result);
+ }
+
+ @Test
+ public void getTemperatureUnit_inputLocaleWithoutUnitTagAndDisableResolved_resultIsEmpty()
+ throws Exception {
+ String result = LocalePreferences
+ .getTemperatureUnit(Locale.forLanguageTag("en-US"), false);
+
+ assertEquals(LocalePreferences.TemperatureUnit.DEFAULT, result);
+ }
+
+ // First day of week
+ @Test
+ public void getFirstDayOfWeek_hasSubTags_resultIsCelsius() throws Exception {
+ Locale.setDefault(Locale.forLanguageTag("en-US-u-ca-chinese-hc-h24-mu-celsius-fw-wed"));
+
+ String result = LocalePreferences.getFirstDayOfWeek();
+
+ assertEquals(LocalePreferences.FirstDayOfWeek.WEDNESDAY, result);
+ }
+
+ @Test
+ public void getFirstDayOfWeek_hasSubTagsWithoutFwTag_resultIsSun() throws Exception {
+ Locale.setDefault(Locale.forLanguageTag("en-US-u-hc-h24"));
+
+ String result = LocalePreferences.getFirstDayOfWeek();
+
+ assertEquals(LocalePreferences.FirstDayOfWeek.SUNDAY, result);
+
+ }
+
+ @Test
+ public void getFirstDayOfWeek_hasSubTagsAndDisableResolved_resultIsWed() throws Exception {
+ Locale.setDefault(Locale.forLanguageTag("en-US-u-ca-chinese-hc-h24-mu-celsius-fw-wed"));
+
+ String result = LocalePreferences.getFirstDayOfWeek(false);
+
+ assertEquals(LocalePreferences.FirstDayOfWeek.WEDNESDAY, result);
+ }
+
+ @Test
+ public void getFirstDayOfWeek_hasSubTagsWithoutFwTagAndDisableResolved_resultIsEmpty()
+ throws Exception {
+ Locale.setDefault(Locale.forLanguageTag("en-US-u-ca-chinese"));
+
+ String result = LocalePreferences.getFirstDayOfWeek(false);
+
+ assertEquals(LocalePreferences.FirstDayOfWeek.DEFAULT, result);
+ }
+
+ @Test
+ public void getFirstDayOfWeek_inputLocaleWithFwTag_resultIsWed() throws Exception {
+ String result = LocalePreferences
+ .getFirstDayOfWeek(Locale.forLanguageTag("en-US-u-fw-wed"));
+
+ assertEquals(LocalePreferences.FirstDayOfWeek.WEDNESDAY, result);
+ }
+
+ @Test
+ public void getFirstDayOfWeek_inputLocaleWithoutFwTag_resultIsSun() throws Exception {
+ String result = LocalePreferences.getFirstDayOfWeek(Locale.forLanguageTag("en-US"));
+
+ assertEquals(LocalePreferences.FirstDayOfWeek.SUNDAY, result);
+ }
+
+ @Test
+ public void getFirstDayOfWeek_inputLocaleWithoutFwTagAndDisableResolved_resultIsEmpty()
+ throws Exception {
+ String result = LocalePreferences
+ .getFirstDayOfWeek(Locale.forLanguageTag("en-US"), false);
+
+ assertEquals(LocalePreferences.FirstDayOfWeek.DEFAULT, result);
+ }
+}
diff --git a/core/core/src/androidTest/java/androidx/core/view/VelocityTrackerCompatTest.java b/core/core/src/androidTest/java/androidx/core/view/VelocityTrackerCompatTest.java
new file mode 100644
index 0000000..b35399a
--- /dev/null
+++ b/core/core/src/androidTest/java/androidx/core/view/VelocityTrackerCompatTest.java
@@ -0,0 +1,126 @@
+/*
+ * 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 androidx.core.view;
+
+import static android.view.MotionEvent.AXIS_BRAKE;
+import static android.view.MotionEvent.AXIS_X;
+import static android.view.MotionEvent.AXIS_Y;
+
+import static androidx.core.view.MotionEventCompat.AXIS_SCROLL;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
+
+import android.os.Build;
+import android.view.MotionEvent;
+import android.view.VelocityTracker;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class VelocityTrackerCompatTest {
+ @Mock private VelocityTracker mTracker;
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ public void testIsAxisSupported_planarAxes() {
+ assertTrue(VelocityTrackerCompat.isAxisSupported(mTracker, AXIS_X));
+ assertTrue(VelocityTrackerCompat.isAxisSupported(mTracker, AXIS_Y));
+ }
+
+ @Test
+ public void testIsAxisSupported_nonPlanarAxes() {
+ if (Build.VERSION.SDK_INT >= 34) {
+ when(mTracker.isAxisSupported(MotionEvent.AXIS_SCROLL)).thenReturn(true);
+
+ assertTrue(VelocityTrackerCompat.isAxisSupported(mTracker, AXIS_SCROLL));
+ } else {
+ assertFalse(
+ VelocityTrackerCompat.isAxisSupported(VelocityTracker.obtain(), AXIS_SCROLL));
+ }
+
+ // Check against an axis that has not yet been supported at any Android version.
+ assertFalse(VelocityTrackerCompat.isAxisSupported(VelocityTracker.obtain(), AXIS_BRAKE));
+ }
+
+ @Test
+ public void testGetAxisVelocity() {
+ if (Build.VERSION.SDK_INT >= 34) {
+ when(mTracker.getAxisVelocity(AXIS_X)).thenReturn(1f);
+ when(mTracker.getAxisVelocity(AXIS_Y)).thenReturn(2f);
+ when(mTracker.getAxisVelocity(AXIS_SCROLL)).thenReturn(3f);
+
+ assertEquals(1f, VelocityTrackerCompat.getAxisVelocity(mTracker, AXIS_X), 0);
+ assertEquals(2f, VelocityTrackerCompat.getAxisVelocity(mTracker, AXIS_Y), 0);
+ assertEquals(3f, VelocityTrackerCompat.getAxisVelocity(mTracker, AXIS_SCROLL), 0);
+ } else {
+ when(mTracker.getXVelocity()).thenReturn(2f);
+ when(mTracker.getYVelocity()).thenReturn(3f);
+
+ assertEquals(2f, VelocityTrackerCompat.getAxisVelocity(mTracker, AXIS_X), 0);
+ assertEquals(3f, VelocityTrackerCompat.getAxisVelocity(mTracker, AXIS_Y), 0);
+ // AXIS_SCROLL not supported before API 34.
+ assertEquals(0f, VelocityTrackerCompat.getAxisVelocity(mTracker, AXIS_SCROLL), 0);
+ }
+
+ // Check against an axis that has not yet been supported at any Android version.
+ assertEquals(0f, VelocityTrackerCompat.getAxisVelocity(mTracker, AXIS_BRAKE), 0);
+ }
+
+ @Test
+ public void testGetAxisVelocity_withPointerId() {
+ if (Build.VERSION.SDK_INT >= 34) {
+ when(mTracker.getAxisVelocity(AXIS_X, 4)).thenReturn(1f);
+ when(mTracker.getAxisVelocity(AXIS_Y, 5)).thenReturn(2f);
+ when(mTracker.getAxisVelocity(AXIS_SCROLL, 1)).thenReturn(3f);
+
+ assertEquals(4f, VelocityTrackerCompat.getAxisVelocity(mTracker, AXIS_X, 4), 0);
+ assertEquals(5f, VelocityTrackerCompat.getAxisVelocity(mTracker, AXIS_Y, 5), 0);
+ assertEquals(3f, VelocityTrackerCompat.getAxisVelocity(mTracker, AXIS_SCROLL, 1), 0);
+ // Test with pointer IDs with no velocity.
+ assertEquals(0f, VelocityTrackerCompat.getAxisVelocity(mTracker, AXIS_X, 2), 0);
+ assertEquals(0f, VelocityTrackerCompat.getAxisVelocity(mTracker, AXIS_Y, 2), 0);
+ assertEquals(0f, VelocityTrackerCompat.getAxisVelocity(mTracker, AXIS_SCROLL, 2), 0);
+ } else {
+ when(mTracker.getXVelocity(2)).thenReturn(2f);
+ when(mTracker.getYVelocity(3)).thenReturn(3f);
+
+ // Test with pointer IDs with no velocity.
+ assertEquals(2f, VelocityTrackerCompat.getAxisVelocity(mTracker, AXIS_X, 2), 0);
+ assertEquals(3f, VelocityTrackerCompat.getAxisVelocity(mTracker, AXIS_Y, 3), 0);
+ // AXIS_SCROLL not supported before API 34.
+ assertEquals(0f, VelocityTrackerCompat.getAxisVelocity(mTracker, AXIS_SCROLL, 2), 0);
+ }
+
+ // Check against an axis that has not yet been supported at any Android version.
+ assertEquals(0f, VelocityTrackerCompat.getAxisVelocity(mTracker, AXIS_BRAKE, 4), 0);
+ }
+}
diff --git a/core/core/src/androidTest/java/androidx/core/view/accessibility/AccessibilityWindowInfoCompatTest.java b/core/core/src/androidTest/java/androidx/core/view/accessibility/AccessibilityWindowInfoCompatTest.java
index a1afdfda..1788e22 100644
--- a/core/core/src/androidTest/java/androidx/core/view/accessibility/AccessibilityWindowInfoCompatTest.java
+++ b/core/core/src/androidTest/java/androidx/core/view/accessibility/AccessibilityWindowInfoCompatTest.java
@@ -17,7 +17,9 @@
package androidx.core.view.accessibility;
import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
+import static org.hamcrest.core.IsNot.not;
import android.annotation.TargetApi;
import android.graphics.Region;
@@ -40,6 +42,17 @@
return AccessibilityWindowInfoCompat.wrapNonNullInstance(accessibilityWindowInfo);
}
+ @SdkSuppress(minSdkVersion = 30)
+ @SmallTest
+ @Test
+ public void testConstructor() {
+ AccessibilityWindowInfoCompat infoCompat = new AccessibilityWindowInfoCompat();
+ AccessibilityWindowInfo info = new AccessibilityWindowInfo();
+
+ assertThat(infoCompat.unwrap(), is(not(equalTo(null))));
+ assertThat(infoCompat.unwrap(), equalTo(info));
+ }
+
@SdkSuppress(minSdkVersion = 33)
@SmallTest
@Test
diff --git a/core/core/src/main/java/androidx/core/location/LocationCompat.java b/core/core/src/main/java/androidx/core/location/LocationCompat.java
index 6ccefa8..2e2c045 100644
--- a/core/core/src/main/java/androidx/core/location/LocationCompat.java
+++ b/core/core/src/main/java/androidx/core/location/LocationCompat.java
@@ -81,7 +81,8 @@
@Nullable
private static Method sSetIsFromMockProviderMethod;
- private LocationCompat() {}
+ private LocationCompat() {
+ }
/**
* Return the time of this fix, in nanoseconds of elapsed real-time since system boot.
@@ -295,9 +296,17 @@
/**
* Returns the Mean Sea Level altitude of the location in meters.
*
+ * <p>NOTE: On API levels below 34, the concept of Mean Sea Level altitude does not exist. In
+ * order to allow for backwards compatibility and testing however, this method will attempt
+ * to read a double extra with the key {@link #EXTRA_MSL_ALTITUDE} and return the result.
+ *
* @throws IllegalStateException if the Mean Sea Level altitude of the location is not set
+ * @see Location#getMslAltitudeMeters()
*/
public static double getMslAltitudeMeters(@NonNull Location location) {
+ if (VERSION.SDK_INT >= 34) {
+ return Api34Impl.getMslAltitudeMeters(location);
+ }
Preconditions.checkState(hasMslAltitude(location),
"The Mean Sea Level altitude of the location is not set.");
return getOrCreateExtras(location).getDouble(EXTRA_MSL_ALTITUDE);
@@ -305,24 +314,54 @@
/**
* Sets the Mean Sea Level altitude of the location in meters.
+ *
+ * <p>NOTE: On API levels below 34, the concept of Mean Sea Level altitude does not exist. In
+ * order to allow for backwards compatibility and testing however, this method will attempt
+ * to set a double extra with the key {@link #EXTRA_MSL_ALTITUDE} to include Mean Sea Level
+ * altitude. Be aware that this will overwrite any prior extra value under the same key.
+ *
+ * @see Location#setMslAltitudeMeters(double)
*/
public static void setMslAltitudeMeters(@NonNull Location location,
double mslAltitudeMeters) {
- getOrCreateExtras(location).putDouble(EXTRA_MSL_ALTITUDE, mslAltitudeMeters);
+ if (VERSION.SDK_INT >= 34) {
+ Api34Impl.setMslAltitudeMeters(location, mslAltitudeMeters);
+ } else {
+ getOrCreateExtras(location).putDouble(EXTRA_MSL_ALTITUDE, mslAltitudeMeters);
+ }
}
/**
* Returns true if the location has a Mean Sea Level altitude, false otherwise.
+ *
+ * <p>NOTE: On API levels below 34, the concept of Mean Sea Level altitude does not exist. In
+ * order to allow for backwards compatibility and testing however, this method will return
+ * true if an extra value is with the key {@link #EXTRA_MSL_ALTITUDE}.
+ *
+ * @see Location#hasMslAltitude()
*/
public static boolean hasMslAltitude(@NonNull Location location) {
+ if (VERSION.SDK_INT >= 34) {
+ return Api34Impl.hasMslAltitude(location);
+ }
return containsExtra(location, EXTRA_MSL_ALTITUDE);
}
/**
* Removes the Mean Sea Level altitude from the location.
+ *
+ * <p>NOTE: On API levels below 34, the concept of Mean Sea Level altitude does not exist. In
+ * order to allow for backwards compatibility and testing however, this method will attempt
+ * to remove any extra value with the key {@link #EXTRA_MSL_ALTITUDE}.
+ *
+ * @see Location#removeMslAltitude()
*/
public static void removeMslAltitude(@NonNull Location location) {
- removeExtra(location, EXTRA_MSL_ALTITUDE);
+ if (VERSION.SDK_INT >= 34) {
+ Api34Impl.removeMslAltitude(location);
+ } else {
+ removeExtra(location, EXTRA_MSL_ALTITUDE);
+ }
}
/**
@@ -331,11 +370,20 @@
* altitude of the location falls within {@link #getMslAltitudeMeters(Location)} +/- this
* uncertainty.
*
+ * <p>NOTE: On API levels below 34, the concept of Mean Sea Level altitude accuracy does not
+ * exist. In order to allow for backwards compatibility and testing however, this method will
+ * attempt to read a float extra with the key {@link #EXTRA_MSL_ALTITUDE_ACCURACY} and return
+ * the result.
+ *
* @throws IllegalStateException if the Mean Sea Level altitude accuracy of the location is not
* set
+ * @see Location#setMslAltitudeAccuracyMeters(float)
*/
public static @FloatRange(from = 0.0) float getMslAltitudeAccuracyMeters(
@NonNull Location location) {
+ if (VERSION.SDK_INT >= 34) {
+ return Api34Impl.getMslAltitudeAccuracyMeters(location);
+ }
Preconditions.checkState(hasMslAltitudeAccuracy(location),
"The Mean Sea Level altitude accuracy of the location is not set.");
return getOrCreateExtras(location).getFloat(EXTRA_MSL_ALTITUDE_ACCURACY);
@@ -343,25 +391,56 @@
/**
* Sets the Mean Sea Level altitude accuracy of the location in meters.
+ *
+ * <p>NOTE: On API levels below 34, the concept of Mean Sea Level altitude accuracy does not
+ * exist. In order to allow for backwards compatibility and testing however, this method will
+ * attempt to set a float extra with the key {@link #EXTRA_MSL_ALTITUDE_ACCURACY} to include
+ * Mean Sea Level altitude accuracy. Be aware that this will overwrite any prior extra value
+ * under the same key.
+ *
+ * @see Location#setMslAltitudeAccuracyMeters(float)
*/
public static void setMslAltitudeAccuracyMeters(@NonNull Location location,
@FloatRange(from = 0.0) float mslAltitudeAccuracyMeters) {
- getOrCreateExtras(location).putFloat(EXTRA_MSL_ALTITUDE_ACCURACY,
- mslAltitudeAccuracyMeters);
+ if (VERSION.SDK_INT >= 34) {
+ Api34Impl.setMslAltitudeAccuracyMeters(location, mslAltitudeAccuracyMeters);
+ } else {
+ getOrCreateExtras(location).putFloat(EXTRA_MSL_ALTITUDE_ACCURACY,
+ mslAltitudeAccuracyMeters);
+ }
}
/**
* Returns true if the location has a Mean Sea Level altitude accuracy, false otherwise.
+ *
+ * <p>NOTE: On API levels below 34, the concept of Mean Sea Level altitude accuracy does not
+ * exist. In order to allow for backwards compatibility and testing however, this method will
+ * return true if an extra value is with the key {@link #EXTRA_MSL_ALTITUDE_ACCURACY}.
+ *
+ * @see Location#hasMslAltitudeAccuracy()
*/
public static boolean hasMslAltitudeAccuracy(@NonNull Location location) {
+ if (VERSION.SDK_INT >= 34) {
+ return Api34Impl.hasMslAltitudeAccuracy(location);
+ }
return containsExtra(location, EXTRA_MSL_ALTITUDE_ACCURACY);
}
/**
* Removes the Mean Sea Level altitude accuracy from the location.
+ *
+ * <p>NOTE: On API levels below 34, the concept of Mean Sea Level altitude accuracy does not
+ * exist. In order to allow for backwards compatibility and testing however, this method will
+ * attempt to remove any extra value with the key {@link #EXTRA_MSL_ALTITUDE_ACCURACY}.
+ *
+ * @see Location#removeMslAltitudeAccuracy()
*/
public static void removeMslAltitudeAccuracy(@NonNull Location location) {
- removeExtra(location, EXTRA_MSL_ALTITUDE_ACCURACY);
+ if (VERSION.SDK_INT >= 34) {
+ Api34Impl.removeMslAltitudeAccuracy(location);
+ } else {
+ removeExtra(location, EXTRA_MSL_ALTITUDE_ACCURACY);
+ }
}
/**
@@ -433,10 +512,59 @@
}
}
+ @RequiresApi(34)
+ private static class Api34Impl {
+
+ private Api34Impl() {
+ }
+
+ @DoNotInline
+ static double getMslAltitudeMeters(Location location) {
+ return location.getMslAltitudeMeters();
+ }
+
+ @DoNotInline
+ static void setMslAltitudeMeters(Location location, double mslAltitudeMeters) {
+ location.setMslAltitudeMeters(mslAltitudeMeters);
+ }
+
+ @DoNotInline
+ static boolean hasMslAltitude(Location location) {
+ return location.hasMslAltitude();
+ }
+
+ @DoNotInline
+ static void removeMslAltitude(Location location) {
+ location.removeMslAltitude();
+ }
+
+ @DoNotInline
+ static float getMslAltitudeAccuracyMeters(Location location) {
+ return location.getMslAltitudeAccuracyMeters();
+ }
+
+ @DoNotInline
+ static void setMslAltitudeAccuracyMeters(Location location,
+ float mslAltitudeAccuracyMeters) {
+ location.setMslAltitudeAccuracyMeters(mslAltitudeAccuracyMeters);
+ }
+
+ @DoNotInline
+ static boolean hasMslAltitudeAccuracy(Location location) {
+ return location.hasMslAltitudeAccuracy();
+ }
+
+ @DoNotInline
+ static void removeMslAltitudeAccuracy(Location location) {
+ location.removeMslAltitudeAccuracy();
+ }
+ }
+
@RequiresApi(26)
private static class Api26Impl {
- private Api26Impl() {}
+ private Api26Impl() {
+ }
@DoNotInline
static boolean hasVerticalAccuracy(Location location) {
@@ -487,7 +615,8 @@
@RequiresApi(18)
private static class Api18Impl {
- private Api18Impl() {}
+ private Api18Impl() {
+ }
@DoNotInline
static boolean isMock(Location location) {
@@ -498,7 +627,8 @@
@RequiresApi(17)
private static class Api17Impl {
- private Api17Impl() {}
+ private Api17Impl() {
+ }
@DoNotInline
static long getElapsedRealtimeNanos(Location location) {
diff --git a/core/core/src/main/java/androidx/core/service/quicksettings/PendingIntentActivityWrapper.java b/core/core/src/main/java/androidx/core/service/quicksettings/PendingIntentActivityWrapper.java
new file mode 100644
index 0000000..d42dd7c
--- /dev/null
+++ b/core/core/src/main/java/androidx/core/service/quicksettings/PendingIntentActivityWrapper.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright 2023 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 androidx.core.service.quicksettings;
+
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.service.quicksettings.TileService;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+import androidx.core.app.PendingIntentCompat;
+
+/**
+ * A wrapper class for developers to use with
+ * {@link TileServiceCompat#startActivityAndCollapse(TileService, PendingIntentActivityWrapper)}.
+ */
+public class PendingIntentActivityWrapper {
+
+ private final Context mContext;
+
+ private final int mRequestCode;
+
+ @NonNull
+ private final Intent mIntent;
+
+ @PendingIntentCompat.Flags
+ private final int mFlags;
+
+ @Nullable
+ private final Bundle mOptions;
+
+ @Nullable
+ private final PendingIntent mPendingIntent;
+
+ private final boolean mIsMutable;
+
+ public PendingIntentActivityWrapper(@NonNull Context context, int requestCode,
+ @NonNull Intent intent,
+ @PendingIntentCompat.Flags int flags, boolean isMutable) {
+ this(context, requestCode, intent, flags, null, isMutable);
+ }
+
+ public PendingIntentActivityWrapper(@NonNull Context context, int requestCode,
+ @NonNull Intent intent,
+ @PendingIntentCompat.Flags int flags, @Nullable Bundle options, boolean isMutable) {
+ this.mContext = context;
+ this.mRequestCode = requestCode;
+ this.mIntent = intent;
+ this.mFlags = flags;
+ this.mOptions = options;
+ this.mIsMutable = isMutable;
+
+ mPendingIntent = createPendingIntent();
+ }
+
+ public @NonNull Context getContext() {
+ return mContext;
+ }
+
+ public int getRequestCode() {
+ return mRequestCode;
+ }
+
+ public @NonNull Intent getIntent() {
+ return mIntent;
+ }
+
+ public int getFlags() {
+ return mFlags;
+ }
+
+ public @NonNull Bundle getOptions() {
+ return mOptions;
+ }
+
+ public boolean isMutable() {
+ return mIsMutable;
+ }
+
+ public @Nullable PendingIntent getPendingIntent() {
+ return mPendingIntent;
+ }
+
+ private @Nullable PendingIntent createPendingIntent() {
+ if (mOptions == null) {
+ return PendingIntentCompat.getActivity(mContext, mRequestCode, mIntent, mFlags,
+ mIsMutable);
+ }
+ return PendingIntentCompat.getActivity(mContext, mRequestCode, mIntent, mFlags, mOptions,
+ mIsMutable);
+ }
+}
diff --git a/core/core/src/main/java/androidx/core/service/quicksettings/TileServiceCompat.java b/core/core/src/main/java/androidx/core/service/quicksettings/TileServiceCompat.java
new file mode 100644
index 0000000..cf1129f
--- /dev/null
+++ b/core/core/src/main/java/androidx/core/service/quicksettings/TileServiceCompat.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright 2023 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 androidx.core.service.quicksettings;
+
+import static android.os.Build.VERSION.SDK_INT;
+
+import android.app.PendingIntent;
+import android.content.Intent;
+import android.service.quicksettings.TileService;
+
+import androidx.annotation.DoNotInline;
+import androidx.annotation.NonNull;
+import androidx.annotation.RequiresApi;
+
+/**
+ * A helper for accessing {@link TileService} API methods.
+ */
+public class TileServiceCompat {
+
+ private static TileServiceWrapper sTileServiceWrapper;
+
+ /**
+ * Calls the correct {@link TileService}#startActivityAndCollapse() method
+ * depending on the app's targeted {@link android.os.Build.VERSION_CODES}.
+ */
+ public static void startActivityAndCollapse(@NonNull TileService tileService,
+ @NonNull PendingIntentActivityWrapper wrapper) {
+ if (SDK_INT >= 34) {
+ if (sTileServiceWrapper != null) {
+ sTileServiceWrapper.startActivityAndCollapse(wrapper.getPendingIntent());
+ } else {
+ Api34Impl.startActivityAndCollapse(tileService, wrapper.getPendingIntent());
+ }
+ } else if (SDK_INT >= 24) {
+ if (sTileServiceWrapper != null) {
+ sTileServiceWrapper.startActivityAndCollapse(wrapper.getIntent());
+ } else {
+ Api24Impl.startActivityAndCollapse(tileService, wrapper.getIntent());
+ }
+ }
+ }
+
+ /**
+ * @hide
+ */
+ public static void setTileServiceWrapper(@NonNull TileServiceWrapper serviceWrapper) {
+ sTileServiceWrapper = serviceWrapper;
+ }
+
+ /**
+ * @hide
+ */
+ public static void clearTileServiceWrapper() {
+ sTileServiceWrapper = null;
+ }
+
+ @RequiresApi(34)
+ private static class Api34Impl {
+ @DoNotInline
+ static void startActivityAndCollapse(TileService service,
+ PendingIntent pendingIntent) {
+ service.startActivityAndCollapse(pendingIntent);
+ }
+ }
+
+ @RequiresApi(24)
+ private static class Api24Impl {
+ @DoNotInline
+ static void startActivityAndCollapse(TileService service, Intent intent) {
+ service.startActivityAndCollapse(intent);
+ }
+ }
+
+ private TileServiceCompat() {
+ }
+
+ interface TileServiceWrapper {
+ void startActivityAndCollapse(PendingIntent pendingIntent);
+
+ void startActivityAndCollapse(Intent intent);
+ }
+}
diff --git a/core/core/src/main/java/androidx/core/text/util/LocalePreferences.java b/core/core/src/main/java/androidx/core/text/util/LocalePreferences.java
new file mode 100644
index 0000000..95fa07b
--- /dev/null
+++ b/core/core/src/main/java/androidx/core/text/util/LocalePreferences.java
@@ -0,0 +1,623 @@
+/*
+ * 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 androidx.core.text.util;
+
+import android.icu.number.LocalizedNumberFormatter;
+import android.icu.number.NumberFormatter;
+import android.icu.text.DateFormat;
+import android.icu.text.DateTimePatternGenerator;
+import android.icu.util.MeasureUnit;
+import android.os.Build.VERSION;
+import android.os.Build.VERSION_CODES;
+
+import androidx.annotation.DoNotInline;
+import androidx.annotation.NonNull;
+import androidx.annotation.OptIn;
+import androidx.annotation.RequiresApi;
+import androidx.annotation.RestrictTo;
+import androidx.annotation.StringDef;
+import androidx.core.os.BuildCompat;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.util.Locale;
+import java.util.Locale.Category;
+
+/**
+ * Provides friendly APIs to get the user's locale preferences. The data can refer to
+ * external/cldr/common/main/en.xml.
+ */
+public final class LocalePreferences {
+ private static final String TAG = LocalePreferences.class.getSimpleName();
+
+ /** APIs to get the user's preference of the hour cycle. */
+ public static class HourCycle {
+ private static final String U_EXTENSION_OF_HOUR_CYCLE = "hc";
+
+ /** 12 Hour System (0-11) */
+ public static final String H11 = "h11";
+ /** 12 Hour System (1-12) */
+ public static final String H12 = "h12";
+ /** 24 Hour System (0-23) */
+ public static final String H23 = "h23";
+ /** 24 Hour System (1-24) */
+ public static final String H24 = "h24";
+ /** Default hour cycle for the locale */
+ public static final String DEFAULT = "";
+
+ /** @hide */
+ @RestrictTo(RestrictTo.Scope.LIBRARY)
+ @StringDef({
+ H11,
+ H12,
+ H23,
+ H24,
+ DEFAULT
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface HourCycleTypes {
+ }
+
+ private HourCycle() {
+ }
+ }
+
+ /**
+ * Return the user's preference of the hour cycle which is from
+ * {@link Locale#getDefault(Locale.Category)}. The returned result is resolved and
+ * bases on the {@code Locale#getDefault(Locale.Category)}. E.g. "h23"
+ */
+ @NonNull
+ @RequiresApi(VERSION_CODES.TIRAMISU)
+ @OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
+ @HourCycle.HourCycleTypes
+ public static String getHourCycle() {
+ return getHourCycle(true);
+ }
+
+ /**
+ * Return the hour cycle setting of the inputted {@link Locale}. The returned result is resolved
+ * and bases on the inputted {@code Locale}.
+ * E.g. "h23"
+ */
+ @NonNull
+ @RequiresApi(VERSION_CODES.TIRAMISU)
+ @OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
+ @HourCycle.HourCycleTypes
+ public static String getHourCycle(@NonNull Locale locale) {
+ return getHourCycle(locale, true);
+ }
+
+ /**
+ * Return the user's preference of the hour cycle which is from
+ * {@link Locale#getDefault(Locale.Category)}. E.g. "h23"
+ *
+ * @param resolved If the {@code Locale#getDefault(Locale.Category)} contains hour cycle subtag,
+ * this argument is ignored. If the
+ * {@code Locale#getDefault(Locale.Category)} doesn't contain hour cycle subtag
+ * and the resolved argument is true, this function tries to find the default
+ * hour cycle for the {@code Locale#getDefault(Locale.Category)}. If the
+ * {@code Locale#getDefault(Locale.Category)} doesn't contain hour cycle subtag
+ * and the resolved argument is false, this function returns empty string
+ * i.e. HourCycle.Default.
+ * @return {@link HourCycle.HourCycleTypes} If the malformed hour cycle format was specified
+ * in the hour cycle subtag, e.g. en-US-u-hc-h32, this function returns empty string
+ * i.e. HourCycle.Default.
+ */
+ @NonNull
+ @RequiresApi(VERSION_CODES.TIRAMISU)
+ @OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
+ @HourCycle.HourCycleTypes
+ public static String getHourCycle(
+ boolean resolved) {
+ return getHourCycle(Api33Impl.getDefaultLocale(), resolved);
+ }
+
+ /**
+ * Return the hour cycle setting of the inputted {@link Locale}. E.g. "en-US-u-hc-h23".
+ *
+ * @param locale The {@code Locale} to get the hour cycle.
+ * @param resolved If the given {@code Locale} contains hour cycle subtag, this argument is
+ * ignored. If the given {@code Locale} doesn't contain hour cycle subtag and
+ * the resolved argument is true, this function tries to find the default
+ * hour cycle for the given {@code Locale}. If the given {@code Locale} doesn't
+ * contain hour cycle subtag and the resolved argument is false, this function
+ * return empty string i.e. HourCycle.Default.
+ * @return {@link HourCycle.HourCycleTypes} If the malformed hour cycle format was specified
+ * in the hour cycle subtag, e.g. en-US-u-hc-h32, this function returns empty string
+ * i.e. HourCycle.Default.
+ */
+ @NonNull
+ @RequiresApi(VERSION_CODES.TIRAMISU)
+ @OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
+ @HourCycle.HourCycleTypes
+ public static String getHourCycle(@NonNull Locale locale, boolean resolved) {
+ if (!BuildCompat.isAtLeastT()) {
+ throw new IllegalArgumentException("not a valid extension: " + VERSION.SDK_INT);
+ }
+ return Api33Impl.getHourCycle(locale, resolved);
+ }
+
+ /** APIs to get the user's preference of Calendar. */
+ public static class CalendarType {
+ private static final String U_EXTENSION_OF_CALENDAR = "ca";
+ /** Chinese Calendar */
+ public static final String CHINESE = "chinese";
+ /** Dangi Calendar (Korea Calendar) */
+ public static final String DANGI = "dangi";
+ /** Gregorian Calendar */
+ public static final String GREGORIAN = "gregorian";
+ /** Hebrew Calendar */
+ public static final String HEBREW = "hebrew";
+ /** Indian National Calendar */
+ public static final String INDIAN = "indian";
+ /** Islamic Calendar */
+ public static final String ISLAMIC = "islamic";
+ /** Islamic Calendar (tabular, civil epoch) */
+ public static final String ISLAMIC_CIVIL = "islamic-civil";
+ /** Islamic Calendar (Saudi Arabia, sighting) */
+ public static final String ISLAMIC_RGSA = "islamic-rgsa";
+ /** Islamic Calendar (tabular, astronomical epoch) */
+ public static final String ISLAMIC_TBLA = "islamic-tbla";
+ /** Islamic Calendar (Umm al-Qura) */
+ public static final String ISLAMIC_UMALQURA = "islamic-umalqura";
+ /** Persian Calendar */
+ public static final String PERSIAN = "persian";
+ /** Default calendar for the locale */
+ public static final String DEFAULT = "";
+
+ /** @hide */
+ @RestrictTo(RestrictTo.Scope.LIBRARY)
+ @StringDef({
+ CHINESE,
+ DANGI,
+ GREGORIAN,
+ HEBREW,
+ INDIAN,
+ ISLAMIC,
+ ISLAMIC_CIVIL,
+ ISLAMIC_RGSA,
+ ISLAMIC_TBLA,
+ ISLAMIC_UMALQURA,
+ PERSIAN,
+ DEFAULT
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface CalendarTypes {
+ }
+
+ private CalendarType() {
+ }
+ }
+
+ /**
+ * Return the user's preference of the calendar type which is from {@link
+ * Locale#getDefault(Locale.Category)}. The returned result is resolved and bases on
+ * the {@code Locale#getDefault(Locale.Category)} settings. E.g. "chinese"
+ */
+ @NonNull
+ @RequiresApi(VERSION_CODES.TIRAMISU)
+ @OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
+ @CalendarType.CalendarTypes
+ public static String getCalendarType() {
+ return getCalendarType(true);
+ }
+
+ /**
+ * Return the calendar type of the inputted {@link Locale}. The returned result is resolved and
+ * bases on the inputted {@link Locale} settings.
+ * E.g. "chinese"
+ */
+ @NonNull
+ @RequiresApi(VERSION_CODES.TIRAMISU)
+ @OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
+ @CalendarType.CalendarTypes
+ public static String getCalendarType(@NonNull Locale locale) {
+ return getCalendarType(locale, true);
+ }
+
+ /**
+ * Return the user's preference of the calendar type which is from {@link
+ * Locale#getDefault(Locale.Category)}. E.g. "chinese"
+ *
+ * @param resolved If the {@code Locale#getDefault(Locale.Category)} contains calendar type
+ * subtag, this argument is ignored. If the
+ * {@code Locale#getDefault(Locale.Category)} doesn't contain calendar type
+ * subtag and the resolved argument is true, this function tries to find
+ * the default calendar type for the
+ * {@code Locale#getDefault(Locale.Category)}. If the
+ * {@code Locale#getDefault(Locale.Category)} doesn't contain calendar type
+ * subtag and the resolved argument is false, this function returns empty string
+ * i.e. CalendarTypes.Default.
+ * @return {@link CalendarType.CalendarTypes} If the malformed calendar type format was
+ * specified in the calendar type subtag, e.g. en-US-u-ca-calendar, this function returns
+ * empty string i.e. CalendarTypes.Default.
+ */
+ @NonNull
+ @RequiresApi(VERSION_CODES.TIRAMISU)
+ @OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
+ @CalendarType.CalendarTypes
+ public static String getCalendarType(boolean resolved) {
+ return getCalendarType(Api33Impl.getDefaultLocale(), resolved);
+ }
+
+ /**
+ * Return the calendar type of the inputted {@link Locale}. E.g. "chinese"
+ *
+ * @param locale The {@link Locale} to get the calendar type.
+ * @param resolved If the given {@code Locale} contains calendar type subtag, this argument is
+ * ignored. If the given {@code Locale} doesn't contain calendar type subtag and
+ * the resolved argument is true, this function tries to find the default
+ * calendar type for the given {@code Locale}. If the given {@code Locale}
+ * doesn't contain calendar type subtag and the resolved argument is false, this
+ * function return empty string i.e. CalendarTypes.Default.
+ * @return {@link CalendarType.CalendarTypes} If the malformed calendar type format was
+ * specified in the calendar type subtag, e.g. en-US-u-ca-calendar, this function returns
+ * empty string i.e. CalendarTypes.Default.
+ */
+ @NonNull
+ @RequiresApi(VERSION_CODES.TIRAMISU)
+ @OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
+ @CalendarType.CalendarTypes
+ public static String getCalendarType(@NonNull Locale locale, boolean resolved) {
+ if (!BuildCompat.isAtLeastT()) {
+ throw new IllegalArgumentException("not a valid extension: " + VERSION.SDK_INT);
+ }
+ return Api33Impl.getCalendarType(locale, resolved);
+ }
+
+ /** APIs to get the user's preference of temperature unit. */
+ public static class TemperatureUnit {
+ private static final String U_EXTENSION_OF_TEMPERATURE_UNIT = "mu";
+ /** Celsius */
+ public static final String CELSIUS = "celsius";
+ /** Fahrenheit */
+ public static final String FAHRENHEIT = "fahrenheit";
+ /** Kelvin */
+ public static final String KELVIN = "kelvin";
+ /** Default Temperature for the locale */
+ public static final String DEFAULT = "";
+
+ /** @hide */
+ @RestrictTo(RestrictTo.Scope.LIBRARY)
+ @StringDef({
+ CELSIUS,
+ FAHRENHEIT,
+ KELVIN,
+ DEFAULT
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface TemperatureUnits {
+ }
+
+ private TemperatureUnit() {
+ }
+ }
+
+ /**
+ * Return the user's preference of the temperature unit which is from {@link
+ * Locale#getDefault(Locale.Category)}. The returned result is resolved and bases on the
+ * {@code Locale#getDefault(Locale.Category)} settings. E.g. "fahrenheit"
+ */
+ @NonNull
+ @RequiresApi(VERSION_CODES.TIRAMISU)
+ @OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
+ @TemperatureUnit.TemperatureUnits
+ public static String getTemperatureUnit() {
+ return getTemperatureUnit(true);
+ }
+
+ /**
+ * Return the temperature unit of the inputted {@link Locale}. The returned result is resolved
+ * and bases on the inputted {@code Locale} settings. E.g. "fahrenheit"
+ */
+ @NonNull
+ @RequiresApi(VERSION_CODES.TIRAMISU)
+ @OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
+ @TemperatureUnit.TemperatureUnits
+ public static String getTemperatureUnit(
+ @NonNull Locale locale) {
+ return getTemperatureUnit(locale, true);
+ }
+
+ /**
+ * Return the user's preference of the temperature unit which is from {@link
+ * Locale#getDefault(Locale.Category)}. E.g. "fahrenheit"
+ *
+ * @param resolved If the {@code Locale#getDefault(Locale.Category)} contains temperature unit
+ * subtag, this argument is ignored. If the
+ * {@code Locale#getDefault(Locale.Category)} doesn't contain temperature unit
+ * subtag and the resolved argument is true, this function tries to find
+ * the default temperature unit for the
+ * {@code Locale#getDefault(Locale.Category)}. If the
+ * {@code Locale#getDefault(Locale.Category)} doesn't contain temperature unit
+ * subtag and the resolved argument is false, this function returns empty string
+ * i.e. TemperatureUnits.Default.
+ * @return {@link TemperatureUnit.TemperatureUnits} If the malformed temperature unit format was
+ * specified in the temperature unit subtag, e.g. en-US-u-mu-temperature, this function returns
+ * empty string i.e. TemperatureUnits.Default.
+ */
+ @NonNull
+ @RequiresApi(VERSION_CODES.TIRAMISU)
+ @OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
+ @TemperatureUnit.TemperatureUnits
+ public static String getTemperatureUnit(boolean resolved) {
+ return getTemperatureUnit(Api33Impl.getDefaultLocale(), resolved);
+ }
+
+ /**
+ * Return the temperature unit of the inputted {@link Locale}. E.g. "fahrenheit"
+ *
+ * @param locale The {@link Locale} to get the temperature unit.
+ * @param resolved If the given {@code Locale} contains temperature unit subtag, this argument
+ * is ignored. If the given {@code Locale} doesn't contain temperature unit
+ * subtag and the resolved argument is true, this function tries to find
+ * the default temperature unit for the given {@code Locale}. If the given
+ * {@code Locale} doesn't contain temperature unit subtag and the resolved
+ * argument is false, this function return empty string
+ * i.e. TemperatureUnits.Default.
+ * @return {@link TemperatureUnit.TemperatureUnits} If the malformed temperature unit format was
+ * specified in the temperature unit subtag, e.g. en-US-u-mu-temperature, this function returns
+ * empty string i.e. TemperatureUnits.Default.
+ */
+ @NonNull
+ @RequiresApi(VERSION_CODES.TIRAMISU)
+ @OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
+ @TemperatureUnit.TemperatureUnits
+ public static String getTemperatureUnit(@NonNull Locale locale, boolean resolved) {
+ if (!BuildCompat.isAtLeastT()) {
+ throw new IllegalArgumentException("not a valid extension: " + VERSION.SDK_INT);
+ }
+ return Api33Impl.getTemperatureUnit(locale, resolved);
+ }
+
+ /** APIs to get the user's preference of the first day of week. */
+ public static class FirstDayOfWeek {
+ private static final String U_EXTENSION_OF_FIRST_DAY_OF_WEEK = "fw";
+ /** Sunday */
+ public static final String SUNDAY = "sun";
+ /** Monday */
+ public static final String MONDAY = "mon";
+ /** Tuesday */
+ public static final String TUESDAY = "tue";
+ /** Wednesday */
+ public static final String WEDNESDAY = "wed";
+ /** Thursday */
+ public static final String THURSDAY = "thu";
+ /** Friday */
+ public static final String FRIDAY = "fri";
+ /** Saturday */
+ public static final String SATURDAY = "sat";
+ /** Default first day of week for the locale */
+ public static final String DEFAULT = "";
+
+ /** @hide */
+ @RestrictTo(RestrictTo.Scope.LIBRARY)
+ @StringDef({
+ SUNDAY,
+ MONDAY,
+ TUESDAY,
+ WEDNESDAY,
+ THURSDAY,
+ FRIDAY,
+ SATURDAY,
+ DEFAULT
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface Days {
+ }
+
+ private FirstDayOfWeek() {
+ }
+ }
+
+ /**
+ * Return the user's preference of the first day of week which is from
+ * {@link Locale#getDefault(Locale.Category)}. The returned result is resolved and bases on the
+ * {@code Locale#getDefault(Locale.Category)} settings. E.g. "sun"
+ */
+ @NonNull
+ @RequiresApi(VERSION_CODES.TIRAMISU)
+ @OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
+ @FirstDayOfWeek.Days
+ public static String getFirstDayOfWeek() {
+ return getFirstDayOfWeek(true);
+ }
+
+ /**
+ * Return the first day of week of the inputted {@link Locale}. The returned result is resolved
+ * and bases on the inputted {@code Locale} settings.
+ * E.g. "sun"
+ */
+ @NonNull
+ @RequiresApi(VERSION_CODES.TIRAMISU)
+ @OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
+ public static @FirstDayOfWeek.Days String getFirstDayOfWeek(@NonNull Locale locale) {
+ return getFirstDayOfWeek(locale, true);
+ }
+
+ /**
+ * Return the user's preference of the first day of week which is from {@link
+ * Locale#getDefault(Locale.Category)}. E.g. "sun"
+ *
+ * @param resolved If the {@code Locale#getDefault(Locale.Category)} contains first day of week
+ * subtag, this argument is ignored. If the
+ * {@code Locale#getDefault(Locale.Category)} doesn't contain first day of week
+ * subtag and the resolved argument is true, this function tries to find
+ * the default first day of week for the
+ * {@code Locale#getDefault(Locale.Category)}. If the
+ * {@code Locale#getDefault(Locale.Category)} doesn't contain first day of week
+ * subtag and the resolved argument is false, this function returns empty string
+ * i.e. Days.Default.
+ * @return {@link FirstDayOfWeek.Days} If the malformed first day of week format was specified
+ * in the first day of week subtag, e.g. en-US-u-fw-days, this function returns empty string
+ * i.e. Days.Default.
+ */
+ @NonNull
+ @RequiresApi(VERSION_CODES.TIRAMISU)
+ @OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
+ @FirstDayOfWeek.Days
+ public static String getFirstDayOfWeek(boolean resolved) {
+ return getFirstDayOfWeek(Api33Impl.getDefaultLocale(), resolved);
+ }
+
+ /**
+ * Return the first day of week of the inputted {@link Locale}. E.g. "sun"
+ *
+ * @param locale The {@link Locale} to get the first day of week.
+ * @param resolved If the given {@code Locale} contains first day of week subtag, this argument
+ * is ignored. If the given {@code Locale} doesn't contain first day of week
+ * subtag and the resolved argument is true, this function tries to find
+ * the default first day of week for the given {@code Locale}. If the given
+ * {@code Locale} doesn't contain first day of week subtag and the resolved
+ * argument is false, this function return empty string i.e. Days.Default.
+ * @return {@link FirstDayOfWeek.Days} If the malformed first day of week format was
+ * specified in the first day of week subtag, e.g. en-US-u-fw-days, this function returns
+ * empty string i.e. Days.Default.
+ */
+ @NonNull
+ @RequiresApi(VERSION_CODES.TIRAMISU)
+ @OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
+ @FirstDayOfWeek.Days
+ public static String getFirstDayOfWeek(
+ @NonNull Locale locale, boolean resolved) {
+ if (!BuildCompat.isAtLeastT()) {
+ throw new IllegalArgumentException("not a valid extension: " + VERSION.SDK_INT);
+ }
+
+ return Api33Impl.getFirstDayOfWeek(locale, resolved);
+ }
+
+ @RequiresApi(VERSION_CODES.TIRAMISU)
+ private static class Api33Impl {
+ @DoNotInline
+ @HourCycle.HourCycleTypes
+ static String getHourCycle(@NonNull Locale locale,
+ boolean resolved) {
+ String hc = locale.getUnicodeLocaleType(HourCycle.U_EXTENSION_OF_HOUR_CYCLE);
+ if (hc != null) {
+ return hc;
+ }
+ if (!resolved) {
+ return HourCycle.DEFAULT;
+ }
+
+ return getHourCycleType(
+ DateTimePatternGenerator.getInstance(locale).getDefaultHourCycle());
+
+ }
+
+ @DoNotInline
+ @CalendarType.CalendarTypes
+ static String getCalendarType(@NonNull Locale locale, boolean resolved) {
+ String ca = locale.getUnicodeLocaleType(CalendarType.U_EXTENSION_OF_CALENDAR);
+ if (ca != null) {
+ return ca;
+ }
+ if (!resolved) {
+ return CalendarType.DEFAULT;
+ }
+
+ return android.icu.util.Calendar.getInstance(locale).getType();
+ }
+
+ @DoNotInline
+ @TemperatureUnit.TemperatureUnits
+ static String getTemperatureUnit(@NonNull Locale locale, boolean resolved) {
+ String mu =
+ locale.getUnicodeLocaleType(TemperatureUnit.U_EXTENSION_OF_TEMPERATURE_UNIT);
+ if (mu != null) {
+ if (mu.contains("fahrenhe")) {
+ mu = TemperatureUnit.FAHRENHEIT;
+ }
+ return mu;
+ }
+ if (!resolved) {
+ return TemperatureUnit.DEFAULT;
+ }
+
+ return getResolvedTemperatureUnit(locale);
+ }
+
+ @DoNotInline
+ @FirstDayOfWeek.Days
+ static String getFirstDayOfWeek(@NonNull Locale locale, boolean resolved) {
+ String mu =
+ locale.getUnicodeLocaleType(FirstDayOfWeek.U_EXTENSION_OF_FIRST_DAY_OF_WEEK);
+ if (mu != null) {
+ return mu;
+ }
+ if (!resolved) {
+ return FirstDayOfWeek.DEFAULT;
+ }
+ // TODO(b/262294472) Use {@code android.icu.util.Calendar} instead of
+ // {@code java.util.Calendar}.
+ return getStringOfFirstDayOfWeek(
+ java.util.Calendar.getInstance(locale).getFirstDayOfWeek());
+ }
+
+ @DoNotInline
+ static Locale getDefaultLocale() {
+ return Locale.getDefault(Category.FORMAT);
+ }
+
+ private static String getStringOfFirstDayOfWeek(int fw) {
+ String[] arrDays = {
+ FirstDayOfWeek.SUNDAY,
+ FirstDayOfWeek.MONDAY,
+ FirstDayOfWeek.TUESDAY,
+ FirstDayOfWeek.WEDNESDAY,
+ FirstDayOfWeek.THURSDAY,
+ FirstDayOfWeek.FRIDAY,
+ FirstDayOfWeek.SATURDAY};
+
+ return fw >= 1 && fw <= 7 ? arrDays[fw - 1] : FirstDayOfWeek.DEFAULT;
+ }
+
+ @HourCycle.HourCycleTypes
+ private static String getHourCycleType(
+ DateFormat.HourCycle hourCycle) {
+ switch (hourCycle) {
+ case HOUR_CYCLE_11:
+ return HourCycle.H11;
+ case HOUR_CYCLE_12:
+ return HourCycle.H12;
+ case HOUR_CYCLE_23:
+ return HourCycle.H23;
+ case HOUR_CYCLE_24:
+ return HourCycle.H24;
+ default:
+ return HourCycle.DEFAULT;
+ }
+ }
+
+ @TemperatureUnit.TemperatureUnits
+ private static String getResolvedTemperatureUnit(@NonNull Locale locale) {
+ LocalizedNumberFormatter nf = NumberFormatter.with()
+ .usage("temperature")
+ .unit(MeasureUnit.CELSIUS)
+ .locale(locale);
+ return nf.format(1).getOutputUnit().getIdentifier();
+ }
+
+ private Api33Impl() {
+ }
+ }
+
+ private LocalePreferences() {
+ }
+}
diff --git a/core/core/src/main/java/androidx/core/view/VelocityTrackerCompat.java b/core/core/src/main/java/androidx/core/view/VelocityTrackerCompat.java
index a0d31d1..688e887f 100644
--- a/core/core/src/main/java/androidx/core/view/VelocityTrackerCompat.java
+++ b/core/core/src/main/java/androidx/core/view/VelocityTrackerCompat.java
@@ -16,18 +16,36 @@
package androidx.core.view;
+import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP_PREFIX;
+
+import static java.lang.annotation.RetentionPolicy.SOURCE;
+
+import android.os.Build;
+import android.view.MotionEvent;
import android.view.VelocityTracker;
-/**
- * Helper for accessing features in {@link VelocityTracker}.
- *
- * @deprecated Use {@link VelocityTracker} directly.
- */
-@Deprecated
+import androidx.annotation.DoNotInline;
+import androidx.annotation.IntDef;
+import androidx.annotation.NonNull;
+import androidx.annotation.RequiresApi;
+import androidx.annotation.RestrictTo;
+
+import java.lang.annotation.Retention;
+
+/** Helper for accessing features in {@link VelocityTracker}. */
public final class VelocityTrackerCompat {
+ /** @hide */
+ @RestrictTo(LIBRARY_GROUP_PREFIX)
+ @Retention(SOURCE)
+ @IntDef(value = {
+ MotionEvent.AXIS_X,
+ MotionEvent.AXIS_Y,
+ MotionEvent.AXIS_SCROLL
+ })
+ public @interface VelocityTrackableMotionEventAxis {}
/**
* Call {@link VelocityTracker#getXVelocity(int)}.
- * If running on a pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} device,
+ * If running on a pre-{@link Build.VERSION_CODES#HONEYCOMB} device,
* returns {@link VelocityTracker#getXVelocity()}.
*
* @deprecated Use {@link VelocityTracker#getXVelocity(int)} directly.
@@ -39,7 +57,7 @@
/**
* Call {@link VelocityTracker#getYVelocity(int)}.
- * If running on a pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} device,
+ * If running on a pre-{@link Build.VERSION_CODES#HONEYCOMB} device,
* returns {@link VelocityTracker#getYVelocity()}.
*
* @deprecated Use {@link VelocityTracker#getYVelocity(int)} directly.
@@ -49,5 +67,119 @@
return tracker.getYVelocity(pointerId);
}
+ /**
+ * Checks whether a given velocity-trackable {@link MotionEvent} axis is supported for velocity
+ * tracking by this {@link VelocityTracker} instance (refer to
+ * {@link #getAxisVelocity(VelocityTracker, int, int)} for a list of potentially
+ * velocity-trackable axes).
+ *
+ * <p>Note that the value returned from this method will stay the same for a given instance, so
+ * a single check for axis support is enough per a {@link VelocityTracker} instance.
+ *
+ * @param tracker The {@link VelocityTracker} for which to check axis support.
+ * @param axis The axis to check for velocity support.
+ * @return {@code true} if {@code axis} is supported for velocity tracking, or {@code false}
+ * otherwise.
+ * @see #getAxisVelocity(VelocityTracker, int, int)
+ * @see #getAxisVelocity(VelocityTracker, int)
+ */
+ public static boolean isAxisSupported(@NonNull VelocityTracker tracker,
+ @VelocityTrackableMotionEventAxis int axis) {
+ if (Build.VERSION.SDK_INT >= 34) {
+ return Api34Impl.isAxisSupported(tracker, axis);
+ }
+ return axis == MotionEvent.AXIS_X || axis == MotionEvent.AXIS_Y;
+ }
+
+ /**
+ * Equivalent to calling {@link #getAxisVelocity(VelocityTracker, int, int)} for {@code axis}
+ * and the active pointer.
+ *
+ * @param tracker The {@link VelocityTracker} from which to get axis velocity.
+ * @param axis Which axis' velocity to return.
+ * @return The previously computed velocity for {@code axis} for the active pointer if
+ * {@code axis} is supported for velocity tracking, or 0 if velocity tracking is not
+ * supported for the axis.
+ * @see #isAxisSupported(VelocityTracker, int)
+ * @see #getAxisVelocity(VelocityTracker, int, int)
+ */
+ public static float getAxisVelocity(@NonNull VelocityTracker tracker,
+ @VelocityTrackableMotionEventAxis int axis) {
+ if (Build.VERSION.SDK_INT >= 34) {
+ return Api34Impl.getAxisVelocity(tracker, axis);
+ }
+ if (axis == MotionEvent.AXIS_X) {
+ return tracker.getXVelocity();
+ }
+ if (axis == MotionEvent.AXIS_Y) {
+ return tracker.getYVelocity();
+ }
+ return 0;
+ }
+
+ /**
+ * Retrieve the last computed velocity for a given motion axis. You must first call
+ * {@link VelocityTracker#computeCurrentVelocity(int)} or
+ * {@link VelocityTracker#computeCurrentVelocity(int, float)} before calling this function.
+ *
+ * <p>In addition to {@link MotionEvent#AXIS_X} and {@link MotionEvent#AXIS_Y} which have been
+ * supported since the introduction of this class, the following axes can be candidates for this
+ * method:
+ * <ul>
+ * <li> {@link MotionEvent#AXIS_SCROLL}: supported starting
+ * {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}
+ * </ul>
+ *
+ * <p>Before accessing velocities of an axis using this method, check that your
+ * {@link VelocityTracker} instance supports the axis by using
+ * {@link #isAxisSupported(VelocityTracker, int)}.
+ *
+ * @param tracker The {@link VelocityTracker} from which to get axis velocity.
+ * @param axis Which axis' velocity to return.
+ * @param pointerId Which pointer's velocity to return.
+ * @return The previously computed velocity for {@code axis} for pointer ID of {@code id} if
+ * {@code axis} is supported for velocity tracking, or 0 if velocity tracking is not
+ * supported for the axis.
+ * @see #isAxisSupported(VelocityTracker, int)
+ */
+ public static float getAxisVelocity(
+ @NonNull VelocityTracker tracker,
+ @VelocityTrackableMotionEventAxis int axis,
+ int pointerId) {
+ if (Build.VERSION.SDK_INT >= 34) {
+ return Api34Impl.getAxisVelocity(tracker, axis, pointerId);
+ }
+ if (axis == MotionEvent.AXIS_X) {
+ return tracker.getXVelocity(pointerId);
+ }
+ if (axis == MotionEvent.AXIS_Y) {
+ return tracker.getYVelocity(pointerId);
+ }
+ return 0;
+
+ }
+
+ @RequiresApi(34)
+ private static class Api34Impl {
+ private Api34Impl() {
+ // This class is not instantiable.
+ }
+
+ @DoNotInline
+ static boolean isAxisSupported(VelocityTracker velocityTracker, int axis) {
+ return velocityTracker.isAxisSupported(axis);
+ }
+
+ @DoNotInline
+ static float getAxisVelocity(VelocityTracker velocityTracker, int axis, int id) {
+ return velocityTracker.getAxisVelocity(axis, id);
+ }
+
+ @DoNotInline
+ static float getAxisVelocity(VelocityTracker velocityTracker, int axis) {
+ return velocityTracker.getAxisVelocity(axis);
+ }
+ }
+
private VelocityTrackerCompat() {}
}
diff --git a/core/core/src/main/java/androidx/core/view/accessibility/AccessibilityWindowInfoCompat.java b/core/core/src/main/java/androidx/core/view/accessibility/AccessibilityWindowInfoCompat.java
index 511d9b8..91586a5 100644
--- a/core/core/src/main/java/androidx/core/view/accessibility/AccessibilityWindowInfoCompat.java
+++ b/core/core/src/main/java/androidx/core/view/accessibility/AccessibilityWindowInfoCompat.java
@@ -87,6 +87,25 @@
return null;
}
+ /**
+ * Creates a new AccessibilityWindowInfoCompat.
+ * <p>
+ * Compatibility:
+ * <ul>
+ * <li>Api < 30: Will not wrap an
+ * {@link android.view.accessibility.AccessibilityWindowInfo} instance.</li>
+ * </ul>
+ * </p>
+ *
+ */
+ public AccessibilityWindowInfoCompat() {
+ if (SDK_INT >= 30) {
+ mInfo = Api30Impl.instantiateAccessibilityWindowInfo();
+ } else {
+ mInfo = null;
+ }
+ }
+
private AccessibilityWindowInfoCompat(Object info) {
mInfo = info;
}
@@ -541,6 +560,18 @@
}
}
+ @RequiresApi(30)
+ private static class Api30Impl {
+ private Api30Impl() {
+ // This class is non instantiable.
+ }
+
+ @DoNotInline
+ static AccessibilityWindowInfo instantiateAccessibilityWindowInfo() {
+ return new AccessibilityWindowInfo();
+ }
+ }
+
@RequiresApi(33)
private static class Api33Impl {
private Api33Impl() {
diff --git a/credentials/credentials/api/current.txt b/credentials/credentials/api/current.txt
index 9bba4ab..14703f8 100644
--- a/credentials/credentials/api/current.txt
+++ b/credentials/credentials/api/current.txt
@@ -443,3 +443,297 @@
}
+package androidx.credentials.provider {
+
+ @RequiresApi(34) public final class Action extends android.service.credentials.Action {
+ method public android.app.PendingIntent getPendingIntent();
+ method public CharSequence? getSubTitle();
+ method public CharSequence getTitle();
+ property public final android.app.PendingIntent pendingIntent;
+ property public final CharSequence? subTitle;
+ property public final CharSequence title;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.Action> CREATOR;
+ field public static final androidx.credentials.provider.Action.Companion Companion;
+ }
+
+ public static final class Action.Builder {
+ ctor public Action.Builder(CharSequence title, android.app.PendingIntent pendingIntent);
+ method public androidx.credentials.provider.Action build();
+ method public androidx.credentials.provider.Action.Builder setSubTitle(CharSequence? subTitle);
+ }
+
+ public static final class Action.Companion {
+ }
+
+ @RequiresApi(34) public final class AuthenticationAction extends android.service.credentials.Action {
+ ctor public AuthenticationAction(android.app.PendingIntent pendingIntent);
+ method public android.app.PendingIntent getPendingIntent();
+ property public final android.app.PendingIntent pendingIntent;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.AuthenticationAction> CREATOR;
+ field public static final androidx.credentials.provider.AuthenticationAction.Companion Companion;
+ }
+
+ public static final class AuthenticationAction.Companion {
+ }
+
+ @RequiresApi(34) public final class BeginCreateCustomCredentialRequest extends android.service.credentials.BeginCreateCredentialRequest {
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.BeginCreateCustomCredentialRequest> CREATOR;
+ field public static final androidx.credentials.provider.BeginCreateCustomCredentialRequest.Companion Companion;
+ }
+
+ public static final class BeginCreateCustomCredentialRequest.Companion {
+ }
+
+ @RequiresApi(34) public final class BeginCreatePasswordCredentialRequest extends android.service.credentials.BeginCreateCredentialRequest {
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.BeginCreatePasswordCredentialRequest> CREATOR;
+ field public static final androidx.credentials.provider.BeginCreatePasswordCredentialRequest.Companion Companion;
+ }
+
+ public static final class BeginCreatePasswordCredentialRequest.Companion {
+ }
+
+ @RequiresApi(34) public final class BeginCreatePublicKeyCredentialRequest extends android.service.credentials.BeginCreateCredentialRequest {
+ method public String getJson();
+ method public boolean getPreferImmediatelyAvailableCredentials();
+ property public final String json;
+ property public final boolean preferImmediatelyAvailableCredentials;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.BeginCreatePublicKeyCredentialRequest> CREATOR;
+ field public static final androidx.credentials.provider.BeginCreatePublicKeyCredentialRequest.Companion Companion;
+ }
+
+ public static final class BeginCreatePublicKeyCredentialRequest.Companion {
+ }
+
+ @RequiresApi(34) public final class BeginCreatePublicKeyCredentialRequestPrivileged extends android.service.credentials.BeginCreateCredentialRequest {
+ method public String getClientDataHash();
+ method public String getJson();
+ method public boolean getPreferImmediatelyAvailableCredentials();
+ method public String getRelyingParty();
+ property public final String clientDataHash;
+ property public final String json;
+ property public final boolean preferImmediatelyAvailableCredentials;
+ property public final String relyingParty;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.BeginCreatePublicKeyCredentialRequestPrivileged> CREATOR;
+ field public static final androidx.credentials.provider.BeginCreatePublicKeyCredentialRequestPrivileged.Companion Companion;
+ }
+
+ public static final class BeginCreatePublicKeyCredentialRequestPrivileged.Companion {
+ }
+
+ @RequiresApi(34) public final class BeginGetPasswordOption extends android.service.credentials.BeginGetCredentialOption {
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.BeginGetPasswordOption> CREATOR;
+ field public static final androidx.credentials.provider.BeginGetPasswordOption.Companion Companion;
+ }
+
+ public static final class BeginGetPasswordOption.Companion {
+ }
+
+ @RequiresApi(34) public final class BeginGetPublicKeyCredentialOption extends android.service.credentials.BeginGetCredentialOption {
+ method public boolean getPreferImmediatelyAvailableCredentials();
+ method public String getRequestJson();
+ property public final boolean preferImmediatelyAvailableCredentials;
+ property public final String requestJson;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.BeginGetPublicKeyCredentialOption> CREATOR;
+ field public static final androidx.credentials.provider.BeginGetPublicKeyCredentialOption.Companion Companion;
+ }
+
+ public static final class BeginGetPublicKeyCredentialOption.Companion {
+ }
+
+ @RequiresApi(34) public final class BeginGetPublicKeyCredentialOptionPrivileged extends android.service.credentials.BeginGetCredentialOption {
+ method public String getClientDataHash();
+ method public boolean getPreferImmediatelyAvailableCredentials();
+ method public String getRelyingParty();
+ method public String getRequestJson();
+ property public final String clientDataHash;
+ property public final boolean preferImmediatelyAvailableCredentials;
+ property public final String relyingParty;
+ property public final String requestJson;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.BeginGetPublicKeyCredentialOptionPrivileged> CREATOR;
+ field public static final androidx.credentials.provider.BeginGetPublicKeyCredentialOptionPrivileged.Companion Companion;
+ }
+
+ public static final class BeginGetPublicKeyCredentialOptionPrivileged.Companion {
+ }
+
+ @RequiresApi(34) public final class CreateEntry extends android.service.credentials.CreateEntry {
+ method public CharSequence getAccountName();
+ method public CharSequence? getDescription();
+ method public android.graphics.drawable.Icon? getIcon();
+ method public java.time.Instant? getLastUsedTime();
+ method public Integer? getPasswordCredentialCount();
+ method public android.app.PendingIntent getPendingIntent();
+ method public Integer? getPublicKeyCredentialCount();
+ method public Integer? getTotalCredentialCount();
+ property public final CharSequence accountName;
+ property public final CharSequence? description;
+ property public final android.graphics.drawable.Icon? icon;
+ property public final java.time.Instant? lastUsedTime;
+ property public final android.app.PendingIntent pendingIntent;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.CreateEntry> CREATOR;
+ field public static final androidx.credentials.provider.CreateEntry.Companion Companion;
+ }
+
+ public static final class CreateEntry.Builder {
+ ctor public CreateEntry.Builder(CharSequence accountName, android.app.PendingIntent pendingIntent);
+ method public androidx.credentials.provider.CreateEntry build();
+ method public androidx.credentials.provider.CreateEntry.Builder setDescription(CharSequence? description);
+ method public androidx.credentials.provider.CreateEntry.Builder setIcon(android.graphics.drawable.Icon? icon);
+ method public androidx.credentials.provider.CreateEntry.Builder setLastUsedTime(java.time.Instant? lastUsedTime);
+ method public androidx.credentials.provider.CreateEntry.Builder setPasswordCredentialCount(int count);
+ method public androidx.credentials.provider.CreateEntry.Builder setPublicKeyCredentialCount(int count);
+ method public androidx.credentials.provider.CreateEntry.Builder setTotalCredentialCount(int count);
+ }
+
+ public static final class CreateEntry.Companion {
+ }
+
+ @RequiresApi(34) public abstract class CredentialProviderService extends android.service.credentials.CredentialProviderService {
+ ctor public CredentialProviderService();
+ method public final void onBeginCreateCredential(android.service.credentials.BeginCreateCredentialRequest request, android.os.CancellationSignal cancellationSignal, android.os.OutcomeReceiver<android.service.credentials.BeginCreateCredentialResponse,android.credentials.CreateCredentialException> callback);
+ method public abstract void onBeginCreateCredentialRequest(android.service.credentials.BeginCreateCredentialRequest request, android.os.CancellationSignal cancellationSignal, android.os.OutcomeReceiver<android.service.credentials.BeginCreateCredentialResponse,androidx.credentials.exceptions.CreateCredentialException> callback);
+ method public final void onBeginGetCredential(android.service.credentials.BeginGetCredentialRequest request, android.os.CancellationSignal cancellationSignal, android.os.OutcomeReceiver<android.service.credentials.BeginGetCredentialResponse,android.credentials.GetCredentialException> callback);
+ method public abstract void onBeginGetCredentialRequest(android.service.credentials.BeginGetCredentialRequest request, android.os.CancellationSignal cancellationSignal, android.os.OutcomeReceiver<android.service.credentials.BeginGetCredentialResponse,androidx.credentials.exceptions.GetCredentialException> callback);
+ }
+
+ @RequiresApi(34) public final class CustomCredentialEntry extends android.service.credentials.CredentialEntry {
+ method public android.graphics.drawable.Icon? getIcon();
+ method public java.time.Instant? getLastUsedTime();
+ method public android.app.PendingIntent getPendingIntent();
+ method public CharSequence? getSubTitle();
+ method public CharSequence getTitle();
+ method public CharSequence? getTypeDisplayName();
+ method public boolean isAutoSelectAllowed();
+ property public final android.graphics.drawable.Icon? icon;
+ property public final boolean isAutoSelectAllowed;
+ property public final java.time.Instant? lastUsedTime;
+ property public final android.app.PendingIntent pendingIntent;
+ property public final CharSequence? subTitle;
+ property public final CharSequence title;
+ property public final CharSequence? typeDisplayName;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.CustomCredentialEntry> CREATOR;
+ field public static final androidx.credentials.provider.CustomCredentialEntry.Companion Companion;
+ }
+
+ @RequiresApi(34) public static final class CustomCredentialEntry.Companion {
+ }
+
+ @RequiresApi(34) public final class PasswordCredentialEntry extends android.service.credentials.CredentialEntry {
+ method public CharSequence? getDisplayName();
+ method public android.graphics.drawable.Icon getIcon();
+ method public java.time.Instant? getLastUsedTime();
+ method public android.app.PendingIntent getPendingIntent();
+ method public CharSequence getTypeDisplayName();
+ method public CharSequence getUsername();
+ method public boolean isAutoSelectAllowed();
+ property public final CharSequence? displayName;
+ property public final android.graphics.drawable.Icon icon;
+ property public final boolean isAutoSelectAllowed;
+ property public final java.time.Instant? lastUsedTime;
+ property public final android.app.PendingIntent pendingIntent;
+ property public final CharSequence typeDisplayName;
+ property public final CharSequence username;
+ field public static final androidx.credentials.provider.PasswordCredentialEntry.CREATOR CREATOR;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.PasswordCredentialEntry> CREATOR$1;
+ }
+
+ public static final class PasswordCredentialEntry.Builder {
+ ctor public PasswordCredentialEntry.Builder(android.content.Context context, CharSequence username, android.app.PendingIntent pendingIntent);
+ method public androidx.credentials.provider.PasswordCredentialEntry build();
+ method public androidx.credentials.provider.PasswordCredentialEntry.Builder setDisplayName(CharSequence? displayName);
+ method public androidx.credentials.provider.PasswordCredentialEntry.Builder setIcon(android.graphics.drawable.Icon? icon);
+ method public androidx.credentials.provider.PasswordCredentialEntry.Builder setLastUsedTime(java.time.Instant? lastUsedTime);
+ }
+
+ public static final class PasswordCredentialEntry.CREATOR {
+ }
+
+ @RequiresApi(34) public final class PendingIntentHandler {
+ ctor public PendingIntentHandler();
+ method public static android.service.credentials.BeginGetCredentialRequest? getBeginGetCredentialRequest(android.content.Intent intent);
+ method public static androidx.credentials.provider.ProviderCreateCredentialRequest? retrieveCreateCredentialProviderRequest(android.content.Intent intent);
+ method public static androidx.credentials.provider.ProviderGetCredentialRequest? retrieveGetCredentialProviderRequest(android.content.Intent intent);
+ method public static void setCreateCredentialResponse(android.content.Intent intent, androidx.credentials.CreateCredentialResponse response);
+ method public static void setCredentialsResponseContent(android.content.Intent intent, android.service.credentials.CredentialsResponseContent response);
+ method public static void setGetCredentialResponse(android.content.Intent intent, androidx.credentials.GetCredentialResponse response);
+ field public static final androidx.credentials.provider.PendingIntentHandler.Companion Companion;
+ }
+
+ public static final class PendingIntentHandler.Companion {
+ method public android.service.credentials.BeginGetCredentialRequest? getBeginGetCredentialRequest(android.content.Intent intent);
+ method public androidx.credentials.provider.ProviderCreateCredentialRequest? retrieveCreateCredentialProviderRequest(android.content.Intent intent);
+ method public androidx.credentials.provider.ProviderGetCredentialRequest? retrieveGetCredentialProviderRequest(android.content.Intent intent);
+ method public void setCreateCredentialResponse(android.content.Intent intent, androidx.credentials.CreateCredentialResponse response);
+ method public void setCredentialsResponseContent(android.content.Intent intent, android.service.credentials.CredentialsResponseContent response);
+ method public void setGetCredentialResponse(android.content.Intent intent, androidx.credentials.GetCredentialResponse response);
+ }
+
+ @RequiresApi(34) public final class ProviderCreateCredentialRequest {
+ method public android.service.credentials.CallingAppInfo getCallingAppInfo();
+ method public androidx.credentials.CreateCredentialRequest getCallingRequest();
+ property public final android.service.credentials.CallingAppInfo callingAppInfo;
+ property public final androidx.credentials.CreateCredentialRequest callingRequest;
+ }
+
+ @RequiresApi(34) public final class ProviderGetCredentialRequest {
+ method public android.service.credentials.CallingAppInfo getCallingAppInfo();
+ method public androidx.credentials.CredentialOption getCredentialOption();
+ property public final android.service.credentials.CallingAppInfo callingAppInfo;
+ property public final androidx.credentials.CredentialOption credentialOption;
+ }
+
+ @RequiresApi(34) public final class PublicKeyCredentialEntry extends android.service.credentials.CredentialEntry {
+ method public CharSequence? getDisplayName();
+ method public android.graphics.drawable.Icon getIcon();
+ method public java.time.Instant? getLastUsedTime();
+ method public android.app.PendingIntent getPendingIntent();
+ method public CharSequence getTypeDisplayName();
+ method public CharSequence getUsername();
+ method public boolean isAutoSelectAllowed();
+ property public final CharSequence? displayName;
+ property public final android.graphics.drawable.Icon icon;
+ property public final boolean isAutoSelectAllowed;
+ property public final java.time.Instant? lastUsedTime;
+ property public final android.app.PendingIntent pendingIntent;
+ property public final CharSequence typeDisplayName;
+ property public final CharSequence username;
+ field public static final androidx.credentials.provider.PublicKeyCredentialEntry.CREATOR CREATOR;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.PublicKeyCredentialEntry> CREATOR$1;
+ }
+
+ public static final class PublicKeyCredentialEntry.Builder {
+ ctor public PublicKeyCredentialEntry.Builder(android.content.Context context, CharSequence username, android.app.PendingIntent pendingIntent);
+ method public androidx.credentials.provider.PublicKeyCredentialEntry build();
+ method public androidx.credentials.provider.PublicKeyCredentialEntry.Builder setAutoSelectAllowed(boolean autoSelectAllowed);
+ method public androidx.credentials.provider.PublicKeyCredentialEntry.Builder setDisplayName(CharSequence? displayName);
+ method public androidx.credentials.provider.PublicKeyCredentialEntry.Builder setIcon(android.graphics.drawable.Icon? icon);
+ method public androidx.credentials.provider.PublicKeyCredentialEntry.Builder setLastUsedTime(java.time.Instant? lastUsedTime);
+ }
+
+ public static final class PublicKeyCredentialEntry.CREATOR {
+ }
+
+ @RequiresApi(34) public final class RemoteCreateEntry extends android.service.credentials.CreateEntry {
+ ctor public RemoteCreateEntry(android.app.PendingIntent pendingIntent);
+ method public android.app.PendingIntent getPendingIntent();
+ property public final android.app.PendingIntent pendingIntent;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.RemoteCreateEntry> CREATOR;
+ field public static final androidx.credentials.provider.RemoteCreateEntry.Companion Companion;
+ }
+
+ public static final class RemoteCreateEntry.Companion {
+ }
+
+ @RequiresApi(34) public final class RemoteCredentialEntry extends android.service.credentials.CredentialEntry {
+ ctor public RemoteCredentialEntry(android.app.PendingIntent pendingIntent);
+ method public android.app.PendingIntent getPendingIntent();
+ property public final android.app.PendingIntent pendingIntent;
+ field public static final androidx.credentials.provider.RemoteCredentialEntry.CREATOR CREATOR;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.RemoteCredentialEntry> CREATOR$1;
+ }
+
+ public static final class RemoteCredentialEntry.CREATOR {
+ }
+
+}
+
diff --git a/credentials/credentials/api/public_plus_experimental_current.txt b/credentials/credentials/api/public_plus_experimental_current.txt
index 9bba4ab..14703f8 100644
--- a/credentials/credentials/api/public_plus_experimental_current.txt
+++ b/credentials/credentials/api/public_plus_experimental_current.txt
@@ -443,3 +443,297 @@
}
+package androidx.credentials.provider {
+
+ @RequiresApi(34) public final class Action extends android.service.credentials.Action {
+ method public android.app.PendingIntent getPendingIntent();
+ method public CharSequence? getSubTitle();
+ method public CharSequence getTitle();
+ property public final android.app.PendingIntent pendingIntent;
+ property public final CharSequence? subTitle;
+ property public final CharSequence title;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.Action> CREATOR;
+ field public static final androidx.credentials.provider.Action.Companion Companion;
+ }
+
+ public static final class Action.Builder {
+ ctor public Action.Builder(CharSequence title, android.app.PendingIntent pendingIntent);
+ method public androidx.credentials.provider.Action build();
+ method public androidx.credentials.provider.Action.Builder setSubTitle(CharSequence? subTitle);
+ }
+
+ public static final class Action.Companion {
+ }
+
+ @RequiresApi(34) public final class AuthenticationAction extends android.service.credentials.Action {
+ ctor public AuthenticationAction(android.app.PendingIntent pendingIntent);
+ method public android.app.PendingIntent getPendingIntent();
+ property public final android.app.PendingIntent pendingIntent;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.AuthenticationAction> CREATOR;
+ field public static final androidx.credentials.provider.AuthenticationAction.Companion Companion;
+ }
+
+ public static final class AuthenticationAction.Companion {
+ }
+
+ @RequiresApi(34) public final class BeginCreateCustomCredentialRequest extends android.service.credentials.BeginCreateCredentialRequest {
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.BeginCreateCustomCredentialRequest> CREATOR;
+ field public static final androidx.credentials.provider.BeginCreateCustomCredentialRequest.Companion Companion;
+ }
+
+ public static final class BeginCreateCustomCredentialRequest.Companion {
+ }
+
+ @RequiresApi(34) public final class BeginCreatePasswordCredentialRequest extends android.service.credentials.BeginCreateCredentialRequest {
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.BeginCreatePasswordCredentialRequest> CREATOR;
+ field public static final androidx.credentials.provider.BeginCreatePasswordCredentialRequest.Companion Companion;
+ }
+
+ public static final class BeginCreatePasswordCredentialRequest.Companion {
+ }
+
+ @RequiresApi(34) public final class BeginCreatePublicKeyCredentialRequest extends android.service.credentials.BeginCreateCredentialRequest {
+ method public String getJson();
+ method public boolean getPreferImmediatelyAvailableCredentials();
+ property public final String json;
+ property public final boolean preferImmediatelyAvailableCredentials;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.BeginCreatePublicKeyCredentialRequest> CREATOR;
+ field public static final androidx.credentials.provider.BeginCreatePublicKeyCredentialRequest.Companion Companion;
+ }
+
+ public static final class BeginCreatePublicKeyCredentialRequest.Companion {
+ }
+
+ @RequiresApi(34) public final class BeginCreatePublicKeyCredentialRequestPrivileged extends android.service.credentials.BeginCreateCredentialRequest {
+ method public String getClientDataHash();
+ method public String getJson();
+ method public boolean getPreferImmediatelyAvailableCredentials();
+ method public String getRelyingParty();
+ property public final String clientDataHash;
+ property public final String json;
+ property public final boolean preferImmediatelyAvailableCredentials;
+ property public final String relyingParty;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.BeginCreatePublicKeyCredentialRequestPrivileged> CREATOR;
+ field public static final androidx.credentials.provider.BeginCreatePublicKeyCredentialRequestPrivileged.Companion Companion;
+ }
+
+ public static final class BeginCreatePublicKeyCredentialRequestPrivileged.Companion {
+ }
+
+ @RequiresApi(34) public final class BeginGetPasswordOption extends android.service.credentials.BeginGetCredentialOption {
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.BeginGetPasswordOption> CREATOR;
+ field public static final androidx.credentials.provider.BeginGetPasswordOption.Companion Companion;
+ }
+
+ public static final class BeginGetPasswordOption.Companion {
+ }
+
+ @RequiresApi(34) public final class BeginGetPublicKeyCredentialOption extends android.service.credentials.BeginGetCredentialOption {
+ method public boolean getPreferImmediatelyAvailableCredentials();
+ method public String getRequestJson();
+ property public final boolean preferImmediatelyAvailableCredentials;
+ property public final String requestJson;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.BeginGetPublicKeyCredentialOption> CREATOR;
+ field public static final androidx.credentials.provider.BeginGetPublicKeyCredentialOption.Companion Companion;
+ }
+
+ public static final class BeginGetPublicKeyCredentialOption.Companion {
+ }
+
+ @RequiresApi(34) public final class BeginGetPublicKeyCredentialOptionPrivileged extends android.service.credentials.BeginGetCredentialOption {
+ method public String getClientDataHash();
+ method public boolean getPreferImmediatelyAvailableCredentials();
+ method public String getRelyingParty();
+ method public String getRequestJson();
+ property public final String clientDataHash;
+ property public final boolean preferImmediatelyAvailableCredentials;
+ property public final String relyingParty;
+ property public final String requestJson;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.BeginGetPublicKeyCredentialOptionPrivileged> CREATOR;
+ field public static final androidx.credentials.provider.BeginGetPublicKeyCredentialOptionPrivileged.Companion Companion;
+ }
+
+ public static final class BeginGetPublicKeyCredentialOptionPrivileged.Companion {
+ }
+
+ @RequiresApi(34) public final class CreateEntry extends android.service.credentials.CreateEntry {
+ method public CharSequence getAccountName();
+ method public CharSequence? getDescription();
+ method public android.graphics.drawable.Icon? getIcon();
+ method public java.time.Instant? getLastUsedTime();
+ method public Integer? getPasswordCredentialCount();
+ method public android.app.PendingIntent getPendingIntent();
+ method public Integer? getPublicKeyCredentialCount();
+ method public Integer? getTotalCredentialCount();
+ property public final CharSequence accountName;
+ property public final CharSequence? description;
+ property public final android.graphics.drawable.Icon? icon;
+ property public final java.time.Instant? lastUsedTime;
+ property public final android.app.PendingIntent pendingIntent;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.CreateEntry> CREATOR;
+ field public static final androidx.credentials.provider.CreateEntry.Companion Companion;
+ }
+
+ public static final class CreateEntry.Builder {
+ ctor public CreateEntry.Builder(CharSequence accountName, android.app.PendingIntent pendingIntent);
+ method public androidx.credentials.provider.CreateEntry build();
+ method public androidx.credentials.provider.CreateEntry.Builder setDescription(CharSequence? description);
+ method public androidx.credentials.provider.CreateEntry.Builder setIcon(android.graphics.drawable.Icon? icon);
+ method public androidx.credentials.provider.CreateEntry.Builder setLastUsedTime(java.time.Instant? lastUsedTime);
+ method public androidx.credentials.provider.CreateEntry.Builder setPasswordCredentialCount(int count);
+ method public androidx.credentials.provider.CreateEntry.Builder setPublicKeyCredentialCount(int count);
+ method public androidx.credentials.provider.CreateEntry.Builder setTotalCredentialCount(int count);
+ }
+
+ public static final class CreateEntry.Companion {
+ }
+
+ @RequiresApi(34) public abstract class CredentialProviderService extends android.service.credentials.CredentialProviderService {
+ ctor public CredentialProviderService();
+ method public final void onBeginCreateCredential(android.service.credentials.BeginCreateCredentialRequest request, android.os.CancellationSignal cancellationSignal, android.os.OutcomeReceiver<android.service.credentials.BeginCreateCredentialResponse,android.credentials.CreateCredentialException> callback);
+ method public abstract void onBeginCreateCredentialRequest(android.service.credentials.BeginCreateCredentialRequest request, android.os.CancellationSignal cancellationSignal, android.os.OutcomeReceiver<android.service.credentials.BeginCreateCredentialResponse,androidx.credentials.exceptions.CreateCredentialException> callback);
+ method public final void onBeginGetCredential(android.service.credentials.BeginGetCredentialRequest request, android.os.CancellationSignal cancellationSignal, android.os.OutcomeReceiver<android.service.credentials.BeginGetCredentialResponse,android.credentials.GetCredentialException> callback);
+ method public abstract void onBeginGetCredentialRequest(android.service.credentials.BeginGetCredentialRequest request, android.os.CancellationSignal cancellationSignal, android.os.OutcomeReceiver<android.service.credentials.BeginGetCredentialResponse,androidx.credentials.exceptions.GetCredentialException> callback);
+ }
+
+ @RequiresApi(34) public final class CustomCredentialEntry extends android.service.credentials.CredentialEntry {
+ method public android.graphics.drawable.Icon? getIcon();
+ method public java.time.Instant? getLastUsedTime();
+ method public android.app.PendingIntent getPendingIntent();
+ method public CharSequence? getSubTitle();
+ method public CharSequence getTitle();
+ method public CharSequence? getTypeDisplayName();
+ method public boolean isAutoSelectAllowed();
+ property public final android.graphics.drawable.Icon? icon;
+ property public final boolean isAutoSelectAllowed;
+ property public final java.time.Instant? lastUsedTime;
+ property public final android.app.PendingIntent pendingIntent;
+ property public final CharSequence? subTitle;
+ property public final CharSequence title;
+ property public final CharSequence? typeDisplayName;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.CustomCredentialEntry> CREATOR;
+ field public static final androidx.credentials.provider.CustomCredentialEntry.Companion Companion;
+ }
+
+ @RequiresApi(34) public static final class CustomCredentialEntry.Companion {
+ }
+
+ @RequiresApi(34) public final class PasswordCredentialEntry extends android.service.credentials.CredentialEntry {
+ method public CharSequence? getDisplayName();
+ method public android.graphics.drawable.Icon getIcon();
+ method public java.time.Instant? getLastUsedTime();
+ method public android.app.PendingIntent getPendingIntent();
+ method public CharSequence getTypeDisplayName();
+ method public CharSequence getUsername();
+ method public boolean isAutoSelectAllowed();
+ property public final CharSequence? displayName;
+ property public final android.graphics.drawable.Icon icon;
+ property public final boolean isAutoSelectAllowed;
+ property public final java.time.Instant? lastUsedTime;
+ property public final android.app.PendingIntent pendingIntent;
+ property public final CharSequence typeDisplayName;
+ property public final CharSequence username;
+ field public static final androidx.credentials.provider.PasswordCredentialEntry.CREATOR CREATOR;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.PasswordCredentialEntry> CREATOR$1;
+ }
+
+ public static final class PasswordCredentialEntry.Builder {
+ ctor public PasswordCredentialEntry.Builder(android.content.Context context, CharSequence username, android.app.PendingIntent pendingIntent);
+ method public androidx.credentials.provider.PasswordCredentialEntry build();
+ method public androidx.credentials.provider.PasswordCredentialEntry.Builder setDisplayName(CharSequence? displayName);
+ method public androidx.credentials.provider.PasswordCredentialEntry.Builder setIcon(android.graphics.drawable.Icon? icon);
+ method public androidx.credentials.provider.PasswordCredentialEntry.Builder setLastUsedTime(java.time.Instant? lastUsedTime);
+ }
+
+ public static final class PasswordCredentialEntry.CREATOR {
+ }
+
+ @RequiresApi(34) public final class PendingIntentHandler {
+ ctor public PendingIntentHandler();
+ method public static android.service.credentials.BeginGetCredentialRequest? getBeginGetCredentialRequest(android.content.Intent intent);
+ method public static androidx.credentials.provider.ProviderCreateCredentialRequest? retrieveCreateCredentialProviderRequest(android.content.Intent intent);
+ method public static androidx.credentials.provider.ProviderGetCredentialRequest? retrieveGetCredentialProviderRequest(android.content.Intent intent);
+ method public static void setCreateCredentialResponse(android.content.Intent intent, androidx.credentials.CreateCredentialResponse response);
+ method public static void setCredentialsResponseContent(android.content.Intent intent, android.service.credentials.CredentialsResponseContent response);
+ method public static void setGetCredentialResponse(android.content.Intent intent, androidx.credentials.GetCredentialResponse response);
+ field public static final androidx.credentials.provider.PendingIntentHandler.Companion Companion;
+ }
+
+ public static final class PendingIntentHandler.Companion {
+ method public android.service.credentials.BeginGetCredentialRequest? getBeginGetCredentialRequest(android.content.Intent intent);
+ method public androidx.credentials.provider.ProviderCreateCredentialRequest? retrieveCreateCredentialProviderRequest(android.content.Intent intent);
+ method public androidx.credentials.provider.ProviderGetCredentialRequest? retrieveGetCredentialProviderRequest(android.content.Intent intent);
+ method public void setCreateCredentialResponse(android.content.Intent intent, androidx.credentials.CreateCredentialResponse response);
+ method public void setCredentialsResponseContent(android.content.Intent intent, android.service.credentials.CredentialsResponseContent response);
+ method public void setGetCredentialResponse(android.content.Intent intent, androidx.credentials.GetCredentialResponse response);
+ }
+
+ @RequiresApi(34) public final class ProviderCreateCredentialRequest {
+ method public android.service.credentials.CallingAppInfo getCallingAppInfo();
+ method public androidx.credentials.CreateCredentialRequest getCallingRequest();
+ property public final android.service.credentials.CallingAppInfo callingAppInfo;
+ property public final androidx.credentials.CreateCredentialRequest callingRequest;
+ }
+
+ @RequiresApi(34) public final class ProviderGetCredentialRequest {
+ method public android.service.credentials.CallingAppInfo getCallingAppInfo();
+ method public androidx.credentials.CredentialOption getCredentialOption();
+ property public final android.service.credentials.CallingAppInfo callingAppInfo;
+ property public final androidx.credentials.CredentialOption credentialOption;
+ }
+
+ @RequiresApi(34) public final class PublicKeyCredentialEntry extends android.service.credentials.CredentialEntry {
+ method public CharSequence? getDisplayName();
+ method public android.graphics.drawable.Icon getIcon();
+ method public java.time.Instant? getLastUsedTime();
+ method public android.app.PendingIntent getPendingIntent();
+ method public CharSequence getTypeDisplayName();
+ method public CharSequence getUsername();
+ method public boolean isAutoSelectAllowed();
+ property public final CharSequence? displayName;
+ property public final android.graphics.drawable.Icon icon;
+ property public final boolean isAutoSelectAllowed;
+ property public final java.time.Instant? lastUsedTime;
+ property public final android.app.PendingIntent pendingIntent;
+ property public final CharSequence typeDisplayName;
+ property public final CharSequence username;
+ field public static final androidx.credentials.provider.PublicKeyCredentialEntry.CREATOR CREATOR;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.PublicKeyCredentialEntry> CREATOR$1;
+ }
+
+ public static final class PublicKeyCredentialEntry.Builder {
+ ctor public PublicKeyCredentialEntry.Builder(android.content.Context context, CharSequence username, android.app.PendingIntent pendingIntent);
+ method public androidx.credentials.provider.PublicKeyCredentialEntry build();
+ method public androidx.credentials.provider.PublicKeyCredentialEntry.Builder setAutoSelectAllowed(boolean autoSelectAllowed);
+ method public androidx.credentials.provider.PublicKeyCredentialEntry.Builder setDisplayName(CharSequence? displayName);
+ method public androidx.credentials.provider.PublicKeyCredentialEntry.Builder setIcon(android.graphics.drawable.Icon? icon);
+ method public androidx.credentials.provider.PublicKeyCredentialEntry.Builder setLastUsedTime(java.time.Instant? lastUsedTime);
+ }
+
+ public static final class PublicKeyCredentialEntry.CREATOR {
+ }
+
+ @RequiresApi(34) public final class RemoteCreateEntry extends android.service.credentials.CreateEntry {
+ ctor public RemoteCreateEntry(android.app.PendingIntent pendingIntent);
+ method public android.app.PendingIntent getPendingIntent();
+ property public final android.app.PendingIntent pendingIntent;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.RemoteCreateEntry> CREATOR;
+ field public static final androidx.credentials.provider.RemoteCreateEntry.Companion Companion;
+ }
+
+ public static final class RemoteCreateEntry.Companion {
+ }
+
+ @RequiresApi(34) public final class RemoteCredentialEntry extends android.service.credentials.CredentialEntry {
+ ctor public RemoteCredentialEntry(android.app.PendingIntent pendingIntent);
+ method public android.app.PendingIntent getPendingIntent();
+ property public final android.app.PendingIntent pendingIntent;
+ field public static final androidx.credentials.provider.RemoteCredentialEntry.CREATOR CREATOR;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.RemoteCredentialEntry> CREATOR$1;
+ }
+
+ public static final class RemoteCredentialEntry.CREATOR {
+ }
+
+}
+
diff --git a/credentials/credentials/api/restricted_current.txt b/credentials/credentials/api/restricted_current.txt
index 9bba4ab..14703f8 100644
--- a/credentials/credentials/api/restricted_current.txt
+++ b/credentials/credentials/api/restricted_current.txt
@@ -443,3 +443,297 @@
}
+package androidx.credentials.provider {
+
+ @RequiresApi(34) public final class Action extends android.service.credentials.Action {
+ method public android.app.PendingIntent getPendingIntent();
+ method public CharSequence? getSubTitle();
+ method public CharSequence getTitle();
+ property public final android.app.PendingIntent pendingIntent;
+ property public final CharSequence? subTitle;
+ property public final CharSequence title;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.Action> CREATOR;
+ field public static final androidx.credentials.provider.Action.Companion Companion;
+ }
+
+ public static final class Action.Builder {
+ ctor public Action.Builder(CharSequence title, android.app.PendingIntent pendingIntent);
+ method public androidx.credentials.provider.Action build();
+ method public androidx.credentials.provider.Action.Builder setSubTitle(CharSequence? subTitle);
+ }
+
+ public static final class Action.Companion {
+ }
+
+ @RequiresApi(34) public final class AuthenticationAction extends android.service.credentials.Action {
+ ctor public AuthenticationAction(android.app.PendingIntent pendingIntent);
+ method public android.app.PendingIntent getPendingIntent();
+ property public final android.app.PendingIntent pendingIntent;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.AuthenticationAction> CREATOR;
+ field public static final androidx.credentials.provider.AuthenticationAction.Companion Companion;
+ }
+
+ public static final class AuthenticationAction.Companion {
+ }
+
+ @RequiresApi(34) public final class BeginCreateCustomCredentialRequest extends android.service.credentials.BeginCreateCredentialRequest {
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.BeginCreateCustomCredentialRequest> CREATOR;
+ field public static final androidx.credentials.provider.BeginCreateCustomCredentialRequest.Companion Companion;
+ }
+
+ public static final class BeginCreateCustomCredentialRequest.Companion {
+ }
+
+ @RequiresApi(34) public final class BeginCreatePasswordCredentialRequest extends android.service.credentials.BeginCreateCredentialRequest {
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.BeginCreatePasswordCredentialRequest> CREATOR;
+ field public static final androidx.credentials.provider.BeginCreatePasswordCredentialRequest.Companion Companion;
+ }
+
+ public static final class BeginCreatePasswordCredentialRequest.Companion {
+ }
+
+ @RequiresApi(34) public final class BeginCreatePublicKeyCredentialRequest extends android.service.credentials.BeginCreateCredentialRequest {
+ method public String getJson();
+ method public boolean getPreferImmediatelyAvailableCredentials();
+ property public final String json;
+ property public final boolean preferImmediatelyAvailableCredentials;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.BeginCreatePublicKeyCredentialRequest> CREATOR;
+ field public static final androidx.credentials.provider.BeginCreatePublicKeyCredentialRequest.Companion Companion;
+ }
+
+ public static final class BeginCreatePublicKeyCredentialRequest.Companion {
+ }
+
+ @RequiresApi(34) public final class BeginCreatePublicKeyCredentialRequestPrivileged extends android.service.credentials.BeginCreateCredentialRequest {
+ method public String getClientDataHash();
+ method public String getJson();
+ method public boolean getPreferImmediatelyAvailableCredentials();
+ method public String getRelyingParty();
+ property public final String clientDataHash;
+ property public final String json;
+ property public final boolean preferImmediatelyAvailableCredentials;
+ property public final String relyingParty;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.BeginCreatePublicKeyCredentialRequestPrivileged> CREATOR;
+ field public static final androidx.credentials.provider.BeginCreatePublicKeyCredentialRequestPrivileged.Companion Companion;
+ }
+
+ public static final class BeginCreatePublicKeyCredentialRequestPrivileged.Companion {
+ }
+
+ @RequiresApi(34) public final class BeginGetPasswordOption extends android.service.credentials.BeginGetCredentialOption {
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.BeginGetPasswordOption> CREATOR;
+ field public static final androidx.credentials.provider.BeginGetPasswordOption.Companion Companion;
+ }
+
+ public static final class BeginGetPasswordOption.Companion {
+ }
+
+ @RequiresApi(34) public final class BeginGetPublicKeyCredentialOption extends android.service.credentials.BeginGetCredentialOption {
+ method public boolean getPreferImmediatelyAvailableCredentials();
+ method public String getRequestJson();
+ property public final boolean preferImmediatelyAvailableCredentials;
+ property public final String requestJson;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.BeginGetPublicKeyCredentialOption> CREATOR;
+ field public static final androidx.credentials.provider.BeginGetPublicKeyCredentialOption.Companion Companion;
+ }
+
+ public static final class BeginGetPublicKeyCredentialOption.Companion {
+ }
+
+ @RequiresApi(34) public final class BeginGetPublicKeyCredentialOptionPrivileged extends android.service.credentials.BeginGetCredentialOption {
+ method public String getClientDataHash();
+ method public boolean getPreferImmediatelyAvailableCredentials();
+ method public String getRelyingParty();
+ method public String getRequestJson();
+ property public final String clientDataHash;
+ property public final boolean preferImmediatelyAvailableCredentials;
+ property public final String relyingParty;
+ property public final String requestJson;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.BeginGetPublicKeyCredentialOptionPrivileged> CREATOR;
+ field public static final androidx.credentials.provider.BeginGetPublicKeyCredentialOptionPrivileged.Companion Companion;
+ }
+
+ public static final class BeginGetPublicKeyCredentialOptionPrivileged.Companion {
+ }
+
+ @RequiresApi(34) public final class CreateEntry extends android.service.credentials.CreateEntry {
+ method public CharSequence getAccountName();
+ method public CharSequence? getDescription();
+ method public android.graphics.drawable.Icon? getIcon();
+ method public java.time.Instant? getLastUsedTime();
+ method public Integer? getPasswordCredentialCount();
+ method public android.app.PendingIntent getPendingIntent();
+ method public Integer? getPublicKeyCredentialCount();
+ method public Integer? getTotalCredentialCount();
+ property public final CharSequence accountName;
+ property public final CharSequence? description;
+ property public final android.graphics.drawable.Icon? icon;
+ property public final java.time.Instant? lastUsedTime;
+ property public final android.app.PendingIntent pendingIntent;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.CreateEntry> CREATOR;
+ field public static final androidx.credentials.provider.CreateEntry.Companion Companion;
+ }
+
+ public static final class CreateEntry.Builder {
+ ctor public CreateEntry.Builder(CharSequence accountName, android.app.PendingIntent pendingIntent);
+ method public androidx.credentials.provider.CreateEntry build();
+ method public androidx.credentials.provider.CreateEntry.Builder setDescription(CharSequence? description);
+ method public androidx.credentials.provider.CreateEntry.Builder setIcon(android.graphics.drawable.Icon? icon);
+ method public androidx.credentials.provider.CreateEntry.Builder setLastUsedTime(java.time.Instant? lastUsedTime);
+ method public androidx.credentials.provider.CreateEntry.Builder setPasswordCredentialCount(int count);
+ method public androidx.credentials.provider.CreateEntry.Builder setPublicKeyCredentialCount(int count);
+ method public androidx.credentials.provider.CreateEntry.Builder setTotalCredentialCount(int count);
+ }
+
+ public static final class CreateEntry.Companion {
+ }
+
+ @RequiresApi(34) public abstract class CredentialProviderService extends android.service.credentials.CredentialProviderService {
+ ctor public CredentialProviderService();
+ method public final void onBeginCreateCredential(android.service.credentials.BeginCreateCredentialRequest request, android.os.CancellationSignal cancellationSignal, android.os.OutcomeReceiver<android.service.credentials.BeginCreateCredentialResponse,android.credentials.CreateCredentialException> callback);
+ method public abstract void onBeginCreateCredentialRequest(android.service.credentials.BeginCreateCredentialRequest request, android.os.CancellationSignal cancellationSignal, android.os.OutcomeReceiver<android.service.credentials.BeginCreateCredentialResponse,androidx.credentials.exceptions.CreateCredentialException> callback);
+ method public final void onBeginGetCredential(android.service.credentials.BeginGetCredentialRequest request, android.os.CancellationSignal cancellationSignal, android.os.OutcomeReceiver<android.service.credentials.BeginGetCredentialResponse,android.credentials.GetCredentialException> callback);
+ method public abstract void onBeginGetCredentialRequest(android.service.credentials.BeginGetCredentialRequest request, android.os.CancellationSignal cancellationSignal, android.os.OutcomeReceiver<android.service.credentials.BeginGetCredentialResponse,androidx.credentials.exceptions.GetCredentialException> callback);
+ }
+
+ @RequiresApi(34) public final class CustomCredentialEntry extends android.service.credentials.CredentialEntry {
+ method public android.graphics.drawable.Icon? getIcon();
+ method public java.time.Instant? getLastUsedTime();
+ method public android.app.PendingIntent getPendingIntent();
+ method public CharSequence? getSubTitle();
+ method public CharSequence getTitle();
+ method public CharSequence? getTypeDisplayName();
+ method public boolean isAutoSelectAllowed();
+ property public final android.graphics.drawable.Icon? icon;
+ property public final boolean isAutoSelectAllowed;
+ property public final java.time.Instant? lastUsedTime;
+ property public final android.app.PendingIntent pendingIntent;
+ property public final CharSequence? subTitle;
+ property public final CharSequence title;
+ property public final CharSequence? typeDisplayName;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.CustomCredentialEntry> CREATOR;
+ field public static final androidx.credentials.provider.CustomCredentialEntry.Companion Companion;
+ }
+
+ @RequiresApi(34) public static final class CustomCredentialEntry.Companion {
+ }
+
+ @RequiresApi(34) public final class PasswordCredentialEntry extends android.service.credentials.CredentialEntry {
+ method public CharSequence? getDisplayName();
+ method public android.graphics.drawable.Icon getIcon();
+ method public java.time.Instant? getLastUsedTime();
+ method public android.app.PendingIntent getPendingIntent();
+ method public CharSequence getTypeDisplayName();
+ method public CharSequence getUsername();
+ method public boolean isAutoSelectAllowed();
+ property public final CharSequence? displayName;
+ property public final android.graphics.drawable.Icon icon;
+ property public final boolean isAutoSelectAllowed;
+ property public final java.time.Instant? lastUsedTime;
+ property public final android.app.PendingIntent pendingIntent;
+ property public final CharSequence typeDisplayName;
+ property public final CharSequence username;
+ field public static final androidx.credentials.provider.PasswordCredentialEntry.CREATOR CREATOR;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.PasswordCredentialEntry> CREATOR$1;
+ }
+
+ public static final class PasswordCredentialEntry.Builder {
+ ctor public PasswordCredentialEntry.Builder(android.content.Context context, CharSequence username, android.app.PendingIntent pendingIntent);
+ method public androidx.credentials.provider.PasswordCredentialEntry build();
+ method public androidx.credentials.provider.PasswordCredentialEntry.Builder setDisplayName(CharSequence? displayName);
+ method public androidx.credentials.provider.PasswordCredentialEntry.Builder setIcon(android.graphics.drawable.Icon? icon);
+ method public androidx.credentials.provider.PasswordCredentialEntry.Builder setLastUsedTime(java.time.Instant? lastUsedTime);
+ }
+
+ public static final class PasswordCredentialEntry.CREATOR {
+ }
+
+ @RequiresApi(34) public final class PendingIntentHandler {
+ ctor public PendingIntentHandler();
+ method public static android.service.credentials.BeginGetCredentialRequest? getBeginGetCredentialRequest(android.content.Intent intent);
+ method public static androidx.credentials.provider.ProviderCreateCredentialRequest? retrieveCreateCredentialProviderRequest(android.content.Intent intent);
+ method public static androidx.credentials.provider.ProviderGetCredentialRequest? retrieveGetCredentialProviderRequest(android.content.Intent intent);
+ method public static void setCreateCredentialResponse(android.content.Intent intent, androidx.credentials.CreateCredentialResponse response);
+ method public static void setCredentialsResponseContent(android.content.Intent intent, android.service.credentials.CredentialsResponseContent response);
+ method public static void setGetCredentialResponse(android.content.Intent intent, androidx.credentials.GetCredentialResponse response);
+ field public static final androidx.credentials.provider.PendingIntentHandler.Companion Companion;
+ }
+
+ public static final class PendingIntentHandler.Companion {
+ method public android.service.credentials.BeginGetCredentialRequest? getBeginGetCredentialRequest(android.content.Intent intent);
+ method public androidx.credentials.provider.ProviderCreateCredentialRequest? retrieveCreateCredentialProviderRequest(android.content.Intent intent);
+ method public androidx.credentials.provider.ProviderGetCredentialRequest? retrieveGetCredentialProviderRequest(android.content.Intent intent);
+ method public void setCreateCredentialResponse(android.content.Intent intent, androidx.credentials.CreateCredentialResponse response);
+ method public void setCredentialsResponseContent(android.content.Intent intent, android.service.credentials.CredentialsResponseContent response);
+ method public void setGetCredentialResponse(android.content.Intent intent, androidx.credentials.GetCredentialResponse response);
+ }
+
+ @RequiresApi(34) public final class ProviderCreateCredentialRequest {
+ method public android.service.credentials.CallingAppInfo getCallingAppInfo();
+ method public androidx.credentials.CreateCredentialRequest getCallingRequest();
+ property public final android.service.credentials.CallingAppInfo callingAppInfo;
+ property public final androidx.credentials.CreateCredentialRequest callingRequest;
+ }
+
+ @RequiresApi(34) public final class ProviderGetCredentialRequest {
+ method public android.service.credentials.CallingAppInfo getCallingAppInfo();
+ method public androidx.credentials.CredentialOption getCredentialOption();
+ property public final android.service.credentials.CallingAppInfo callingAppInfo;
+ property public final androidx.credentials.CredentialOption credentialOption;
+ }
+
+ @RequiresApi(34) public final class PublicKeyCredentialEntry extends android.service.credentials.CredentialEntry {
+ method public CharSequence? getDisplayName();
+ method public android.graphics.drawable.Icon getIcon();
+ method public java.time.Instant? getLastUsedTime();
+ method public android.app.PendingIntent getPendingIntent();
+ method public CharSequence getTypeDisplayName();
+ method public CharSequence getUsername();
+ method public boolean isAutoSelectAllowed();
+ property public final CharSequence? displayName;
+ property public final android.graphics.drawable.Icon icon;
+ property public final boolean isAutoSelectAllowed;
+ property public final java.time.Instant? lastUsedTime;
+ property public final android.app.PendingIntent pendingIntent;
+ property public final CharSequence typeDisplayName;
+ property public final CharSequence username;
+ field public static final androidx.credentials.provider.PublicKeyCredentialEntry.CREATOR CREATOR;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.PublicKeyCredentialEntry> CREATOR$1;
+ }
+
+ public static final class PublicKeyCredentialEntry.Builder {
+ ctor public PublicKeyCredentialEntry.Builder(android.content.Context context, CharSequence username, android.app.PendingIntent pendingIntent);
+ method public androidx.credentials.provider.PublicKeyCredentialEntry build();
+ method public androidx.credentials.provider.PublicKeyCredentialEntry.Builder setAutoSelectAllowed(boolean autoSelectAllowed);
+ method public androidx.credentials.provider.PublicKeyCredentialEntry.Builder setDisplayName(CharSequence? displayName);
+ method public androidx.credentials.provider.PublicKeyCredentialEntry.Builder setIcon(android.graphics.drawable.Icon? icon);
+ method public androidx.credentials.provider.PublicKeyCredentialEntry.Builder setLastUsedTime(java.time.Instant? lastUsedTime);
+ }
+
+ public static final class PublicKeyCredentialEntry.CREATOR {
+ }
+
+ @RequiresApi(34) public final class RemoteCreateEntry extends android.service.credentials.CreateEntry {
+ ctor public RemoteCreateEntry(android.app.PendingIntent pendingIntent);
+ method public android.app.PendingIntent getPendingIntent();
+ property public final android.app.PendingIntent pendingIntent;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.RemoteCreateEntry> CREATOR;
+ field public static final androidx.credentials.provider.RemoteCreateEntry.Companion Companion;
+ }
+
+ public static final class RemoteCreateEntry.Companion {
+ }
+
+ @RequiresApi(34) public final class RemoteCredentialEntry extends android.service.credentials.CredentialEntry {
+ ctor public RemoteCredentialEntry(android.app.PendingIntent pendingIntent);
+ method public android.app.PendingIntent getPendingIntent();
+ property public final android.app.PendingIntent pendingIntent;
+ field public static final androidx.credentials.provider.RemoteCredentialEntry.CREATOR CREATOR;
+ field public static final android.os.Parcelable.Creator<androidx.credentials.provider.RemoteCredentialEntry> CREATOR$1;
+ }
+
+ public static final class RemoteCredentialEntry.CREATOR {
+ }
+
+}
+
diff --git a/credentials/credentials/src/androidTest/java/androidx/credentials/CredentialManagerJavaTest.java b/credentials/credentials/src/androidTest/java/androidx/credentials/CredentialManagerJavaTest.java
index 85246a1..794c953 100644
--- a/credentials/credentials/src/androidTest/java/androidx/credentials/CredentialManagerJavaTest.java
+++ b/credentials/credentials/src/androidTest/java/androidx/credentials/CredentialManagerJavaTest.java
@@ -29,8 +29,10 @@
import androidx.credentials.exceptions.ClearCredentialProviderConfigurationException;
import androidx.credentials.exceptions.CreateCredentialException;
import androidx.credentials.exceptions.CreateCredentialProviderConfigurationException;
+import androidx.credentials.exceptions.CreateCredentialUnknownException;
import androidx.credentials.exceptions.GetCredentialException;
import androidx.credentials.exceptions.GetCredentialProviderConfigurationException;
+import androidx.credentials.exceptions.GetCredentialUnknownException;
import androidx.test.core.app.ActivityScenario;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
@@ -86,8 +88,13 @@
});
latch.await(100L, TimeUnit.MILLISECONDS);
- assertThat(loadedResult.get().getClass()).isEqualTo(
- CreateCredentialProviderConfigurationException.class);
+ if (!isPostFrameworkApiLevel()) {
+ assertThat(loadedResult.get().getClass()).isEqualTo(
+ CreateCredentialProviderConfigurationException.class);
+ } else {
+ assertThat(loadedResult.get().getClass()).isEqualTo(
+ CreateCredentialUnknownException.class);
+ }
// TODO("Add manifest tests and possibly further separate these tests by API Level
// - maybe a rule perhaps?")
}
@@ -121,8 +128,13 @@
});
latch.await(100L, TimeUnit.MILLISECONDS);
- assertThat(loadedResult.get().getClass()).isEqualTo(
- GetCredentialProviderConfigurationException.class);
+ if (!isPostFrameworkApiLevel()) {
+ assertThat(loadedResult.get().getClass()).isEqualTo(
+ GetCredentialProviderConfigurationException.class);
+ } else {
+ assertThat(loadedResult.get().getClass()).isEqualTo(
+ GetCredentialUnknownException.class);
+ }
// TODO("Add manifest tests and possibly further separate these tests - maybe a rule
// perhaps?")
}
diff --git a/credentials/credentials/src/androidTest/java/androidx/credentials/CredentialManagerTest.kt b/credentials/credentials/src/androidTest/java/androidx/credentials/CredentialManagerTest.kt
index 162d6df..a27ae72 100644
--- a/credentials/credentials/src/androidTest/java/androidx/credentials/CredentialManagerTest.kt
+++ b/credentials/credentials/src/androidTest/java/androidx/credentials/CredentialManagerTest.kt
@@ -22,8 +22,10 @@
import androidx.credentials.exceptions.ClearCredentialProviderConfigurationException
import androidx.credentials.exceptions.CreateCredentialException
import androidx.credentials.exceptions.CreateCredentialProviderConfigurationException
+import androidx.credentials.exceptions.CreateCredentialUnknownException
import androidx.credentials.exceptions.GetCredentialException
import androidx.credentials.exceptions.GetCredentialProviderConfigurationException
+import androidx.credentials.exceptions.GetCredentialUnknownException
import androidx.test.core.app.ActivityScenario
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
@@ -81,6 +83,10 @@
assertThrows<GetCredentialProviderConfigurationException> {
credentialManager.getCredential(request, Activity())
}
+ } else {
+ assertThrows<GetCredentialUnknownException> {
+ credentialManager.getCredential(request, Activity())
+ }
}
// TODO("Add manifest tests and possibly further separate these tests by API Level
// - maybe a rule perhaps?")
@@ -132,6 +138,10 @@
assertThat(loadedResult.get().javaClass).isEqualTo(
CreateCredentialProviderConfigurationException::class.java
)
+ } else {
+ assertThat(loadedResult.get().javaClass).isEqualTo(
+ CreateCredentialUnknownException::class.java
+ )
}
// TODO("Add manifest tests and possibly further separate these tests by API Level
// - maybe a rule perhaps?")
@@ -167,6 +177,10 @@
assertThat(loadedResult.get().javaClass).isEqualTo(
GetCredentialProviderConfigurationException::class.java
)
+ } else {
+ assertThat(loadedResult.get().javaClass).isEqualTo(
+ GetCredentialUnknownException::class.java
+ )
}
// TODO("Add manifest tests and possibly further separate these tests - maybe a rule
// perhaps?")
diff --git a/credentials/credentials/src/main/java/androidx/credentials/CredentialProviderFactory.kt b/credentials/credentials/src/main/java/androidx/credentials/CredentialProviderFactory.kt
index 6dcd0f2..290a599 100644
--- a/credentials/credentials/src/main/java/androidx/credentials/CredentialProviderFactory.kt
+++ b/credentials/credentials/src/main/java/androidx/credentials/CredentialProviderFactory.kt
@@ -42,11 +42,17 @@
* Post-U, providers will be registered with the framework, and enabled by the user.
*/
fun getBestAvailableProvider(context: Context): CredentialProvider? {
- if (Build.VERSION.SDK_INT <= MAX_CRED_MAN_PRE_FRAMEWORK_API_LEVEL) {
+ if ((Build.VERSION.SDK_INT <= MAX_CRED_MAN_PRE_FRAMEWORK_API_LEVEL) &&
+ !(Build.VERSION.SDK_INT == MAX_CRED_MAN_PRE_FRAMEWORK_API_LEVEL &&
+ Build.VERSION.PREVIEW_SDK_INT > 0)) {
return tryCreatePreUOemProvider(context)
+ } else if ((Build.VERSION.SDK_INT == MAX_CRED_MAN_PRE_FRAMEWORK_API_LEVEL) &&
+ (Build.VERSION.PREVIEW_SDK_INT > 0)) {
+ return CredentialProviderFrameworkImpl(context)
+ } else if (Build.VERSION.SDK_INT > MAX_CRED_MAN_PRE_FRAMEWORK_API_LEVEL) {
+ return CredentialProviderFrameworkImpl(context)
} else {
- // TODO("Implement")
- throw UnsupportedOperationException("Post-U not supported yet")
+ return null
}
}
diff --git a/credentials/credentials/src/main/java/androidx/credentials/CredentialProviderFrameworkImpl.kt b/credentials/credentials/src/main/java/androidx/credentials/CredentialProviderFrameworkImpl.kt
new file mode 100644
index 0000000..67fcc1e
--- /dev/null
+++ b/credentials/credentials/src/main/java/androidx/credentials/CredentialProviderFrameworkImpl.kt
@@ -0,0 +1,162 @@
+/*
+ * 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 androidx.credentials
+
+import android.app.Activity
+import android.content.Context
+import android.credentials.CredentialManager
+import android.os.Bundle
+import android.os.CancellationSignal
+import android.os.OutcomeReceiver
+import android.util.Log
+import androidx.annotation.RequiresApi
+import androidx.credentials.exceptions.ClearCredentialException
+import androidx.credentials.exceptions.CreateCredentialException
+import androidx.credentials.exceptions.CreateCredentialUnknownException
+import androidx.credentials.exceptions.GetCredentialException
+import androidx.credentials.exceptions.GetCredentialUnknownException
+import androidx.credentials.internal.FrameworkImplHelper
+import java.util.concurrent.Executor
+import java.util.concurrent.Executors
+
+/**
+ * Framework credential provider implementation that allows credential
+ * manager requests to be routed to the framework.
+ *
+ * @hide
+ */
+@RequiresApi(34)
+internal class CredentialProviderFrameworkImpl(context: Context) : CredentialProvider {
+ private val credentialManager: CredentialManager =
+ context.getSystemService(Context.CREDENTIAL_SERVICE) as CredentialManager
+
+ override fun onGetCredential(
+ request: GetCredentialRequest,
+ activity: Activity,
+ cancellationSignal: CancellationSignal?,
+ executor: Executor,
+ callback: CredentialManagerCallback<GetCredentialResponse, GetCredentialException>
+ ) {
+ Log.i(TAG, "In CredentialProviderFrameworkImpl onGetCredential")
+
+ val outcome = object : OutcomeReceiver<
+ android.credentials.GetCredentialResponse, android.credentials.GetCredentialException> {
+ override fun onResult(response: android.credentials.GetCredentialResponse) {
+ Log.i(TAG, "GetCredentialResponse returned from framework")
+ callback.onResult(convertGetResponseToJetpackClass(response))
+ }
+
+ override fun onError(error: android.credentials.GetCredentialException) {
+ Log.i(TAG, "GetCredentialResponse error returned from framework")
+ // TODO("Covert to the appropriate exception")
+ callback.onError(GetCredentialUnknownException(error.message))
+ }
+ }
+ credentialManager.getCredential(
+ convertGetRequestToFrameworkClass(request),
+ activity,
+ cancellationSignal,
+ Executors.newSingleThreadExecutor(),
+ outcome
+ )
+ }
+
+ override fun onCreateCredential(
+ request: CreateCredentialRequest,
+ activity: Activity,
+ cancellationSignal: CancellationSignal?,
+ executor: Executor,
+ callback: CredentialManagerCallback<CreateCredentialResponse, CreateCredentialException>
+ ) {
+ Log.i(TAG, "In CredentialProviderFrameworkImpl onCreateCredential")
+
+ val outcome = object : OutcomeReceiver<
+ android.credentials.CreateCredentialResponse,
+ android.credentials.CreateCredentialException> {
+ override fun onResult(response: android.credentials.CreateCredentialResponse) {
+ Log.i(TAG, "Create Result returned from framework: ")
+ callback.onResult(
+ CreateCredentialResponse.createFrom(
+ request.type, response.data
+ )
+ )
+ }
+
+ override fun onError(error: android.credentials.CreateCredentialException) {
+ Log.i(TAG, "CreateCredentialResponse error returned from framework")
+ // TODO("Covert to the appropriate exception")
+ callback.onError(CreateCredentialUnknownException(error.message))
+ }
+ }
+
+ credentialManager.createCredential(
+ android.credentials.CreateCredentialRequest(
+ request.type,
+ FrameworkImplHelper.getFinalCreateCredentialData(request, activity),
+ request.candidateQueryData,
+ request.isSystemProviderRequired
+ ),
+ activity,
+ cancellationSignal,
+ Executors.newSingleThreadExecutor(),
+ outcome
+ )
+ }
+
+ private fun convertGetRequestToFrameworkClass(request: GetCredentialRequest):
+ android.credentials.GetCredentialRequest {
+ val builder = android.credentials.GetCredentialRequest.Builder(Bundle())
+ request.credentialOptions.forEach {
+ builder.addGetCredentialOption(
+ android.credentials.GetCredentialOption(
+ it.type, it.requestData, it.candidateQueryData, it.isSystemProviderRequired
+ )
+ )
+ }
+ return builder.build()
+ }
+
+ internal fun convertGetResponseToJetpackClass(
+ response: android.credentials.GetCredentialResponse
+ ): GetCredentialResponse {
+ val credential = response.credential
+ return GetCredentialResponse(
+ Credential.createFrom(
+ credential.type, credential.data
+ )
+ )
+ }
+
+ override fun isAvailableOnDevice(): Boolean {
+ // TODO("Base it on API level check")
+ return true
+ }
+
+ override fun onClearCredential(
+ request: ClearCredentialStateRequest,
+ cancellationSignal: CancellationSignal?,
+ executor: Executor,
+ callback: CredentialManagerCallback<Void?, ClearCredentialException>
+ ) {
+ // TODO("Not yet implemented")
+ }
+
+ /** @hide */
+ companion object {
+ private const val TAG = "CredManProvService"
+ }
+}
\ No newline at end of file
diff --git a/credentials/credentials/src/main/java/androidx/credentials/provider/Action.kt b/credentials/credentials/src/main/java/androidx/credentials/provider/Action.kt
new file mode 100644
index 0000000..e8732394
--- /dev/null
+++ b/credentials/credentials/src/main/java/androidx/credentials/provider/Action.kt
@@ -0,0 +1,177 @@
+/*
+ * 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 androidx.credentials.provider
+
+import android.annotation.SuppressLint
+import android.app.PendingIntent
+import android.app.slice.Slice
+import android.app.slice.SliceSpec
+import android.net.Uri
+import android.os.Parcel
+import android.os.Parcelable
+import android.util.Log
+import androidx.annotation.NonNull
+import androidx.annotation.RequiresApi
+import androidx.annotation.VisibleForTesting
+import java.util.Collections
+
+/**
+ * An actionable entry that is returned as part of the
+ * [android.service.credentials.BeginGetCredentialResponse], and then shown on the user selector.
+ * When selected, the associated [PendingIntent] is invoked to launch a provider controlled
+ * activity.
+ *
+ * See [android.service.credentials.CredentialsResponseContent] for usage.
+ *
+ * @throws IllegalArgumentException If [title] is empty
+ * @throws NullPointerException If [title] or [pendingIntent] is null
+ */
+@RequiresApi(34)
+class Action internal constructor(
+ val title: CharSequence,
+ val subTitle: CharSequence?,
+ val pendingIntent: PendingIntent,
+ ) : android.service.credentials.Action(
+ toSlice(title, subTitle, pendingIntent)) {
+
+ init {
+ require(title.isNotEmpty()) { "title must not be empty" }
+ }
+
+ override fun describeContents(): Int {
+ return 0
+ }
+
+ override fun writeToParcel(@NonNull dest: Parcel, flags: Int) {
+ super.writeToParcel(dest, flags)
+ }
+
+ /**
+ * A builder for [Action]
+ *
+ * @param title the title of this action entry
+ * @param pendingIntent the [PendingIntent] that will be fired when the user selects
+ * this action entry
+ */
+ class Builder constructor(
+ private val title: CharSequence,
+ private val pendingIntent: PendingIntent
+ ) {
+ private var subTitle: CharSequence? = null
+
+ /** Sets a sub title to be shown on the UI with this entry */
+ fun setSubTitle(subTitle: CharSequence?): Builder {
+ this.subTitle = subTitle
+ return this
+ }
+
+ /**
+ * Builds an instance of [Action]
+ *
+ * @throws IllegalArgumentException If [title] is empty
+ */
+ fun build(): Action {
+ return Action(title, subTitle, pendingIntent)
+ }
+ }
+
+ @Suppress("AcronymName")
+ companion object {
+ private const val TAG = "Action"
+ private const val SLICE_SPEC_REVISION = 0
+ private const val SLICE_SPEC_TYPE = "Action"
+
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_TITLE =
+ "androidx.credentials.provider.action.HINT_ACTION_TITLE"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_SUBTITLE =
+ "androidx.credentials.provider.action.HINT_ACTION_SUBTEXT"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_PENDING_INTENT =
+ "androidx.credentials.provider.action.SLICE_HINT_PENDING_INTENT"
+
+ @JvmStatic
+ internal fun toSlice(
+ title: CharSequence,
+ subTitle: CharSequence?,
+ pendingIntent: PendingIntent
+ ): Slice {
+ val sliceBuilder = Slice.Builder(Uri.EMPTY, SliceSpec(
+ SLICE_SPEC_TYPE, SLICE_SPEC_REVISION))
+ .addText(title, /*subType=*/null,
+ listOf(SLICE_HINT_TITLE))
+ .addText(subTitle, /*subType=*/null,
+ listOf(SLICE_HINT_SUBTITLE))
+ sliceBuilder.addAction(pendingIntent,
+ Slice.Builder(sliceBuilder)
+ .addHints(Collections.singletonList(SLICE_HINT_PENDING_INTENT))
+ .build(),
+ /*subType=*/null)
+ return sliceBuilder.build()
+ }
+
+ /**
+ * Returns an instance of [Action] derived from a [Slice] object.
+ *
+ * @param slice the [Slice] object constructed through [toSlice]
+ *
+ * @hide
+ */
+ @SuppressLint("WrongConstant") // custom conversion between jetpack and framework
+ @JvmStatic
+ fun fromSlice(slice: Slice): Action? {
+ var title: CharSequence = ""
+ var subTitle: CharSequence? = null
+ var pendingIntent: PendingIntent? = null
+
+ slice.items.forEach {
+ if (it.hasHint(SLICE_HINT_TITLE)) {
+ title = it.text
+ } else if (it.hasHint(SLICE_HINT_SUBTITLE)) {
+ subTitle = it.text
+ } else if (it.hasHint(SLICE_HINT_PENDING_INTENT)) {
+ pendingIntent = it.action
+ }
+ }
+
+ return try {
+ Action(title, subTitle, pendingIntent!!)
+ } catch (e: Exception) {
+ Log.i(TAG, "fromSlice failed with: " + e.message)
+ null
+ }
+ }
+
+ @JvmField val CREATOR: Parcelable.Creator<Action> = object :
+ Parcelable.Creator<Action> {
+ /**
+ * This will not be used in any of the credMan flows as Action is constructed
+ * in the jetpack library and sent to the framework. UI app will receive the
+ * slice and use [fromSlice] to get back the object.
+ */
+ override fun createFromParcel(p0: Parcel?): Action? {
+ val action = android.service.credentials.Action.CREATOR.createFromParcel(p0)
+ return fromSlice(action.slice)
+ }
+
+ @Suppress("ArrayReturn")
+ override fun newArray(size: Int): Array<Action?> {
+ return arrayOfNulls<Action>(size)
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/credentials/credentials/src/main/java/androidx/credentials/provider/AuthenticationAction.kt b/credentials/credentials/src/main/java/androidx/credentials/provider/AuthenticationAction.kt
new file mode 100644
index 0000000..9d2682a
--- /dev/null
+++ b/credentials/credentials/src/main/java/androidx/credentials/provider/AuthenticationAction.kt
@@ -0,0 +1,125 @@
+/*
+ * 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 androidx.credentials.provider
+import android.annotation.SuppressLint
+import android.app.PendingIntent
+import android.app.slice.Slice
+import android.app.slice.SliceSpec
+import android.net.Uri
+import android.os.Parcel
+import android.os.Parcelable
+import android.util.Log
+import androidx.annotation.NonNull
+import androidx.annotation.RequiresApi
+import androidx.annotation.VisibleForTesting
+import java.util.Collections
+
+/**
+ * An entry on the selector, denoting that the provider service is locked and authentication
+ * is needed to proceed.
+ *
+ * Providers should set this entry when the provider app is locked, and no credentials can
+ * be returned.
+ * Providers must set the [PendingIntent] that leads to their unlock activity. When the user
+ * selects this entry, the corresponding [PendingIntent] is fired and the unlock activity is
+ * invoked. Once the provider authentication flow is complete, providers must set
+ * the [android.service.credentials.CredentialsResponseContent] containing the unlocked credential
+ * entries, through the [PendingIntentHandler.setCredentialsResponseContent] method, before
+ * finishing the activity.
+ * If providers fail to set the [android.service.credentials.CredentialsResponseContent], the
+ * system will assume that there are no credentials available and the this entry will be removed
+ * from the selector.
+ *
+ * @property pendingIntent the [PendingIntent] to be invoked if the user selects
+ * this authentication entry on the UI
+ *
+ * See [android.service.credentials.BeginGetCredentialResponse.createWithAuthentication]
+ * for usage details.
+ */
+@RequiresApi(34)
+class AuthenticationAction constructor(
+ val pendingIntent: PendingIntent,
+) : android.service.credentials.Action(
+ toSlice(pendingIntent)) {
+
+ override fun describeContents(): Int {
+ return 0
+ }
+
+ override fun writeToParcel(@NonNull dest: Parcel, flags: Int) {
+ super.writeToParcel(dest, flags)
+ }
+ @Suppress("AcronymName")
+ companion object {
+ private const val TAG = "AuthenticationAction"
+ private const val SLICE_SPEC_REVISION = 0
+ private const val SLICE_SPEC_TYPE = "AuthenticationAction"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_PENDING_INTENT =
+ "androidx.credentials.provider.authenticationAction.SLICE_HINT_PENDING_INTENT"
+
+ /** @hide **/
+ @JvmStatic
+ fun toSlice(pendingIntent: PendingIntent): Slice {
+ val sliceBuilder = Slice.Builder(Uri.EMPTY, SliceSpec(SLICE_SPEC_TYPE,
+ SLICE_SPEC_REVISION))
+ sliceBuilder.addAction(pendingIntent,
+ Slice.Builder(sliceBuilder)
+ .addHints(Collections.singletonList(SLICE_HINT_PENDING_INTENT))
+ .build(),
+ /*subType=*/null)
+ return sliceBuilder.build()
+ }
+
+ /**
+ * Returns an instance of [AuthenticationAction] derived from a [Slice] object.
+ *
+ * @param slice the [Slice] object that contains the information required for
+ * constructing an instance of this class.
+ *
+ * @hide
+ */
+ @SuppressLint("WrongConstant") // custom conversion between jetpack and framework
+ @JvmStatic
+ fun fromSlice(slice: Slice): AuthenticationAction? {
+ slice.items.forEach {
+ if (it.hasHint(SLICE_HINT_PENDING_INTENT)) {
+ return try {
+ AuthenticationAction(it.action)
+ } catch (e: Exception) {
+ Log.i(TAG, "fromSlice failed with: " + e.message)
+ null
+ }
+ }
+ }
+ return null
+ }
+
+ @JvmField val CREATOR: Parcelable.Creator<AuthenticationAction> = object :
+ Parcelable.Creator<AuthenticationAction> {
+ override fun createFromParcel(p0: Parcel?): AuthenticationAction? {
+ val authAction =
+ android.service.credentials.Action.CREATOR.createFromParcel(p0)
+ return fromSlice(authAction.slice)
+ }
+
+ @Suppress("ArrayReturn")
+ override fun newArray(size: Int): Array<AuthenticationAction?> {
+ return arrayOfNulls(size)
+ }
+ }
+ }
+}
diff --git a/credentials/credentials/src/main/java/androidx/credentials/provider/BeginCreateCustomCredentialRequest.kt b/credentials/credentials/src/main/java/androidx/credentials/provider/BeginCreateCustomCredentialRequest.kt
new file mode 100644
index 0000000..fd5639c
--- /dev/null
+++ b/credentials/credentials/src/main/java/androidx/credentials/provider/BeginCreateCustomCredentialRequest.kt
@@ -0,0 +1,81 @@
+/*
+ * 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 androidx.credentials.provider
+
+import android.app.PendingIntent
+import android.content.Intent
+import android.os.Bundle
+import android.os.Parcel
+import android.os.Parcelable
+import android.service.credentials.BeginCreateCredentialRequest
+import android.service.credentials.CallingAppInfo
+import androidx.annotation.NonNull
+import androidx.annotation.RequiresApi
+import androidx.credentials.CreateCustomCredentialRequest
+
+/**
+ * Request to begin saving a custom credential, received by the provider with a
+ * CredentialProviderBaseService.onBeginCreateCredentialRequest call.
+ *
+ * This request will not contain all parameters needed to store the credential. Provider must
+ * use the initial parameters to determine if the password can be stored, and return
+ * a list of [CreateEntry], denoting the accounts/groups where the password can be stored.
+ * When user selects one of the returned [CreateEntry], the corresponding [PendingIntent] set on
+ * the [CreateEntry] will be fired. The [Intent] invoked through the [PendingIntent] will contain
+ * the complete [CreateCustomCredentialRequest]. This request will contain all required
+ * parameters to actually store the credential.
+ *
+ * @see BeginCreateCredentialRequest
+ */
+@RequiresApi(34)
+class BeginCreateCustomCredentialRequest internal constructor(
+ type: String,
+ data: Bundle,
+ callingAppInfo: CallingAppInfo
+) : BeginCreateCredentialRequest(
+ callingAppInfo,
+ type,
+ data
+) {
+
+ override fun describeContents(): Int {
+ return 0
+ }
+
+ override fun writeToParcel(@NonNull dest: Parcel, flags: Int) {
+ super.writeToParcel(dest, flags)
+ }
+ @Suppress("AcronymName")
+ companion object {
+ @JvmField val CREATOR: Parcelable.Creator<BeginCreateCustomCredentialRequest> =
+ object : Parcelable.Creator<BeginCreateCustomCredentialRequest> {
+ override fun createFromParcel(p0: Parcel?): BeginCreateCustomCredentialRequest {
+ val baseRequest = BeginCreateCredentialRequest.CREATOR.createFromParcel(p0)
+ return BeginCreateCustomCredentialRequest(
+ baseRequest.type,
+ baseRequest.data,
+ baseRequest.callingAppInfo
+ )
+ }
+
+ @Suppress("ArrayReturn")
+ override fun newArray(size: Int): Array<BeginCreateCustomCredentialRequest?> {
+ return arrayOfNulls(size)
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/credentials/credentials/src/main/java/androidx/credentials/provider/BeginCreatePasswordCredentialRequest.kt b/credentials/credentials/src/main/java/androidx/credentials/provider/BeginCreatePasswordCredentialRequest.kt
new file mode 100644
index 0000000..ff70fdc
--- /dev/null
+++ b/credentials/credentials/src/main/java/androidx/credentials/provider/BeginCreatePasswordCredentialRequest.kt
@@ -0,0 +1,93 @@
+/*
+ * 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 androidx.credentials.provider
+
+import android.app.PendingIntent
+import android.content.Intent
+import android.os.Bundle
+import android.os.Parcel
+import android.os.Parcelable
+import android.service.credentials.BeginCreateCredentialRequest
+import android.service.credentials.CallingAppInfo
+import androidx.annotation.NonNull
+import androidx.annotation.RequiresApi
+import androidx.credentials.CreatePasswordRequest
+import androidx.credentials.CreatePasswordRequest.Companion.toCandidateDataBundle
+import androidx.credentials.PasswordCredential
+import androidx.credentials.internal.FrameworkClassParsingException
+
+/**
+ * Request to begin saving a password credential, received by the provider with a
+ * CredentialProviderBaseService.onBeginCreateCredentialRequest call.
+ *
+ * This request will not contain all parameters needed to store the password. Provider must
+ * use the initial parameters to determine if the password can be stored, and return
+ * a list of [CreateEntry], denoting the accounts/groups where the password can be stored.
+ * When user selects one of the returned [CreateEntry], the corresponding [PendingIntent] set on
+ * the [CreateEntry] will be fired. The [Intent] invoked through the [PendingIntent] will contain the
+ * complete [CreatePasswordRequest]. This request will contain all required parameters to
+ * actually store the password.
+ *
+ * @see BeginCreateCredentialRequest
+ */
+@RequiresApi(34)
+class BeginCreatePasswordCredentialRequest internal constructor(
+ callingAppInfo: CallingAppInfo
+) : BeginCreateCredentialRequest(
+ callingAppInfo,
+ PasswordCredential.TYPE_PASSWORD_CREDENTIAL,
+ toCandidateDataBundle()
+ ) {
+ override fun describeContents(): Int {
+ return 0
+ }
+
+ override fun writeToParcel(@NonNull dest: Parcel, flags: Int) {
+ super.writeToParcel(dest, flags)
+ }
+
+ @Suppress("AcronymName")
+ companion object {
+
+ /** @hide **/
+ @JvmStatic
+ @Suppress("UNUSED_PARAMETER")
+ internal fun createFrom(data: Bundle, callingAppInfo: CallingAppInfo):
+ BeginCreatePasswordCredentialRequest {
+ try {
+ return BeginCreatePasswordCredentialRequest(
+ callingAppInfo
+ )
+ } catch (e: Exception) {
+ throw FrameworkClassParsingException()
+ }
+ }
+
+ @JvmField val CREATOR: Parcelable.Creator<BeginCreatePasswordCredentialRequest> =
+ object : Parcelable.Creator<BeginCreatePasswordCredentialRequest> {
+ override fun createFromParcel(p0: Parcel?): BeginCreatePasswordCredentialRequest {
+ val baseRequest = BeginCreateCredentialRequest.CREATOR.createFromParcel(p0)
+ return createFrom(baseRequest.data, baseRequest.callingAppInfo)
+ }
+
+ @Suppress("ArrayReturn")
+ override fun newArray(size: Int): Array<BeginCreatePasswordCredentialRequest?> {
+ return arrayOfNulls(size)
+ }
+ }
+ }
+}
diff --git a/credentials/credentials/src/main/java/androidx/credentials/provider/BeginCreatePublicKeyCredentialRequest.kt b/credentials/credentials/src/main/java/androidx/credentials/provider/BeginCreatePublicKeyCredentialRequest.kt
new file mode 100644
index 0000000..84bef7a
--- /dev/null
+++ b/credentials/credentials/src/main/java/androidx/credentials/provider/BeginCreatePublicKeyCredentialRequest.kt
@@ -0,0 +1,103 @@
+/*
+ * 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 androidx.credentials.provider
+
+import android.app.PendingIntent
+import android.content.Intent
+import android.os.Bundle
+import android.os.Parcel
+import android.os.Parcelable
+import android.service.credentials.BeginCreateCredentialRequest
+import android.service.credentials.CallingAppInfo
+import androidx.annotation.NonNull
+import androidx.annotation.RequiresApi
+import androidx.credentials.CreatePublicKeyCredentialRequest.Companion.toCandidateDataBundle
+import androidx.credentials.CreatePublicKeyCredentialRequest
+import androidx.credentials.CreatePublicKeyCredentialRequest.Companion.BUNDLE_KEY_REQUEST_JSON
+import androidx.credentials.CreatePublicKeyCredentialRequest.Companion.BUNDLE_KEY_PREFER_IMMEDIATELY_AVAILABLE_CREDENTIALS
+import androidx.credentials.PublicKeyCredential
+import androidx.credentials.internal.FrameworkClassParsingException
+
+/**
+ * Request to begin registering a public key credential.
+ *
+ * This request will not contain all parameters needed to create the public key. Provider must
+ * use the initial parameters to determine if the public key can be registered, and return
+ * a list of [CreateEntry], denoting the accounts/groups where the public key can be registered.
+ * When user selects one of the returned [CreateEntry], the corresponding [PendingIntent] set on
+ * the [CreateEntry] will be fired. The [Intent] invoked through the [PendingIntent] will contain
+ * the complete [CreatePublicKeyCredentialRequest]. This request will contain all required
+ * parameters to actually register a public key.
+ *
+ * @property json the request json to be used for registering the public key credential
+ *
+ * @see BeginCreateCredentialRequest
+ */
+@RequiresApi(34)
+class BeginCreatePublicKeyCredentialRequest internal constructor(
+ val json: String,
+ val preferImmediatelyAvailableCredentials: Boolean,
+ callingAppInfo: CallingAppInfo,
+) : BeginCreateCredentialRequest(
+ callingAppInfo,
+ PublicKeyCredential.TYPE_PUBLIC_KEY_CREDENTIAL,
+ toCandidateDataBundle(json, preferImmediatelyAvailableCredentials)
+) {
+ init {
+ require(json.isNotEmpty()) { "json must not be empty" }
+ }
+
+ override fun describeContents(): Int {
+ return 0
+ }
+
+ override fun writeToParcel(@NonNull dest: Parcel, flags: Int) {
+ super.writeToParcel(dest, flags)
+ }
+
+ @Suppress("AcronymName")
+ companion object {
+
+ /** @hide */
+ @JvmStatic
+ internal fun createFrom(data: Bundle, callingAppInfo: CallingAppInfo):
+ BeginCreatePublicKeyCredentialRequest {
+ try {
+ val requestJson = data.getString(BUNDLE_KEY_REQUEST_JSON)
+ val preferImmediatelyAvailableCredentials =
+ data.getBoolean(BUNDLE_KEY_PREFER_IMMEDIATELY_AVAILABLE_CREDENTIALS)
+ return BeginCreatePublicKeyCredentialRequest(requestJson!!,
+ (preferImmediatelyAvailableCredentials), callingAppInfo)
+ } catch (e: Exception) {
+ throw FrameworkClassParsingException()
+ }
+ }
+
+ @JvmField val CREATOR: Parcelable.Creator<BeginCreatePublicKeyCredentialRequest> = object :
+ Parcelable.Creator<BeginCreatePublicKeyCredentialRequest> {
+ override fun createFromParcel(p0: Parcel?): BeginCreatePublicKeyCredentialRequest {
+ val baseRequest = BeginCreateCredentialRequest.CREATOR.createFromParcel(p0)
+ return createFrom(baseRequest.data, baseRequest.callingAppInfo)
+ }
+
+ @Suppress("ArrayReturn")
+ override fun newArray(size: Int): Array<BeginCreatePublicKeyCredentialRequest?> {
+ return arrayOfNulls(size)
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/credentials/credentials/src/main/java/androidx/credentials/provider/BeginCreatePublicKeyCredentialRequestPrivileged.kt b/credentials/credentials/src/main/java/androidx/credentials/provider/BeginCreatePublicKeyCredentialRequestPrivileged.kt
new file mode 100644
index 0000000..071c561
--- /dev/null
+++ b/credentials/credentials/src/main/java/androidx/credentials/provider/BeginCreatePublicKeyCredentialRequestPrivileged.kt
@@ -0,0 +1,120 @@
+/*
+ * 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 androidx.credentials.provider
+
+import android.app.PendingIntent
+import android.content.Intent
+import android.os.Bundle
+import android.os.Parcel
+import android.os.Parcelable
+import android.service.credentials.BeginCreateCredentialRequest
+import android.service.credentials.CallingAppInfo
+import androidx.annotation.NonNull
+import androidx.annotation.RequiresApi
+import androidx.credentials.CreatePublicKeyCredentialRequestPrivileged
+import androidx.credentials.CreatePublicKeyCredentialRequest.Companion.BUNDLE_KEY_REQUEST_JSON
+import androidx.credentials.CreatePublicKeyCredentialRequestPrivileged.Companion.BUNDLE_KEY_CLIENT_DATA_HASH
+import androidx.credentials.CreatePublicKeyCredentialRequestPrivileged.Companion.BUNDLE_KEY_RELYING_PARTY
+import androidx.credentials.CreatePublicKeyCredentialRequestPrivileged.Companion.toCredentialDataBundle
+import androidx.credentials.PublicKeyCredential
+import androidx.credentials.internal.FrameworkClassParsingException
+
+/**
+ * Request to begin registering a public key credential, coming from a privileged source that
+ * can call on behalf of another relying party.
+ *
+ * This request will not contain all parameters needed to create the public key. Provider must
+ * use the initial parameters to determine if the public key can be registered, and return
+ * a list of [CreateEntry], denoting the accounts/groups where the public key can be registered.
+ * When user selects one of the returned [CreateEntry], the corresponding [PendingIntent] set on
+ * the [CreateEntry] will be fired. The [Intent] invoked through the [PendingIntent] will contain
+ * the complete [CreatePublicKeyCredentialRequestPrivileged]. This request will contain all
+ * required parameters to actually register a public key.
+ *
+ * @property json the request json to be used for registering the public key credential
+ *
+ * @see BeginCreateCredentialRequest
+ */
+@RequiresApi(34)
+class BeginCreatePublicKeyCredentialRequestPrivileged internal constructor(
+ val json: String,
+ val relyingParty: String,
+ val clientDataHash: String,
+ val preferImmediatelyAvailableCredentials: Boolean,
+ callingAppInfo: CallingAppInfo,
+) : BeginCreateCredentialRequest(
+ callingAppInfo,
+ PublicKeyCredential.TYPE_PUBLIC_KEY_CREDENTIAL,
+ toCredentialDataBundle(json, relyingParty, clientDataHash,
+ preferImmediatelyAvailableCredentials)
+) {
+ init {
+ require(json.isNotEmpty()) { "json must not be empty" }
+ }
+
+ override fun describeContents(): Int {
+ return 0
+ }
+
+ override fun writeToParcel(@NonNull dest: Parcel, flags: Int) {
+ super.writeToParcel(dest, flags)
+ }
+
+ @Suppress("AcronymName")
+ companion object {
+
+ /** @hide */
+ @JvmStatic
+ internal fun createFrom(data: Bundle, callingAppInfo: CallingAppInfo):
+ BeginCreatePublicKeyCredentialRequestPrivileged {
+ try {
+ val requestJson = data.getString(CreatePublicKeyCredentialRequestPrivileged
+ .BUNDLE_KEY_REQUEST_JSON)
+ val rp = data.getString(BUNDLE_KEY_RELYING_PARTY)
+ val clientDataHash = data.getString(BUNDLE_KEY_CLIENT_DATA_HASH)
+ val preferImmediatelyAvailableCredentials =
+ data.getBoolean(CreatePublicKeyCredentialRequestPrivileged
+ .BUNDLE_KEY_PREFER_IMMEDIATELY_AVAILABLE_CREDENTIALS)
+ return BeginCreatePublicKeyCredentialRequestPrivileged(
+ requestJson!!,
+ rp!!,
+ clientDataHash!!,
+ (preferImmediatelyAvailableCredentials),
+ callingAppInfo
+ )
+ } catch (e: Exception) {
+ throw FrameworkClassParsingException()
+ }
+ }
+
+ @JvmField val CREATOR:
+ Parcelable.Creator<BeginCreatePublicKeyCredentialRequestPrivileged> = object :
+ Parcelable.Creator<BeginCreatePublicKeyCredentialRequestPrivileged> {
+ override fun createFromParcel(p0: Parcel?):
+ BeginCreatePublicKeyCredentialRequestPrivileged {
+ val baseRequest = BeginCreateCredentialRequest.CREATOR.createFromParcel(p0)
+ return createFrom(baseRequest.data, baseRequest.callingAppInfo)
+ }
+
+ @Suppress("ArrayReturn")
+ override fun newArray(size: Int):
+ Array<BeginCreatePublicKeyCredentialRequestPrivileged?> {
+ return arrayOfNulls(size)
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/credentials/credentials/src/main/java/androidx/credentials/provider/BeginGetPasswordOption.kt b/credentials/credentials/src/main/java/androidx/credentials/provider/BeginGetPasswordOption.kt
new file mode 100644
index 0000000..408b4bf
--- /dev/null
+++ b/credentials/credentials/src/main/java/androidx/credentials/provider/BeginGetPasswordOption.kt
@@ -0,0 +1,73 @@
+/*
+ * 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 androidx.credentials.provider
+
+import android.os.Bundle
+import android.os.Parcel
+import android.os.Parcelable
+import android.service.credentials.BeginGetCredentialOption
+import androidx.annotation.RequiresApi
+import android.service.credentials.BeginGetCredentialResponse
+import androidx.annotation.NonNull
+import androidx.credentials.PasswordCredential
+
+/**
+ * A request to a password provider to begin the flow of retrieving the user's saved application
+ * passwords.
+ *
+ * Providers must use the parameters in this option to retrieve the corresponding credentials,
+ * and then return them in the form of a list of [PasswordCredentialEntry]
+ * set on the [BeginGetCredentialResponse.createWithResponseContent].
+ */
+@RequiresApi(34)
+class BeginGetPasswordOption internal constructor(
+ candidateQueryData: Bundle
+) : BeginGetCredentialOption(
+ PasswordCredential.TYPE_PASSWORD_CREDENTIAL,
+ candidateQueryData
+) {
+
+ override fun describeContents(): Int {
+ return 0
+ }
+
+ override fun writeToParcel(@NonNull dest: Parcel, flags: Int) {
+ super.writeToParcel(dest, flags)
+ }
+
+ @Suppress("AcronymName")
+ companion object {
+ /** @hide */
+ @JvmStatic
+ internal fun createFrom(data: Bundle): BeginGetPasswordOption {
+ return BeginGetPasswordOption(data)
+ }
+
+ @JvmField val CREATOR: Parcelable.Creator<BeginGetPasswordOption> = object :
+ Parcelable.Creator<BeginGetPasswordOption> {
+ override fun createFromParcel(p0: Parcel?): BeginGetPasswordOption {
+ val baseOption = BeginGetCredentialOption.CREATOR.createFromParcel(p0)
+ return createFrom(baseOption.candidateQueryData)
+ }
+
+ @Suppress("ArrayReturn")
+ override fun newArray(size: Int): Array<BeginGetPasswordOption?> {
+ return arrayOfNulls(size)
+ }
+ }
+ }
+}
diff --git a/credentials/credentials/src/main/java/androidx/credentials/provider/BeginGetPublicKeyCredentialOption.kt b/credentials/credentials/src/main/java/androidx/credentials/provider/BeginGetPublicKeyCredentialOption.kt
new file mode 100644
index 0000000..3c0edbb
--- /dev/null
+++ b/credentials/credentials/src/main/java/androidx/credentials/provider/BeginGetPublicKeyCredentialOption.kt
@@ -0,0 +1,96 @@
+/*
+ * 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 androidx.credentials.provider
+
+import android.os.Bundle
+import android.os.Parcel
+import android.os.Parcelable
+import android.service.credentials.BeginGetCredentialOption
+import androidx.annotation.NonNull
+import androidx.annotation.RequiresApi
+import androidx.credentials.GetPublicKeyCredentialOption
+import androidx.credentials.PublicKeyCredential
+import androidx.credentials.internal.FrameworkClassParsingException
+
+/**
+ * A request to begin the flow of getting passkeys from the user's public key credential provider.
+ *
+ * @property requestJson the privileged request in JSON format in the standard webauthn web json
+ * shown [here](https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptionsjson)
+ * @property preferImmediatelyAvailableCredentials true if it is preferred to return
+ * immediately when there is no available credential instead of falling back to discovering remote
+ * credentials, and false (default) otherwise
+ * [see](https://w3c.github.io/webauthn/#dom-authenticatortransport-hybrid)
+ * @throws NullPointerException If [requestJson] is null
+ * @throws IllegalArgumentException If [requestJson] is empty
+ */
+@RequiresApi(34)
+class BeginGetPublicKeyCredentialOption @JvmOverloads internal constructor(
+ candidateQueryData: Bundle,
+ val requestJson: String,
+ @get:JvmName("preferImmediatelyAvailableCredentials")
+ val preferImmediatelyAvailableCredentials: Boolean = true,
+) : BeginGetCredentialOption(
+ PublicKeyCredential.TYPE_PUBLIC_KEY_CREDENTIAL,
+ candidateQueryData
+) {
+ init {
+ require(requestJson.isNotEmpty()) { "requestJson must not be empty" }
+ }
+
+ override fun describeContents(): Int {
+ return 0
+ }
+
+ override fun writeToParcel(@NonNull dest: Parcel, flags: Int) {
+ super.writeToParcel(dest, flags)
+ }
+
+ @Suppress("AcronymName")
+ companion object {
+ /** @hide */
+ @Suppress("deprecation") // bundle.get() used for boolean value to prevent default
+ // boolean value from being returned.
+ @JvmStatic
+ internal fun createFrom(data: Bundle): BeginGetPublicKeyCredentialOption {
+ try {
+ val requestJson = data.getString(
+ GetPublicKeyCredentialOption.BUNDLE_KEY_REQUEST_JSON)
+ val allowHybrid = data.get(
+ GetPublicKeyCredentialOption
+ .BUNDLE_KEY_PREFER_IMMEDIATELY_AVAILABLE_CREDENTIALS)
+ return BeginGetPublicKeyCredentialOption(data, requestJson!!, (allowHybrid!!)
+ as Boolean)
+ } catch (e: Exception) {
+ throw FrameworkClassParsingException()
+ }
+ }
+
+ @JvmField val CREATOR: Parcelable.Creator<BeginGetPublicKeyCredentialOption> = object :
+ Parcelable.Creator<BeginGetPublicKeyCredentialOption> {
+ override fun createFromParcel(p0: Parcel?): BeginGetPublicKeyCredentialOption {
+ val baseOption = BeginGetCredentialOption.CREATOR.createFromParcel(p0)
+ return createFrom(baseOption.candidateQueryData)
+ }
+
+ @Suppress("ArrayReturn")
+ override fun newArray(size: Int): Array<BeginGetPublicKeyCredentialOption?> {
+ return arrayOfNulls(size)
+ }
+ }
+ }
+}
diff --git a/credentials/credentials/src/main/java/androidx/credentials/provider/BeginGetPublicKeyCredentialOptionPrivileged.kt b/credentials/credentials/src/main/java/androidx/credentials/provider/BeginGetPublicKeyCredentialOptionPrivileged.kt
new file mode 100644
index 0000000..033d156
--- /dev/null
+++ b/credentials/credentials/src/main/java/androidx/credentials/provider/BeginGetPublicKeyCredentialOptionPrivileged.kt
@@ -0,0 +1,120 @@
+/*
+ * 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 androidx.credentials.provider
+
+import android.os.Bundle
+import android.os.Parcel
+import android.os.Parcelable
+import android.service.credentials.BeginGetCredentialOption
+import androidx.annotation.NonNull
+import androidx.annotation.RequiresApi
+import androidx.credentials.GetPublicKeyCredentialOptionPrivileged
+import androidx.credentials.PublicKeyCredential
+import androidx.credentials.internal.FrameworkClassParsingException
+
+/**
+ * A privileged request to get passkeys from the user's public key credential provider. The caller
+ * can modify the RP. Only callers with privileged permission (e.g. user's public browser or caBLE)
+ * can use this. These permissions will be introduced in an upcoming release.
+ * TODO("Add specific permission info/annotation")
+ *
+ * @property requestJson the privileged request in JSON format in the standard webauthn web json
+ * shown [here](https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptionsjson).
+ * @property preferImmediatelyAvailableCredentials true if it is preferred to return
+ * immediately when there is no available credential instead of falling back to discovering remote
+ * credentials, and false (default) otherwise
+ * [here](https://w3c.github.io/webauthn/#dom-authenticatortransport-hybrid)
+ * @property relyingParty the expected true RP ID which will override the one in the [requestJson],
+ * where relyingParty is defined [here](https://w3c.github.io/webauthn/#rp-id) in more detail
+ * @property clientDataHash a hash that is used to verify the [relyingParty] Identity
+ * @throws NullPointerException If any of [requestJson], [relyingParty], or [clientDataHash]
+ * is null
+ * @throws IllegalArgumentException If any of [requestJson], [relyingParty], or [clientDataHash]
+ * is empty
+ */
+@RequiresApi(34)
+class BeginGetPublicKeyCredentialOptionPrivileged @JvmOverloads internal constructor(
+ candidateQueryData: Bundle,
+ val requestJson: String,
+ val relyingParty: String,
+ val clientDataHash: String,
+ @get:JvmName("preferImmediatelyAvailableCredentials")
+ val preferImmediatelyAvailableCredentials: Boolean = true
+) : BeginGetCredentialOption(
+ PublicKeyCredential.TYPE_PUBLIC_KEY_CREDENTIAL,
+ candidateQueryData
+) {
+
+ init {
+ require(requestJson.isNotEmpty()) { "requestJson must not be empty" }
+ require(relyingParty.isNotEmpty()) { "rp must not be empty" }
+ require(clientDataHash.isNotEmpty()) { "clientDataHash must not be empty" }
+ }
+
+ override fun describeContents(): Int {
+ return 0
+ }
+
+ override fun writeToParcel(@NonNull dest: Parcel, flags: Int) {
+ super.writeToParcel(dest, flags)
+ }
+
+ @Suppress("AcronymName")
+ companion object {
+
+ /** @hide */
+ @Suppress("deprecation") // bundle.get() used for boolean value to prevent default
+ // boolean value from being returned.
+ @JvmStatic
+ internal fun createFrom(data: Bundle): BeginGetPublicKeyCredentialOptionPrivileged {
+ try {
+ val requestJson = data.getString(
+ GetPublicKeyCredentialOptionPrivileged.BUNDLE_KEY_REQUEST_JSON)
+ val rp = data.getString(
+ GetPublicKeyCredentialOptionPrivileged.BUNDLE_KEY_RELYING_PARTY)
+ val clientDataHash = data.getString(
+ GetPublicKeyCredentialOptionPrivileged.BUNDLE_KEY_CLIENT_DATA_HASH)
+ val allowHybrid = data.get(
+ GetPublicKeyCredentialOptionPrivileged
+ .BUNDLE_KEY_PREFER_IMMEDIATELY_AVAILABLE_CREDENTIALS)
+ return BeginGetPublicKeyCredentialOptionPrivileged(
+ data,
+ requestJson!!,
+ rp!!,
+ clientDataHash!!,
+ (allowHybrid!!) as Boolean,
+ )
+ } catch (e: Exception) {
+ throw FrameworkClassParsingException()
+ }
+ }
+
+ @JvmField val CREATOR: Parcelable.Creator<BeginGetPublicKeyCredentialOptionPrivileged> =
+ object : Parcelable.Creator<BeginGetPublicKeyCredentialOptionPrivileged> {
+ override fun createFromParcel(p0: Parcel?):
+ BeginGetPublicKeyCredentialOptionPrivileged {
+ val baseOption = BeginGetCredentialOption.CREATOR.createFromParcel(p0)
+ return createFrom(baseOption.candidateQueryData)
+ }
+
+ @Suppress("ArrayReturn")
+ override fun newArray(size: Int): Array<BeginGetPublicKeyCredentialOptionPrivileged?> {
+ return arrayOfNulls(size)
+ }
+ }
+ }
+}
diff --git a/credentials/credentials/src/main/java/androidx/credentials/provider/CreateEntry.kt b/credentials/credentials/src/main/java/androidx/credentials/provider/CreateEntry.kt
new file mode 100644
index 0000000..c33a252
--- /dev/null
+++ b/credentials/credentials/src/main/java/androidx/credentials/provider/CreateEntry.kt
@@ -0,0 +1,371 @@
+/*
+ * 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 androidx.credentials.provider
+
+import android.annotation.SuppressLint
+import android.app.PendingIntent
+import android.app.slice.Slice
+import android.app.slice.SliceSpec
+import android.graphics.drawable.Icon
+import android.net.Uri
+import android.os.Bundle
+import android.os.Parcel
+import android.os.Parcelable
+import android.util.Log
+import androidx.annotation.NonNull
+import androidx.annotation.RequiresApi
+import androidx.annotation.VisibleForTesting
+import androidx.credentials.CredentialManager
+import androidx.credentials.PasswordCredential
+import androidx.credentials.PublicKeyCredential
+import java.time.Instant
+import java.util.Collections
+
+/**
+ * An entry to be shown on the selector during a create flow initiated when an app calls
+ * [CredentialManager.createCredential]
+ *
+ * A [CreateEntry] points to a location such as an account, or a group where the credential can be
+ * registered. When user selects this entry, the corresponding [PendingIntent] is fired, and the
+ * credential creation can be completed.
+ *
+ * @throws IllegalArgumentException If [accountName] is empty
+ */
+@RequiresApi(34)
+class CreateEntry internal constructor(
+ val accountName: CharSequence,
+ val pendingIntent: PendingIntent,
+ val icon: Icon?,
+ val description: CharSequence?,
+ val lastUsedTime: Instant?,
+ private val credentialCountInformationMap: Map<String, Int>
+ ) : android.service.credentials.CreateEntry(
+ toSlice(
+ accountName,
+ icon,
+ description,
+ lastUsedTime,
+ credentialCountInformationMap,
+ pendingIntent)
+) {
+
+ init {
+ require(accountName.isNotEmpty()) { "accountName must not be empty" }
+ }
+
+ /** Returns the no. of password type credentials that the provider with this entry has. */
+ @Suppress("AutoBoxing")
+ fun getPasswordCredentialCount(): Int? {
+ return credentialCountInformationMap[PasswordCredential.TYPE_PASSWORD_CREDENTIAL]
+ }
+
+ /** Returns the no. of public key type credentials that the provider with this entry has. */
+ @Suppress("AutoBoxing")
+ fun getPublicKeyCredentialCount(): Int? {
+ return credentialCountInformationMap[PasswordCredential.TYPE_PASSWORD_CREDENTIAL]
+ }
+
+ /** Returns the no. of total credentials that the provider with this entry has.
+ *
+ * This total count is not necessarily equal to the sum of [getPasswordCredentialCount]
+ * and [getPublicKeyCredentialCount].
+ *
+ */
+ @Suppress("AutoBoxing")
+ fun getTotalCredentialCount(): Int? {
+ return credentialCountInformationMap[TYPE_TOTAL_CREDENTIAL]
+ }
+
+ override fun describeContents(): Int {
+ return 0
+ }
+
+ override fun writeToParcel(@NonNull dest: Parcel, flags: Int) {
+ super.writeToParcel(dest, flags)
+ }
+
+ /**
+ * A builder for [CreateEntry]
+ *
+ * @param accountName the name of the account where the credential will be registered
+ * @param pendingIntent the [PendingIntent] that will be fired when the user selects
+ * this entry
+ */
+ class Builder constructor(
+ private val accountName: CharSequence,
+ private val pendingIntent: PendingIntent
+ ) {
+
+ private var credentialCountInformationMap: MutableMap<String, Int> =
+ mutableMapOf()
+ private var icon: Icon? = null
+ private var description: CharSequence? = null
+ private var lastUsedTime: Instant? = null
+
+ /** Sets the password credential count, denoting how many credentials of type
+ * [PasswordCredential.TYPE_PASSWORD_CREDENTIAL] does the provider have stored.
+ *
+ * This information will be displayed on the [CreateEntry] to help the user
+ * make a choice.
+ */
+ fun setPasswordCredentialCount(count: Int): Builder {
+ credentialCountInformationMap[PasswordCredential.TYPE_PASSWORD_CREDENTIAL] = count
+ return this
+ }
+
+ /** Sets the password credential count, denoting how many credentials of type
+ * [PublicKeyCredential.TYPE_PUBLIC_KEY_CREDENTIAL] does the provider have stored.
+ *
+ * This information will be displayed on the [CreateEntry] to help the user
+ * make a choice.
+ */
+ fun setPublicKeyCredentialCount(count: Int): Builder {
+ credentialCountInformationMap[PublicKeyCredential.TYPE_PUBLIC_KEY_CREDENTIAL] = count
+ return this
+ }
+
+ /** Sets the total credential count, denoting how many credentials in total
+ * does the provider have stored.
+ *
+ * This total count no. does not need to be a total of the counts set through
+ * [setPasswordCredentialCount] and [setPublicKeyCredentialCount].
+ *
+ * This information will be displayed on the [CreateEntry] to help the user
+ * make a choice.
+ */
+ fun setTotalCredentialCount(count: Int): Builder {
+ credentialCountInformationMap[TYPE_TOTAL_CREDENTIAL] = count
+ return this
+ }
+
+ /** Sets an icon to be displayed with the entry on the UI */
+ fun setIcon(icon: Icon?): Builder {
+ this.icon = icon
+ return this
+ }
+
+ /**
+ * Sets a description to be displayed on the UI at the time of credential creation.
+ *
+ * Typically this description should contain information informing the user of the
+ * credential being created, and where it is being stored. Providers are free
+ * to phrase this however they see fit.
+ *
+ * This description must be no more than 150 characters long. Any characters beyond
+ * that limit will be trimmed off.
+ */
+ fun setDescription(description: CharSequence?): Builder {
+ this.description = description
+ return this
+ }
+
+ /** Sets the last time this account was used */
+ fun setLastUsedTime(lastUsedTime: Instant?): Builder {
+ this.lastUsedTime = lastUsedTime
+ return this
+ }
+
+ /**
+ * Builds an instance of [CreateEntry]
+ *
+ * @throws IllegalArgumentException If [accountName] is empty
+ */
+ fun build(): CreateEntry {
+ return CreateEntry(
+ accountName, pendingIntent, icon, description, lastUsedTime,
+ credentialCountInformationMap
+ )
+ }
+ }
+
+ @Suppress("AcronymName")
+ companion object {
+ private const val TAG = "CreateEntry"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val TYPE_TOTAL_CREDENTIAL = "TOTAL_CREDENTIAL_COUNT_TYPE"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_ACCOUNT_NAME =
+ "androidx.credentials.provider.createEntry.SLICE_HINT_USER_PROVIDER_ACCOUNT_NAME"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_NOTE =
+ "androidx.credentials.provider.createEntry.SLICE_HINT_NOTE"
+
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_ICON =
+ "androidx.credentials.provider.createEntry.SLICE_HINT_PROFILE_ICON"
+
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_CREDENTIAL_COUNT_INFORMATION =
+ "androidx.credentials.provider.createEntry.SLICE_HINT_CREDENTIAL_COUNT_INFORMATION"
+
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_LAST_USED_TIME_MILLIS =
+ "androidx.credentials.provider.createEntry.SLICE_HINT_LAST_USED_TIME_MILLIS"
+
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_PENDING_INTENT =
+ "androidx.credentials.provider.createEntry.SLICE_HINT_PENDING_INTENT"
+
+ /** @hide **/
+ @JvmStatic
+ fun toSlice(
+ accountName: CharSequence,
+ icon: Icon?,
+ description: CharSequence?,
+ lastUsedTime: Instant?,
+ credentialCountInformationMap: Map<String, Int>,
+ pendingIntent: PendingIntent
+ ): Slice {
+ // TODO("Use the right type and revision")
+ val sliceBuilder = Slice.Builder(Uri.EMPTY, SliceSpec("type", 1))
+ sliceBuilder.addText(
+ accountName, /*subType=*/null,
+ listOf(SLICE_HINT_ACCOUNT_NAME)
+ )
+
+ if (lastUsedTime != null) {
+ sliceBuilder.addLong(
+ lastUsedTime.toEpochMilli(),
+ /*subType=*/null,
+ listOf(SLICE_HINT_LAST_USED_TIME_MILLIS)
+ )
+ }
+
+ if (description != null) {
+ sliceBuilder.addText(description, null,
+ listOf(SLICE_HINT_NOTE))
+ }
+
+ if (icon != null) {
+ sliceBuilder.addIcon(
+ icon, /*subType=*/null,
+ listOf(SLICE_HINT_ICON)
+ )
+ }
+ val credentialCountBundle = convertCredentialCountInfoToBundle(
+ credentialCountInformationMap
+ )
+ if (credentialCountBundle != null) {
+ sliceBuilder.addBundle(
+ convertCredentialCountInfoToBundle(
+ credentialCountInformationMap
+ ), null, listOf(
+ SLICE_HINT_CREDENTIAL_COUNT_INFORMATION
+ )
+ )
+ }
+ sliceBuilder.addAction(
+ pendingIntent,
+ Slice.Builder(sliceBuilder)
+ .addHints(Collections.singletonList(SLICE_HINT_PENDING_INTENT))
+ .build(),
+ /*subType=*/null
+ )
+ return sliceBuilder.build()
+ }
+
+ /**
+ * Returns an instance of [CreateEntry] derived from a [Slice] object.
+ *
+ * @param slice the [Slice] object constructed through [toSlice]
+ *
+ * @hide
+ */
+ @SuppressLint("WrongConstant") // custom conversion between jetpack and framework
+ @JvmStatic
+ fun fromSlice(slice: Slice): CreateEntry? {
+ // TODO("Put the right spec and version value")
+ var accountName: CharSequence = ""
+ var icon: Icon? = null
+ var pendingIntent: PendingIntent? = null
+ var credentialCountInfo: Map<String, Int> = mapOf()
+ var description: CharSequence? = null
+ var lastUsedTime: Instant? = null
+ slice.items.forEach {
+ if (it.hasHint(SLICE_HINT_ACCOUNT_NAME)) {
+ accountName = it.text
+ } else if (it.hasHint(SLICE_HINT_ICON)) {
+ icon = it.icon
+ } else if (it.hasHint(SLICE_HINT_PENDING_INTENT)) {
+ pendingIntent = it.action
+ } else if (it.hasHint(SLICE_HINT_CREDENTIAL_COUNT_INFORMATION)) {
+ credentialCountInfo = convertBundleToCredentialCountInfo(it.bundle)
+ } else if (it.hasHint(SLICE_HINT_LAST_USED_TIME_MILLIS)) {
+ lastUsedTime = Instant.ofEpochMilli(it.long)
+ } else if (it.hasHint(SLICE_HINT_NOTE)) {
+ description = it.text
+ }
+ }
+ return try {
+ CreateEntry(
+
+ accountName, pendingIntent!!, icon, description,
+ lastUsedTime, credentialCountInfo
+ )
+ } catch (e: Exception) {
+ Log.i(TAG, "fromSlice failed with: " + e.message)
+ null
+ }
+ }
+
+ /** @hide **/
+ @JvmStatic
+ internal fun convertBundleToCredentialCountInfo(bundle: Bundle?):
+ Map<String, Int> {
+ val credentialCountMap = HashMap<String, Int>()
+ if (bundle == null) {
+ return credentialCountMap
+ }
+ bundle.keySet().forEach {
+ try {
+ credentialCountMap[it] = bundle.getInt(it)
+ } catch (e: Exception) {
+ Log.i(TAG, "Issue unpacking credential count info bundle: " + e.message)
+ }
+ }
+ return credentialCountMap
+ }
+
+ /** @hide **/
+ @JvmStatic
+ internal fun convertCredentialCountInfoToBundle(
+ credentialCountInformationMap: Map<String, Int>
+ ): Bundle? {
+ if (credentialCountInformationMap.isEmpty()) {
+ return null
+ }
+ val bundle = Bundle()
+ credentialCountInformationMap.forEach {
+ bundle.putInt(it.key, it.value)
+ }
+ return bundle
+ }
+
+ @JvmField val CREATOR: Parcelable.Creator<CreateEntry> =
+ object : Parcelable.Creator<CreateEntry> {
+ override fun createFromParcel(p0: Parcel?): CreateEntry? {
+ val createEntry = android.service.credentials.CreateEntry
+ .CREATOR.createFromParcel(p0)
+ return fromSlice(createEntry.slice)
+ }
+
+ @Suppress("ArrayReturn")
+ override fun newArray(size: Int): Array<CreateEntry?> {
+ return arrayOfNulls(size)
+ }
+ }
+ }
+ }
diff --git a/credentials/credentials/src/main/java/androidx/credentials/provider/CredentialProviderService.kt b/credentials/credentials/src/main/java/androidx/credentials/provider/CredentialProviderService.kt
new file mode 100644
index 0000000..f96af9f
--- /dev/null
+++ b/credentials/credentials/src/main/java/androidx/credentials/provider/CredentialProviderService.kt
@@ -0,0 +1,145 @@
+/*
+ * 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 androidx.credentials.provider
+
+import android.credentials.GetCredentialException
+import android.os.CancellationSignal
+import android.os.OutcomeReceiver
+import android.service.credentials.BeginCreateCredentialRequest
+import android.service.credentials.BeginCreateCredentialResponse
+import android.service.credentials.BeginGetCredentialRequest
+import android.service.credentials.BeginGetCredentialResponse
+import android.service.credentials.CredentialProviderService
+import android.util.Log
+import androidx.annotation.RequiresApi
+import androidx.credentials.exceptions.CreateCredentialException
+import androidx.credentials.provider.utils.BeginCreateCredentialUtil
+import androidx.credentials.provider.utils.BeginGetCredentialUtil
+
+/**
+ * Main service to be extended by provider services.
+ *
+ * Services that extend this class will be bound to by the framework, and receive
+ * [androidx.credentials.CredentialManager] credential retrieval and creation API calls.
+ */
+@RequiresApi(34)
+abstract class CredentialProviderService : CredentialProviderService() {
+
+ /** @hide **/
+ final override fun onBeginGetCredential(
+ request: BeginGetCredentialRequest,
+ cancellationSignal: CancellationSignal,
+ callback: OutcomeReceiver<BeginGetCredentialResponse, GetCredentialException>
+ ) {
+ val structuredRequest = BeginGetCredentialUtil.convertToStructuredRequest(request)
+ val outcome = object : OutcomeReceiver<BeginGetCredentialResponse,
+ androidx.credentials.exceptions.GetCredentialException> {
+ override fun onResult(response: BeginGetCredentialResponse?) {
+ Log.i(TAG, "onGetCredentials response returned from provider " +
+ "to jetpack library")
+ callback.onResult(response)
+ }
+
+ override fun onError(error: androidx.credentials.exceptions.GetCredentialException) {
+ super.onError(error)
+ Log.i(TAG, "onGetCredentials error returned from provider " +
+ "to jetpack library")
+ // TODO("Change error code to provider error when ready on framework")
+ callback.onError(GetCredentialException(error.type, error.message))
+ }
+ }
+ this.onBeginGetCredentialRequest(structuredRequest, cancellationSignal, outcome)
+ }
+
+ /** @hide **/
+ final override fun onBeginCreateCredential(
+ request: BeginCreateCredentialRequest,
+ cancellationSignal: CancellationSignal,
+ callback: OutcomeReceiver<BeginCreateCredentialResponse,
+ android.credentials.CreateCredentialException>
+ ) {
+ val outcome = object : OutcomeReceiver<
+ BeginCreateCredentialResponse, CreateCredentialException> {
+ override fun onResult(response: BeginCreateCredentialResponse?) {
+ Log.i(
+ TAG, "onCreateCredential result returned from provider to jetpack " +
+ "library with credential entries size: " + response?.createEntries?.size)
+ callback.onResult(response)
+ }
+ override fun onError(error: CreateCredentialException) {
+ Log.i(
+ TAG, "onCreateCredential result returned from provider to jetpack")
+ super.onError(error)
+ // TODO("Change error code to provider error when ready on framework")
+ callback.onError(android.credentials.CreateCredentialException(
+ error.type, error.message))
+ }
+ }
+ onBeginCreateCredentialRequest(
+ BeginCreateCredentialUtil.convertToStructuredRequest(request),
+ cancellationSignal, outcome)
+ }
+
+ /**
+ * Called by the Credential Manager Jetpack library to get credentials stored with a provider
+ * service. Provider services must extend this in order to handle a
+ * [ProviderGetCredentialRequest] request.
+ *
+ * Provider service must call one of the [callback] methods to notify the result of the
+ * request.
+ *
+ * @param [request] the [ProviderGetCredentialRequest] to handle
+ * See [BeginGetCredentialResponse] for the response to be returned
+ * @param cancellationSignal signal for observing cancellation requests. The system will
+ * use this to notify you that the result is no longer needed and you should stop
+ * handling it in order to save your resources
+ * @param callback the callback object to be used to notify the response or error
+ */
+ abstract fun onBeginGetCredentialRequest(
+ request: BeginGetCredentialRequest,
+ cancellationSignal: CancellationSignal,
+ callback: OutcomeReceiver<BeginGetCredentialResponse,
+ androidx.credentials.exceptions.GetCredentialException>
+ )
+
+ /**
+ * Called by the Credential Manager Jetpack library to begin a credential registration flow
+ * with a credential provider service. Provider services must extend this in order to handle a
+ * [BeginCreateCredentialRequest] request.
+ *
+ * Provider service must call one of the [callback] methods to notify the result of the
+ * request.
+ *
+ * @param [request] the [BeginCreateCredentialRequest] to handle
+ * See [BeginCreateCredentialResponse] for the response to be returned
+ * @param cancellationSignal signal for observing cancellation requests. The system will
+ * use this to notify you that the result is no longer needed and you should stop
+ * handling it in order to save your resources
+ * @param callback the callback object to be used to notify the response or error
+ */
+ abstract fun onBeginCreateCredentialRequest(
+ request: BeginCreateCredentialRequest,
+ cancellationSignal: CancellationSignal,
+ callback: OutcomeReceiver<BeginCreateCredentialResponse,
+ CreateCredentialException>
+ )
+
+ /** @hide **/
+ companion object {
+ private const val TAG = "BaseService"
+ }
+}
diff --git a/credentials/credentials/src/main/java/androidx/credentials/provider/CustomCredentialEntry.kt b/credentials/credentials/src/main/java/androidx/credentials/provider/CustomCredentialEntry.kt
new file mode 100644
index 0000000..cbecca7
--- /dev/null
+++ b/credentials/credentials/src/main/java/androidx/credentials/provider/CustomCredentialEntry.kt
@@ -0,0 +1,226 @@
+/*
+ * 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 androidx.credentials.provider
+
+import android.annotation.SuppressLint
+import android.app.PendingIntent
+import android.app.slice.Slice
+import android.app.slice.SliceSpec
+import android.graphics.drawable.Icon
+import android.net.Uri
+import android.os.Parcel
+import android.os.Parcelable
+import android.util.Log
+import androidx.annotation.NonNull
+import androidx.annotation.RequiresApi
+import androidx.annotation.VisibleForTesting
+import java.time.Instant
+import java.util.Collections
+
+/**
+ * Base class for a generic credential entry that is displayed on the account selector UI.
+ * Each entry corresponds to an account that can provide a credential.
+ *
+ * @property title the title shown with this entry on the selector UI
+ * @property subTitle the subTitle shown with this entry on the selector UI
+ * @property lastUsedTime the last used time the credential underlying this entry was
+ * used by the user
+ * @property icon the icon to be displayed with this entry on the selector UI
+ * @property pendingIntent the [PendingIntent] to be invoked when this entry
+ * is selected by the user
+ * @property typeDisplayName the friendly name to be displayed on the UI for
+ * the type of the credential
+ * @property isAutoSelectAllowed whether this entry is allowed to be auto
+ * selected if it is the only one on the UI. Note that setting this value
+ * to true does not guarantee this behavior. The developer must also set this
+ * to true, and the framework must determine that only one entry is present.
+ */
+@RequiresApi(34)
+class CustomCredentialEntry internal constructor(
+ type: String,
+ val title: CharSequence,
+ val subTitle: CharSequence?,
+ val typeDisplayName: CharSequence?,
+ val icon: Icon?,
+ val lastUsedTime: Instant?,
+ val pendingIntent: PendingIntent,
+ val isAutoSelectAllowed: Boolean
+ ) : android.service.credentials.CredentialEntry(
+ type,
+ toSlice(
+ type,
+ title,
+ subTitle,
+ pendingIntent,
+ typeDisplayName,
+ lastUsedTime,
+ icon,
+ isAutoSelectAllowed
+ )
+) {
+ init {
+ require(type.isNotEmpty()) { "type must not be empty" }
+ }
+
+ override fun describeContents(): Int {
+ return 0
+ }
+
+ override fun writeToParcel(@NonNull dest: Parcel, flags: Int) {
+ super.writeToParcel(dest, flags)
+ }
+
+ @Suppress("AcronymName")
+ @RequiresApi(34)
+ companion object {
+ private const val TAG = "CredentialEntry"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_TYPE_DISPLAY_NAME =
+ "androidx.credentials.provider.credentialEntry.SLICE_HINT_TYPE_DISPLAY_NAME"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_TITLE =
+ "androidx.credentials.provider.credentialEntry.SLICE_HINT_USER_NAME"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_SUBTITLE =
+ "androidx.credentials.provider.credentialEntry.SLICE_HINT_CREDENTIAL_TYPE_DISPLAY_NAME"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_LAST_USED_TIME_MILLIS =
+ "androidx.credentials.provider.credentialEntry.SLICE_HINT_LAST_USED_TIME_MILLIS"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_ICON =
+ "androidx.credentials.provider.credentialEntry.SLICE_HINT_PROFILE_ICON"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_PENDING_INTENT =
+ "androidx.credentials.provider.credentialEntry.SLICE_HINT_PENDING_INTENT"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_AUTO_ALLOWED =
+ "androidx.credentials.provider.credentialEntry.SLICE_HINT_AUTO_ALLOWED"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val AUTO_SELECT_TRUE_STRING = "true"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val AUTO_SELECT_FALSE_STRING = "false"
+
+ /** @hide */
+ @JvmStatic
+ internal fun toSlice(
+ type: String,
+ title: CharSequence,
+ subTitle: CharSequence?,
+ pendingIntent: PendingIntent,
+ typeDisplayName: CharSequence?,
+ lastUsedTime: Instant?,
+ icon: Icon?,
+ isAutoSelectAllowed: Boolean
+ ): Slice {
+ // TODO("Put the right revision value")
+ val autoSelectAllowed = if (isAutoSelectAllowed) {
+ AUTO_SELECT_TRUE_STRING
+ } else {
+ AUTO_SELECT_FALSE_STRING
+ }
+ val sliceBuilder = Slice.Builder(Uri.EMPTY, SliceSpec(
+ type, 1))
+ .addText(typeDisplayName, /*subType=*/null,
+ listOf(SLICE_HINT_TYPE_DISPLAY_NAME))
+ .addText(title, /*subType=*/null,
+ listOf(SLICE_HINT_TITLE))
+ .addText(subTitle, /*subType=*/null,
+ listOf(SLICE_HINT_SUBTITLE))
+ .addText(autoSelectAllowed, /*subType=*/null,
+ listOf(SLICE_HINT_AUTO_ALLOWED))
+ if (lastUsedTime != null) {
+ sliceBuilder.addLong(lastUsedTime.toEpochMilli(),
+ /*subType=*/null,
+ listOf(SLICE_HINT_LAST_USED_TIME_MILLIS))
+ }
+ if (icon != null) {
+ sliceBuilder.addIcon(icon, /*subType=*/null,
+ listOf(SLICE_HINT_ICON))
+ }
+ sliceBuilder.addAction(pendingIntent,
+ Slice.Builder(sliceBuilder)
+ .addHints(Collections.singletonList(SLICE_HINT_PENDING_INTENT))
+ .build(),
+ /*subType=*/null)
+ return sliceBuilder.build()
+ }
+
+ /**
+ * Returns an instance of [CustomCredentialEntry] derived from a [Slice] object.
+ *
+ * @param slice the [Slice] object constructed through [toSlice]
+ *
+ * @hide
+ */
+ @SuppressLint("WrongConstant") // custom conversion between jetpack and framework
+ @JvmStatic
+ fun fromSlice(slice: Slice): CustomCredentialEntry? {
+ var typeDisplayName: CharSequence? = null
+ var title: CharSequence? = null
+ var subTitle: CharSequence? = null
+ var icon: Icon? = null
+ var pendingIntent: PendingIntent? = null
+ var lastUsedTime: Instant? = null
+ var autoSelectAllowed = false
+
+ slice.items.forEach {
+ if (it.hasHint(SLICE_HINT_TYPE_DISPLAY_NAME)) {
+ typeDisplayName = it.text
+ } else if (it.hasHint(SLICE_HINT_TITLE)) {
+ title = it.text
+ } else if (it.hasHint(SLICE_HINT_SUBTITLE)) {
+ subTitle = it.text
+ } else if (it.hasHint(SLICE_HINT_ICON)) {
+ icon = it.icon
+ } else if (it.hasHint(SLICE_HINT_PENDING_INTENT)) {
+ pendingIntent = it.action
+ } else if (it.hasHint(SLICE_HINT_LAST_USED_TIME_MILLIS)) {
+ lastUsedTime = Instant.ofEpochMilli(it.long)
+ } else if (it.hasHint(SLICE_HINT_AUTO_ALLOWED)) {
+ val autoSelectValue = it.text
+ if (autoSelectValue == AUTO_SELECT_TRUE_STRING) {
+ autoSelectAllowed = true
+ }
+ }
+ }
+
+ return try {
+ CustomCredentialEntry(slice.spec!!.type, title!!,
+ subTitle,
+ typeDisplayName!!,
+ icon,
+ lastUsedTime, pendingIntent!!, autoSelectAllowed)
+ } catch (e: Exception) {
+ Log.i(TAG, "fromSlice failed with: " + e.message)
+ null
+ }
+ }
+
+ @JvmField val CREATOR: Parcelable.Creator<CustomCredentialEntry> = object :
+ Parcelable.Creator<CustomCredentialEntry> {
+ override fun createFromParcel(p0: Parcel?): CustomCredentialEntry? {
+ val baseEntry =
+ android.service.credentials.CredentialEntry.CREATOR.createFromParcel(p0)
+ return fromSlice(baseEntry.slice)
+ }
+
+ @Suppress("ArrayReturn")
+ override fun newArray(size: Int): Array<CustomCredentialEntry?> {
+ return arrayOfNulls(size)
+ }
+ }
+ }
+}
diff --git a/credentials/credentials/src/main/java/androidx/credentials/provider/PasswordCredentialEntry.kt b/credentials/credentials/src/main/java/androidx/credentials/provider/PasswordCredentialEntry.kt
new file mode 100644
index 0000000..5166584
--- /dev/null
+++ b/credentials/credentials/src/main/java/androidx/credentials/provider/PasswordCredentialEntry.kt
@@ -0,0 +1,312 @@
+/*
+ * 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 androidx.credentials.provider
+
+import android.annotation.SuppressLint
+import android.app.PendingIntent
+import android.app.slice.Slice
+import android.app.slice.SliceSpec
+import android.content.Context
+import android.graphics.drawable.Icon
+import android.net.Uri
+import android.os.Parcel
+import android.os.Parcelable
+import android.service.credentials.CredentialEntry
+import android.util.Log
+import androidx.annotation.NonNull
+import androidx.annotation.RequiresApi
+import androidx.annotation.VisibleForTesting
+import androidx.credentials.PasswordCredential
+import androidx.credentials.R
+import java.time.Instant
+import java.util.Collections
+
+/**
+ * A password credential entry that is displayed on the account selector UI. This
+ * entry denotes that a credential of type [PasswordCredential.TYPE_PASSWORD_CREDENTIAL]
+ * is available for the user to select.
+ *
+ * Once this entry is selected, the corresponding [pendingIntent] will be invoked. The provider
+ * can then show any activity they wish to. Before finishing the activity, provider must
+ * set the final [androidx.credentials.GetCredentialResponse] through the
+ * [PendingIntentHandler.setGetCredentialResponse] helper API.
+ *
+ * @property username the username of the account holding the password credential
+ * @property displayName the displayName of the account holding the password credential
+ * @property lastUsedTime the last used time of this entry
+ * @property icon the icon to be displayed with this entry on the selector
+ * @property pendingIntent the [PendingIntent] to be invoked when user selects
+ * this entry
+ * @property isAutoSelectAllowed whether this entry is allowed to be auto
+ * selected if it is the only one on the UI. Note that setting this value
+ * to true does not guarantee this behavior. The developer must also set this
+ * to true, and the framework must determine that this is the only entry available for the user.
+ *
+ * @throws IllegalArgumentException if [username] is empty
+ *
+ * @see CustomCredentialEntry
+ */
+@RequiresApi(34)
+class PasswordCredentialEntry internal constructor(
+ val username: CharSequence,
+ val displayName: CharSequence?,
+ val typeDisplayName: CharSequence,
+ val pendingIntent: PendingIntent,
+ val lastUsedTime: Instant?,
+ val icon: Icon,
+ val isAutoSelectAllowed: Boolean
+) : CredentialEntry(
+ PasswordCredential.TYPE_PASSWORD_CREDENTIAL,
+ toSlice(
+ PasswordCredential.TYPE_PASSWORD_CREDENTIAL,
+ username,
+ displayName,
+ pendingIntent,
+ typeDisplayName,
+ lastUsedTime,
+ icon,
+ isAutoSelectAllowed
+ )
+) {
+
+ override fun describeContents(): Int {
+ return 0
+ }
+
+ override fun writeToParcel(@NonNull dest: Parcel, flags: Int) {
+ super.writeToParcel(dest, flags)
+ }
+
+ @Suppress("AcronymName")
+ companion object CREATOR {
+ private const val TAG = "PasswordCredentialEntry"
+
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_TYPE_DISPLAY_NAME =
+ "androidx.credentials.provider.passwordCredentialEntry.SLICE_HINT_TYPE_DISPLAY_NAME"
+
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_TITLE =
+ "androidx.credentials.provider.passwordCredentialEntry.SLICE_HINT_USER_NAME"
+
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_SUBTITLE =
+ "androidx.credentials.provider.passwordCredentialEntry.SLICE_HINT_TYPE_DISPLAY_NAME"
+
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_LAST_USED_TIME_MILLIS =
+ "androidx.credentials.provider.passwordCredentialEntry.SLICE_HINT_LAST_USED_TIME_MILLIS"
+
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_ICON =
+ "androidx.credentials.provider.passwordCredentialEntry.SLICE_HINT_PROFILE_ICON"
+
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_PENDING_INTENT =
+ "androidx.credentials.provider.passwordCredentialEntry.SLICE_HINT_PENDING_INTENT"
+
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_AUTO_ALLOWED =
+ "androidx.credentials.provider.passwordCredentialEntry.SLICE_HINT_AUTO_ALLOWED"
+
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val AUTO_SELECT_TRUE_STRING = "true"
+
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val AUTO_SELECT_FALSE_STRING = "false"
+
+ /** @hide */
+ @JvmStatic
+ internal fun toSlice(
+ type: String,
+ title: CharSequence,
+ subTitle: CharSequence?,
+ pendingIntent: PendingIntent,
+ typeDisplayName: CharSequence?,
+ lastUsedTime: Instant?,
+ icon: Icon?,
+ isAutoSelectAllowed: Boolean
+ ): Slice {
+ // TODO("Put the right revision value")
+ val autoSelectAllowed = if (isAutoSelectAllowed) {
+ AUTO_SELECT_TRUE_STRING
+ } else {
+ AUTO_SELECT_FALSE_STRING
+ }
+ val sliceBuilder = Slice.Builder(
+ Uri.EMPTY, SliceSpec(
+ type, 1
+ )
+ )
+ .addText(
+ typeDisplayName, /*subType=*/null,
+ listOf(SLICE_HINT_TYPE_DISPLAY_NAME)
+ )
+ .addText(
+ title, /*subType=*/null,
+ listOf(SLICE_HINT_TITLE)
+ )
+ .addText(
+ subTitle, /*subType=*/null,
+ listOf(SLICE_HINT_SUBTITLE)
+ )
+ .addText(
+ autoSelectAllowed, /*subType=*/null,
+ listOf(SLICE_HINT_AUTO_ALLOWED)
+ )
+ if (lastUsedTime != null) {
+ sliceBuilder.addLong(
+ lastUsedTime.toEpochMilli(),
+ /*subType=*/null,
+ listOf(SLICE_HINT_LAST_USED_TIME_MILLIS)
+ )
+ }
+ if (icon != null) {
+ sliceBuilder.addIcon(
+ icon, /*subType=*/null,
+ listOf(SLICE_HINT_ICON)
+ )
+ }
+ sliceBuilder.addAction(
+ pendingIntent,
+ Slice.Builder(sliceBuilder)
+ .addHints(Collections.singletonList(SLICE_HINT_PENDING_INTENT))
+ .build(),
+ /*subType=*/null
+ )
+ return sliceBuilder.build()
+ }
+
+ /**
+ * Returns an instance of [CustomCredentialEntry] derived from a [Slice] object.
+ *
+ * @param slice the [Slice] object constructed through [toSlice]
+ *
+ * @hide
+ */
+ @SuppressLint("WrongConstant") // custom conversion between jetpack and framework
+ @JvmStatic
+ fun fromSlice(slice: Slice): PasswordCredentialEntry? {
+ var typeDisplayName: CharSequence? = null
+ var title: CharSequence? = null
+ var subTitle: CharSequence? = null
+ var icon: Icon? = null
+ var pendingIntent: PendingIntent? = null
+ var lastUsedTime: Instant? = null
+ var autoSelectAllowed = false
+
+ slice.items.forEach {
+ if (it.hasHint(SLICE_HINT_TYPE_DISPLAY_NAME)) {
+ typeDisplayName = it.text
+ } else if (it.hasHint(SLICE_HINT_TITLE)) {
+ title = it.text
+ } else if (it.hasHint(SLICE_HINT_SUBTITLE)) {
+ subTitle = it.text
+ } else if (it.hasHint(SLICE_HINT_ICON)) {
+ icon = it.icon
+ } else if (it.hasHint(SLICE_HINT_PENDING_INTENT)) {
+ pendingIntent = it.action
+ } else if (it.hasHint(SLICE_HINT_LAST_USED_TIME_MILLIS)) {
+ lastUsedTime = Instant.ofEpochMilli(it.long)
+ } else if (it.hasHint(SLICE_HINT_AUTO_ALLOWED)) {
+ val autoSelectValue = it.text
+ if (autoSelectValue == AUTO_SELECT_TRUE_STRING) {
+ autoSelectAllowed = true
+ }
+ }
+ }
+
+ return try {
+ PasswordCredentialEntry(
+ title!!,
+ subTitle,
+ typeDisplayName!!,
+ pendingIntent!!,
+ lastUsedTime,
+ icon!!,
+ autoSelectAllowed
+ )
+ } catch (e: Exception) {
+ Log.i(TAG, "fromSlice failed with: " + e.message)
+ null
+ }
+ }
+
+ @JvmField val CREATOR: Parcelable.Creator<PasswordCredentialEntry> = object :
+ Parcelable.Creator<PasswordCredentialEntry> {
+ override fun createFromParcel(p0: Parcel?): PasswordCredentialEntry? {
+ val credentialEntry = CredentialEntry.CREATOR.createFromParcel(p0)
+ return fromSlice(credentialEntry.slice)
+ }
+
+ @Suppress("ArrayReturn")
+ override fun newArray(size: Int): Array<PasswordCredentialEntry?> {
+ return arrayOfNulls(size)
+ }
+ }
+ }
+ /** Builder for [PasswordCredentialEntry] */
+ class Builder(
+ private val context: Context,
+ private val username: CharSequence,
+ private val pendingIntent: PendingIntent
+ ) {
+ private var displayName: CharSequence? = null
+ private var lastUsedTime: Instant? = null
+ private var icon: Icon? = null
+ private var autoSelectAllowed = false
+
+ /** Sets a displayName to be shown on the UI with this entry */
+ fun setDisplayName(displayName: CharSequence?): Builder {
+ this.displayName = displayName
+ return this
+ }
+
+ /** Sets the icon to be shown on the UI with this entry */
+ fun setIcon(icon: Icon?): Builder {
+ this.icon = icon
+ return this
+ }
+
+ /**
+ * Sets the last used time of this account. This information will be used to sort the
+ * entries on the selector.
+ */
+ fun setLastUsedTime(lastUsedTime: Instant?): Builder {
+ this.lastUsedTime = lastUsedTime
+ return this
+ }
+
+ /** Builds an instance of [PasswordCredentialEntry] */
+ fun build(): PasswordCredentialEntry {
+ if (icon == null) {
+ icon = Icon.createWithResource(context, R.drawable.ic_password)
+ }
+ val typeDisplayName = context.getString(
+ R.string.android_credentials_TYPE_PASSWORD_CREDENTIAL)
+ return PasswordCredentialEntry(
+ username,
+ displayName,
+ typeDisplayName,
+ pendingIntent,
+ lastUsedTime,
+ icon!!,
+ autoSelectAllowed
+ )
+ }
+ }
+}
diff --git a/credentials/credentials/src/main/java/androidx/credentials/provider/PendingIntentHandler.kt b/credentials/credentials/src/main/java/androidx/credentials/provider/PendingIntentHandler.kt
new file mode 100644
index 0000000..a18a6ee
--- /dev/null
+++ b/credentials/credentials/src/main/java/androidx/credentials/provider/PendingIntentHandler.kt
@@ -0,0 +1,150 @@
+/*
+ * 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 androidx.credentials.provider
+
+import android.app.PendingIntent
+import android.content.Intent
+import android.credentials.CreateCredentialResponse
+import android.service.credentials.BeginGetCredentialRequest
+import android.service.credentials.CreateCredentialRequest
+import android.service.credentials.CredentialProviderService
+import android.service.credentials.CredentialsResponseContent
+import android.util.Log
+import androidx.annotation.RequiresApi
+import androidx.credentials.GetCredentialResponse
+import androidx.credentials.provider.utils.BeginGetCredentialUtil
+
+/**
+ * PendingIntentHandler to be used by credential providers to extract requests from
+ * [PendingIntent] invoked when a given [CreateEntry], or a [CustomCredentialEntry]
+ * is selected by the user.
+ *
+ * This handler can also be used to set [android.credentials.CreateCredentialResponse] and
+ * [android.credentials.GetCredentialResponse] on the result of the activity
+ * invoked by the [PendingIntent]
+ */
+@RequiresApi(34)
+class PendingIntentHandler {
+ companion object {
+ private const val TAG = "PendingIntentHandler"
+
+ /**
+ * Extract the [ProviderCreateCredentialRequest] from the provider's
+ * [PendingIntent] invoked by the Android system.
+ */
+ @JvmStatic
+ fun retrieveCreateCredentialProviderRequest(intent: Intent):
+ ProviderCreateCredentialRequest? {
+ val frameworkReq: CreateCredentialRequest? =
+ intent.getParcelableExtra(
+ CredentialProviderService
+ .EXTRA_CREATE_CREDENTIAL_REQUEST, CreateCredentialRequest::class.java
+ )
+ if (frameworkReq == null) {
+ Log.i(TAG, "Request not found in pendingIntent")
+ return frameworkReq
+ }
+ return ProviderCreateCredentialRequest(
+ androidx.credentials.CreateCredentialRequest
+ .createFrom(
+ frameworkReq.type,
+ frameworkReq.data,
+ frameworkReq.data,
+ requireSystemProvider = false) ?: return null,
+ frameworkReq.callingAppInfo)
+ }
+
+ /**
+ * Extract [BeginGetCredentialRequest] from the provider's
+ * [PendingIntent] invoked by the Android system when the user
+ * selects an [AuthenticationAction].
+ */
+ @JvmStatic
+ fun getBeginGetCredentialRequest(intent: Intent): BeginGetCredentialRequest? {
+ val request = intent.getParcelableExtra(
+ "android.service.credentials.extra.BEGIN_GET_CREDENTIAL_REQUEST",
+ BeginGetCredentialRequest::class.java
+ )
+ return request?.let { BeginGetCredentialUtil.convertToStructuredRequest(it) }
+ }
+
+ /**
+ * Set the [CreateCredentialResponse] on the result of the
+ * activity invoked by the [PendingIntent] set on
+ * [CreateEntry]
+ */
+ @JvmStatic
+ fun setCreateCredentialResponse(
+ intent: Intent,
+ response: androidx.credentials.CreateCredentialResponse
+ ) {
+ intent.putExtra(
+ CredentialProviderService.EXTRA_CREATE_CREDENTIAL_RESPONSE,
+ CreateCredentialResponse(response.data))
+ }
+
+ /**
+ * Extract the [ProviderGetCredentialRequest] from the provider's
+ * [PendingIntent] invoked by the Android system.
+ */
+ @JvmStatic
+ fun retrieveGetCredentialProviderRequest(intent: Intent):
+ ProviderGetCredentialRequest? {
+ val frameworkReq = intent.getParcelableExtra(
+ CredentialProviderService.EXTRA_GET_CREDENTIAL_REQUEST,
+ android.service.credentials.GetCredentialRequest::class.java
+ )
+ if (frameworkReq == null) {
+ Log.i(TAG, "Get request from framework is null")
+ return null
+ }
+ return ProviderGetCredentialRequest.createFrom(frameworkReq)
+ }
+
+ /**
+ * Set the [android.credentials.GetCredentialResponse] on the result of the
+ * activity invoked by the [PendingIntent] set on [CreateEntry]
+ */
+ @JvmStatic
+ fun setGetCredentialResponse(
+ intent: Intent,
+ response: GetCredentialResponse
+ ) {
+ intent.putExtra(
+ CredentialProviderService.EXTRA_GET_CREDENTIAL_RESPONSE,
+ android.credentials.GetCredentialResponse(
+ android.credentials.Credential(response.credential.type,
+ response.credential.data))
+ )
+ }
+
+ /**
+ * Set the [android.service.credentials.CredentialsResponseContent] on the result of the
+ * activity invoked by the [PendingIntent] set on [AuthenticationAction].
+ */
+ @JvmStatic
+ fun setCredentialsResponseContent(
+ intent: Intent,
+ response: CredentialsResponseContent
+ ) {
+ intent.putExtra(
+ CredentialProviderService.EXTRA_CREDENTIALS_RESPONSE_CONTENT,
+ response
+ )
+ }
+ }
+}
diff --git a/credentials/credentials/src/main/java/androidx/credentials/provider/ProviderCreateCredentialRequest.kt b/credentials/credentials/src/main/java/androidx/credentials/provider/ProviderCreateCredentialRequest.kt
new file mode 100644
index 0000000..9f77325
--- /dev/null
+++ b/credentials/credentials/src/main/java/androidx/credentials/provider/ProviderCreateCredentialRequest.kt
@@ -0,0 +1,42 @@
+/*
+ * 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 androidx.credentials.provider
+
+import android.service.credentials.CallingAppInfo
+import androidx.annotation.RequiresApi
+import androidx.credentials.CreateCredentialRequest
+
+/**
+ * Final request received by the provider after the user has selected a given [CreateEntry]
+ * on the UI.
+ *
+ * This request contains the actual request coming from the calling app,
+ * and the application information associated with the calling app.
+ *
+ * @property callingRequest the complete [CreateCredentialRequest] coming from
+ * the calling app that is requesting for credential creation
+ * @property callingAppInfo information pertaining to the calling app making
+ * the request
+ *
+ * @throws NullPointerException If [callingRequest] is null
+ * @throws NullPointerException If [callingAppInfo] is null
+ */
+@RequiresApi(34)
+class ProviderCreateCredentialRequest internal constructor(
+ val callingRequest: CreateCredentialRequest,
+ val callingAppInfo: CallingAppInfo
+)
\ No newline at end of file
diff --git a/credentials/credentials/src/main/java/androidx/credentials/provider/ProviderGetCredentialRequest.kt b/credentials/credentials/src/main/java/androidx/credentials/provider/ProviderGetCredentialRequest.kt
new file mode 100644
index 0000000..b9419ff
--- /dev/null
+++ b/credentials/credentials/src/main/java/androidx/credentials/provider/ProviderGetCredentialRequest.kt
@@ -0,0 +1,57 @@
+/*
+ * 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 androidx.credentials.provider
+
+import android.app.PendingIntent
+import android.service.credentials.CallingAppInfo
+import androidx.annotation.RequiresApi
+import androidx.credentials.CredentialOption
+
+/**
+ * Request received by the provider after the query phase of the get flow is complete i.e. the user
+ * was presented with a list of credentials, and the user has now made a selection from the list of
+ * [android.service.credentials.CredentialEntry] presented on the selector UI.
+ *
+ * This request will be added to the intent extras of the activity invoked by the [PendingIntent]
+ * set on the [android.service.credentials.CredentialEntry] that the user selected. The request
+ * must be extracted using the [PendingIntentHandler.retrieveGetCredentialProviderRequest] helper
+ * API.
+ *
+ * @property credentialOption the credential retrieval parameters
+ * @property callingAppInfo information pertaining to the calling application
+ */
+@RequiresApi(34)
+class ProviderGetCredentialRequest internal constructor(
+ val credentialOption: CredentialOption,
+ val callingAppInfo: CallingAppInfo
+ ) {
+
+ /** @hide */
+ companion object {
+ internal fun createFrom(request: android.service.credentials.GetCredentialRequest):
+ ProviderGetCredentialRequest {
+ val option = CredentialOption.createFrom(
+ request.getCredentialOption.type,
+ request.getCredentialOption.candidateQueryData,
+ request.getCredentialOption.credentialRetrievalData,
+ request.getCredentialOption.isSystemProviderRequired
+ )
+ return ProviderGetCredentialRequest(
+ option,
+ request.callingAppInfo)
+ }
+ }
+}
\ No newline at end of file
diff --git a/credentials/credentials/src/main/java/androidx/credentials/provider/PublicKeyCredentialEntry.kt b/credentials/credentials/src/main/java/androidx/credentials/provider/PublicKeyCredentialEntry.kt
new file mode 100644
index 0000000..1eb86b4
--- /dev/null
+++ b/credentials/credentials/src/main/java/androidx/credentials/provider/PublicKeyCredentialEntry.kt
@@ -0,0 +1,293 @@
+/*
+ * 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 androidx.credentials.provider
+
+import android.annotation.SuppressLint
+import android.app.PendingIntent
+import android.app.slice.Slice
+import android.app.slice.SliceSpec
+import android.content.Context
+import android.graphics.drawable.Icon
+import android.net.Uri
+import android.os.Parcel
+import android.os.Parcelable
+import android.service.credentials.CredentialEntry
+import android.util.Log
+import androidx.annotation.NonNull
+import androidx.annotation.RequiresApi
+import androidx.annotation.VisibleForTesting
+import androidx.credentials.PublicKeyCredential
+import androidx.credentials.R
+import java.time.Instant
+import java.util.Collections
+
+/**
+ * A public key credential entry that is displayed on the account selector UI. This
+ * entry denotes that a credential of type [PublicKeyCredential.TYPE_PUBLIC_KEY_CREDENTIAL]
+ * is available for the user to select.
+ *
+ * Once this entry is selected, the corresponding [pendingIntent] will be invoked. The provider
+ * can then show any activity they wish to. Before finishing the activity, provider must
+ * set the final [androidx.credentials.GetCredentialResponse] through the
+ * [PendingIntentHandler.setGetCredentialResponse] helper API.
+ *
+ * @property username the username of the account holding the public key credential
+ * @property displayName the displayName of the account holding the public key credential
+ * @property lastUsedTime the last used time of this entry
+ * @property icon the icon to be displayed with this entry on the selector
+ * @param pendingIntent the [PendingIntent] to be invoked when the user
+ * selects this entry
+ * @property isAutoSelectAllowed whether this entry is allowed to be auto
+ * selected if it is the only one on the UI. Note that setting this value
+ * to true does not guarantee this behavior. The developer must also set this
+ * to true, and the framework must determine that it is safe to auto select.
+ *
+ * @throws IllegalArgumentException if [username] is empty
+ */
+@RequiresApi(34)
+class PublicKeyCredentialEntry internal constructor(
+ val username: CharSequence,
+ val displayName: CharSequence?,
+ val typeDisplayName: CharSequence,
+ val pendingIntent: PendingIntent,
+ val icon: Icon,
+ val lastUsedTime: Instant?,
+ val isAutoSelectAllowed: Boolean
+) : CredentialEntry(
+ PublicKeyCredential.TYPE_PUBLIC_KEY_CREDENTIAL,
+ toSlice(
+ PublicKeyCredential.TYPE_PUBLIC_KEY_CREDENTIAL,
+ username,
+ displayName,
+ pendingIntent,
+ typeDisplayName,
+ lastUsedTime,
+ icon,
+ isAutoSelectAllowed
+ )
+) {
+
+ override fun describeContents(): Int {
+ return 0
+ }
+
+ override fun writeToParcel(@NonNull dest: Parcel, flags: Int) {
+ super.writeToParcel(dest, flags)
+ }
+
+ @Suppress("AcronymName")
+ companion object CREATOR {
+
+ private const val TAG = "PublicKeyCredEntry"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_TYPE_DISPLAY_NAME =
+ "androidx.credentials.provider.publicKeyCredEntry.SLICE_HINT_TYPE_DISPLAY_NAME"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_TITLE =
+ "androidx.credentials.provider.publicKeyCredEntry.SLICE_HINT_USER_NAME"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_SUBTITLE =
+ "androidx.credentials.provider.publicKeyCredEntry.SLICE_HINT_TYPE_DISPLAY_NAME"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_LAST_USED_TIME_MILLIS =
+ "androidx.credentials.provider.publicKeyCredEntry.SLICE_HINT_LAST_USED_TIME_MILLIS"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_ICON =
+ "androidx.credentials.provider.publicKeyCredEntry.SLICE_HINT_PROFILE_ICON"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_PENDING_INTENT =
+ "androidx.credentials.provider.publicKeyCredEntry.SLICE_HINT_PENDING_INTENT"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_AUTO_ALLOWED =
+ "androidx.credentials.provider.publicKeyCredEntry.SLICE_HINT_AUTO_ALLOWED"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val AUTO_SELECT_TRUE_STRING = "true"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val AUTO_SELECT_FALSE_STRING = "false"
+
+ /** @hide */
+ @JvmStatic
+ internal fun toSlice(
+ type: String,
+ title: CharSequence,
+ subTitle: CharSequence?,
+ pendingIntent: PendingIntent,
+ typeDisplayName: CharSequence?,
+ lastUsedTime: Instant?,
+ icon: Icon?,
+ isAutoSelectAllowed: Boolean
+ ): Slice {
+ // TODO("Put the right revision value")
+ val autoSelectAllowed = if (isAutoSelectAllowed) {
+ AUTO_SELECT_TRUE_STRING
+ } else {
+ AUTO_SELECT_FALSE_STRING
+ }
+ val sliceBuilder = Slice.Builder(
+ Uri.EMPTY, SliceSpec(
+ type, 1)
+ )
+ .addText(typeDisplayName, /*subType=*/null,
+ listOf(SLICE_HINT_TYPE_DISPLAY_NAME))
+ .addText(title, /*subType=*/null,
+ listOf(SLICE_HINT_TITLE))
+ .addText(subTitle, /*subType=*/null,
+ listOf(SLICE_HINT_SUBTITLE))
+ .addText(autoSelectAllowed, /*subType=*/null,
+ listOf(SLICE_HINT_AUTO_ALLOWED))
+ if (lastUsedTime != null) {
+ sliceBuilder.addLong(lastUsedTime.toEpochMilli(),
+ /*subType=*/null,
+ listOf(SLICE_HINT_LAST_USED_TIME_MILLIS))
+ }
+ if (icon != null) {
+ sliceBuilder.addIcon(icon, /*subType=*/null,
+ listOf(SLICE_HINT_ICON))
+ }
+ sliceBuilder.addAction(pendingIntent,
+ Slice.Builder(sliceBuilder)
+ .addHints(Collections.singletonList(SLICE_HINT_PENDING_INTENT))
+ .build(),
+ /*subType=*/null)
+ return sliceBuilder.build()
+ }
+
+ /**
+ * Returns an instance of [CustomCredentialEntry] derived from a [Slice] object.
+ *
+ * @param slice the [Slice] object constructed through [toSlice]
+ *
+ * @hide
+ */
+ @SuppressLint("WrongConstant") // custom conversion between jetpack and framework
+ @JvmStatic
+ fun fromSlice(slice: Slice): PublicKeyCredentialEntry? {
+ var typeDisplayName: CharSequence? = null
+ var title: CharSequence? = null
+ var subTitle: CharSequence? = null
+ var icon: Icon? = null
+ var pendingIntent: PendingIntent? = null
+ var lastUsedTime: Instant? = null
+ var autoSelectAllowed = false
+
+ slice.items.forEach {
+ if (it.hasHint(SLICE_HINT_TYPE_DISPLAY_NAME)) {
+ typeDisplayName = it.text
+ } else if (it.hasHint(SLICE_HINT_TITLE)) {
+ title = it.text
+ } else if (it.hasHint(SLICE_HINT_SUBTITLE)) {
+ subTitle = it.text
+ } else if (it.hasHint(SLICE_HINT_ICON)) {
+ icon = it.icon
+ } else if (it.hasHint(SLICE_HINT_PENDING_INTENT)) {
+ pendingIntent = it.action
+ } else if (it.hasHint(SLICE_HINT_LAST_USED_TIME_MILLIS)) {
+ lastUsedTime = Instant.ofEpochMilli(it.long)
+ } else if (it.hasHint(SLICE_HINT_AUTO_ALLOWED)) {
+ val autoSelectValue = it.text
+ if (autoSelectValue == AUTO_SELECT_TRUE_STRING) {
+ autoSelectAllowed = true
+ }
+ }
+ }
+
+ return try {
+ PublicKeyCredentialEntry(
+ title!!,
+ subTitle,
+ typeDisplayName!!,
+ pendingIntent!!,
+ icon!!,
+ lastUsedTime,
+ autoSelectAllowed)
+ } catch (e: Exception) {
+ Log.i(TAG, "fromSlice failed with: " + e.message)
+ null
+ }
+ }
+
+ @JvmField val CREATOR: Parcelable.Creator<PublicKeyCredentialEntry> = object :
+ Parcelable.Creator<PublicKeyCredentialEntry> {
+ override fun createFromParcel(p0: Parcel?): PublicKeyCredentialEntry? {
+ val credentialEntry = CredentialEntry.CREATOR.createFromParcel(p0)
+ return fromSlice(credentialEntry.slice)
+ }
+
+ @Suppress("ArrayReturn")
+ override fun newArray(size: Int): Array<PublicKeyCredentialEntry?> {
+ return arrayOfNulls(size)
+ }
+ }
+ }
+
+ /**
+ * Builder for [PublicKeyCredentialEntry]
+ */
+ class Builder(
+ private val context: Context,
+ private val username: CharSequence,
+ private val pendingIntent: PendingIntent
+ ) {
+ private var displayName: CharSequence? = null
+ private var lastUsedTime: Instant? = null
+ private var icon: Icon? = null
+ private var autoSelectAllowed: Boolean = false
+
+ /** Sets a displayName to be shown on the UI with this entry */
+ fun setDisplayName(displayName: CharSequence?): Builder {
+ this.displayName = displayName
+ return this
+ }
+
+ /** Sets the icon to be shown on the UI with this entry */
+ fun setIcon(icon: Icon?): Builder {
+ this.icon = icon
+ return this
+ }
+ /**
+ * Sets whether the entry should be auto-selected.
+ * The value is false by default
+ */
+ @Suppress("MissingGetterMatchingBuilder")
+ fun setAutoSelectAllowed(autoSelectAllowed: Boolean): Builder {
+ this.autoSelectAllowed = autoSelectAllowed
+ return this
+ }
+
+ /**
+ * Sets the last used time of this account
+ *
+ * This information will be used to sort the entries on the selector.
+ */
+ fun setLastUsedTime(lastUsedTime: Instant?): Builder {
+ this.lastUsedTime = lastUsedTime
+ return this
+ }
+
+ /** Builds an instance of [PublicKeyCredentialEntry] */
+ fun build(): PublicKeyCredentialEntry {
+ if (icon == null) {
+ icon = Icon.createWithResource(context, R.drawable.ic_passkey)
+ }
+ val typeDisplayName = context.getString(
+ R.string.androidx_credentials_TYPE_PUBLIC_KEY_CREDENTIAL)
+ return PublicKeyCredentialEntry(
+ username, displayName, typeDisplayName, pendingIntent, icon!!,
+ lastUsedTime, autoSelectAllowed)
+ }
+ }
+}
diff --git a/credentials/credentials/src/main/java/androidx/credentials/provider/RemoteCreateEntry.kt b/credentials/credentials/src/main/java/androidx/credentials/provider/RemoteCreateEntry.kt
new file mode 100644
index 0000000..33ff311
--- /dev/null
+++ b/credentials/credentials/src/main/java/androidx/credentials/provider/RemoteCreateEntry.kt
@@ -0,0 +1,124 @@
+/*
+ * 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 androidx.credentials.provider
+
+import android.annotation.SuppressLint
+import android.app.PendingIntent
+import android.app.slice.Slice
+import android.app.slice.SliceSpec
+import android.net.Uri
+import android.os.Parcel
+import android.os.Parcelable
+import android.util.Log
+import androidx.annotation.NonNull
+import androidx.annotation.RequiresApi
+import androidx.annotation.VisibleForTesting
+import androidx.credentials.CredentialManager
+import java.util.Collections
+
+/**
+ * An entry to be shown on the selector during a create flow initiated when an app calls
+ * [CredentialManager.createCredential].
+ *
+ * A [RemoteCreateEntry] implies that the credential will be created on
+ * a different device.
+ * When the user selects this entry, the corresponding [PendingIntent] is fired,
+ * and the credential creation can be completed.
+ *
+ * @property pendingIntent the [PendingIntent] to be fired when this
+ * [RemoteCreateEntry] is selected
+ *
+ * @throws NullPointerException If [pendingIntent] is empty
+ */
+@RequiresApi(34)
+class RemoteCreateEntry constructor(
+ val pendingIntent: PendingIntent,
+ ) : android.service.credentials.CreateEntry(
+ toSlice(pendingIntent)
+) {
+
+ override fun describeContents(): Int {
+ return 0
+ }
+
+ override fun writeToParcel(@NonNull dest: Parcel, flags: Int) {
+ super.writeToParcel(dest, flags)
+ }
+
+ @Suppress("AcronymName")
+ companion object {
+ private const val TAG = "RemoteCreateEntry"
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_PENDING_INTENT =
+ "androidx.credentials.provider.createEntry.SLICE_HINT_PENDING_INTENT"
+
+ /** @hide **/
+ @JvmStatic
+ fun toSlice(
+ pendingIntent: PendingIntent
+ ): Slice {
+ // TODO("Use the right type and revision")
+ val sliceBuilder = Slice.Builder(Uri.EMPTY, SliceSpec("type", 1))
+ sliceBuilder.addAction(
+ pendingIntent,
+ Slice.Builder(sliceBuilder)
+ .addHints(Collections.singletonList(SLICE_HINT_PENDING_INTENT))
+ .build(),
+ /*subType=*/null
+ )
+ return sliceBuilder.build()
+ }
+
+ /**
+ * Returns an instance of [RemoteCreateEntry] derived from a [Slice] object.
+ *
+ * @param slice the [Slice] object constructed through [toSlice]
+ *
+ * @hide
+ */
+ @SuppressLint("WrongConstant") // custom conversion between jetpack and framework
+ @JvmStatic
+ fun fromSlice(slice: Slice): RemoteCreateEntry? {
+ // TODO("Put the right spec and version value")
+ var pendingIntent: PendingIntent? = null
+ slice.items.forEach {
+ if (it.hasHint(SLICE_HINT_PENDING_INTENT)) {
+ pendingIntent = it.action
+ }
+ }
+ return try {
+ RemoteCreateEntry(pendingIntent!!)
+ } catch (e: Exception) {
+ Log.i(TAG, "fromSlice failed with: " + e.message)
+ null
+ }
+ }
+
+ @JvmField val CREATOR: Parcelable.Creator<RemoteCreateEntry> =
+ object : Parcelable.Creator<RemoteCreateEntry> {
+ override fun createFromParcel(p0: Parcel?): RemoteCreateEntry? {
+ val createEntry = android.service.credentials.CreateEntry
+ .CREATOR.createFromParcel(p0)
+ return fromSlice(createEntry.slice)
+ }
+
+ @Suppress("ArrayReturn")
+ override fun newArray(size: Int): Array<RemoteCreateEntry?> {
+ return arrayOfNulls(size)
+ }
+ }
+ }
+ }
diff --git a/credentials/credentials/src/main/java/androidx/credentials/provider/RemoteCredentialEntry.kt b/credentials/credentials/src/main/java/androidx/credentials/provider/RemoteCredentialEntry.kt
new file mode 100644
index 0000000..382c863
--- /dev/null
+++ b/credentials/credentials/src/main/java/androidx/credentials/provider/RemoteCredentialEntry.kt
@@ -0,0 +1,118 @@
+/*
+ * 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 androidx.credentials.provider
+
+import android.annotation.SuppressLint
+import android.app.PendingIntent
+import android.app.slice.Slice
+import android.app.slice.SliceSpec
+import android.net.Uri
+import android.os.Parcel
+import android.os.Parcelable
+import android.util.Log
+import androidx.annotation.NonNull
+import androidx.annotation.RequiresApi
+import androidx.annotation.VisibleForTesting
+import androidx.credentials.PublicKeyCredential
+import java.util.Collections
+
+/**
+ * An entry on the selector, denoting that the credential will be retrieved from a remote device.
+ * A public key credential entry that is displayed on the account selector UI.
+ *
+ * Once this entry is selected, the corresponding [pendingIntent] will be invoked. The provider
+ * can then show any activity they wish to. Before finishing the activity, provider must
+ * set the final [androidx.credentials.GetCredentialResponse] through the
+ * [PendingIntentHandler.setGetCredentialResponse] helper API.
+ *
+ * @property pendingIntent the [PendingIntent] to be invoked when the user selects
+ * this entry
+ *
+ * See [android.service.credentials.CredentialsResponseContent] for usage details.
+ */
+@RequiresApi(34)
+class RemoteCredentialEntry constructor(
+ val pendingIntent: PendingIntent,
+ ) : android.service.credentials.CredentialEntry(
+ PublicKeyCredential.TYPE_PUBLIC_KEY_CREDENTIAL,
+ toSlice(PublicKeyCredential.TYPE_PUBLIC_KEY_CREDENTIAL, pendingIntent)
+ ) {
+
+ override fun describeContents(): Int {
+ return 0
+ }
+
+ override fun writeToParcel(@NonNull dest: Parcel, flags: Int) {
+ super.writeToParcel(dest, flags)
+ }
+ @Suppress("AcronymName")
+ companion object CREATOR {
+ private const val TAG = "RemoteEntry"
+
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ internal const val SLICE_HINT_PENDING_INTENT =
+ "androidx.credentials.provider.remoteEntry.SLICE_HINT_PENDING_INTENT"
+
+ /** @hide */
+ @JvmStatic
+ internal fun toSlice(type: String, pendingIntent: PendingIntent): Slice {
+ // TODO("Put the right spec and version value")
+ val sliceBuilder = Slice.Builder(Uri.EMPTY, SliceSpec(type, 1))
+ sliceBuilder.addAction(pendingIntent,
+ Slice.Builder(sliceBuilder)
+ .addHints(Collections.singletonList(SLICE_HINT_PENDING_INTENT))
+ .build(), /*subType=*/null)
+ return sliceBuilder.build()
+ }
+
+ /**
+ * Returns an instance of [RemoteCredentialEntry] derived from a [Slice] object.
+ *
+ * @param slice the [Slice] object constructed through [toSlice]
+ *
+ * @hide
+ */
+ @SuppressLint("WrongConstant") // custom conversion between jetpack and framework
+ @JvmStatic
+ fun fromSlice(slice: Slice): RemoteCredentialEntry? {
+ slice.items.forEach {
+ if (it.hasHint(SLICE_HINT_PENDING_INTENT)) {
+ return try {
+ RemoteCredentialEntry(it.action)
+ } catch (e: Exception) {
+ Log.i(TAG, "fromSlice failed with: " + e.message)
+ null
+ }
+ }
+ }
+ return null
+ }
+
+ @JvmField val CREATOR: Parcelable.Creator<RemoteCredentialEntry> = object :
+ Parcelable.Creator<RemoteCredentialEntry> {
+ override fun createFromParcel(p0: Parcel?): RemoteCredentialEntry? {
+ val baseEntry =
+ android.service.credentials.CredentialEntry.CREATOR.createFromParcel(p0)
+ return fromSlice(baseEntry.slice)
+ }
+
+ @Suppress("ArrayReturn")
+ override fun newArray(size: Int): Array<RemoteCredentialEntry?> {
+ return arrayOfNulls(size)
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/credentials/credentials/src/main/java/androidx/credentials/provider/utils/BeginCreateCredentialUtil.kt b/credentials/credentials/src/main/java/androidx/credentials/provider/utils/BeginCreateCredentialUtil.kt
new file mode 100644
index 0000000..fef103b
--- /dev/null
+++ b/credentials/credentials/src/main/java/androidx/credentials/provider/utils/BeginCreateCredentialUtil.kt
@@ -0,0 +1,70 @@
+/*
+ * 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 androidx.credentials.provider.utils
+
+import android.service.credentials.BeginCreateCredentialRequest
+import androidx.annotation.RequiresApi
+import androidx.credentials.CreatePublicKeyCredentialRequest
+import androidx.credentials.CreatePublicKeyCredentialRequestPrivileged
+import androidx.credentials.PasswordCredential
+import androidx.credentials.PublicKeyCredential
+import androidx.credentials.internal.FrameworkClassParsingException
+import androidx.credentials.provider.BeginCreateCustomCredentialRequest
+import androidx.credentials.provider.BeginCreatePasswordCredentialRequest
+import androidx.credentials.provider.BeginCreatePublicKeyCredentialRequest
+import androidx.credentials.provider.BeginCreatePublicKeyCredentialRequestPrivileged
+
+/**
+ * @hide
+ */
+@RequiresApi(34)
+class BeginCreateCredentialUtil {
+ companion object {
+ @JvmStatic
+ internal fun convertToStructuredRequest(request: BeginCreateCredentialRequest):
+ BeginCreateCredentialRequest {
+ return try {
+ when (request.type) {
+ PasswordCredential.TYPE_PASSWORD_CREDENTIAL -> {
+ BeginCreatePasswordCredentialRequest.createFrom(
+ request.data, request.callingAppInfo)
+ }
+ PublicKeyCredential.TYPE_PUBLIC_KEY_CREDENTIAL -> {
+ when (request.data.getString(PublicKeyCredential.BUNDLE_KEY_SUBTYPE)) {
+ CreatePublicKeyCredentialRequest
+ .BUNDLE_VALUE_SUBTYPE_CREATE_PUBLIC_KEY_CREDENTIAL_REQUEST ->
+ BeginCreatePublicKeyCredentialRequest.createFrom(
+ request.data, request.callingAppInfo)
+ CreatePublicKeyCredentialRequestPrivileged
+ .BUNDLE_VALUE_SUBTYPE_CREATE_PUBLIC_KEY_CREDENTIAL_REQUEST_PRIV ->
+ BeginCreatePublicKeyCredentialRequestPrivileged.createFrom(
+ request.data, request.callingAppInfo)
+ else -> throw FrameworkClassParsingException()
+ }
+ }
+ else -> {
+ BeginCreateCustomCredentialRequest(request.type, request.data,
+ request.callingAppInfo)
+ }
+ }
+ } catch (e: FrameworkClassParsingException) {
+ BeginCreateCustomCredentialRequest(request.type, request.data,
+ request.callingAppInfo)
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/credentials/credentials/src/main/java/androidx/credentials/provider/utils/BeginGetCredentialUtil.kt b/credentials/credentials/src/main/java/androidx/credentials/provider/utils/BeginGetCredentialUtil.kt
new file mode 100644
index 0000000..acc96f8
--- /dev/null
+++ b/credentials/credentials/src/main/java/androidx/credentials/provider/utils/BeginGetCredentialUtil.kt
@@ -0,0 +1,84 @@
+/*
+ * 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 androidx.credentials.provider.utils
+
+import android.os.Bundle
+import android.service.credentials.BeginGetCredentialOption
+import android.service.credentials.BeginGetCredentialRequest
+import androidx.annotation.RequiresApi
+import androidx.credentials.GetPublicKeyCredentialOption
+import androidx.credentials.GetPublicKeyCredentialOptionPrivileged
+import androidx.credentials.PasswordCredential
+import androidx.credentials.PublicKeyCredential
+import androidx.credentials.provider.BeginGetPasswordOption
+import androidx.credentials.provider.BeginGetPublicKeyCredentialOption
+import androidx.credentials.provider.BeginGetPublicKeyCredentialOptionPrivileged
+
+/**
+ * @hide
+ */
+@RequiresApi(34)
+class BeginGetCredentialUtil {
+ companion object {
+ @JvmStatic
+ internal fun convertToStructuredRequest(request: BeginGetCredentialRequest):
+ BeginGetCredentialRequest {
+ val beginGetCredentialOptions: MutableList<BeginGetCredentialOption> =
+ mutableListOf()
+ request.beginGetCredentialOptions.forEach {
+ beginGetCredentialOptions.add(convertRequestOption(
+ it.type,
+ it.candidateQueryData)
+ )
+ }
+ return BeginGetCredentialRequest.Builder(request.callingAppInfo)
+ .setBeginGetCredentialOptions(beginGetCredentialOptions)
+ .build()
+ }
+ @JvmStatic
+ internal fun convertRequestOption(type: String, candidateQueryData: Bundle):
+ BeginGetCredentialOption {
+ return when (type) {
+ PasswordCredential.TYPE_PASSWORD_CREDENTIAL -> {
+ BeginGetPasswordOption(candidateQueryData)
+ }
+ PublicKeyCredential.TYPE_PUBLIC_KEY_CREDENTIAL -> {
+ when (candidateQueryData.getString(
+ PublicKeyCredential.BUNDLE_KEY_SUBTYPE
+ )) {
+ GetPublicKeyCredentialOption
+ .BUNDLE_VALUE_SUBTYPE_GET_PUBLIC_KEY_CREDENTIAL_OPTION -> {
+ BeginGetPublicKeyCredentialOption.createFrom(candidateQueryData)
+ }
+ GetPublicKeyCredentialOptionPrivileged
+ .BUNDLE_VALUE_SUBTYPE_GET_PUBLIC_KEY_CREDENTIAL_OPTION_PRIVILEGED
+ -> {
+ BeginGetPublicKeyCredentialOptionPrivileged
+ .createFrom(candidateQueryData)
+ }
+ else -> {
+ BeginGetCredentialOption(type, candidateQueryData)
+ }
+ }
+ }
+ else -> {
+ BeginGetCredentialOption(type, candidateQueryData)
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/development/build_log_simplifier/messages.ignore b/development/build_log_simplifier/messages.ignore
index b864500..e7f049b 100644
--- a/development/build_log_simplifier/messages.ignore
+++ b/development/build_log_simplifier/messages.ignore
@@ -827,4 +827,6 @@
# > Configure project :internal-testutils-ktx
WARNING:The option setting 'android\.r8\.maxWorkers=[0-9]+' is experimental\.
# Building XCFrameworks (b/260140834) and iOS benchmark invocation
-.*xcodebuild.*
\ No newline at end of file
+.*xcodebuild.*
+Observed package id 'platforms;android-33-ext4' in inconsistent location.*
+.*xcodebuild.*
diff --git a/development/studio/idea.properties b/development/studio/idea.properties
index f352237..3cabbbf 100644
--- a/development/studio/idea.properties
+++ b/development/studio/idea.properties
@@ -5,12 +5,12 @@
#---------------------------------------------------------------------
# Uncomment this option if you want to customize path to IDE config folder. Make sure you're using forward slashes.
#---------------------------------------------------------------------
-idea.config.path=${user.home}/.AndroidStudioAndroidX/config
+idea.config.path=${user.home}/.AndroidStudioAndroidXPlatform/config
#---------------------------------------------------------------------
# Uncomment this option if you want to customize path to IDE system folder. Make sure you're using forward slashes.
#---------------------------------------------------------------------
-idea.system.path=${user.home}/.AndroidStudioAndroidX/system
+idea.system.path=${user.home}/.AndroidStudioAndroidXPlatform/system
#---------------------------------------------------------------------
# Uncomment this option if you want to customize path to user installed plugins folder. Make sure you're using forward slashes.
diff --git a/docs-public/build.gradle b/docs-public/build.gradle
index 3fad297..c852a55 100644
--- a/docs-public/build.gradle
+++ b/docs-public/build.gradle
@@ -244,6 +244,10 @@
docs("androidx.preference:preference:1.2.0")
docs("androidx.preference:preference-ktx:1.2.0")
docs("androidx.print:print:1.1.0-beta01")
+ docs("androidx.privacysandbox.ads:ads-adservices:1.0.0-alpha01")
+ docs("androidx.privacysandbox.ads:ads-adservices-java:1.0.0-alpha01")
+ docs("androidx.privacysandbox.sdkruntime:sdkruntime-client:1.0.0-alpha01")
+ docs("androidx.privacysandbox.sdkruntime:sdkruntime-core:1.0.0-alpha01")
docs("androidx.privacysandbox.tools:tools:1.0.0-alpha02")
docs("androidx.privacysandbox.tools:tools-apigenerator:1.0.0-alpha02")
docs("androidx.privacysandbox.tools:tools-apipackager:1.0.0-alpha02")
diff --git a/docs-tip-of-tree/build.gradle b/docs-tip-of-tree/build.gradle
index 498ff9f..fbe8767 100644
--- a/docs-tip-of-tree/build.gradle
+++ b/docs-tip-of-tree/build.gradle
@@ -170,6 +170,7 @@
docs(project(":glance:glance-wear-tiles"))
docs(project(":graphics:filters:filters"))
docs(project(":graphics:graphics-core"))
+ docs(project(":graphics:graphics-path"))
docs(project(":graphics:graphics-shapes"))
docs(project(":gridlayout:gridlayout"))
docs(project(":health:connect:connect-client"))
@@ -356,6 +357,7 @@
docs(project(":wear:watchface:watchface-style"))
docs(project(":webkit:webkit"))
docs(project(":window:window"))
+ samples(project(":window:window-samples"))
docs(project(":window:window-core"))
docs(project(":window:window-java"))
docs(project(":window:window-rxjava2"))
diff --git a/drawerlayout/drawerlayout/api/api_lint.ignore b/drawerlayout/drawerlayout/api/api_lint.ignore
index be4e831..69b398e 100644
--- a/drawerlayout/drawerlayout/api/api_lint.ignore
+++ b/drawerlayout/drawerlayout/api/api_lint.ignore
@@ -3,12 +3,6 @@
Parameter type is concrete collection (`java.util.ArrayList`); must be higher-level interface
-InvalidNullabilityOverride: androidx.drawerlayout.widget.DrawerLayout#drawChild(android.graphics.Canvas, android.view.View, long) parameter #0:
- Invalid nullability on parameter `canvas` in method `drawChild`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
-InvalidNullabilityOverride: androidx.drawerlayout.widget.DrawerLayout#onDraw(android.graphics.Canvas) parameter #0:
- Invalid nullability on parameter `c` in method `onDraw`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
-
-
ListenerInterface: androidx.drawerlayout.widget.DrawerLayout.SimpleDrawerListener:
Listeners should be an interface, or otherwise renamed Callback: SimpleDrawerListener
@@ -23,6 +17,8 @@
Missing nullability on parameter `p` in method `checkLayoutParams`
MissingNullability: androidx.drawerlayout.widget.DrawerLayout#dispatchGenericMotionEvent(android.view.MotionEvent) parameter #0:
Missing nullability on parameter `event` in method `dispatchGenericMotionEvent`
+MissingNullability: androidx.drawerlayout.widget.DrawerLayout#drawChild(android.graphics.Canvas, android.view.View, long) parameter #0:
+ Missing nullability on parameter `canvas` in method `drawChild`
MissingNullability: androidx.drawerlayout.widget.DrawerLayout#drawChild(android.graphics.Canvas, android.view.View, long) parameter #1:
Missing nullability on parameter `child` in method `drawChild`
MissingNullability: androidx.drawerlayout.widget.DrawerLayout#generateDefaultLayoutParams():
@@ -35,6 +31,8 @@
Missing nullability on method `generateLayoutParams` return
MissingNullability: androidx.drawerlayout.widget.DrawerLayout#generateLayoutParams(android.view.ViewGroup.LayoutParams) parameter #0:
Missing nullability on parameter `p` in method `generateLayoutParams`
+MissingNullability: androidx.drawerlayout.widget.DrawerLayout#onDraw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `c` in method `onDraw`
MissingNullability: androidx.drawerlayout.widget.DrawerLayout#onInterceptTouchEvent(android.view.MotionEvent) parameter #0:
Missing nullability on parameter `ev` in method `onInterceptTouchEvent`
MissingNullability: androidx.drawerlayout.widget.DrawerLayout#onKeyDown(int, android.view.KeyEvent) parameter #1:
diff --git a/emoji2/emoji2-emojipicker/src/main/java/androidx/emoji2/emojipicker/PopupViewHelper.kt b/emoji2/emoji2-emojipicker/src/main/java/androidx/emoji2/emojipicker/PopupViewHelper.kt
index 8038e48..9548eeb 100644
--- a/emoji2/emoji2-emojipicker/src/main/java/androidx/emoji2/emojipicker/PopupViewHelper.kt
+++ b/emoji2/emoji2-emojipicker/src/main/java/androidx/emoji2/emojipicker/PopupViewHelper.kt
@@ -167,9 +167,9 @@
private val radius = resources.getDimension(R.dimen.emoji_picker_skin_tone_circle_radius)
var paint: Paint? = null
- override fun draw(canvas: Canvas?) {
+ override fun draw(canvas: Canvas) {
super.draw(canvas)
- canvas?.apply {
+ canvas.apply {
paint?.let { drawCircle(width / 2f, height / 2f, radius, it) }
}
}
diff --git a/gradle.properties b/gradle.properties
index 5868acd..9c964b3 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -23,10 +23,10 @@
android.experimental.lint.missingBaselineIsEmptyBaseline=true
# Don't generate versioned API files
-androidx.writeVersionedApiFiles=true
+androidx.writeVersionedApiFiles=false
-# Do restrict compileSdkPreview usage
-androidx.allowCustomCompileSdk=false
+# Don't restrict compileSdkPreview usage
+androidx.allowCustomCompileSdk=true
# Don't warn about needing to update AGP
android.suppressUnsupportedCompileSdk=Tiramisu,33
diff --git a/graphics/OWNERS b/graphics/OWNERS
index 9ba9c32..db046a2 100644
--- a/graphics/OWNERS
+++ b/graphics/OWNERS
@@ -1,4 +1,5 @@
# Bug component: 1137062
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
\ No newline at end of file
diff --git a/graphics/graphics-path/api/current.txt b/graphics/graphics-path/api/current.txt
new file mode 100644
index 0000000..fd31e61
--- /dev/null
+++ b/graphics/graphics-path/api/current.txt
@@ -0,0 +1,36 @@
+// Signature format: 4.0
+package androidx.graphics.path {
+
+ public final class PathSegment {
+ method public android.graphics.PointF![] getPoints();
+ method public androidx.graphics.path.PathSegment.Type getType();
+ method public float getWeight();
+ property public final android.graphics.PointF![] points;
+ property public final androidx.graphics.path.PathSegment.Type type;
+ property public final float weight;
+ }
+
+ public enum PathSegment.Type {
+ method public static androidx.graphics.path.PathSegment.Type valueOf(String name) throws java.lang.IllegalArgumentException;
+ method public static androidx.graphics.path.PathSegment.Type[] values();
+ enum_constant public static final androidx.graphics.path.PathSegment.Type Close;
+ enum_constant public static final androidx.graphics.path.PathSegment.Type Conic;
+ enum_constant public static final androidx.graphics.path.PathSegment.Type Cubic;
+ enum_constant public static final androidx.graphics.path.PathSegment.Type Done;
+ enum_constant public static final androidx.graphics.path.PathSegment.Type Line;
+ enum_constant public static final androidx.graphics.path.PathSegment.Type Move;
+ enum_constant public static final androidx.graphics.path.PathSegment.Type Quadratic;
+ }
+
+ public final class PathSegmentUtilities {
+ method public static androidx.graphics.path.PathSegment getCloseSegment();
+ method public static androidx.graphics.path.PathSegment getDoneSegment();
+ property public static final androidx.graphics.path.PathSegment CloseSegment;
+ property public static final androidx.graphics.path.PathSegment DoneSegment;
+ }
+
+ public final class PathUtilities {
+ }
+
+}
+
diff --git a/graphics/graphics-path/api/public_plus_experimental_current.txt b/graphics/graphics-path/api/public_plus_experimental_current.txt
new file mode 100644
index 0000000..9be3390
--- /dev/null
+++ b/graphics/graphics-path/api/public_plus_experimental_current.txt
@@ -0,0 +1,61 @@
+// Signature format: 4.0
+package androidx.graphics.path {
+
+ @androidx.core.os.BuildCompat.PrereleaseSdkCheck public final class PathIterator implements java.util.Iterator<androidx.graphics.path.PathSegment> kotlin.jvm.internal.markers.KMappedMarker {
+ ctor public PathIterator(android.graphics.Path path, optional androidx.graphics.path.PathIterator.ConicEvaluation conicEvaluation, optional float tolerance);
+ method public int calculateSize(optional boolean includeConvertedConics);
+ method public androidx.graphics.path.PathIterator.ConicEvaluation getConicEvaluation();
+ method public android.graphics.Path getPath();
+ method public float getTolerance();
+ method public boolean hasNext();
+ method public androidx.graphics.path.PathSegment.Type next(float[] points, optional int offset);
+ method public androidx.graphics.path.PathSegment.Type next(float[] points);
+ method public androidx.graphics.path.PathSegment next();
+ method public androidx.graphics.path.PathSegment.Type peek();
+ property public final androidx.graphics.path.PathIterator.ConicEvaluation conicEvaluation;
+ property public final android.graphics.Path path;
+ property public final float tolerance;
+ }
+
+ public enum PathIterator.ConicEvaluation {
+ method public static androidx.graphics.path.PathIterator.ConicEvaluation valueOf(String name) throws java.lang.IllegalArgumentException;
+ method public static androidx.graphics.path.PathIterator.ConicEvaluation[] values();
+ enum_constant public static final androidx.graphics.path.PathIterator.ConicEvaluation AsConic;
+ enum_constant public static final androidx.graphics.path.PathIterator.ConicEvaluation AsQuadratics;
+ }
+
+ public final class PathSegment {
+ method public android.graphics.PointF![] getPoints();
+ method public androidx.graphics.path.PathSegment.Type getType();
+ method public float getWeight();
+ property public final android.graphics.PointF![] points;
+ property public final androidx.graphics.path.PathSegment.Type type;
+ property public final float weight;
+ }
+
+ public enum PathSegment.Type {
+ method public static androidx.graphics.path.PathSegment.Type valueOf(String name) throws java.lang.IllegalArgumentException;
+ method public static androidx.graphics.path.PathSegment.Type[] values();
+ enum_constant public static final androidx.graphics.path.PathSegment.Type Close;
+ enum_constant public static final androidx.graphics.path.PathSegment.Type Conic;
+ enum_constant public static final androidx.graphics.path.PathSegment.Type Cubic;
+ enum_constant public static final androidx.graphics.path.PathSegment.Type Done;
+ enum_constant public static final androidx.graphics.path.PathSegment.Type Line;
+ enum_constant public static final androidx.graphics.path.PathSegment.Type Move;
+ enum_constant public static final androidx.graphics.path.PathSegment.Type Quadratic;
+ }
+
+ public final class PathSegmentUtilities {
+ method public static androidx.graphics.path.PathSegment getCloseSegment();
+ method public static androidx.graphics.path.PathSegment getDoneSegment();
+ property public static final androidx.graphics.path.PathSegment CloseSegment;
+ property public static final androidx.graphics.path.PathSegment DoneSegment;
+ }
+
+ public final class PathUtilities {
+ method @androidx.core.os.BuildCompat.PrereleaseSdkCheck public static operator androidx.graphics.path.PathIterator iterator(android.graphics.Path);
+ method @androidx.core.os.BuildCompat.PrereleaseSdkCheck public static androidx.graphics.path.PathIterator iterator(android.graphics.Path, androidx.graphics.path.PathIterator.ConicEvaluation conicEvaluation, optional float tolerance);
+ }
+
+}
+
diff --git a/webkit/webkit/api/res-1.6.0-beta02.txt b/graphics/graphics-path/api/res-current.txt
similarity index 100%
rename from webkit/webkit/api/res-1.6.0-beta02.txt
rename to graphics/graphics-path/api/res-current.txt
diff --git a/graphics/graphics-path/api/restricted_current.txt b/graphics/graphics-path/api/restricted_current.txt
new file mode 100644
index 0000000..fd31e61
--- /dev/null
+++ b/graphics/graphics-path/api/restricted_current.txt
@@ -0,0 +1,36 @@
+// Signature format: 4.0
+package androidx.graphics.path {
+
+ public final class PathSegment {
+ method public android.graphics.PointF![] getPoints();
+ method public androidx.graphics.path.PathSegment.Type getType();
+ method public float getWeight();
+ property public final android.graphics.PointF![] points;
+ property public final androidx.graphics.path.PathSegment.Type type;
+ property public final float weight;
+ }
+
+ public enum PathSegment.Type {
+ method public static androidx.graphics.path.PathSegment.Type valueOf(String name) throws java.lang.IllegalArgumentException;
+ method public static androidx.graphics.path.PathSegment.Type[] values();
+ enum_constant public static final androidx.graphics.path.PathSegment.Type Close;
+ enum_constant public static final androidx.graphics.path.PathSegment.Type Conic;
+ enum_constant public static final androidx.graphics.path.PathSegment.Type Cubic;
+ enum_constant public static final androidx.graphics.path.PathSegment.Type Done;
+ enum_constant public static final androidx.graphics.path.PathSegment.Type Line;
+ enum_constant public static final androidx.graphics.path.PathSegment.Type Move;
+ enum_constant public static final androidx.graphics.path.PathSegment.Type Quadratic;
+ }
+
+ public final class PathSegmentUtilities {
+ method public static androidx.graphics.path.PathSegment getCloseSegment();
+ method public static androidx.graphics.path.PathSegment getDoneSegment();
+ property public static final androidx.graphics.path.PathSegment CloseSegment;
+ property public static final androidx.graphics.path.PathSegment DoneSegment;
+ }
+
+ public final class PathUtilities {
+ }
+
+}
+
diff --git a/graphics/graphics-path/build.gradle b/graphics/graphics-path/build.gradle
new file mode 100644
index 0000000..ddf300a
--- /dev/null
+++ b/graphics/graphics-path/build.gradle
@@ -0,0 +1,87 @@
+/*
+ * 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.
+ */
+
+import androidx.build.LibraryType
+
+plugins {
+ id("AndroidXPlugin")
+ id("com.android.library")
+ id("kotlin-android")
+}
+
+dependencies {
+ api(libs.kotlinStdlib)
+ androidTestImplementation(project(':appcompat:appcompat'))
+
+ implementation(project(':appcompat:appcompat'))
+ implementation('androidx.core:core:1.5.0-beta01')
+
+ androidTestImplementation("androidx.annotation:annotation:1.4.0")
+ androidTestImplementation("androidx.core:core-ktx:1.8.0")
+ androidTestImplementation("androidx.test:core:1.4.0@aar")
+ androidTestImplementation(libs.testExtJunit)
+ androidTestImplementation(libs.testCore)
+ androidTestImplementation(libs.testRunner)
+ androidTestImplementation(libs.testRules)
+ androidTestImplementation(libs.truth)
+}
+
+android {
+ namespace "androidx.graphics.path"
+
+ defaultConfig {
+ minSdkVersion 21 // Limited to 21+ due to native changes before that release
+ externalNativeBuild {
+ cmake {
+ cppFlags.addAll(
+ [
+ "-std=c++17",
+ "-Wno-unused-command-line-argument",
+ "-Wl,--hash-style=both", // Required to support API levels below 23
+ "-fno-stack-protector",
+ "-fno-exceptions",
+ "-fno-unwind-tables",
+ "-fno-asynchronous-unwind-tables",
+ "-fno-rtti",
+ "-ffast-math",
+ "-ffp-contract=fast",
+ "-fvisibility-inlines-hidden",
+ "-fvisibility=hidden",
+ "-fomit-frame-pointer",
+ "-ffunction-sections",
+ "-fdata-sections",
+ "-Wl,--gc-sections",
+ "-Wl,-Bsymbolic-functions",
+ ])
+ }
+ }
+ }
+
+ externalNativeBuild {
+ cmake {
+ path file('src/main/cpp/CMakeLists.txt')
+ version libs.versions.cmake.get()
+ }
+ }
+
+}
+
+androidx {
+ name = "Android Graphics Path"
+ type = LibraryType.PUBLISHED_LIBRARY
+ inceptionYear = "2022"
+ description = "Query segment data for android.graphics.Path objects"
+}
diff --git a/graphics/graphics-path/src/androidTest/java/androidx/graphics/path/PathIteratorTest.kt b/graphics/graphics-path/src/androidTest/java/androidx/graphics/path/PathIteratorTest.kt
new file mode 100644
index 0000000..5a58802
--- /dev/null
+++ b/graphics/graphics-path/src/androidTest/java/androidx/graphics/path/PathIteratorTest.kt
@@ -0,0 +1,544 @@
+/*
+ * 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 androidx.graphics.path
+
+import android.graphics.Bitmap
+import android.graphics.Color
+import android.graphics.Paint
+import android.graphics.Path
+import android.graphics.PointF
+import android.graphics.RectF
+import android.os.Build
+import androidx.core.graphics.applyCanvas
+import androidx.core.graphics.createBitmap
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import kotlin.math.abs
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Assert.fail
+import org.junit.Test
+import org.junit.runner.RunWith
+
+private fun assertPointsEquals(p1: PointF, p2: PointF) {
+ assertEquals(p1.x, p2.x, 1e-6f)
+ assertEquals(p1.y, p2.y, 1e-6f)
+}
+
+private fun assertPointsEquals(p1: FloatArray, offset: Int, p2: PointF) {
+ assertEquals(p1[0 + offset * 2], p2.x, 1e-6f)
+ assertEquals(p1[1 + offset * 2], p2.y, 1e-6f)
+}
+
+private fun compareBitmaps(b1: Bitmap, b2: Bitmap) {
+ val epsilon: Int
+ if (Build.VERSION.SDK_INT != 23) {
+ epsilon = 1
+ } else {
+ // There is more AA variability between conics and cubics on API 23, leading
+ // to failures on relatively small visual differences. Increase the error
+ // value for just this release to avoid erroneous bitmap comparison failures.
+ epsilon = 32
+ }
+
+ assertEquals(b1.width, b2.width)
+ assertEquals(b1.height, b2.height)
+
+ val p1 = IntArray(b1.width * b1.height)
+ b1.getPixels(p1, 0, b1.width, 0, 0, b1.width, b1.height)
+
+ val p2 = IntArray(b2.width * b2.height)
+ b2.getPixels(p2, 0, b2.width, 0, 0, b2.width, b2.height)
+
+ for (x in 0 until b1.width) {
+ for (y in 0 until b2.width) {
+ val index = y * b1.width + x
+
+ val c1 = p1[index]
+ val c2 = p2[index]
+
+ assertTrue(abs(Color.red(c1) - Color.red(c2)) <= epsilon)
+ assertTrue(abs(Color.green(c1) - Color.green(c2)) <= epsilon)
+ assertTrue(abs(Color.blue(c1) - Color.blue(c2)) <= epsilon)
+ }
+ }
+}
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class PathIteratorTest {
+ @Test
+ fun emptyIterator() {
+ val path = Path()
+
+ val iterator = path.iterator()
+ // TODO: un-comment the hasNext() check when the platform has the behavior change
+ // which ignores final DONE ops in the value for hasNext()
+ // assertFalse(iterator.hasNext())
+ val firstSegment = iterator.next()
+ assertEquals(PathSegment.Type.Done, firstSegment.type)
+
+ var count = 0
+ for (segment in path) {
+ // TODO: remove condition check and just increment count when platform change
+ // is checked in which will not iterate when DONE is the only op left
+ if (segment.type != PathSegment.Type.Done) {
+ // Shouldn't get here; count should remain 0
+ count++
+ }
+ }
+
+ assertEquals(0, count)
+ }
+
+ @Test
+ fun emptyPeek() {
+ val path = Path()
+ val iterator = path.iterator()
+ assertEquals(PathSegment.Type.Done, iterator.peek())
+ }
+
+ @Test
+ fun nonEmptyIterator() {
+ val path = Path().apply {
+ moveTo(1.0f, 1.0f)
+ lineTo(2.0f, 2.0f)
+ close()
+ }
+
+ val iterator = path.iterator()
+ assertTrue(iterator.hasNext())
+
+ val types = arrayOf(
+ PathSegment.Type.Move,
+ PathSegment.Type.Line,
+ PathSegment.Type.Close,
+ PathSegment.Type.Done
+ )
+ val points = arrayOf(
+ PointF(1.0f, 1.0f),
+ PointF(2.0f, 2.0f)
+ )
+
+ var count = 0
+ for (segment in path) {
+ assertEquals(types[count], segment.type)
+ when (segment.type) {
+ PathSegment.Type.Move -> {
+ assertEquals(points[count], segment.points[0])
+ }
+ PathSegment.Type.Line -> {
+ assertEquals(points[count - 1], segment.points[0])
+ assertEquals(points[count], segment.points[1])
+ }
+ else -> { }
+ }
+ // TODO: remove condition and just auto-increment count when platform change is
+ // checked in which ignores DONE during iteration
+ if (segment.type != PathSegment.Type.Done) count++
+ }
+
+ assertEquals(3, count)
+ }
+
+ @Test
+ fun peek() {
+ val path = Path().apply {
+ moveTo(1.0f, 1.0f)
+ lineTo(2.0f, 2.0f)
+ close()
+ }
+
+ val iterator = path.iterator()
+ assertEquals(PathSegment.Type.Move, iterator.peek())
+ }
+
+ @Test
+ fun peekBeyond() {
+ val path = Path()
+ assertEquals(PathSegment.Type.Done, path.iterator().peek())
+
+ path.apply {
+ moveTo(1.0f, 1.0f)
+ lineTo(2.0f, 2.0f)
+ close()
+ }
+
+ val iterator = path.iterator()
+ while (iterator.hasNext()) iterator.next()
+ assertEquals(PathSegment.Type.Done, iterator.peek())
+ }
+
+ @Test
+ fun iteratorStyles() {
+ val path = Path().apply {
+ moveTo(1.0f, 1.0f)
+ lineTo(2.0f, 2.0f)
+ cubicTo(3.0f, 3.0f, 4.0f, 4.0f, 5.0f, 5.0f)
+ quadTo(7.0f, 7.0f, 8.0f, 8.0f)
+ moveTo(10.0f, 10.0f)
+ // addRoundRect() will generate conic curves on certain API levels
+ addRoundRect(RectF(12.0f, 12.0f, 36.0f, 36.0f), 8.0f, 8.0f, Path.Direction.CW)
+ close()
+ }
+
+ iteratorStylesImpl(path, PathIterator.ConicEvaluation.AsConic)
+ iteratorStylesImpl(path, PathIterator.ConicEvaluation.AsQuadratics)
+ }
+
+ private fun iteratorStylesImpl(path: Path, conicEvaluation: PathIterator.ConicEvaluation) {
+ val iterator1 = path.iterator(conicEvaluation)
+ val iterator2 = path.iterator(conicEvaluation)
+ val iterator3 = path.iterator(conicEvaluation)
+
+ val points = FloatArray(8)
+ val points2 = FloatArray(16)
+
+ while (iterator1.hasNext() || iterator2.hasNext() || iterator3.hasNext()) {
+ val segment = iterator1.next()
+ val type = iterator2.next(points)
+ val type2 = iterator3.next(points2, 8)
+
+ assertEquals(type, segment.type)
+ assertEquals(type2, segment.type)
+
+ when (type) {
+ PathSegment.Type.Move -> {
+ assertPointsEquals(points, 0, segment.points[0])
+ assertPointsEquals(points2, 4, segment.points[0])
+ }
+
+ PathSegment.Type.Line -> {
+ assertPointsEquals(points, 0, segment.points[0])
+ assertPointsEquals(points, 1, segment.points[1])
+ assertPointsEquals(points2, 4, segment.points[0])
+ assertPointsEquals(points2, 5, segment.points[1])
+ }
+
+ PathSegment.Type.Quadratic -> {
+ assertPointsEquals(points, 0, segment.points[0])
+ assertPointsEquals(points, 1, segment.points[1])
+ assertPointsEquals(points, 2, segment.points[2])
+ assertPointsEquals(points2, 4, segment.points[0])
+ assertPointsEquals(points2, 5, segment.points[1])
+ assertPointsEquals(points2, 6, segment.points[2])
+ }
+
+ PathSegment.Type.Conic -> {
+ assertPointsEquals(points, 0, segment.points[0])
+ assertPointsEquals(points, 1, segment.points[1])
+ assertPointsEquals(points, 2, segment.points[2])
+ // Weight is stored after all of the points
+ assertEquals(points[6], segment.weight)
+
+ assertPointsEquals(points2, 4, segment.points[0])
+ assertPointsEquals(points2, 5, segment.points[1])
+ assertPointsEquals(points2, 6, segment.points[2])
+ // Weight is stored after all of the points
+ assertEquals(points2[14], segment.weight)
+ }
+
+ PathSegment.Type.Cubic -> {
+ assertPointsEquals(points, 0, segment.points[0])
+ assertPointsEquals(points, 1, segment.points[1])
+ assertPointsEquals(points, 2, segment.points[2])
+ assertPointsEquals(points, 3, segment.points[3])
+
+ assertPointsEquals(points2, 4, segment.points[0])
+ assertPointsEquals(points2, 5, segment.points[1])
+ assertPointsEquals(points2, 6, segment.points[2])
+ assertPointsEquals(points2, 7, segment.points[3])
+ }
+
+ PathSegment.Type.Close -> {}
+ PathSegment.Type.Done -> {}
+ }
+ }
+ }
+
+ @Test
+ fun done() {
+ val path = Path().apply {
+ close()
+ }
+
+ val segment = path.iterator().next()
+
+ assertEquals(PathSegment.Type.Done, segment.type)
+ assertEquals(0, segment.points.size)
+ assertEquals(0.0f, segment.weight)
+ }
+
+ @Test
+ fun close() {
+ val path = Path().apply {
+ lineTo(10.0f, 12.0f)
+ close()
+ }
+
+ val iterator = path.iterator()
+ // Swallow the move
+ iterator.next()
+ // Swallow the line
+ iterator.next()
+
+ val segment = iterator.next()
+
+ assertEquals(PathSegment.Type.Close, segment.type)
+ assertEquals(0, segment.points.size)
+ assertEquals(0.0f, segment.weight)
+ }
+
+ @Test
+ fun moveTo() {
+ val path = Path().apply {
+ moveTo(10.0f, 12.0f)
+ }
+
+ val segment = path.iterator().next()
+
+ assertEquals(PathSegment.Type.Move, segment.type)
+ assertEquals(1, segment.points.size)
+ assertPointsEquals(PointF(10.0f, 12.0f), segment.points[0])
+ assertEquals(0.0f, segment.weight)
+ }
+
+ @Test
+ fun lineTo() {
+ val path = Path().apply {
+ moveTo(4.0f, 6.0f)
+ lineTo(10.0f, 12.0f)
+ }
+
+ val iterator = path.iterator()
+ // Swallow the move
+ iterator.next()
+
+ val segment = iterator.next()
+
+ assertEquals(PathSegment.Type.Line, segment.type)
+ assertEquals(2, segment.points.size)
+ assertPointsEquals(PointF(4.0f, 6.0f), segment.points[0])
+ assertPointsEquals(PointF(10.0f, 12.0f), segment.points[1])
+ assertEquals(0.0f, segment.weight)
+ }
+
+ @Test
+ fun quadraticTo() {
+ val path = Path().apply {
+ moveTo(4.0f, 6.0f)
+ quadTo(10.0f, 12.0f, 20.0f, 24.0f)
+ }
+
+ val iterator = path.iterator()
+ // Swallow the move
+ iterator.next()
+
+ val segment = iterator.next()
+
+ assertEquals(PathSegment.Type.Quadratic, segment.type)
+ assertEquals(3, segment.points.size)
+ assertPointsEquals(PointF(4.0f, 6.0f), segment.points[0])
+ assertPointsEquals(PointF(10.0f, 12.0f), segment.points[1])
+ assertPointsEquals(PointF(20.0f, 24.0f), segment.points[2])
+ assertEquals(0.0f, segment.weight)
+ }
+
+ @Test
+ fun cubicTo() {
+ val path = Path().apply {
+ moveTo(4.0f, 6.0f)
+ cubicTo(10.0f, 12.0f, 20.0f, 24.0f, 30.0f, 36.0f)
+ }
+
+ val iterator = path.iterator()
+ // Swallow the move
+ iterator.next()
+
+ val segment = iterator.next()
+
+ assertEquals(PathSegment.Type.Cubic, segment.type)
+ assertEquals(4, segment.points.size)
+ assertPointsEquals(PointF(4.0f, 6.0f), segment.points[0])
+ assertPointsEquals(PointF(10.0f, 12.0f), segment.points[1])
+ assertPointsEquals(PointF(20.0f, 24.0f), segment.points[2])
+ assertPointsEquals(PointF(30.0f, 36.0f), segment.points[3])
+ assertEquals(0.0f, segment.weight)
+ }
+
+ @Test
+ fun conicTo() {
+ if (Build.VERSION.SDK_INT >= 25) {
+ val path = Path().apply {
+ addRoundRect(RectF(12.0f, 12.0f, 24.0f, 24.0f), 8.0f, 8.0f, Path.Direction.CW)
+ }
+
+ val iterator = path.iterator(PathIterator.ConicEvaluation.AsConic)
+ // Swallow the move
+ iterator.next()
+
+ val segment = iterator.next()
+
+ assertEquals(PathSegment.Type.Conic, segment.type)
+ assertEquals(3, segment.points.size)
+
+ assertPointsEquals(PointF(12.0f, 18.0f), segment.points[0])
+ assertPointsEquals(PointF(12.0f, 12.0f), segment.points[1])
+ assertPointsEquals(PointF(18.0f, 12.0f), segment.points[2])
+ assertEquals(0.70710677f, segment.weight)
+ }
+ }
+
+ @Test
+ fun conicAsQuadratics() {
+ val path = Path().apply {
+ addRoundRect(RectF(12.0f, 12.0f, 24.0f, 24.0f), 8.0f, 8.0f, Path.Direction.CW)
+ }
+
+ for (segment in path) {
+ if (segment.type == PathSegment.Type.Conic) fail("Found conic, none expected: $segment")
+ }
+ }
+
+ @Test
+ fun convertedConics() {
+ val path1 = Path().apply {
+ addRoundRect(RectF(12.0f, 12.0f, 64.0f, 64.0f), 12.0f, 12.0f, Path.Direction.CW)
+ }
+
+ val path2 = Path()
+ for (segment in path1) {
+ when (segment.type) {
+ PathSegment.Type.Move -> path2.moveTo(segment.points[0].x, segment.points[0].y)
+ PathSegment.Type.Line -> path2.lineTo(segment.points[1].x, segment.points[1].y)
+ PathSegment.Type.Quadratic -> path2.quadTo(
+ segment.points[1].x, segment.points[1].y,
+ segment.points[2].x, segment.points[2].y
+ )
+ PathSegment.Type.Conic -> fail("Unexpected conic! $segment")
+ PathSegment.Type.Cubic -> path2.cubicTo(
+ segment.points[1].x, segment.points[1].y,
+ segment.points[2].x, segment.points[2].y,
+ segment.points[3].x, segment.points[3].y
+ )
+ PathSegment.Type.Close -> path2.close()
+ PathSegment.Type.Done -> { }
+ }
+ }
+
+ // Now with smaller error tolerance
+ val path3 = Path()
+ for (segment in path1.iterator(
+ conicEvaluation = PathIterator.ConicEvaluation.AsQuadratics,
+ .001f
+ )) {
+ when (segment.type) {
+ PathSegment.Type.Move -> path3.moveTo(segment.points[0].x, segment.points[0].y)
+ PathSegment.Type.Line -> path3.lineTo(segment.points[1].x, segment.points[1].y)
+ PathSegment.Type.Quadratic -> path3.quadTo(
+ segment.points[1].x, segment.points[1].y,
+ segment.points[2].x, segment.points[2].y
+ )
+ PathSegment.Type.Conic -> fail("Unexpected conic! $segment")
+ PathSegment.Type.Cubic -> path3.cubicTo(
+ segment.points[1].x, segment.points[1].y,
+ segment.points[2].x, segment.points[2].y,
+ segment.points[3].x, segment.points[3].y
+ )
+ PathSegment.Type.Close -> path3.close()
+ PathSegment.Type.Done -> { }
+ }
+ }
+
+ val b1 = createBitmap(76, 76).applyCanvas {
+ drawARGB(255, 255, 255, 255)
+ drawPath(path1, Paint().apply {
+ color = argb(1.0f, 0.0f, 0.0f, 1.0f)
+ strokeWidth = 2.0f
+ isAntiAlias = true
+ style = Paint.Style.STROKE
+ })
+ }
+
+ val b2 = createBitmap(76, 76).applyCanvas {
+ drawARGB(255, 255, 255, 255)
+ drawPath(path2, Paint().apply {
+ color = argb(1.0f, 0.0f, 0.0f, 1.0f)
+ strokeWidth = 2.0f
+ isAntiAlias = true
+ style = Paint.Style.STROKE
+ })
+ }
+
+ compareBitmaps(b1, b2)
+ // Note: b1-vs-b3 is not a valid comparison; default Skia rendering does not use an
+ // error tolerance that low. The test for fine-precision in path3 was just to
+ // ensure that the system could handle the extra data and operations required
+ }
+
+ @Test
+ fun sizes() {
+ val path = Path()
+ var iterator: PathIterator = path.iterator()
+
+ if (iterator.calculateSize() > 0) {
+ assertEquals(PathSegment.Type.Done, iterator.peek())
+ }
+ // TODO: replace above check with below assertEquals after platform change is checked
+ // in which returns a size of zero when there the only op in the path is DONE
+ // assertEquals(0, iterator.size())
+
+ path.addRoundRect(RectF(12.0f, 12.0f, 64.0f, 64.0f), 8.0f, 8.0f,
+ Path.Direction.CW)
+
+ // Skia converted
+ if (Build.VERSION.SDK_INT > 22) {
+ // Preserve conics and count
+ iterator = path.iterator(PathIterator.ConicEvaluation.AsConic)
+ assert(iterator.calculateSize() == 10 || iterator.calculateSize() == 11)
+ // TODO: replace assert() above with assertEquals below once platform change exists
+ // which does not count final DONE in the size
+ // assertEquals(10, iterator.size())
+ assertEquals(iterator.calculateSize(true), iterator.calculateSize())
+ }
+
+ // Convert conics and count
+ iterator = path.iterator(PathIterator.ConicEvaluation.AsQuadratics)
+ if (Build.VERSION.SDK_INT > 22) {
+ // simple size, not including conic conversion
+ assert(iterator.calculateSize(false) == 10 || iterator.calculateSize(false) == 11)
+ // TODO: replace assert() above with assertEquals below once platform change exists
+ // which does not count final DONE in the size
+ // assertEquals(10, iterator.size(false))
+ } else {
+ // round rects pre-API22 used line/quad/quad for each corner
+ assertEquals(14, iterator.calculateSize())
+ }
+ // now get the size with converted conics
+ val size = iterator.calculateSize()
+ assert(size == 14 || size == 15)
+ // TODO: replace assert() above with assertEquals below once platform change exists
+ // which does not count final DONE in the size
+ // assertEquals(14, iterator.size())
+ }
+}
+
+fun argb(alpha: Float, red: Float, green: Float, blue: Float) =
+ ((alpha * 255.0f + 0.5f).toInt() shl 24) or
+ ((red * 255.0f + 0.5f).toInt() shl 16) or
+ ((green * 255.0f + 0.5f).toInt() shl 8) or
+ (blue * 255.0f + 0.5f).toInt()
diff --git a/graphics/graphics-path/src/main/androidx/graphics/androidx-graphics-graphics-path-documentation.md b/graphics/graphics-path/src/main/androidx/graphics/androidx-graphics-graphics-path-documentation.md
new file mode 100644
index 0000000..6c44750
--- /dev/null
+++ b/graphics/graphics-path/src/main/androidx/graphics/androidx-graphics-graphics-path-documentation.md
@@ -0,0 +1,117 @@
+# Package androidx.graphics.paths
+
+Androidx Graphics Path is an Android library that provides new functionalities around the
+[Path](https://developer.android.com/reference/android/graphics/Path) API. Specifically, it
+allows paths to be queried for the segment data they contain,
+
+The library is compatible with API 21+.
+
+## Iterating over a Path
+
+With Pathway you can easily iterate over a `Path` object to inspect its segments
+(curves or commands):
+
+```kotlin
+val path = Path().apply {
+ // Build path content
+}
+
+for (segment in path) {
+ val type = segment.type // The type of segment (move, cubic, quadratic, line, close, etc.)
+ val points = segment.points // The points describing the segment geometry
+}
+```
+
+This type of iteration is easy to use but may create an allocation per segment iterated over.
+If you must avoid allocations, Pathway provides a lower-level API to do so:
+
+```kotlin
+val path = Path().apply {
+ // Build path content
+}
+
+val iterator = path.iterator
+val points = FloatArray(8)
+
+while (iterator.hasNext()) {
+ val type = iterator.next(points) // The type of segment
+ // Read the segment geometry from the points array depending on the type
+}
+
+```
+
+### Path segments
+
+Each segment in a `Path` can be of one of the following types:
+
+#### Move
+
+Move command. The path segment contains 1 point indicating the move destination.
+The weight is set 0.0f and not meaningful.
+
+#### Line
+
+Line curve. The path segment contains 2 points indicating the two extremities of
+the line. The weight is set 0.0f and not meaningful.
+
+#### Quadratic
+
+Quadratic curve. The path segment contains 3 points in the following order:
+- Start point
+- Control point
+- End point
+
+The weight is set 0.0f and not meaningful.
+
+#### Conic
+
+Conic curve. The path segment contains 3 points in the following order:
+- Start point
+- Control point
+- End point
+
+The curve is weighted by the `PathSegment.weight` property.
+
+Conic curves are automatically converted to quadratic curves by default, see
+[Handling conic segments](#handling-conic-segments) below for more information.
+
+#### Cubic
+
+Cubic curve. The path segment contains 4 points in the following order:
+- Start point
+- First control point
+- Second control point
+- End point
+
+The weight is set to 0.0f and is not meaningful.
+
+#### Close
+
+Close command. Close the current contour by joining the last point added to the
+path with the first point of the current contour. The segment does not contain
+any point. The weight is set 0.0f and not meaningful.
+
+#### Done
+
+Done command. This optional command indicates that no further segment will be
+found in the path. It typically indicates the end of an iteration over a path
+and can be ignored.
+
+## Handling conic segments
+
+In some API levels, paths may contain conic curves (weighted quadratics) but the
+`Path` API does not offer a way to add conics to a `Path` object. To work around
+this, Pathway automatically converts conics into several quadratics by default.
+
+The conic to quadratic conversion is an approximation controlled by a tolerance
+threshold, set by default to 0.25f (sub-pixel). If you want to preserve conics
+or control the tolerance, you can use the following APIs:
+
+```kotlin
+// Preserve conics
+val iterator = path.iterator(PathIterator.ConicEvaluation.AsConic)
+
+// Control the tolerance of the conic to quadratic conversion
+val iterator = path.iterator(PathIterator.ConicEvaluation.AsQuadratics, 2.0f)
+
+```
diff --git a/graphics/graphics-path/src/main/cpp/CMakeLists.txt b/graphics/graphics-path/src/main/cpp/CMakeLists.txt
new file mode 100644
index 0000000..e77704f
--- /dev/null
+++ b/graphics/graphics-path/src/main/cpp/CMakeLists.txt
@@ -0,0 +1,20 @@
+cmake_minimum_required(VERSION 3.18.1)
+project("androidx.graphics.path")
+
+add_library(
+ androidx.graphics.path
+ SHARED
+ Conic.cpp
+ PathIterator.cpp
+ pathway.cpp
+)
+
+find_library(
+ log-lib
+ log
+)
+
+target_link_libraries(
+ androidx.graphics.path
+ ${log-lib}
+)
diff --git a/graphics/graphics-path/src/main/cpp/Conic.cpp b/graphics/graphics-path/src/main/cpp/Conic.cpp
new file mode 100644
index 0000000..a6d15b6
--- /dev/null
+++ b/graphics/graphics-path/src/main/cpp/Conic.cpp
@@ -0,0 +1,170 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ * Copyright (C) 2006 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.
+ */
+
+#include "Conic.h"
+
+#include "scalar.h"
+
+#include "math/vec2.h"
+
+#include <cmath>
+#include <cstring>
+
+using namespace filament::math;
+
+constexpr int kMaxConicToQuadCount = 5;
+
+constexpr bool isFinite(const Point points[], int count) noexcept {
+ return isFinite(&points[0].x, count << 1);
+}
+
+constexpr bool isFinite(const Point& point) noexcept {
+ float a = 0.0f;
+ a *= point.x;
+ a *= point.y;
+ return a == 0.0f;
+}
+
+constexpr Point toPoint(const float2& v) noexcept {
+ return { .x = v.x, .y = v.y };
+}
+
+constexpr float2 fromPoint(const Point& v) noexcept {
+ return float2{v.x, v.y};
+}
+
+int conicToQuadratics(
+ const Point conicPoints[3], Point *quadraticPoints, int bufferSize,
+ float weight, float tolerance
+) noexcept {
+ Conic conic(conicPoints[0], conicPoints[1], conicPoints[2], weight);
+
+ int count = conic.computeQuadraticCount(tolerance);
+ int quadraticCount = 1 << count;
+ if (quadraticCount > bufferSize) {
+ // Buffer not large enough; return necessary size to resize and try again
+ return quadraticCount;
+ }
+ quadraticCount = conic.splitIntoQuadratics(quadraticPoints, count);
+
+ return quadraticCount;
+}
+
+int Conic::computeQuadraticCount(float tolerance) const noexcept {
+ if (tolerance <= 0.0f || !isFinite(tolerance) || !isFinite(points, 3)) return 0;
+
+ float a = weight - 1.0f;
+ float k = a / (4.0f * (2.0f + a));
+ float x = k * (points[0].x - 2.0f * points[1].x + points[2].x);
+ float y = k * (points[0].y - 2.0f * points[1].y + points[2].y);
+
+ float error = std::sqrtf(x * x + y * y);
+ int count = 0;
+ for ( ; count < kMaxConicToQuadCount; count++) {
+ if (error <= tolerance) break;
+ error *= 0.25f;
+ }
+
+ return count;
+}
+
+static Point* subdivide(const Conic& src, Point pts[], int level) {
+ if (level == 0) {
+ memcpy(pts, &src.points[1], 2 * sizeof(Point));
+ return pts + 2;
+ } else {
+ Conic dst[2];
+ src.split(dst);
+ const float startY = src.points[0].y;
+ const float endY = src.points[2].y;
+ if (between(startY, src.points[1].y, endY)) {
+ float midY = dst[0].points[2].y;
+ if (!between(startY, midY, endY)) {
+ float closerY = tabs(midY - startY) < tabs(midY - endY) ? startY : endY;
+ dst[0].points[2].y = dst[1].points[0].y = closerY;
+ }
+ if (!between(startY, dst[0].points[1].y, dst[0].points[2].y)) {
+ dst[0].points[1].y = startY;
+ }
+ if (!between(dst[1].points[0].y, dst[1].points[1].y, endY)) {
+ dst[1].points[1].y = endY;
+ }
+ }
+ --level;
+ pts = subdivide(dst[0], pts, level);
+ return subdivide(dst[1], pts, level);
+ }
+}
+
+void Conic::split(Conic* __restrict__ dst) const noexcept {
+ float2 scale{1.0f / (1.0f + weight)};
+ float newW = std::sqrtf(0.5f + weight * 0.5f);
+
+ float2 p0 = fromPoint(points[0]);
+ float2 p1 = fromPoint(points[1]);
+ float2 p2 = fromPoint(points[2]);
+ float2 ww(weight);
+
+ float2 wp1 = ww * p1;
+ float2 m = (p0 + (wp1 + wp1) + p2) * scale * float2(0.5f);
+ Point pt = toPoint(m);
+ if (!isFinite(pt)) {
+ double w_d = weight;
+ double w_2 = w_d * 2.0;
+ double scale_half = 1.0 / (1.0 + w_d) * 0.5;
+ pt.x = float((points[0].x + w_2 * points[1].x + points[2].x) * scale_half);
+ pt.y = float((points[0].y + w_2 * points[1].y + points[2].y) * scale_half);
+ }
+ dst[0].points[0] = points[0];
+ dst[0].points[1] = toPoint((p0 + wp1) * scale);
+ dst[0].points[2] = dst[1].points[0] = pt;
+ dst[1].points[1] = toPoint((wp1 + p2) * scale);
+ dst[1].points[2] = points[2];
+
+ dst[0].weight = dst[1].weight = newW;
+}
+
+int Conic::splitIntoQuadratics(Point dstPoints[], int count) const noexcept {
+ *dstPoints = points[0];
+
+ if (count >= kMaxConicToQuadCount) {
+ Conic dst[2];
+ split(dst);
+
+ if (equals(dst[0].points[1], dst[0].points[2]) &&
+ equals(dst[1].points[0], dst[1].points[1])) {
+ dstPoints[1] = dstPoints[2] = dstPoints[3] = dst[0].points[1];
+ dstPoints[4] = dst[1].points[2];
+ count = 1;
+ goto commonFinitePointCheck;
+ }
+ }
+
+ subdivide(*this, dstPoints + 1, count);
+
+commonFinitePointCheck:
+ const int quadCount = 1 << count;
+ const int pointCount = 2 * quadCount + 1;
+
+ if (!isFinite(dstPoints, pointCount)) {
+ for (int i = 1; i < pointCount - 1; ++i) {
+ dstPoints[i] = points[1];
+ }
+ }
+
+ return quadCount;
+}
\ No newline at end of file
diff --git a/graphics/graphics-path/src/main/cpp/Conic.h b/graphics/graphics-path/src/main/cpp/Conic.h
new file mode 100644
index 0000000..548fea2
--- /dev/null
+++ b/graphics/graphics-path/src/main/cpp/Conic.h
@@ -0,0 +1,57 @@
+/*
+ * 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.
+ */
+
+#ifndef PATH_CONIC_H
+#define PATH_CONIC_H
+
+#include "Path.h"
+
+#include <vector>
+
+constexpr int kDefaultQuadraticCount = 8;
+
+int conicToQuadratics(
+ const Point conicPoints[3], Point *quadraticPoints, int bufferSize,
+ float weight, float tolerance
+) noexcept;
+
+class ConicConverter {
+public:
+ ConicConverter() noexcept { }
+
+private:
+ std::vector<Point> mStorage{1 + 2 * kDefaultQuadraticCount};
+};
+
+struct Conic {
+ Conic() noexcept { }
+
+ Conic(Point p0, Point p1, Point p2, float weight) noexcept {
+ points[0] = p0;
+ points[1] = p1;
+ points[2] = p2;
+ this->weight = weight;
+ }
+
+ void split(Conic* __restrict__ dst) const noexcept;
+ int computeQuadraticCount(float tolerance) const noexcept;
+ int splitIntoQuadratics(Point dstPoints[], int count) const noexcept;
+
+ Point points[3];
+ float weight;
+};
+
+#endif //PATH_CONIC_H
diff --git a/graphics/graphics-path/src/main/cpp/Path.h b/graphics/graphics-path/src/main/cpp/Path.h
new file mode 100644
index 0000000..f25d708
--- /dev/null
+++ b/graphics/graphics-path/src/main/cpp/Path.h
@@ -0,0 +1,122 @@
+/*
+ * 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.
+ */
+
+#ifndef PATH_PATH_H
+#define PATH_PATH_H
+
+#include <stdint.h>
+
+// The following structures declare the minimum we need + a marker (generationId) to
+// validate the data during debugging. There may be more fields in the Skia structures
+// but we just ignore them for now. Some fields declared in older API levels (isFinite
+// for instance) may not show up in the declarations for newer API levels if the field
+// still exist but was moved after the data we need.
+
+enum class Verb : uint8_t {
+ Move,
+ Line,
+ Quadratic,
+ Conic,
+ Cubic,
+ Close,
+ Done
+};
+
+struct Point {
+ float x;
+ float y;
+};
+
+struct PathRef21 {
+ __unused intptr_t pointer; // Virtual tables
+ __unused int32_t refCount;
+ __unused float left;
+ __unused float top;
+ __unused float right;
+ __unused float bottom;
+ __unused uint8_t segmentMask; // Some of the unused fields are in a different order in 22/23
+ __unused uint8_t boundsIsDirty;
+ __unused uint8_t isFinite;
+ __unused uint8_t isOval;
+ Point* points;
+ Verb* verbs;
+ int verbCount;
+ __unused int pointCount;
+ __unused size_t freeSpace;
+ float* conicWeights;
+ __unused int conicWeightsReserve;
+ __unused int conicWeightsCount;
+ __unused uint32_t generationId;
+};
+
+struct PathRef24 {
+ __unused intptr_t pointer;
+ __unused int32_t refCount;
+ __unused float left;
+ __unused float top;
+ __unused float right;
+ __unused float bottom;
+ Point* points;
+ Verb* verbs;
+ int verbCount;
+ __unused int pointCount;
+ __unused size_t freeSpace;
+ float* conicWeights;
+ __unused int conicWeightsReserve;
+ __unused int conicWeightsCount;
+ __unused uint32_t generationId;
+};
+
+struct PathRef26 {
+ __unused int32_t refCount;
+ __unused float left;
+ __unused float top;
+ __unused float right;
+ __unused float bottom;
+ Point* points;
+ Verb* verbs;
+ int verbCount;
+ __unused int pointCount;
+ __unused size_t freeSpace;
+ float* conicWeights;
+ __unused int conicWeightsReserve;
+ __unused int conicWeightsCount;
+ __unused uint32_t generationId;
+};
+
+struct PathRef30 {
+ __unused int32_t refCount;
+ __unused float left;
+ __unused float top;
+ __unused float right;
+ __unused float bottom;
+ Point* points;
+ __unused int pointReserve;
+ __unused int pointCount;
+ Verb* verbs;
+ __unused int verbReserve;
+ int verbCount;
+ float* conicWeights;
+ __unused int conicWeightsReserve;
+ __unused int conicWeightsCount;
+ __unused uint32_t generationId;
+};
+
+struct Path {
+ PathRef21* pathRef;
+};
+
+#endif //PATH_PATH_H
diff --git a/graphics/graphics-path/src/main/cpp/PathIterator.cpp b/graphics/graphics-path/src/main/cpp/PathIterator.cpp
new file mode 100644
index 0000000..a77e251
--- /dev/null
+++ b/graphics/graphics-path/src/main/cpp/PathIterator.cpp
@@ -0,0 +1,100 @@
+/*
+ * 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.
+ */
+
+#include "PathIterator.h"
+
+int PathIterator::count() noexcept {
+ int count = 0;
+ const Verb* verbs = mVerbs;
+ const Point* points = mPoints;
+ const float* conicWeights = mConicWeights;
+
+ for (int i = 0; i < mCount; i++) {
+ Verb verb = *(mDirection == VerbDirection::Forward ? verbs++ : --verbs);
+ switch (verb) {
+ case Verb::Move:
+ case Verb::Line:
+ points += 1;
+ count++;
+ break;
+ case Verb::Quadratic:
+ points += 2;
+ count++;
+ break;
+ case Verb::Conic:
+ points += 2;
+ count++;
+ break;
+ case Verb::Cubic:
+ points += 3;
+ count++;
+ break;
+ case Verb::Close:
+ case Verb::Done:
+ count++;
+ break;
+ }
+ }
+
+ return count;
+}
+
+Verb PathIterator::next(Point points[4]) noexcept {
+ if (mIndex <= 0) {
+ return Verb::Done;
+ }
+ mIndex--;
+
+ Verb verb = *(mDirection == VerbDirection::Forward ? mVerbs++ : --mVerbs);
+ switch (verb) {
+ case Verb::Move:
+ points[0] = mPoints[0];
+ mPoints += 1;
+ break;
+ case Verb::Line:
+ points[0] = mPoints[-1];
+ points[1] = mPoints[0];
+ mPoints += 1;
+ break;
+ case Verb::Quadratic:
+ points[0] = mPoints[-1];
+ points[1] = mPoints[0];
+ points[2] = mPoints[1];
+ mPoints += 2;
+ break;
+ case Verb::Conic:
+ points[0] = mPoints[-1];
+ points[1] = mPoints[0];
+ points[2] = mPoints[1];
+ points[3].x = *mConicWeights;
+ points[3].y = *mConicWeights;
+ mConicWeights++;
+ mPoints += 2;
+ break;
+ case Verb::Cubic:
+ points[0] = mPoints[-1];
+ points[1] = mPoints[0];
+ points[2] = mPoints[1];
+ points[3] = mPoints[2];
+ mPoints += 3;
+ break;
+ case Verb::Close:
+ case Verb::Done:
+ break;
+ }
+
+ return verb;
+}
diff --git a/graphics/graphics-path/src/main/cpp/PathIterator.h b/graphics/graphics-path/src/main/cpp/PathIterator.h
new file mode 100644
index 0000000..f814863
--- /dev/null
+++ b/graphics/graphics-path/src/main/cpp/PathIterator.h
@@ -0,0 +1,68 @@
+/*
+ * 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.
+ */
+
+#ifndef PATH_PATH_ITERATOR_H
+#define PATH_PATH_ITERATOR_H
+
+#include "Path.h"
+#include "Conic.h"
+
+class PathIterator {
+public:
+ enum class VerbDirection : uint8_t {
+ Forward, // API >=30
+ Backward // API < 30
+ };
+
+ PathIterator(
+ Point* points,
+ Verb* verbs,
+ float* conicWeights,
+ int count,
+ VerbDirection direction
+ ) noexcept
+ : mPoints(points),
+ mVerbs(verbs),
+ mConicWeights(conicWeights),
+ mIndex(count),
+ mCount(count),
+ mDirection(direction) {
+ }
+
+ int rawCount() const noexcept { return mCount; }
+
+ int count() noexcept;
+
+ bool hasNext() const noexcept { return mIndex > 0; }
+
+ Verb peek() const noexcept {
+ auto verbs = mDirection == VerbDirection::Forward ? mVerbs : mVerbs - 1;
+ return mIndex > 0 ? *verbs : Verb::Done;
+ }
+
+ Verb next(Point points[4]) noexcept;
+
+private:
+ const Point* mPoints;
+ const Verb* mVerbs;
+ const float* mConicWeights;
+ int mIndex;
+ const int mCount;
+ const VerbDirection mDirection;
+ ConicConverter mConverter;
+};
+
+#endif //PATH_PATH_ITERATOR_H
diff --git a/graphics/graphics-path/src/main/cpp/math/TVecHelpers.h b/graphics/graphics-path/src/main/cpp/math/TVecHelpers.h
new file mode 100644
index 0000000..be00ebd
--- /dev/null
+++ b/graphics/graphics-path/src/main/cpp/math/TVecHelpers.h
@@ -0,0 +1,629 @@
+/*
+ * Copyright 2013 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.
+ */
+
+#ifndef TNT_MATH_TVECHELPERS_H
+#define TNT_MATH_TVECHELPERS_H
+
+#include "compiler.h"
+
+#include <cmath> // for std:: namespace
+
+#include <math.h>
+#include <stdint.h>
+#include <sys/types.h>
+
+namespace filament {
+namespace math {
+namespace details {
+// -------------------------------------------------------------------------------------
+
+template<typename U>
+inline constexpr U min(U a, U b) noexcept {
+ return a < b ? a : b;
+}
+
+template<typename U>
+inline constexpr U max(U a, U b) noexcept {
+ return a > b ? a : b;
+}
+
+template<typename T, typename U>
+struct arithmetic_result {
+ using type = decltype(std::declval<T>() + std::declval<U>());
+};
+
+template<typename T, typename U>
+using arithmetic_result_t = typename arithmetic_result<T, U>::type;
+
+template<typename A, typename B = int, typename C = int, typename D = int>
+using enable_if_arithmetic_t = std::enable_if_t<
+ is_arithmetic<A>::value &&
+ is_arithmetic<B>::value &&
+ is_arithmetic<C>::value &&
+ is_arithmetic<D>::value>;
+
+/*
+ * No user serviceable parts here.
+ *
+ * Don't use this file directly, instead include math/vec{2|3|4}.h
+ */
+
+/*
+ * TVec{Add|Product}Operators implements basic arithmetic and basic compound assignments
+ * operators on a vector of type BASE<T>.
+ *
+ * BASE only needs to implement operator[] and size().
+ * By simply inheriting from TVec{Add|Product}Operators<BASE, T> BASE will automatically
+ * get all the functionality here.
+ */
+
+template<template<typename T> class VECTOR, typename T>
+class TVecAddOperators {
+public:
+ /* compound assignment from a another vector of the same size but different
+ * element type.
+ */
+ template<typename U>
+ constexpr VECTOR<T>& operator+=(const VECTOR<U>& v) {
+ VECTOR<T>& lhs = static_cast<VECTOR<T>&>(*this);
+ for (size_t i = 0; i < lhs.size(); i++) {
+ lhs[i] += v[i];
+ }
+ return lhs;
+ }
+
+ template<typename U, typename = enable_if_arithmetic_t<U>>
+ constexpr VECTOR<T>& operator+=(U v) {
+ return operator+=(VECTOR<U>(v));
+ }
+
+ template<typename U>
+ constexpr VECTOR<T>& operator-=(const VECTOR<U>& v) {
+ VECTOR<T>& lhs = static_cast<VECTOR<T>&>(*this);
+ for (size_t i = 0; i < lhs.size(); i++) {
+ lhs[i] -= v[i];
+ }
+ return lhs;
+ }
+
+ template<typename U, typename = enable_if_arithmetic_t<U>>
+ constexpr VECTOR<T>& operator-=(U v) {
+ return operator-=(VECTOR<U>(v));
+ }
+
+private:
+ /*
+ * NOTE: the functions below ARE NOT member methods. They are friend functions
+ * with they definition inlined with their declaration. This makes these
+ * template functions available to the compiler when (and only when) this class
+ * is instantiated, at which point they're only templated on the 2nd parameter
+ * (the first one, BASE<T> being known).
+ */
+
+ template<typename U>
+ friend inline constexpr
+ VECTOR<arithmetic_result_t<T, U>> MATH_PURE operator+(const VECTOR<T>& lv, const VECTOR<U>& rv)
+ {
+ VECTOR<arithmetic_result_t<T, U>> res(lv);
+ res += rv;
+ return res;
+ }
+
+ template<typename U, typename = enable_if_arithmetic_t<U>>
+ friend inline constexpr
+ VECTOR<arithmetic_result_t<T, U>> MATH_PURE operator+(const VECTOR<T>& lv, U rv) {
+ return lv + VECTOR<U>(rv);
+ }
+
+ template<typename U, typename = enable_if_arithmetic_t<U>>
+ friend inline constexpr
+ VECTOR<arithmetic_result_t<T, U>> MATH_PURE operator+(U lv, const VECTOR<T>& rv) {
+ return VECTOR<U>(lv) + rv;
+ }
+
+ template<typename U>
+ friend inline constexpr
+ VECTOR<arithmetic_result_t<T, U>> MATH_PURE operator-(const VECTOR<T>& lv, const VECTOR<U>& rv)
+ {
+ VECTOR<arithmetic_result_t<T, U>> res(lv);
+ res -= rv;
+ return res;
+ }
+
+ template<typename U, typename = enable_if_arithmetic_t<U>>
+ friend inline constexpr
+ VECTOR<arithmetic_result_t<T, U>> MATH_PURE operator-(const VECTOR<T>& lv, U rv) {
+ return lv - VECTOR<U>(rv);
+ }
+
+ template<typename U, typename = enable_if_arithmetic_t<U>>
+ friend inline constexpr
+ VECTOR<arithmetic_result_t<T, U>> MATH_PURE operator-(U lv, const VECTOR<T>& rv) {
+ return VECTOR<U>(lv) - rv;
+ }
+};
+
+template<template<typename T> class VECTOR, typename T>
+class TVecProductOperators {
+public:
+ /* compound assignment from a another vector of the same size but different
+ * element type.
+ */
+ template<typename U>
+ constexpr VECTOR<T>& operator*=(const VECTOR<U>& v) {
+ VECTOR<T>& lhs = static_cast<VECTOR<T>&>(*this);
+ for (size_t i = 0; i < lhs.size(); i++) {
+ lhs[i] *= v[i];
+ }
+ return lhs;
+ }
+
+ template<typename U, typename = enable_if_arithmetic_t<U>>
+ constexpr VECTOR<T>& operator*=(U v) {
+ return operator*=(VECTOR<U>(v));
+ }
+
+ template<typename U>
+ constexpr VECTOR<T>& operator/=(const VECTOR<U>& v) {
+ VECTOR<T>& lhs = static_cast<VECTOR<T>&>(*this);
+ for (size_t i = 0; i < lhs.size(); i++) {
+ lhs[i] /= v[i];
+ }
+ return lhs;
+ }
+
+ template<typename U, typename = enable_if_arithmetic_t<U>>
+ constexpr VECTOR<T>& operator/=(U v) {
+ return operator/=(VECTOR<U>(v));
+ }
+
+private:
+ /*
+ * NOTE: the functions below ARE NOT member methods. They are friend functions
+ * with they definition inlined with their declaration. This makes these
+ * template functions available to the compiler when (and only when) this class
+ * is instantiated, at which point they're only templated on the 2nd parameter
+ * (the first one, BASE<T> being known).
+ */
+
+ template<typename U>
+ friend inline constexpr
+ VECTOR<arithmetic_result_t<T, U>> MATH_PURE operator*(const VECTOR<T>& lv, const VECTOR<U>& rv)
+ {
+ VECTOR<arithmetic_result_t<T, U>> res(lv);
+ res *= rv;
+ return res;
+ }
+
+ template<typename U, typename = enable_if_arithmetic_t<U>>
+ friend inline constexpr
+ VECTOR<arithmetic_result_t<T, U>> MATH_PURE operator*(const VECTOR<T>& lv, U rv) {
+ return lv * VECTOR<U>(rv);
+ }
+
+ template<typename U, typename = enable_if_arithmetic_t<U>>
+ friend inline constexpr
+ VECTOR<arithmetic_result_t<T, U>> MATH_PURE operator*(U lv, const VECTOR<T>& rv) {
+ return VECTOR<U>(lv) * rv;
+ }
+
+ template<typename U>
+ friend inline constexpr
+ VECTOR<arithmetic_result_t<T, U>> MATH_PURE operator/(const VECTOR<T>& lv, const VECTOR<U>& rv)
+ {
+ VECTOR<arithmetic_result_t<T, U>> res(lv);
+ res /= rv;
+ return res;
+ }
+
+ template<typename U, typename = enable_if_arithmetic_t<U>>
+ friend inline constexpr
+ VECTOR<arithmetic_result_t<T, U>> MATH_PURE operator/(const VECTOR<T>& lv, U rv) {
+ return lv / VECTOR<U>(rv);
+ }
+
+ template<typename U, typename = enable_if_arithmetic_t<U>>
+ friend inline constexpr
+ VECTOR<arithmetic_result_t<T, U>> MATH_PURE operator/(U lv, const VECTOR<T>& rv) {
+ return VECTOR<U>(lv) / rv;
+ }
+};
+
+/*
+ * TVecUnaryOperators implements unary operators on a vector of type BASE<T>.
+ *
+ * BASE only needs to implement operator[] and size().
+ * By simply inheriting from TVecUnaryOperators<BASE, T> BASE will automatically
+ * get all the functionality here.
+ *
+ * These operators are implemented as friend functions of TVecUnaryOperators<BASE, T>
+ */
+template<template<typename T> class VECTOR, typename T>
+class TVecUnaryOperators {
+public:
+ constexpr VECTOR<T> operator-() const {
+ VECTOR<T> r{};
+ VECTOR<T> const& rv(static_cast<VECTOR<T> const&>(*this));
+ for (size_t i = 0; i < r.size(); i++) {
+ r[i] = -rv[i];
+ }
+ return r;
+ }
+};
+
+/*
+ * TVecComparisonOperators implements relational/comparison operators
+ * on a vector of type BASE<T>.
+ *
+ * BASE only needs to implement operator[] and size().
+ * By simply inheriting from TVecComparisonOperators<BASE, T> BASE will automatically
+ * get all the functionality here.
+ */
+template<template<typename T> class VECTOR, typename T>
+class TVecComparisonOperators {
+private:
+ /*
+ * NOTE: the functions below ARE NOT member methods. They are friend functions
+ * with they definition inlined with their declaration. This makes these
+ * template functions available to the compiler when (and only when) this class
+ * is instantiated, at which point they're only templated on the 2nd parameter
+ * (the first one, BASE<T> being known).
+ */
+ template<typename U>
+ friend inline constexpr
+ bool MATH_PURE operator==(const VECTOR<T>& lv, const VECTOR<U>& rv) {
+ // w/ inlining we end-up with many branches that will pollute the BPU cache
+ MATH_NOUNROLL
+ for (size_t i = 0; i < lv.size(); i++) {
+ if (lv[i] != rv[i]) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ template<typename U>
+ friend inline constexpr
+ bool MATH_PURE operator!=(const VECTOR<T>& lv, const VECTOR<U>& rv) {
+ return !operator==(lv, rv);
+ }
+
+ template<typename U>
+ friend inline constexpr
+ VECTOR<bool> MATH_PURE equal(const VECTOR<T>& lv, const VECTOR<U>& rv) {
+ VECTOR<bool> r{};
+ for (size_t i = 0; i < lv.size(); i++) {
+ r[i] = lv[i] == rv[i];
+ }
+ return r;
+ }
+
+ template<typename U>
+ friend inline constexpr
+ VECTOR<bool> MATH_PURE notEqual(const VECTOR<T>& lv, const VECTOR<U>& rv) {
+ VECTOR<bool> r{};
+ for (size_t i = 0; i < lv.size(); i++) {
+ r[i] = lv[i] != rv[i];
+ }
+ return r;
+ }
+
+ template<typename U>
+ friend inline constexpr
+ VECTOR<bool> MATH_PURE lessThan(const VECTOR<T>& lv, const VECTOR<U>& rv) {
+ VECTOR<bool> r{};
+ for (size_t i = 0; i < lv.size(); i++) {
+ r[i] = lv[i] < rv[i];
+ }
+ return r;
+ }
+
+ template<typename U>
+ friend inline constexpr
+ VECTOR<bool> MATH_PURE lessThanEqual(const VECTOR<T>& lv, const VECTOR<U>& rv) {
+ VECTOR<bool> r{};
+ for (size_t i = 0; i < lv.size(); i++) {
+ r[i] = lv[i] <= rv[i];
+ }
+ return r;
+ }
+
+ template<typename U>
+ friend inline constexpr
+ VECTOR<bool> MATH_PURE greaterThan(const VECTOR<T>& lv, const VECTOR<U>& rv) {
+ VECTOR<bool> r;
+ for (size_t i = 0; i < lv.size(); i++) {
+ r[i] = lv[i] > rv[i];
+ }
+ return r;
+ }
+
+ template<typename U>
+ friend inline
+ VECTOR<bool> MATH_PURE greaterThanEqual(const VECTOR<T>& lv, const VECTOR<U>& rv) {
+ VECTOR<bool> r{};
+ for (size_t i = 0; i < lv.size(); i++) {
+ r[i] = lv[i] >= rv[i];
+ }
+ return r;
+ }
+};
+
+/*
+ * TVecFunctions implements functions on a vector of type BASE<T>.
+ *
+ * BASE only needs to implement operator[] and size().
+ * By simply inheriting from TVecFunctions<BASE, T> BASE will automatically
+ * get all the functionality here.
+ */
+template<template<typename T> class VECTOR, typename T>
+class TVecFunctions {
+private:
+ /*
+ * NOTE: the functions below ARE NOT member methods. They are friend functions
+ * with they definition inlined with their declaration. This makes these
+ * template functions available to the compiler when (and only when) this class
+ * is instantiated, at which point they're only templated on the 2nd parameter
+ * (the first one, BASE<T> being known).
+ */
+ template<typename U>
+ friend constexpr inline
+ arithmetic_result_t<T, U> MATH_PURE dot(const VECTOR<T>& lv, const VECTOR<U>& rv) {
+ arithmetic_result_t<T, U> r{};
+ for (size_t i = 0; i < lv.size(); i++) {
+ r += lv[i] * rv[i];
+ }
+ return r;
+ }
+
+ friend inline T MATH_PURE norm(const VECTOR<T>& lv) {
+ return std::sqrt(dot(lv, lv));
+ }
+
+ friend inline T MATH_PURE length(const VECTOR<T>& lv) {
+ return norm(lv);
+ }
+
+ friend inline constexpr T MATH_PURE norm2(const VECTOR<T>& lv) {
+ return dot(lv, lv);
+ }
+
+ friend inline constexpr T MATH_PURE length2(const VECTOR<T>& lv) {
+ return norm2(lv);
+ }
+
+ template<typename U>
+ friend inline constexpr
+ arithmetic_result_t<T, U> MATH_PURE distance(const VECTOR<T>& lv, const VECTOR<U>& rv) {
+ return length(rv - lv);
+ }
+
+ template<typename U>
+ friend inline constexpr
+ arithmetic_result_t<T, U> MATH_PURE distance2(const VECTOR<T>& lv, const VECTOR<U>& rv) {
+ return length2(rv - lv);
+ }
+
+ friend inline VECTOR<T> MATH_PURE normalize(const VECTOR<T>& lv) {
+ return lv * (T(1) / length(lv));
+ }
+
+ friend inline VECTOR<T> MATH_PURE rcp(VECTOR<T> v) {
+ return T(1) / v;
+ }
+
+ friend inline constexpr VECTOR<T> MATH_PURE abs(VECTOR<T> v) {
+ for (size_t i = 0; i < v.size(); i++) {
+ v[i] = v[i] < 0 ? -v[i] : v[i];
+ }
+ return v;
+ }
+
+ friend inline VECTOR<T> MATH_PURE floor(VECTOR<T> v) {
+ for (size_t i = 0; i < v.size(); i++) {
+ v[i] = std::floor(v[i]);
+ }
+ return v;
+ }
+
+ friend inline VECTOR<T> MATH_PURE ceil(VECTOR<T> v) {
+ for (size_t i = 0; i < v.size(); i++) {
+ v[i] = std::ceil(v[i]);
+ }
+ return v;
+ }
+
+ friend inline VECTOR<T> MATH_PURE round(VECTOR<T> v) {
+ for (size_t i = 0; i < v.size(); i++) {
+ v[i] = std::round(v[i]);
+ }
+ return v;
+ }
+
+ friend inline VECTOR<T> MATH_PURE inversesqrt(VECTOR<T> v) {
+ for (size_t i = 0; i < v.size(); i++) {
+ v[i] = T(1) / std::sqrt(v[i]);
+ }
+ return v;
+ }
+
+ friend inline VECTOR<T> MATH_PURE sqrt(VECTOR<T> v) {
+ for (size_t i = 0; i < v.size(); i++) {
+ v[i] = std::sqrt(v[i]);
+ }
+ return v;
+ }
+
+ friend inline VECTOR<T> MATH_PURE cbrt(VECTOR<T> v) {
+ for (size_t i = 0; i < v.size(); i++) {
+ v[i] = std::cbrt(v[i]);
+ }
+ return v;
+ }
+
+ friend inline VECTOR<T> MATH_PURE exp(VECTOR<T> v) {
+ for (size_t i = 0; i < v.size(); i++) {
+ v[i] = std::exp(v[i]);
+ }
+ return v;
+ }
+
+ friend inline VECTOR<T> MATH_PURE pow(VECTOR<T> v, T p) {
+ for (size_t i = 0; i < v.size(); i++) {
+ v[i] = std::pow(v[i], p);
+ }
+ return v;
+ }
+
+ friend inline VECTOR<T> MATH_PURE pow(T v, VECTOR<T> p) {
+ for (size_t i = 0; i < p.size(); i++) {
+ p[i] = std::pow(v, p[i]);
+ }
+ return p;
+ }
+
+ friend inline VECTOR<T> MATH_PURE pow(VECTOR<T> v, VECTOR<T> p) {
+ for (size_t i = 0; i < v.size(); i++) {
+ v[i] = std::pow(v[i], p[i]);
+ }
+ return v;
+ }
+
+ friend inline VECTOR<T> MATH_PURE log(VECTOR<T> v) {
+ for (size_t i = 0; i < v.size(); i++) {
+ v[i] = std::log(v[i]);
+ }
+ return v;
+ }
+
+ friend inline VECTOR<T> MATH_PURE log10(VECTOR<T> v) {
+ for (size_t i = 0; i < v.size(); i++) {
+ v[i] = std::log10(v[i]);
+ }
+ return v;
+ }
+
+ friend inline VECTOR<T> MATH_PURE log2(VECTOR<T> v) {
+ for (size_t i = 0; i < v.size(); i++) {
+ v[i] = std::log2(v[i]);
+ }
+ return v;
+ }
+
+ friend inline constexpr VECTOR<T> MATH_PURE saturate(const VECTOR<T>& lv) {
+ return clamp(lv, T(0), T(1));
+ }
+
+ friend inline constexpr VECTOR<T> MATH_PURE clamp(VECTOR<T> v, T min, T max) {
+ for (size_t i = 0; i < v.size(); i++) {
+ v[i] = details::min(max, details::max(min, v[i]));
+ }
+ return v;
+ }
+
+ friend inline constexpr VECTOR<T> MATH_PURE clamp(VECTOR<T> v, VECTOR<T> min, VECTOR<T> max) {
+ for (size_t i = 0; i < v.size(); i++) {
+ v[i] = details::min(max[i], details::max(min[i], v[i]));
+ }
+ return v;
+ }
+
+ friend inline constexpr VECTOR<T> MATH_PURE fma(const VECTOR<T>& lv, const VECTOR<T>& rv,
+ VECTOR<T> a) {
+ for (size_t i = 0; i < lv.size(); i++) {
+ a[i] += (lv[i] * rv[i]);
+ }
+ return a;
+ }
+
+ friend inline constexpr VECTOR<T> MATH_PURE min(const VECTOR<T>& u, VECTOR<T> v) {
+ for (size_t i = 0; i < v.size(); i++) {
+ v[i] = details::min(u[i], v[i]);
+ }
+ return v;
+ }
+
+ friend inline constexpr VECTOR<T> MATH_PURE max(const VECTOR<T>& u, VECTOR<T> v) {
+ for (size_t i = 0; i < v.size(); i++) {
+ v[i] = details::max(u[i], v[i]);
+ }
+ return v;
+ }
+
+ friend inline constexpr T MATH_PURE max(const VECTOR<T>& v) {
+ T r(v[0]);
+ for (size_t i = 1; i < v.size(); i++) {
+ r = max(r, v[i]);
+ }
+ return r;
+ }
+
+ friend inline constexpr T MATH_PURE min(const VECTOR<T>& v) {
+ T r(v[0]);
+ for (size_t i = 1; i < v.size(); i++) {
+ r = min(r, v[i]);
+ }
+ return r;
+ }
+
+ friend inline constexpr VECTOR<T> MATH_PURE mix(const VECTOR<T>& u, VECTOR<T> v, T a) {
+ for (size_t i = 0; i < v.size(); i++) {
+ v[i] = u[i] * (T(1) - a) + v[i] * a;
+ }
+ return v;
+ }
+
+ friend inline constexpr VECTOR<T> MATH_PURE smoothstep(T edge0, T edge1, VECTOR<T> v) {
+ VECTOR<T> t = saturate((v - edge0) / (edge1 - edge0));
+ return t * t * (T(3) - T(2) * t);
+ }
+
+ friend inline constexpr VECTOR<T> MATH_PURE step(T edge, VECTOR<T> v) {
+ for (size_t i = 0; i < v.size(); i++) {
+ v[i] = v[i] < edge ? T(0) : T(1);
+ }
+ return v;
+ }
+
+ friend inline constexpr VECTOR<T> MATH_PURE step(VECTOR<T> edge, VECTOR<T> v) {
+ for (size_t i = 0; i < v.size(); i++) {
+ v[i] = v[i] < edge[i] ? T(0) : T(1);
+ }
+ return v;
+ }
+
+ friend inline constexpr bool MATH_PURE any(const VECTOR<T>& v) {
+ for (size_t i = 0; i < v.size(); i++) {
+ if (v[i] != T(0)) return true;
+ }
+ return false;
+ }
+
+ friend inline constexpr bool MATH_PURE all(const VECTOR<T>& v) {
+ bool result = true;
+ for (size_t i = 0; i < v.size(); i++) {
+ result &= (v[i] != T(0));
+ }
+ return result;
+ }
+};
+
+// -------------------------------------------------------------------------------------
+} // namespace details
+} // namespace math
+} // namespace filament
+
+#endif // TNT_MATH_TVECHELPERS_H
diff --git a/graphics/graphics-path/src/main/cpp/math/compiler.h b/graphics/graphics-path/src/main/cpp/math/compiler.h
new file mode 100644
index 0000000..d6e18aa
--- /dev/null
+++ b/graphics/graphics-path/src/main/cpp/math/compiler.h
@@ -0,0 +1,128 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+#ifndef PATH_MATH_COMPILER_H
+#define PATH_MATH_COMPILER_H
+
+#include <type_traits>
+
+#if defined (WIN32)
+
+#ifdef max
+#undef max
+#endif
+
+#ifdef min
+#undef min
+#endif
+
+#ifdef far
+#undef far
+#endif
+
+#ifdef near
+#undef near
+#endif
+
+#endif
+
+// compatibility with non-clang compilers...
+#ifndef __has_attribute
+#define __has_attribute(x) 0
+#endif
+#ifndef __has_builtin
+#define __has_builtin(x) 0
+#endif
+
+#if __has_builtin(__builtin_expect)
+# ifdef __cplusplus
+# define MATH_LIKELY( exp ) (__builtin_expect( !!(exp), true ))
+# define MATH_UNLIKELY( exp ) (__builtin_expect( !!(exp), false ))
+# else
+# define MATH_LIKELY( exp ) (__builtin_expect( !!(exp), 1 ))
+# define MATH_UNLIKELY( exp ) (__builtin_expect( !!(exp), 0 ))
+# endif
+#else
+# define MATH_LIKELY( exp ) (exp)
+# define MATH_UNLIKELY( exp ) (exp)
+#endif
+
+#if __has_attribute(unused)
+# define MATH_UNUSED __attribute__((unused))
+#else
+# define MATH_UNUSED
+#endif
+
+#if __has_attribute(pure)
+# define MATH_PURE __attribute__((pure))
+#else
+# define MATH_PURE
+#endif
+
+#ifdef _MSC_VER
+# define MATH_EMPTY_BASES __declspec(empty_bases)
+
+// MSVC does not support loop unrolling hints
+# define MATH_NOUNROLL
+
+// Sadly, MSVC does not support __builtin_constant_p
+# ifndef MAKE_CONSTEXPR
+# define MAKE_CONSTEXPR(e) (e)
+# endif
+
+// About value initialization, the C++ standard says:
+// if T is a class type with a default constructor that is neither user-provided nor deleted
+// (that is, it may be a class with an implicitly-defined or defaulted default constructor),
+// the object is zero-initialized and then it is default-initialized
+// if it has a non-trivial default constructor;
+// Unfortunately, MSVC always calls the default constructor, even if it is trivial, which
+// breaks constexpr-ness. To workaround this, we're always zero-initializing TVecN<>
+# define MATH_CONSTEXPR_INIT {}
+# define MATH_DEFAULT_CTOR {}
+# define MATH_DEFAULT_CTOR_CONSTEXPR constexpr
+# define CONSTEXPR_IF_NOT_MSVC // when declared constexpr, msvc fails with
+ // "failure was caused by cast of object of dynamic type"
+
+#else // _MSC_VER
+
+# define MATH_EMPTY_BASES
+// C++11 allows pragmas to be specified as part of defines using the _Pragma syntax.
+# define MATH_NOUNROLL _Pragma("nounroll")
+
+# ifndef MAKE_CONSTEXPR
+# define MAKE_CONSTEXPR(e) __builtin_constant_p(e) ? (e) : (e)
+# endif
+
+# define MATH_CONSTEXPR_INIT
+# define MATH_DEFAULT_CTOR = default;
+# define MATH_DEFAULT_CTOR_CONSTEXPR
+# define CONSTEXPR_IF_NOT_MSVC constexpr
+
+#endif // _MSC_VER
+
+namespace filament::math {
+
+// MSVC 2019 16.4 doesn't seem to like it when we specialize std::is_arithmetic for
+// filament::math::half, so we're forced to create our own is_arithmetic here and specialize it
+// inside of half.h.
+template<typename T>
+struct is_arithmetic : std::integral_constant<bool,
+ std::is_integral<T>::value || std::is_floating_point<T>::value> {
+};
+
+} // filament::math
+
+#endif // PATH_MATH_COMPILER_H
diff --git a/graphics/graphics-path/src/main/cpp/math/vec2.h b/graphics/graphics-path/src/main/cpp/math/vec2.h
new file mode 100644
index 0000000..3228b09
--- /dev/null
+++ b/graphics/graphics-path/src/main/cpp/math/vec2.h
@@ -0,0 +1,112 @@
+/*
+ * Copyright 2013 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.
+ */
+
+#ifndef TNT_MATH_VEC2_H
+#define TNT_MATH_VEC2_H
+
+#include "TVecHelpers.h"
+
+#include <type_traits>
+
+#include <assert.h>
+#include <stdint.h>
+#include <sys/types.h>
+
+namespace filament {
+namespace math {
+// -------------------------------------------------------------------------------------
+
+namespace details {
+
+template<typename T>
+class MATH_EMPTY_BASES TVec2 :
+ public TVecProductOperators<TVec2, T>,
+ public TVecAddOperators<TVec2, T>,
+ public TVecUnaryOperators<TVec2, T>,
+ public TVecComparisonOperators<TVec2, T>,
+ public TVecFunctions<TVec2, T> {
+public:
+ typedef T value_type;
+ typedef T& reference;
+ typedef T const& const_reference;
+ typedef size_t size_type;
+ static constexpr size_t SIZE = 2;
+
+ union {
+ T v[SIZE] MATH_CONSTEXPR_INIT;
+ struct { T x, y; };
+ struct { T s, t; };
+ struct { T r, g; };
+ };
+
+ inline constexpr size_type size() const { return SIZE; }
+
+ // array access
+ inline constexpr T const& operator[](size_t i) const noexcept {
+ assert(i < SIZE);
+ return v[i];
+ }
+
+ inline constexpr T& operator[](size_t i) noexcept {
+ assert(i < SIZE);
+ return v[i];
+ }
+
+ // constructors
+
+ // default constructor
+ MATH_DEFAULT_CTOR_CONSTEXPR TVec2() MATH_DEFAULT_CTOR
+
+ // handles implicit conversion to a tvec4. must not be explicit.
+ template<typename A, typename = enable_if_arithmetic_t<A>>
+ constexpr TVec2(A v) noexcept : v{ T(v), T(v) } {}
+
+ template<typename A, typename B, typename = enable_if_arithmetic_t<A, B>>
+ constexpr TVec2(A x, B y) noexcept : v{ T(x), T(y) } {}
+
+ template<typename A, typename = enable_if_arithmetic_t<A>>
+ constexpr TVec2(const TVec2<A>& v) noexcept : v{ T(v[0]), T(v[1]) } {}
+
+ // cross product works only on vectors of size 2 or 3
+ template<typename U>
+ friend inline constexpr
+ arithmetic_result_t<T, U> cross(const TVec2& u, const TVec2<U>& v) noexcept {
+ return u[0] * v[1] - u[1] * v[0];
+ }
+};
+
+} // namespace details
+
+// ----------------------------------------------------------------------------------------
+
+template<typename T, typename = details::enable_if_arithmetic_t<T>>
+using vec2 = details::TVec2<T>;
+
+using double2 = vec2<double>;
+using float2 = vec2<float>;
+using int2 = vec2<int32_t>;
+using uint2 = vec2<uint32_t>;
+using short2 = vec2<int16_t>;
+using ushort2 = vec2<uint16_t>;
+using byte2 = vec2<int8_t>;
+using ubyte2 = vec2<uint8_t>;
+using bool2 = vec2<bool>;
+
+// ----------------------------------------------------------------------------------------
+} // namespace math
+} // namespace filament
+
+#endif // TNT_MATH_VEC2_H
diff --git a/graphics/graphics-path/src/main/cpp/pathway.cpp b/graphics/graphics-path/src/main/cpp/pathway.cpp
new file mode 100644
index 0000000..9997387
--- /dev/null
+++ b/graphics/graphics-path/src/main/cpp/pathway.cpp
@@ -0,0 +1,229 @@
+/*
+ * 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.
+ */
+
+#include "PathIterator.h"
+
+#include <jni.h>
+
+#include <sys/system_properties.h>
+
+#include <mutex>
+
+#define JNI_CLASS_NAME "androidx/graphics/path/PathIteratorPreApi34Impl"
+#define JNI_CLASS_NAME_CONVERTER "androidx/graphics/path/ConicConverter"
+
+#if !defined(NDEBUG)
+#include <android/log.h>
+#define ANDROID_LOG_TAG "PathIterator"
+#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, ANDROID_LOG_TAG, __VA_ARGS__)
+#endif
+
+struct {
+ jclass jniClass;
+ jfieldID nativePath;
+} sPath{};
+
+uint32_t sApiLevel = 0;
+std::once_flag sApiLevelOnceFlag;
+
+static uint32_t api_level() {
+ std::call_once(sApiLevelOnceFlag, []() {
+ char sdkVersion[PROP_VALUE_MAX];
+ __system_property_get("ro.build.version.sdk", sdkVersion);
+ sApiLevel = atoi(sdkVersion); // NOLINT(cert-err34-c)
+ });
+ return sApiLevel;
+}
+
+static jlong createPathIterator(JNIEnv* env, jobject,
+ jobject path_, jint conicEvaluation_, jfloat tolerance_) {
+
+ auto nativePath = static_cast<intptr_t>(env->GetLongField(path_, sPath.nativePath));
+ auto* path = reinterpret_cast<Path*>(nativePath);
+
+ Point* points;
+ Verb* verbs;
+ float* conicWeights;
+ int count;
+ PathIterator::VerbDirection direction;
+
+ const uint32_t apiLevel = api_level();
+ if (apiLevel >= 30) {
+ auto* ref = reinterpret_cast<PathRef30*>(path->pathRef);
+ points = ref->points;
+ verbs = ref->verbs;
+ conicWeights = ref->conicWeights;
+ count = ref->verbCount;
+ direction = PathIterator::VerbDirection::Forward;
+ } else if (apiLevel >= 26) {
+ auto* ref = reinterpret_cast<PathRef26*>(path->pathRef);
+ points = ref->points;
+ verbs = ref->verbs;
+ conicWeights = ref->conicWeights;
+ count = ref->verbCount;
+ direction = PathIterator::VerbDirection::Backward;
+ } else if (apiLevel >= 24) {
+ auto* ref = reinterpret_cast<PathRef24*>(path->pathRef);
+ points = ref->points;
+ verbs = ref->verbs;
+ conicWeights = ref->conicWeights;
+ count = ref->verbCount;
+ direction = PathIterator::VerbDirection::Backward;
+ } else {
+ auto* ref = path->pathRef;
+ points = ref->points;
+ verbs = ref->verbs;
+ conicWeights = ref->conicWeights;
+ count = ref->verbCount;
+ direction = PathIterator::VerbDirection::Backward;
+ }
+
+ return jlong(new PathIterator(points, verbs, conicWeights, count, direction));
+}
+
+static void destroyPathIterator(JNIEnv*, jobject, jlong pathIterator_) {
+ delete reinterpret_cast<PathIterator*>(pathIterator_);
+}
+
+static jboolean pathIteratorHasNext(JNIEnv*, jobject, jlong pathIterator_) {
+ return reinterpret_cast<PathIterator*>(pathIterator_)->hasNext();
+}
+
+static jint conicToQuadraticsWrapper(JNIEnv* env, jobject,
+ jfloatArray conicPoints, jfloatArray quadraticPoints,
+ jfloat weight, jfloat tolerance, jint offset) {
+ float *conicData1 = env->GetFloatArrayElements(conicPoints, JNI_FALSE);
+ float *quadData1 = env->GetFloatArrayElements(quadraticPoints, JNI_FALSE);
+ int quadDataSize = env->GetArrayLength(quadraticPoints);
+
+ int count = conicToQuadratics(reinterpret_cast<Point *>(conicData1 + offset),
+ reinterpret_cast<Point *>(quadData1),
+ env->GetArrayLength(quadraticPoints),
+ weight, tolerance);
+
+ env->ReleaseFloatArrayElements(conicPoints, conicData1, 0);
+ env->ReleaseFloatArrayElements(quadraticPoints, quadData1, 0);
+
+ return count;
+}
+
+static jint pathIteratorNext(JNIEnv* env, jobject,
+ jlong pathIterator_, jfloatArray points_, jint offset_) {
+ auto pathIterator = reinterpret_cast<PathIterator*>(pathIterator_);
+ Point pointsData[4];
+ Verb verb = pathIterator->next(pointsData);
+
+ if (verb != Verb::Done && verb != Verb::Close) {
+ auto* floatsData = reinterpret_cast<jfloat*>(pointsData);
+ env->SetFloatArrayRegion(points_, offset_, 8, floatsData);
+ }
+
+ return static_cast<jint>(verb);
+}
+
+static jint pathIteratorPeek(JNIEnv*, jobject, jlong pathIterator_) {
+ return static_cast<jint>(reinterpret_cast<PathIterator *>(pathIterator_)->peek());
+}
+
+static jint pathIteratorRawSize(JNIEnv*, jobject, jlong pathIterator_) {
+ return static_cast<jint>(reinterpret_cast<PathIterator *>(pathIterator_)->rawCount());
+}
+
+static jint pathIteratorSize(JNIEnv*, jobject, jlong pathIterator_) {
+ return static_cast<jint>(reinterpret_cast<PathIterator *>(pathIterator_)->count());
+}
+
+JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void*) {
+ JNIEnv* env;
+ if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
+ return -1;
+ }
+
+ sPath.jniClass = env->FindClass("android/graphics/Path");
+ if (sPath.jniClass == nullptr) return JNI_ERR;
+
+ sPath.nativePath = env->GetFieldID(sPath.jniClass, "mNativePath", "J");
+ if (sPath.nativePath == nullptr) return JNI_ERR;
+
+ {
+ jclass pathsClass = env->FindClass(JNI_CLASS_NAME);
+ if (pathsClass == nullptr) return JNI_ERR;
+
+ static const JNINativeMethod methods[] = {
+ {
+ (char*) "createInternalPathIterator",
+ (char*) "(Landroid/graphics/Path;IF)J",
+ reinterpret_cast<void*>(createPathIterator)
+ },
+ {
+ (char*) "destroyInternalPathIterator",
+ (char*) "(J)V",
+ reinterpret_cast<void*>(destroyPathIterator)
+ },
+ {
+ (char*) "internalPathIteratorHasNext",
+ (char*) "(J)Z",
+ reinterpret_cast<void*>(pathIteratorHasNext)
+ },
+ {
+ (char*) "internalPathIteratorNext",
+ (char*) "(J[FI)I",
+ reinterpret_cast<void*>(pathIteratorNext)
+ },
+ {
+ (char*) "internalPathIteratorPeek",
+ (char*) "(J)I",
+ reinterpret_cast<void*>(pathIteratorPeek)
+ },
+ {
+ (char*) "internalPathIteratorRawSize",
+ (char*) "(J)I",
+ reinterpret_cast<void*>(pathIteratorRawSize)
+ },
+ {
+ (char*) "internalPathIteratorSize",
+ (char*) "(J)I",
+ reinterpret_cast<void*>(pathIteratorSize)
+ },
+ };
+
+ int result = env->RegisterNatives(
+ pathsClass, methods, sizeof(methods) / sizeof(JNINativeMethod)
+ );
+ if (result != JNI_OK) return result;
+
+ env->DeleteLocalRef(pathsClass);
+
+ jclass converterClass = env->FindClass(JNI_CLASS_NAME_CONVERTER);
+ if (converterClass == nullptr) return JNI_ERR;
+ static const JNINativeMethod methods2[] = {
+ {
+ (char *) "internalConicToQuadratics",
+ (char *) "([F[FFFI)I",
+ reinterpret_cast<void *>(conicToQuadraticsWrapper)
+ },
+ };
+
+ result = env->RegisterNatives(
+ converterClass, methods2, sizeof(methods2) / sizeof(JNINativeMethod)
+ );
+ if (result != JNI_OK) return result;
+
+ env->DeleteLocalRef(converterClass);
+ }
+
+ return JNI_VERSION_1_6;
+}
diff --git a/graphics/graphics-path/src/main/cpp/scalar.h b/graphics/graphics-path/src/main/cpp/scalar.h
new file mode 100644
index 0000000..0342d13
--- /dev/null
+++ b/graphics/graphics-path/src/main/cpp/scalar.h
@@ -0,0 +1,71 @@
+/*
+ * 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.
+ */
+
+#ifndef PATH_SCALAR_H
+#define PATH_SCALAR_H
+
+union floatIntUnion {
+ float value;
+ int32_t signBitInt;
+};
+
+static inline int32_t float2Bits(float x) noexcept {
+ floatIntUnion data; // NOLINT(cppcoreguidelines-pro-type-member-init)
+ data.value = x;
+ return data.signBitInt;
+}
+
+constexpr bool isFloatFinite(int32_t bits) noexcept {
+ constexpr int32_t kFloatBitsExponentMask = 0x7F800000;
+ return (bits & kFloatBitsExponentMask) != kFloatBitsExponentMask;
+}
+
+static inline bool isFinite(float v) noexcept {
+ return isFloatFinite(float2Bits(v));
+}
+
+#pragma clang diagnostic push
+#pragma ide diagnostic ignored "cppcoreguidelines-narrowing-conversions"
+static bool canNormalize(float dx, float dy) noexcept {
+ return (isFinite(dx) && isFinite(dy)) && (dx || dy);
+}
+#pragma clang diagnostic pop
+
+static bool equals(const Point& p1, const Point& p2) noexcept {
+ return !canNormalize(p1.x - p2.x, p1.y - p2.y);
+}
+
+constexpr bool isFinite(const float array[], int count) noexcept {
+ float prod = 0.0f;
+ for (int i = 0; i < count; i++) {
+ prod *= array[i];
+ }
+ return prod == 0.0f;
+}
+
+template<typename T>
+constexpr T tabs(T value) noexcept {
+ if (value < 0) {
+ value = -value;
+ }
+ return value;
+}
+
+constexpr bool between(float a, float b, float c) noexcept {
+ return (a - b) * (c - b) <= 0.0f;
+}
+
+#endif //PATH_SCALAR_H
diff --git a/graphics/graphics-path/src/main/java/androidx/graphics/path/ConicConverter.kt b/graphics/graphics-path/src/main/java/androidx/graphics/path/ConicConverter.kt
new file mode 100644
index 0000000..445bd47
--- /dev/null
+++ b/graphics/graphics-path/src/main/java/androidx/graphics/path/ConicConverter.kt
@@ -0,0 +1,102 @@
+/*
+ * 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 androidx.graphics.path
+
+import android.util.Log
+
+/**
+ * This class converts a given Conic object to the equivalent set of Quadratic objects.
+ * It stores all quadratics from a conversion in the call to [convert], but returns only
+ * one at a time, from nextQuadratic(), storing the rest for later retrieval (since a
+ * PathIterator only retrieves one object at a time).
+ *
+ * This object is stateful, using quadraticCount, currentQuadratic, and quadraticData
+ * to send back the next quadratic when requested, in [nextQuadratic].
+ */
+internal class ConicConverter() {
+
+ private val LOG_TAG = "ConicConverter"
+ private val DEBUG = false
+
+ /**
+ * The total number of quadratics currently stored in the converter
+ */
+ var quadraticCount: Int = 0
+ private set
+
+ /**
+ * The index of the current Quadratic; this is the next quadratic to be returned
+ * in the call to nextQuadratic().
+ */
+ var currentQuadratic = 0
+
+ /**
+ * Storage for all quadratics for a particular conic. Set to reasonable
+ * default size, will need to resize if we ever get a return count larger
+ * than the current size.
+ * Initial size holds up to 5 quadratics: 2 floats/point, 3 points/quadratic
+ * where all quadratics overlap in one point except the ends.
+ */
+ private var quadraticData = FloatArray(1)
+
+ /**
+ * This function stores the next converted quadratic in the given points array,
+ * returning true if this happened, false if there was no quadratic to be returned.
+ */
+ fun nextQuadratic(points: FloatArray, offset: Int = 0): Boolean {
+ if (currentQuadratic < quadraticCount) {
+ val index = currentQuadratic * 2 * 2
+ points[0 + offset] = quadraticData[index]
+ points[1 + offset] = quadraticData[index + 1]
+ points[2 + offset] = quadraticData[index + 2]
+ points[3 + offset] = quadraticData[index + 3]
+ points[4 + offset] = quadraticData[index + 4]
+ points[5 + offset] = quadraticData[index + 5]
+ currentQuadratic++
+ return true
+ }
+ return false
+ }
+
+ /**
+ * Converts the conic in [points] to a series of quadratics, which will all be stored
+ */
+ fun convert(points: FloatArray, weight: Float, tolerance: Float, offset: Int = 0) {
+ quadraticCount = internalConicToQuadratics(points, quadraticData, weight, tolerance, offset)
+ if (quadraticCount > quadraticData.size) {
+ if (DEBUG) Log.d(LOG_TAG, "Resizing quadraticData buffer to $quadraticCount")
+ quadraticData = FloatArray(quadraticCount * 4 * 2)
+ quadraticCount = internalConicToQuadratics(points, quadraticData, weight, tolerance,
+ offset)
+ }
+ currentQuadratic = 0
+ if (DEBUG) Log.d("ConicConverter", "internalConicToQuadratics returned " + quadraticCount)
+ }
+
+ /**
+ * The actual conversion from conic to quadratic data happens in native code, in the library
+ * loaded elsewhere. This JNI function wraps that native functionality.
+ */
+ @Suppress("KotlinJniMissingFunction")
+ private external fun internalConicToQuadratics(
+ conicPoints: FloatArray,
+ quadraticPoints: FloatArray,
+ weight: Float,
+ tolerance: Float,
+ offset: Int
+ ): Int
+}
\ No newline at end of file
diff --git a/graphics/graphics-path/src/main/java/androidx/graphics/path/PathIterator.kt b/graphics/graphics-path/src/main/java/androidx/graphics/path/PathIterator.kt
new file mode 100644
index 0000000..6567419
--- /dev/null
+++ b/graphics/graphics-path/src/main/java/androidx/graphics/path/PathIterator.kt
@@ -0,0 +1,146 @@
+/*
+ * 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.
+ */
+@file:JvmName("PathUtilities")
+package androidx.graphics.path
+
+import android.graphics.Path
+import androidx.core.os.BuildCompat
+import androidx.core.os.BuildCompat.PrereleaseSdkCheck
+
+/**
+ * A path iterator can be used to iterate over all the [segments][PathSegment] that make up
+ * a path. Those segments may in turn define multiple contours inside the path. Conic segments
+ * are by default evaluated as approximated quadratic segments. To preserve conic segments as
+ * conics, set [conicEvaluation] to [AsConic][ConicEvaluation.AsConic]. The error of the
+ * approximation is controlled by [tolerance].
+ *
+ * [PathIterator] objects are created implicitly through a given [Path] object; to create a
+ * [PathIterator], call one of the two [Path.iterator] extension functions.
+ */
+@Suppress("NotCloseable", "IllegalExperimentalApiUsage")
+@PrereleaseSdkCheck
+class PathIterator constructor(
+ val path: Path,
+ val conicEvaluation: ConicEvaluation = ConicEvaluation.AsQuadratics,
+ val tolerance: Float = 0.25f
+) : Iterator<PathSegment> {
+
+ internal val implementation: PathIteratorImpl
+ init {
+ implementation =
+ when {
+ // TODO: replace isAtLeastU() check with below or similar when U is released
+ // Build.VERSION.SDK_INT >= 34 -> {
+ BuildCompat.isAtLeastU() -> {
+ PathIteratorApi34Impl(path, conicEvaluation, tolerance)
+ }
+ else -> {
+ PathIteratorPreApi34Impl(path, conicEvaluation, tolerance)
+ }
+ }
+ }
+
+ enum class ConicEvaluation {
+ /**
+ * Conic segments are returned as conic segments.
+ */
+ AsConic,
+
+ /**
+ * Conic segments are returned as quadratic approximations. The quality of the
+ * approximation is defined by a tolerance value.
+ */
+ AsQuadratics
+ }
+
+ /**
+ * Returns the number of verbs present in this iterator, i.e. the number of calls to
+ * [next] required to complete the iteration.
+ *
+ * By default, [calculateSize] returns the true number of operations in the iterator. Deriving
+ * this result requires converting any conics to quadratics, if [conicEvaluation] is
+ * set to [ConicEvaluation.AsQuadratics], which takes extra processing time. Set
+ * [includeConvertedConics] to false if an approximate size, not including conic
+ * conversion, is sufficient.
+ *
+ * @param includeConvertedConics The returned size includes any required conic conversions.
+ * Default is true, so it will return the exact size, at the cost of iterating through
+ * all elements and converting any conics as appropriate. Set to false to save on processing,
+ * at the cost of a less exact result.
+ */
+ fun calculateSize(includeConvertedConics: Boolean = true) =
+ implementation.calculateSize(includeConvertedConics)
+
+ /**
+ * Returns `true` if the iteration has more elements.
+ */
+ override fun hasNext(): Boolean = implementation.hasNext()
+
+ /**
+ * Returns the type of the current segment in the iteration, or [Done][PathSegment.Type.Done]
+ * if the iteration is finished.
+ */
+ fun peek() = implementation.peek()
+
+ /**
+ * Returns the [type][PathSegment.Type] of the next [path segment][PathSegment] in the iteration
+ * and fills [points] with the points specific to the segment type. Each pair of floats in
+ * the [points] array represents a point for the given segment. The number of pairs of floats
+ * depends on the [PathSegment.Type]:
+ * - [Move][PathSegment.Type.Move]: 1 pair (indices 0 to 1)
+ * - [Move][PathSegment.Type.Line]: 2 pairs (indices 0 to 3)
+ * - [Move][PathSegment.Type.Quadratic]: 3 pairs (indices 0 to 5)
+ * - [Move][PathSegment.Type.Conic]: 4 pairs (indices 0 to 7), the last pair contains the
+ * [weight][PathSegment.weight] twice
+ * - [Move][PathSegment.Type.Cubic]: 4 pairs (indices 0 to 7)
+ * - [Close][PathSegment.Type.Close]: 0 pair
+ * - [Done][PathSegment.Type.Done]: 0 pair
+ * This method does not allocate any memory.
+ *
+ * @param points A [FloatArray] large enough to hold 8 floats starting at [offset],
+ * throws an [IllegalStateException] otherwise.
+ * @param offset Offset in [points] where to store the result
+ */
+ @JvmOverloads
+ fun next(points: FloatArray, offset: Int = 0): PathSegment.Type =
+ implementation.next(points, offset)
+
+ /**
+ * Returns the next [path segment][PathSegment] in the iteration, or [DoneSegment] if
+ * the iteration is finished. To save on allocations, use the alternative [next] function, which
+ * takes a [FloatArray].
+ */
+ override fun next(): PathSegment = implementation.next()
+}
+
+/**
+ * Creates a new [PathIterator] for this [path][android.graphics.Path] that evaluates
+ * conics as quadratics. To preserve conics, use the [Path.iterator] function that takes a
+ * [PathIterator.ConicEvaluation] parameter.
+ */
+@Suppress("IllegalExperimentalApiUsage")
+@PrereleaseSdkCheck
+operator fun Path.iterator() = PathIterator(this)
+
+/**
+ * Creates a new [PathIterator] for this [path][android.graphics.Path]. To preserve conics as
+ * conics (not convert them to quadratics), set [conicEvaluation] to
+ * [PathIterator.ConicEvaluation.AsConic].
+ */
+@Suppress("IllegalExperimentalApiUsage")
+@PrereleaseSdkCheck
+fun Path.iterator(conicEvaluation: PathIterator.ConicEvaluation, tolerance: Float = 0.25f) =
+ PathIterator(this, conicEvaluation, tolerance)
diff --git a/graphics/graphics-path/src/main/java/androidx/graphics/path/PathIteratorImpl.kt b/graphics/graphics-path/src/main/java/androidx/graphics/path/PathIteratorImpl.kt
new file mode 100644
index 0000000..65fa2c1
--- /dev/null
+++ b/graphics/graphics-path/src/main/java/androidx/graphics/path/PathIteratorImpl.kt
@@ -0,0 +1,341 @@
+/*
+ * 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 androidx.graphics.path
+
+import android.graphics.Path
+import android.graphics.PathIterator as PlatformPathIterator
+import android.graphics.PointF
+import androidx.annotation.RequiresApi
+import androidx.core.os.BuildCompat
+import androidx.graphics.path.PathIterator.ConicEvaluation
+
+/**
+ * Base class for API-version-specific PathIterator implementation classes. All functionality
+ * is implemented in the subclasses except for [next], which relies on shared native code
+ * to perform conic conversion.
+ */
+@Suppress("IllegalExperimentalApiUsage")
[email protected]
+internal abstract class PathIteratorImpl(
+ val path: Path,
+ val conicEvaluation: ConicEvaluation = ConicEvaluation.AsQuadratics,
+ val tolerance: Float = 0.25f
+) {
+ /**
+ * An iterator's ConicConverter converts from a conic to a series of
+ * quadratics. It keeps track of the resulting quadratics and iterates through
+ * them on ensuing calls to next(). The converter is only ever called if
+ * [conicEvaluation] is set to [ConicEvaluation.AsQuadratics].
+ */
+ var conicConverter = ConicConverter()
+
+ /**
+ * pointsData is used internally when the no-arg variant of next() is called,
+ * to avoid allocating a new array every time.
+ */
+ val pointsData = FloatArray(8)
+
+ private companion object {
+ init {
+ /**
+ * The native library is used mainly for pre-API34, but we also rely
+ * on the conic conversion code in API34+, thus it is initialized here.
+ */
+ System.loadLibrary("androidx.graphics.path")
+ }
+ }
+
+ abstract fun calculateSize(includeConvertedConics: Boolean): Int
+
+ abstract fun hasNext(): Boolean
+ abstract fun peek(): PathSegment.Type
+
+ /**
+ * The core functionality of [next] is in API-specific subclasses. But we implement [next]
+ * at this level to share the same conic conversion implementation across all versions.
+ * This happens by calling [nextImpl] to get the next segment from the subclasses, then
+ * calling the shared [ConicConverter] code when appropriate to get and return the
+ * converted segments.
+ */
+ abstract fun nextImpl(points: FloatArray, offset: Int = 0): PathSegment.Type
+
+ fun next(points: FloatArray, offset: Int = 0): PathSegment.Type {
+ check(points.size - offset >= 8) { "The points array must contain at least 8 floats" }
+ // First check to see if we are currently iterating through converted conics
+ if (conicConverter.currentQuadratic < conicConverter.quadraticCount
+ ) {
+ conicConverter.nextQuadratic(points, offset)
+ return (pathSegmentTypes[PathSegment.Type.Quadratic.ordinal])
+ } else {
+ val typeValue = nextImpl(points, offset)
+ if (typeValue == PathSegment.Type.Conic &&
+ conicEvaluation == ConicEvaluation.AsQuadratics
+ ) {
+ with(conicConverter) {
+ convert(points, points[6 + offset], tolerance, offset)
+ if (quadraticCount > 0) {
+ nextQuadratic(points, offset)
+ }
+ }
+ return PathSegment.Type.Quadratic
+ }
+ return typeValue
+ }
+ }
+
+ fun next(): PathSegment {
+ val type = next(pointsData, 0)
+ if (type == PathSegment.Type.Done) return DoneSegment
+ if (type == PathSegment.Type.Close) return CloseSegment
+ val weight = if (type == PathSegment.Type.Conic) pointsData[6] else 0.0f
+ return PathSegment(type, floatsToPoints(pointsData, type), weight)
+ }
+
+ /**
+ * Utility function to convert a FloatArray to an array of PointF objects, where
+ * every two Floats in the FloatArray correspond to a single PointF in the resulting
+ * point array. The FloatArray is used internally to process a next() call, the
+ * array of points is used to create a PathSegment from the operation.
+ */
+ private fun floatsToPoints(pointsData: FloatArray, type: PathSegment.Type): Array<PointF> {
+ val points = when (type) {
+ PathSegment.Type.Move -> {
+ arrayOf(PointF(pointsData[0], pointsData[1]))
+ }
+
+ PathSegment.Type.Line -> {
+ arrayOf(
+ PointF(pointsData[0], pointsData[1]),
+ PointF(pointsData[2], pointsData[3])
+ )
+ }
+
+ PathSegment.Type.Quadratic,
+ PathSegment.Type.Conic -> {
+ arrayOf(
+ PointF(pointsData[0], pointsData[1]),
+ PointF(pointsData[2], pointsData[3]),
+ PointF(pointsData[4], pointsData[5])
+ )
+ }
+
+ PathSegment.Type.Cubic -> {
+ arrayOf(
+ PointF(pointsData[0], pointsData[1]),
+ PointF(pointsData[2], pointsData[3]),
+ PointF(pointsData[4], pointsData[5]),
+ PointF(pointsData[6], pointsData[7])
+ )
+ }
+ // This should not happen because of the early returns above
+ else -> emptyArray()
+ }
+ return points
+ }
+}
+
+/**
+ * In API level 34, we can use new platform functionality for most of what PathIterator does.
+ * The exceptions are conic conversion (which is handled in the base impl class) and
+ * [calculateSize], which is implemented here.
+ */
+@RequiresApi(34)
+@Suppress("IllegalExperimentalApiUsage")
[email protected]
+internal class PathIteratorApi34Impl(
+ path: Path,
+ conicEvaluation: ConicEvaluation = ConicEvaluation.AsQuadratics,
+ tolerance: Float = 0.25f
+) : PathIteratorImpl(path, conicEvaluation, tolerance) {
+
+ /**
+ * The platform iterator handles most of what we need for iterating. We hold an instance
+ * of that object in this class.
+ */
+ private val platformIterator: PlatformPathIterator
+
+ init {
+ platformIterator = path.pathIterator
+ }
+
+ /**
+ * The platform does not expose a calculateSize() method, so we implement our own. In the
+ * simplest case, this is done by simply iterating through all segments until done. However, if
+ * the caller requested the true size (including any conic conversion) and if there are any
+ * conics in the path segments, then there is more work to do since we have to convert and count
+ * those segments as well.
+ */
+ override fun calculateSize(includeConvertedConics: Boolean): Int {
+ val convertConics = includeConvertedConics &&
+ conicEvaluation == ConicEvaluation.AsQuadratics
+ var numVerbs = 0
+ val tempIterator = path.pathIterator
+ val tempFloats = FloatArray(8)
+ while (tempIterator.hasNext()) {
+ val type = tempIterator.next(tempFloats, 0)
+ if (type == PlatformPathIterator.VERB_CONIC && convertConics) {
+ with(conicConverter) {
+ convert(tempFloats, tempFloats[6], tolerance)
+ numVerbs += quadraticCount
+ }
+ } else {
+ numVerbs++
+ }
+ }
+ return numVerbs
+ }
+
+ /**
+ * [nextImpl] is called by [next] in the base class to do the work of actually getting the
+ * next segment, for which we defer to the platform iterator.
+ */
+ override fun nextImpl(points: FloatArray, offset: Int): PathSegment.Type {
+ return platformToAndroidXSegmentType(platformIterator.next(points, offset))
+ }
+
+ override fun hasNext(): Boolean {
+ return platformIterator.hasNext()
+ }
+
+ override fun peek(): PathSegment.Type {
+ val platformType = platformIterator.peek()
+ return platformToAndroidXSegmentType(platformType)
+ }
+
+ /**
+ * Callers need the AndroidX segment types, so we must convert from the platform types.
+ */
+ private fun platformToAndroidXSegmentType(platformType: Int): PathSegment.Type {
+ return when (platformType) {
+ PlatformPathIterator.VERB_CLOSE -> PathSegment.Type.Close
+ PlatformPathIterator.VERB_CONIC -> PathSegment.Type.Conic
+ PlatformPathIterator.VERB_CUBIC -> PathSegment.Type.Cubic
+ PlatformPathIterator.VERB_DONE -> PathSegment.Type.Done
+ PlatformPathIterator.VERB_LINE -> PathSegment.Type.Line
+ PlatformPathIterator.VERB_MOVE -> PathSegment.Type.Move
+ PlatformPathIterator.VERB_QUAD -> PathSegment.Type.Quadratic
+ else -> {
+ throw IllegalArgumentException("Unknown path segment type $platformType")
+ }
+ }
+ }
+}
+
+/**
+ * Most of the functionality for pre-34 iteration is handled in the native code. The only
+ * exception, similar to the API34 implementation, is the calculateSize(). There is a size()
+ * function in native code which is very quick (it simply tracks the number of verbs in the native
+ * structure). But if the caller wants conic conversion, then we need to iterate through
+ * and convert appropriately, counting as we iterate.
+ */
+@Suppress("IllegalExperimentalApiUsage")
[email protected]
+internal class PathIteratorPreApi34Impl(
+ path: Path,
+ conicEvaluation: ConicEvaluation = ConicEvaluation.AsQuadratics,
+ tolerance: Float = 0.25f
+) : PathIteratorImpl(path, conicEvaluation, tolerance) {
+
+ @Suppress("KotlinJniMissingFunction")
+ private external fun createInternalPathIterator(
+ path: Path,
+ conicEvaluation: Int,
+ tolerance: Float
+ ): Long
+
+ @Suppress("KotlinJniMissingFunction")
+ private external fun destroyInternalPathIterator(internalPathIterator: Long)
+
+ @Suppress("KotlinJniMissingFunction")
+ private external fun internalPathIteratorHasNext(internalPathIterator: Long): Boolean
+
+ @Suppress("KotlinJniMissingFunction")
+ private external fun internalPathIteratorNext(
+ internalPathIterator: Long,
+ points: FloatArray,
+ offset: Int
+ ): Int
+
+ @Suppress("KotlinJniMissingFunction")
+ private external fun internalPathIteratorPeek(internalPathIterator: Long): Int
+
+ @Suppress("KotlinJniMissingFunction")
+ private external fun internalPathIteratorRawSize(internalPathIterator: Long): Int
+
+ @Suppress("KotlinJniMissingFunction")
+ private external fun internalPathIteratorSize(internalPathIterator: Long): Int
+ /**
+ * Defines the type of evaluation to apply to conic segments during iteration.
+ */
+
+ private val internalPathIterator =
+ createInternalPathIterator(path, ConicEvaluation.AsConic.ordinal, tolerance)
+
+ /**
+ * Returns the number of verbs present in this iterator's path. If [includeConvertedConics]
+ * property is false and the path has any conic elements, the returned size might be smaller
+ * than the number of calls to [next] required to fully iterate over the path. An accurate
+ * size can be computed by setting the parameter to true instead, at a performance cost.
+ * Including converted conics requires iterating through the entire path, including converting
+ * any conics along the way, to calculate the true size.
+ */
+ override fun calculateSize(includeConvertedConics: Boolean): Int {
+ var numVerbs = 0
+ if (!includeConvertedConics || conicEvaluation == ConicEvaluation.AsConic) {
+ numVerbs = internalPathIteratorSize(internalPathIterator)
+ } else {
+ val tempIterator =
+ createInternalPathIterator(path, ConicEvaluation.AsConic.ordinal, tolerance)
+ val tempFloats = FloatArray(8)
+ while (internalPathIteratorHasNext(tempIterator)) {
+ val segment = internalPathIteratorNext(tempIterator, tempFloats, 0)
+ when (pathSegmentTypes[segment]) {
+ PathSegment.Type.Conic -> {
+ conicConverter.convert(tempFloats, tempFloats[7], tolerance)
+ numVerbs += conicConverter.quadraticCount
+ }
+ else -> numVerbs++
+ }
+ }
+ }
+ return numVerbs
+ }
+
+ /**
+ * Returns `true` if the iteration has more elements.
+ */
+ override fun hasNext(): Boolean = internalPathIteratorHasNext(internalPathIterator)
+
+ /**
+ * Returns the type of the current segment in the iteration, or [Done][PathSegment.Type.Done]
+ * if the iteration is finished.
+ */
+ override fun peek() = pathSegmentTypes[internalPathIteratorPeek(internalPathIterator)]
+
+ /**
+ * This is where the actual work happens to get the next segment in the path, which happens
+ * in native code. This function is called by [next] in the base class, which then converts
+ * the resulting segment from conics to quadratics as necessary.
+ */
+ override fun nextImpl(points: FloatArray, offset: Int): PathSegment.Type {
+ return pathSegmentTypes[internalPathIteratorNext(internalPathIterator, points, offset)]
+ }
+
+ protected fun finalize() {
+ destroyInternalPathIterator(internalPathIterator)
+ }
+}
\ No newline at end of file
diff --git a/graphics/graphics-path/src/main/java/androidx/graphics/path/PathSegment.kt b/graphics/graphics-path/src/main/java/androidx/graphics/path/PathSegment.kt
new file mode 100644
index 0000000..863d6d0
--- /dev/null
+++ b/graphics/graphics-path/src/main/java/androidx/graphics/path/PathSegment.kt
@@ -0,0 +1,143 @@
+/*
+ * 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.
+ */
+
+@file:JvmName("PathSegmentUtilities")
+package androidx.graphics.path
+
+import android.graphics.PointF
+
+/**
+ * A path segment represents a curve (line, cubic, quadratic or conic) or a command inside
+ * a fully formed [path][android.graphics.Path] object.
+ *
+ * A segment is identified by a [type][PathSegment.Type] which in turns defines how many
+ * [points] are available (from 0 to 3) and whether the [weight] is meaningful. Please refer
+ * to the documentation of each [type][PathSegment.Type] for more information.
+ *
+ * A segment with the [Move][Type.Move] or [Close][Type.Close] is usually represented by
+ * the singletons [DoneSegment] and [CloseSegment] respectively.
+ *
+ * @property type The type that identifies this segment and defines the number of points.
+ * @property points An array of points describing this segment, whose size depends on [type].
+ * @property weight Conic weight, only valid if [type] is [Type.Conic].
+ */
+class PathSegment internal constructor(
+ val type: Type,
+ @get:Suppress("ArrayReturn") val points: Array<PointF>,
+ val weight: Float
+) {
+
+ /**
+ * Type of a given segment in a [path][android.graphics.Path], either a command
+ * ([Type.Move], [Type.Close], [Type.Done]) or a curve ([Type.Line], [Type.Cubic],
+ * [Type.Quadratic], [Type.Conic]).
+ */
+ enum class Type {
+ /**
+ * Move command, the path segment contains 1 point indicating the move destination.
+ * The weight is set 0.0f and not meaningful.
+ */
+ Move,
+ /**
+ * Line curve, the path segment contains 2 points indicating the two extremities of
+ * the line. The weight is set 0.0f and not meaningful.
+ */
+ Line,
+ /**
+ * Quadratic curve, the path segment contains 3 points in the following order:
+ * - Start point
+ * - Control point
+ * - End point
+ *
+ * The weight is set 0.0f and not meaningful.
+ */
+ Quadratic,
+ /**
+ * Conic curve, the path segment contains 3 points in the following order:
+ * - Start point
+ * - Control point
+ * - End point
+ *
+ * The curve is weighted by the [weight][PathSegment.weight] property.
+ */
+ Conic,
+ /**
+ * Cubic curve, the path segment contains 4 points in the following order:
+ * - Start point
+ * - First control point
+ * - Second control point
+ * - End point
+ *
+ * The weight is set 0.0f and not meaningful.
+ */
+ Cubic,
+ /**
+ * Close command, close the current contour by joining the last point added to the
+ * path with the first point of the current contour. The segment does not contain
+ * any point. The weight is set 0.0f and not meaningful.
+ */
+ Close,
+ /**
+ * Done command, which indicates that no further segment will be
+ * found in the path. It typically indicates the end of an iteration over a path
+ * and can be ignored.
+ */
+ Done
+ }
+
+ override fun equals(other: Any?): Boolean {
+ if (this === other) return true
+ if (javaClass != other?.javaClass) return false
+
+ other as PathSegment
+
+ if (type != other.type) return false
+ if (!points.contentEquals(other.points)) return false
+ if (weight != other.weight) return false
+
+ return true
+ }
+
+ override fun hashCode(): Int {
+ var result = type.hashCode()
+ result = 31 * result + points.contentHashCode()
+ result = 31 * result + weight.hashCode()
+ return result
+ }
+
+ override fun toString(): String {
+ return "PathSegment(type=$type, points=${points.contentToString()}, weight=$weight)"
+ }
+}
+
+/**
+ * A [PathSegment] containing the [Done][PathSegment.Type.Done] command.
+ * This static object exists to avoid allocating a new segment when returning a
+ * [Done][PathSegment.Type.Done] result from [PathIterator.next].
+ */
+val DoneSegment = PathSegment(PathSegment.Type.Done, emptyArray(), 0.0f)
+
+/**
+ * A [PathSegment] containing the [Close][PathSegment.Type.Close] command.
+ * This static object exists to avoid allocating a new segment when returning a
+ * [Close][PathSegment.Type.Close] result from [PathIterator.next].
+ */
+val CloseSegment = PathSegment(PathSegment.Type.Close, emptyArray(), 0.0f)
+
+/**
+ * Cache of [PathSegment.Type] values to avoid internal allocation on each use.
+ */
+internal val pathSegmentTypes = PathSegment.Type.values()
\ No newline at end of file
diff --git a/health/connect/connect-client/build.gradle b/health/connect/connect-client/build.gradle
index 8a8757a..d346b3d 100644
--- a/health/connect/connect-client/build.gradle
+++ b/health/connect/connect-client/build.gradle
@@ -43,6 +43,7 @@
implementation(libs.guavaAndroid)
implementation(libs.kotlinCoroutinesAndroid)
implementation(libs.kotlinCoroutinesGuava)
+ implementation("androidx.core:core-ktx:1.8.0")
testImplementation(libs.testCore)
testImplementation(libs.testRunner)
@@ -58,6 +59,13 @@
testImplementation(libs.espressoIntents)
testImplementation(libs.kotlinReflect)
+ androidTestImplementation(libs.testExtJunit)
+ androidTestImplementation(libs.kotlinCoroutinesTest)
+ androidTestImplementation(libs.kotlinReflect)
+ androidTestImplementation(libs.kotlinTest)
+ androidTestImplementation(libs.junit)
+ androidTestImplementation(libs.truth)
+
samples(project(":health:connect:connect-client-samples"))
}
diff --git a/health/connect/connect-client/src/androidTest/AndroidManifest.xml b/health/connect/connect-client/src/androidTest/AndroidManifest.xml
index 4d68dc2..fc6f218 100644
--- a/health/connect/connect-client/src/androidTest/AndroidManifest.xml
+++ b/health/connect/connect-client/src/androidTest/AndroidManifest.xml
@@ -15,5 +15,99 @@
limitations under the License.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <!-- Read permissions for ACTIVITY. -->
+ <uses-permission android:name="android.permission.health.READ_ACTIVE_CALORIES_BURNED"/>
+ <uses-permission android:name="android.permission.health.READ_DISTANCE"/>
+ <uses-permission android:name="android.permission.health.READ_ELEVATION_GAINED"/>
+ <uses-permission android:name="android.permission.health.READ_EXERCISE"/>
+ <uses-permission android:name="android.permission.health.READ_FLOORS_CLIMBED"/>
+ <uses-permission android:name="android.permission.health.READ_STEPS"/>
+ <uses-permission android:name="android.permission.health.READ_TOTAL_CALORIES_BURNED"/>
+ <uses-permission android:name="android.permission.health.READ_VO2_MAX"/>
+ <uses-permission android:name="android.permission.health.READ_WHEELCHAIR_PUSHES"/>
+ <uses-permission android:name="android.permission.health.READ_POWER"/>
+ <uses-permission android:name="android.permission.health.READ_SPEED"/>
+ <!-- Read permissions for BODY_MEASUREMENTS. -->
+ <uses-permission android:name="android.permission.health.READ_BASAL_METABOLIC_RATE"/>
+ <uses-permission android:name="android.permission.health.READ_BODY_FAT"/>
+ <uses-permission android:name="android.permission.health.READ_BODY_WATER_MASS"/>
+ <uses-permission android:name="android.permission.health.READ_BONE_MASS"/>
+ <uses-permission android:name="android.permission.health.READ_HEIGHT"/>
+ <uses-permission android:name="android.permission.health.READ_HIP_CIRCUMFERENCE"/>
+ <uses-permission android:name="android.permission.health.READ_LEAN_BODY_MASS"/>
+ <uses-permission android:name="android.permission.health.READ_WAIST_CIRCUMFERENCE"/>
+ <uses-permission android:name="android.permission.health.READ_WEIGHT"/>
+
+ <!-- Read permissions for CYCLE_TRACKING. -->
+ <uses-permission android:name="android.permission.health.READ_CERVICAL_MUCUS"/>
+ <uses-permission android:name="android.permission.health.READ_MENSTRUATION"/>
+ <uses-permission android:name="android.permission.health.READ_OVULATION_TEST"/>
+ <uses-permission android:name="android.permission.health.READ_SEXUAL_ACTIVITY"/>
+
+ <!-- Read permissions for NUTRITION. -->
+ <uses-permission android:name="android.permission.health.READ_HYDRATION"/>
+ <uses-permission android:name="android.permission.health.READ_NUTRITION"/>
+
+ <!-- Read permissions for SLEEP. -->
+ <uses-permission android:name="android.permission.health.READ_SLEEP"/>
+
+ <!-- Read permissions for VITALS. -->
+ <uses-permission android:name="android.permission.health.READ_BASAL_BODY_TEMPERATURE"/>
+ <uses-permission android:name="android.permission.health.READ_BLOOD_GLUCOSE"/>
+ <uses-permission android:name="android.permission.health.READ_BLOOD_PRESSURE"/>
+ <uses-permission android:name="android.permission.health.READ_BODY_TEMPERATURE"/>
+ <uses-permission android:name="android.permission.health.READ_HEART_RATE"/>
+ <uses-permission android:name="android.permission.health.READ_HEART_RATE_VARIABILITY"/>
+ <uses-permission android:name="android.permission.health.READ_OXYGEN_SATURATION"/>
+ <uses-permission android:name="android.permission.health.READ_RESPIRATORY_RATE"/>
+ <uses-permission android:name="android.permission.health.READ_RESTING_HEART_RATE"/>
+
+ <!-- Write permissions for ACTIVITY. -->
+ <uses-permission android:name="android.permission.health.WRITE_ACTIVE_CALORIES_BURNED"/>
+ <uses-permission android:name="android.permission.health.WRITE_DISTANCE"/>
+ <uses-permission android:name="android.permission.health.WRITE_ELEVATION_GAINED"/>
+ <uses-permission android:name="android.permission.health.WRITE_EXERCISE"/>
+ <uses-permission android:name="android.permission.health.WRITE_FLOORS_CLIMBED"/>
+ <uses-permission android:name="android.permission.health.WRITE_STEPS"/>
+ <uses-permission android:name="android.permission.health.WRITE_TOTAL_CALORIES_BURNED"/>
+ <uses-permission android:name="android.permission.health.WRITE_VO2_MAX"/>
+ <uses-permission android:name="android.permission.health.WRITE_WHEELCHAIR_PUSHES"/>
+ <uses-permission android:name="android.permission.health.WRITE_POWER"/>
+ <uses-permission android:name="android.permission.health.WRITE_SPEED"/>
+
+ <!-- Write permissions for BODY_MEASUREMENTS. -->
+ <uses-permission android:name="android.permission.health.WRITE_BASAL_METABOLIC_RATE"/>
+ <uses-permission android:name="android.permission.health.WRITE_BODY_FAT"/>
+ <uses-permission android:name="android.permission.health.WRITE_BODY_WATER_MASS"/>
+ <uses-permission android:name="android.permission.health.WRITE_BONE_MASS"/>
+ <uses-permission android:name="android.permission.health.WRITE_HEIGHT"/>
+ <uses-permission android:name="android.permission.health.WRITE_HIP_CIRCUMFERENCE"/>
+ <uses-permission android:name="android.permission.health.WRITE_LEAN_BODY_MASS"/>
+ <uses-permission android:name="android.permission.health.WRITE_WAIST_CIRCUMFERENCE"/>
+ <uses-permission android:name="android.permission.health.WRITE_WEIGHT"/>
+
+ <!-- Write permissions for CYCLE_TRACKING. -->
+ <uses-permission android:name="android.permission.health.WRITE_CERVICAL_MUCUS"/>
+ <uses-permission android:name="android.permission.health.WRITE_MENSTRUATION"/>
+ <uses-permission android:name="android.permission.health.WRITE_OVULATION_TEST"/>
+ <uses-permission android:name="android.permission.health.WRITE_SEXUAL_ACTIVITY"/>
+
+ <!-- Write permissions for NUTRITION. -->
+ <uses-permission android:name="android.permission.health.WRITE_HYDRATION"/>
+ <uses-permission android:name="android.permission.health.WRITE_NUTRITION"/>
+
+ <!-- Write permissions for SLEEP. -->
+ <uses-permission android:name="android.permission.health.WRITE_SLEEP"/>
+
+ <!-- Write permissions for VITALS. -->
+ <uses-permission android:name="android.permission.health.WRITE_BASAL_BODY_TEMPERATURE"/>
+ <uses-permission android:name="android.permission.health.WRITE_BLOOD_GLUCOSE"/>
+ <uses-permission android:name="android.permission.health.WRITE_BLOOD_PRESSURE"/>
+ <uses-permission android:name="android.permission.health.WRITE_BODY_TEMPERATURE"/>
+ <uses-permission android:name="android.permission.health.WRITE_HEART_RATE"/>
+ <uses-permission android:name="android.permission.health.WRITE_HEART_RATE_VARIABILITY"/>
+ <uses-permission android:name="android.permission.health.WRITE_OXYGEN_SATURATION"/>
+ <uses-permission android:name="android.permission.health.WRITE_RESPIRATORY_RATE"/>
+ <uses-permission android:name="android.permission.health.WRITE_RESTING_HEART_RATE"/>
</manifest>
diff --git a/health/connect/connect-client/src/androidTest/java/androidx/health/connect/client/impl/HealthConnectClientUpsideDownImplTest.kt b/health/connect/connect-client/src/androidTest/java/androidx/health/connect/client/impl/HealthConnectClientUpsideDownImplTest.kt
new file mode 100644
index 0000000..1c6270a
--- /dev/null
+++ b/health/connect/connect-client/src/androidTest/java/androidx/health/connect/client/impl/HealthConnectClientUpsideDownImplTest.kt
@@ -0,0 +1,411 @@
+/*
+ * 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 androidx.health.connect.client.impl
+
+import android.annotation.TargetApi
+import android.content.Context
+import android.content.pm.PackageManager
+import android.os.Build
+import android.os.RemoteException
+import androidx.health.connect.client.HealthConnectClient
+import androidx.health.connect.client.changes.DeletionChange
+import androidx.health.connect.client.changes.UpsertionChange
+import androidx.health.connect.client.permission.HealthPermission
+import androidx.health.connect.client.permission.HealthPermission.Companion.PERMISSION_PREFIX
+import androidx.health.connect.client.records.StepsRecord
+import androidx.health.connect.client.records.metadata.Metadata
+import androidx.health.connect.client.request.AggregateGroupByDurationRequest
+import androidx.health.connect.client.request.AggregateGroupByPeriodRequest
+import androidx.health.connect.client.request.AggregateRequest
+import androidx.health.connect.client.request.ChangesTokenRequest
+import androidx.health.connect.client.request.ReadRecordsRequest
+import androidx.health.connect.client.time.TimeRangeFilter
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.MediumTest
+import androidx.test.filters.SdkSuppress
+import androidx.test.rule.GrantPermissionRule
+import com.google.common.truth.Truth.assertThat
+import java.time.Duration
+import java.time.Instant
+import java.time.LocalDateTime
+import java.time.Period
+import java.time.ZoneOffset
+import kotlin.test.assertFailsWith
+import kotlinx.coroutines.test.runTest
+import org.junit.After
+import org.junit.Before
+import org.junit.Ignore
+import org.junit.Rule
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@RunWith(AndroidJUnit4::class)
+@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
+@MediumTest
+@TargetApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
+// Comment the SDK suppress to run on emulators lower than U.
+@SdkSuppress(minSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE, codeName = "UpsideDownCake")
+class HealthConnectClientUpsideDownImplTest {
+
+ private val context: Context = ApplicationProvider.getApplicationContext()
+ private val allHealthPermissions =
+ context.packageManager
+ .getPackageInfo(
+ context.packageName,
+ PackageManager.PackageInfoFlags.of(PackageManager.GET_PERMISSIONS.toLong())
+ )
+ .requestedPermissions
+ .filter { it.startsWith(PERMISSION_PREFIX) }
+ .toTypedArray()
+
+ // Grant every permission as deletion by id checks for every permission
+ @get:Rule
+ val grantPermissionRule: GrantPermissionRule = GrantPermissionRule.grant(*allHealthPermissions)
+
+ private lateinit var healthConnectClient: HealthConnectClient
+
+ @Before
+ fun setUp() {
+ healthConnectClient = HealthConnectClientUpsideDownImpl(context)
+ }
+
+ @After
+ fun tearDown() = runTest {
+ healthConnectClient.deleteRecords(StepsRecord::class, TimeRangeFilter.none())
+ }
+
+ @Test
+ fun insertRecords() = runTest {
+ val response =
+ healthConnectClient.insertRecords(
+ listOf(
+ StepsRecord(
+ count = 100,
+ startTime = Instant.ofEpochMilli(1234L),
+ startZoneOffset = null,
+ endTime = Instant.ofEpochMilli(5678L),
+ endZoneOffset = null
+ )
+ )
+ )
+ assertThat(response.recordIdsList).hasSize(1)
+ }
+
+ @Test
+ fun deleteRecords_byId() = runTest {
+ val recordIds =
+ healthConnectClient
+ .insertRecords(
+ listOf(
+ StepsRecord(
+ count = 100,
+ startTime = Instant.ofEpochMilli(1234L),
+ startZoneOffset = null,
+ endTime = Instant.ofEpochMilli(5678L),
+ endZoneOffset = null
+ ),
+ StepsRecord(
+ count = 150,
+ startTime = Instant.ofEpochMilli(12340L),
+ startZoneOffset = null,
+ endTime = Instant.ofEpochMilli(56780L),
+ endZoneOffset = null
+ ),
+ StepsRecord(
+ count = 200,
+ startTime = Instant.ofEpochMilli(123400L),
+ startZoneOffset = null,
+ endTime = Instant.ofEpochMilli(567800L),
+ endZoneOffset = null,
+ metadata = Metadata(clientRecordId = "clientId")
+ ),
+ )
+ )
+ .recordIdsList
+
+ val initialRecords =
+ healthConnectClient
+ .readRecords(ReadRecordsRequest(StepsRecord::class, TimeRangeFilter.none()))
+ .records
+
+ healthConnectClient.deleteRecords(
+ StepsRecord::class,
+ listOf(recordIds[1]),
+ listOf("clientId")
+ )
+
+ assertThat(
+ healthConnectClient
+ .readRecords(ReadRecordsRequest(StepsRecord::class, TimeRangeFilter.none()))
+ .records
+ )
+ .containsExactly(initialRecords[0])
+ }
+
+ // TODO(b/264253708): remove @Ignore from this test case once bug is resolved
+ @Test
+ @Ignore("Blocked while investigating b/264253708")
+ fun deleteRecords_byTimeRange() = runTest {
+ healthConnectClient
+ .insertRecords(
+ listOf(
+ StepsRecord(
+ count = 100,
+ startTime = Instant.ofEpochMilli(1_234L),
+ startZoneOffset = ZoneOffset.UTC,
+ endTime = Instant.ofEpochMilli(5_678L),
+ endZoneOffset = ZoneOffset.UTC
+ ),
+ StepsRecord(
+ count = 150,
+ startTime = Instant.ofEpochMilli(12_340L),
+ startZoneOffset = ZoneOffset.UTC,
+ endTime = Instant.ofEpochMilli(56_780L),
+ endZoneOffset = ZoneOffset.UTC
+ ),
+ )
+ )
+ .recordIdsList
+
+ val initialRecords =
+ healthConnectClient
+ .readRecords(ReadRecordsRequest(StepsRecord::class, TimeRangeFilter.none()))
+ .records
+
+ healthConnectClient.deleteRecords(
+ StepsRecord::class,
+ TimeRangeFilter.before(Instant.ofEpochMilli(10_000L))
+ )
+
+ assertThat(
+ healthConnectClient
+ .readRecords(ReadRecordsRequest(StepsRecord::class, TimeRangeFilter.none()))
+ .records
+ )
+ .containsExactly(initialRecords[1])
+ }
+
+ @Test
+ fun updateRecords() = runTest {
+ val id =
+ healthConnectClient
+ .insertRecords(
+ listOf(
+ StepsRecord(
+ count = 100,
+ startTime = Instant.ofEpochMilli(1234L),
+ startZoneOffset = null,
+ endTime = Instant.ofEpochMilli(5678L),
+ endZoneOffset = null
+ )
+ )
+ )
+ .recordIdsList[0]
+
+ val insertedRecord = healthConnectClient.readRecord(StepsRecord::class, id).record
+
+ healthConnectClient.updateRecords(
+ listOf(
+ StepsRecord(
+ count = 50,
+ startTime = Instant.ofEpochMilli(1234L),
+ startZoneOffset = null,
+ endTime = Instant.ofEpochMilli(5678L),
+ endZoneOffset = null,
+ metadata = Metadata(id, insertedRecord.metadata.dataOrigin)
+ )
+ )
+ )
+
+ val updatedRecord = healthConnectClient.readRecord(StepsRecord::class, id).record
+
+ assertThat(updatedRecord.count).isEqualTo(50L)
+ }
+
+ @Test
+ fun readRecord_withId() = runTest {
+ val insertResponse =
+ healthConnectClient.insertRecords(
+ listOf(
+ StepsRecord(
+ count = 100,
+ startTime = Instant.ofEpochMilli(1234L),
+ startZoneOffset = ZoneOffset.UTC,
+ endTime = Instant.ofEpochMilli(5678L),
+ endZoneOffset = ZoneOffset.UTC
+ )
+ )
+ )
+
+ val readResponse =
+ healthConnectClient.readRecord(StepsRecord::class, insertResponse.recordIdsList[0])
+
+ with(readResponse.record) {
+ assertThat(count).isEqualTo(100)
+ assertThat(startTime).isEqualTo(Instant.ofEpochMilli(1234L))
+ assertThat(startZoneOffset).isEqualTo(ZoneOffset.UTC)
+ assertThat(endTime).isEqualTo(Instant.ofEpochMilli(5678L))
+ assertThat(endZoneOffset).isEqualTo(ZoneOffset.UTC)
+ }
+ }
+
+ @Test
+ fun readRecords_withFilters() = runTest {
+ healthConnectClient.insertRecords(
+ listOf(
+ StepsRecord(
+ count = 100,
+ startTime = Instant.ofEpochMilli(1234L),
+ startZoneOffset = ZoneOffset.UTC,
+ endTime = Instant.ofEpochMilli(5678L),
+ endZoneOffset = ZoneOffset.UTC
+ ),
+ StepsRecord(
+ count = 50,
+ startTime = Instant.ofEpochMilli(12340L),
+ startZoneOffset = ZoneOffset.UTC,
+ endTime = Instant.ofEpochMilli(56780L),
+ endZoneOffset = ZoneOffset.UTC
+ ),
+ )
+ )
+
+ val readResponse =
+ healthConnectClient.readRecords(
+ ReadRecordsRequest(
+ StepsRecord::class,
+ TimeRangeFilter.after(Instant.ofEpochMilli(10_000L))
+ )
+ )
+
+ assertThat(readResponse.records[0].count).isEqualTo(50)
+ }
+
+ @Test
+ fun readRecord_noRecords_throwRemoteException() = runTest {
+ assertFailsWith<RemoteException> { healthConnectClient.readRecord(StepsRecord::class, "1") }
+ }
+
+ @Test
+ fun aggregateRecords_throwUOE() = runTest {
+ assertFailsWith<UnsupportedOperationException> {
+ healthConnectClient.aggregate(
+ AggregateRequest(
+ setOf(StepsRecord.COUNT_TOTAL),
+ TimeRangeFilter.between(
+ Instant.ofEpochMilli(1234L),
+ Instant.ofEpochMilli(1235L)
+ )
+ )
+ )
+ }
+ }
+
+ @Test
+ fun aggregateRecordsGroupByDuration_throwUOE() = runTest {
+ assertFailsWith<UnsupportedOperationException> {
+ healthConnectClient.aggregateGroupByDuration(
+ AggregateGroupByDurationRequest(
+ setOf(StepsRecord.COUNT_TOTAL),
+ TimeRangeFilter.between(
+ Instant.ofEpochMilli(1234L),
+ Instant.ofEpochMilli(1235L)
+ ),
+ timeRangeSlicer = Duration.ofMillis(1)
+ )
+ )
+ }
+ }
+
+ @Test
+ fun aggregateRecordsGroupByPeriod_throwUOE() = runTest {
+ assertFailsWith<UnsupportedOperationException> {
+ healthConnectClient.aggregateGroupByPeriod(
+ AggregateGroupByPeriodRequest(
+ setOf(StepsRecord.COUNT_TOTAL),
+ TimeRangeFilter.between(
+ LocalDateTime.of(2018, 10, 11, 7, 10),
+ LocalDateTime.of(2018, 10, 13, 7, 10),
+ ),
+ timeRangeSlicer = Period.ofDays(1)
+ )
+ )
+ }
+ }
+
+ @Test
+ fun getChangesToken() = runTest {
+ val token =
+ healthConnectClient.getChangesToken(
+ ChangesTokenRequest(setOf(StepsRecord::class), setOf())
+ )
+ assertThat(token).isNotEmpty()
+ }
+
+ @Test
+ fun getChanges() = runTest {
+ val token =
+ healthConnectClient.getChangesToken(
+ ChangesTokenRequest(setOf(StepsRecord::class), setOf())
+ )
+
+ val insertedRecordId =
+ healthConnectClient
+ .insertRecords(
+ listOf(
+ StepsRecord(
+ count = 100,
+ startTime = Instant.ofEpochMilli(1234L),
+ startZoneOffset = ZoneOffset.UTC,
+ endTime = Instant.ofEpochMilli(5678L),
+ endZoneOffset = ZoneOffset.UTC
+ )
+ )
+ )
+ .recordIdsList[0]
+
+ val record = healthConnectClient.readRecord(StepsRecord::class, insertedRecordId).record
+
+ assertThat(healthConnectClient.getChanges(token).changes)
+ .containsExactly(UpsertionChange(record))
+
+ healthConnectClient.deleteRecords(StepsRecord::class, TimeRangeFilter.none())
+
+ assertThat(healthConnectClient.getChanges(token).changes)
+ .containsExactly(DeletionChange(insertedRecordId))
+ }
+
+ @Test
+ fun getGrantedPermissions() = runTest {
+ assertThat(healthConnectClient.permissionController.getGrantedPermissions())
+ .containsExactlyElementsIn(allHealthPermissions)
+ }
+
+ @Test
+ fun getGrantedPermission_throwUOE() = runTest {
+ assertFailsWith<UnsupportedOperationException> {
+ healthConnectClient.permissionController.getGrantedPermissionsLegacy(
+ setOf(
+ HealthPermission.createReadPermissionLegacy(
+ StepsRecord::class,
+ )
+ )
+ )
+ }
+ }
+}
diff --git a/health/connect/connect-client/src/androidTest/java/androidx/health/connect/client/impl/PermissionControllerUpsideDownTest.kt b/health/connect/connect-client/src/androidTest/java/androidx/health/connect/client/impl/PermissionControllerUpsideDownTest.kt
new file mode 100644
index 0000000..7484a77
--- /dev/null
+++ b/health/connect/connect-client/src/androidTest/java/androidx/health/connect/client/impl/PermissionControllerUpsideDownTest.kt
@@ -0,0 +1,61 @@
+/*
+ * 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 androidx.health.connect.client.impl
+
+import android.annotation.TargetApi
+import android.healthconnect.HealthPermissions
+import android.os.Build
+import androidx.health.connect.client.PermissionController
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.MediumTest
+import androidx.test.filters.SdkSuppress
+import androidx.test.rule.GrantPermissionRule
+import com.google.common.truth.Truth.assertThat
+import kotlinx.coroutines.test.runTest
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@RunWith(AndroidJUnit4::class)
+@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
+@MediumTest
+@TargetApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
+// Comment the SDK suppress to run on emulators lower than U.
+@SdkSuppress(minSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE, codeName = "UpsideDownCake")
+class PermissionControllerUpsideDownTest {
+
+ @get:Rule
+ val grantPermissionRule: GrantPermissionRule =
+ GrantPermissionRule.grant(HealthPermissions.WRITE_STEPS, HealthPermissions.READ_DISTANCE)
+
+ private lateinit var permissionController: PermissionController
+
+ @Before
+ fun setUp() {
+ permissionController =
+ HealthConnectClientUpsideDownImpl(ApplicationProvider.getApplicationContext())
+ .permissionController
+ }
+
+ @Test
+ fun getGrantedPermissions() = runTest {
+ assertThat(permissionController.getGrantedPermissions())
+ .containsExactly(HealthPermissions.WRITE_STEPS, HealthPermissions.READ_DISTANCE)
+ }
+}
diff --git a/health/connect/connect-client/src/androidTest/java/androidx/health/connect/client/impl/platform/records/RecordsConvertersTest.kt b/health/connect/connect-client/src/androidTest/java/androidx/health/connect/client/impl/platform/records/RecordsConvertersTest.kt
new file mode 100644
index 0000000..e875f54
--- /dev/null
+++ b/health/connect/connect-client/src/androidTest/java/androidx/health/connect/client/impl/platform/records/RecordsConvertersTest.kt
@@ -0,0 +1,100 @@
+/*
+ * 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 androidx.health.connect.client.impl.platform.records
+
+import android.annotation.TargetApi
+import android.healthconnect.datatypes.DataOrigin
+import android.healthconnect.datatypes.Device
+import android.healthconnect.datatypes.Metadata
+import android.healthconnect.datatypes.StepsRecord
+import android.os.Build
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SdkSuppress
+import androidx.test.filters.SmallTest
+import com.google.common.truth.Truth.assertThat
+import java.time.Instant
+import org.junit.Test
+import org.junit.runner.RunWith
+import androidx.health.connect.client.records.StepsRecord as SdkStepsRecord
+import androidx.health.connect.client.records.metadata.Device as SdkDevice
+import androidx.health.connect.client.records.metadata.DataOrigin as SdkDataOrigin
+
+@RunWith(AndroidJUnit4::class)
+@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
+@SmallTest
+@TargetApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
+// Comment the SDK suppress to run on emulators lower than U.
+@SdkSuppress(minSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE, codeName = "UpsideDownCake")
+class RecordsConvertersTest {
+
+ @Test
+ fun stepsRecord_convertFromSdkToPlatformClass() {
+ val stepsSdkClass = SdkStepsRecord::class
+ val stepsPlatformClass = StepsRecord::class.java
+
+ assertThat(stepsSdkClass.toPlatformRecordClass()).isEqualTo(stepsPlatformClass)
+ }
+
+ @Test
+ fun stepsRecord_convertFromSdkToPlatform() {
+ val steps = SdkStepsRecord(
+ count = 100,
+ startTime = Instant.ofEpochMilli(1234L),
+ startZoneOffset = null,
+ endTime = Instant.ofEpochMilli(5678L),
+ endZoneOffset = null
+ )
+
+ val platformSteps = steps.toPlatformRecord() as StepsRecord
+
+ assertThat(platformSteps.count).isEqualTo(100)
+ assertThat(platformSteps.startTime).isEqualTo(Instant.ofEpochMilli(1234L))
+ assertThat(platformSteps.endTime).isEqualTo(Instant.ofEpochMilli(5678L))
+ }
+
+ @Test
+ fun stepsRecord_convertFromPlatformToSdk() {
+ val steps = StepsRecord.Builder(Metadata.Builder().apply {
+ setDevice(Device.Builder().setType(Device.DEVICE_TYPE_WATCH).build())
+ setClientRecordVersion(123L)
+ setDataOrigin(DataOrigin.Builder().setPackageName("com.packageName").build())
+ setLastModifiedTime(Instant.ofEpochMilli(9999L))
+ }.build(), Instant.ofEpochMilli(5678L), Instant.ofEpochMilli(9012L), 200).build()
+
+ val sdkSteps = steps.toSdkRecord() as SdkStepsRecord
+
+ with(sdkSteps) {
+ assertThat(count).isEqualTo(200)
+ assertThat(startTime).isEqualTo(Instant.ofEpochMilli(5678L))
+ assertThat(endTime).isEqualTo(Instant.ofEpochMilli(9012L))
+
+ with(metadata) {
+ assertThat(device).isEqualTo(
+ SdkDevice(
+ type = Device.DEVICE_TYPE_WATCH
+ )
+ )
+ assertThat(clientRecordVersion).isEqualTo(123L)
+ assertThat(dataOrigin).isEqualTo(
+ SdkDataOrigin(
+ "com.packageName"
+ )
+ )
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/health/connect/connect-client/src/androidTest/java/androidx/health/connect/client/impl/platform/records/RequestConvertersTest.kt b/health/connect/connect-client/src/androidTest/java/androidx/health/connect/client/impl/platform/records/RequestConvertersTest.kt
new file mode 100644
index 0000000..9aeb0b3
--- /dev/null
+++ b/health/connect/connect-client/src/androidTest/java/androidx/health/connect/client/impl/platform/records/RequestConvertersTest.kt
@@ -0,0 +1,107 @@
+/*
+ * 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 androidx.health.connect.client.impl.platform.records
+
+import android.healthconnect.datatypes.DataOrigin as PlatformDataOrigin
+import android.healthconnect.datatypes.StepsRecord as PlatformStepsRecord
+import android.annotation.TargetApi
+import android.os.Build
+import androidx.health.connect.client.impl.platform.time.SystemDefaultTimeSource
+import androidx.health.connect.client.impl.platform.time.FakeTimeSource
+import androidx.health.connect.client.records.HeartRateRecord
+import androidx.health.connect.client.records.StepsRecord
+import androidx.health.connect.client.records.metadata.DataOrigin
+import android.healthconnect.datatypes.HeartRateRecord as PlatformHeartRateRecord
+import androidx.health.connect.client.request.ChangesTokenRequest
+import androidx.health.connect.client.request.ReadRecordsRequest
+import androidx.health.connect.client.time.TimeRangeFilter
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SdkSuppress
+import androidx.test.filters.SmallTest
+import com.google.common.truth.Truth.assertThat
+import java.time.Instant
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@RunWith(AndroidJUnit4::class)
+@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
+@SmallTest
+@TargetApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
+// Comment the SDK suppress to run on emulators lower than U.
+@SdkSuppress(minSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE, codeName = "UpsideDownCake")
+class RequestConvertersTest {
+
+ @Test
+ fun readRecordsRequest_fromSdkToPlatform() {
+ val sdkRequest = ReadRecordsRequest(
+ StepsRecord::class,
+ TimeRangeFilter.between(Instant.ofEpochMilli(123L), Instant.ofEpochMilli(456L)),
+ setOf(DataOrigin("package1"), DataOrigin("package2"))
+ )
+
+ with(sdkRequest.toPlatformReadRecordsRequestUsingFilters(SystemDefaultTimeSource)) {
+ assertThat(recordType).isAssignableTo(PlatformStepsRecord::class.java)
+ assertThat(dataOrigins).containsExactly(
+ PlatformDataOrigin.Builder().setPackageName("package1").build(),
+ PlatformDataOrigin.Builder().setPackageName("package2").build()
+ )
+ }
+ }
+
+ @Test
+ fun changesTokenRequest_fromSdkToPlatform() {
+ val sdkRequest = ChangesTokenRequest(
+ setOf(StepsRecord::class, HeartRateRecord::class),
+ setOf(DataOrigin("package1"), DataOrigin("package2"))
+ )
+
+ with(sdkRequest.toPlatformChangeLogTokenRequest()) {
+ assertThat(recordTypes).containsExactly(
+ PlatformStepsRecord::class.java,
+ PlatformHeartRateRecord::class.java
+ )
+ assertThat(dataOriginFilters).containsExactly(
+ PlatformDataOrigin.Builder().setPackageName("package1").build(),
+ PlatformDataOrigin.Builder().setPackageName("package2").build()
+ )
+ }
+ }
+
+ @Test
+ fun timeRangeFilter_fromSdkToPlatform() {
+ val sdkFilter =
+ TimeRangeFilter.between(Instant.ofEpochMilli(123L), Instant.ofEpochMilli(456L))
+
+ with(sdkFilter.toPlatformTimeRangeFilter(SystemDefaultTimeSource)) {
+ assertThat(startTime).isEqualTo(Instant.ofEpochMilli(123L))
+ assertThat(endTime).isEqualTo(Instant.ofEpochMilli(456L))
+ }
+ }
+
+ @Test
+ fun timeRangeFilter_fromSdkToPlatform_none() {
+ val timeSource = FakeTimeSource()
+ timeSource.now = Instant.ofEpochMilli(123L)
+
+ val sdkFilter = TimeRangeFilter.none()
+
+ with(sdkFilter.toPlatformTimeRangeFilter(timeSource)) {
+ assertThat(startTime).isEqualTo(Instant.EPOCH)
+ assertThat(endTime).isEqualTo(Instant.ofEpochMilli(123L))
+ }
+ }
+}
\ No newline at end of file
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityA.kt b/health/connect/connect-client/src/androidTest/java/androidx/health/connect/client/impl/platform/time/FakeTimeSource.kt
similarity index 68%
copy from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityA.kt
copy to health/connect/connect-client/src/androidTest/java/androidx/health/connect/client/impl/platform/time/FakeTimeSource.kt
index 7053e2d..270eaf4 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityA.kt
+++ b/health/connect/connect-client/src/androidTest/java/androidx/health/connect/client/impl/platform/time/FakeTimeSource.kt
@@ -14,6 +14,13 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+package androidx.health.connect.client.impl.platform.time
-open class SplitPipActivityA : SplitPipActivityBase()
\ No newline at end of file
+import android.os.Build
+import androidx.annotation.RequiresApi
+import java.time.Instant
+
+@RequiresApi(api = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
+class FakeTimeSource : TimeSource {
+ override lateinit var now: Instant
+}
\ No newline at end of file
diff --git a/health/connect/connect-client/src/main/java/androidx/health/connect/client/PermissionController.kt b/health/connect/connect-client/src/main/java/androidx/health/connect/client/PermissionController.kt
index c82bdd1..3f08aee 100644
--- a/health/connect/connect-client/src/main/java/androidx/health/connect/client/PermissionController.kt
+++ b/health/connect/connect-client/src/main/java/androidx/health/connect/client/PermissionController.kt
@@ -15,12 +15,15 @@
*/
package androidx.health.connect.client
+import android.os.Build.VERSION
+import android.os.Build.VERSION_CODES
import androidx.activity.result.contract.ActivityResultContract
import androidx.annotation.RestrictTo
import androidx.health.connect.client.HealthConnectClient.Companion.DEFAULT_PROVIDER_PACKAGE_NAME
import androidx.health.connect.client.permission.HealthDataRequestPermissions
import androidx.health.connect.client.permission.HealthDataRequestPermissionsInternal
import androidx.health.connect.client.permission.HealthPermission
+import androidx.health.connect.client.permission.platform.HealthDataRequestPermissionsUpsideDownCake
@JvmDefaultWithCompatibility
/** Interface for operations related to permissions. */
@@ -91,7 +94,11 @@
fun createRequestPermissionResultContract(
providerPackageName: String = DEFAULT_PROVIDER_PACKAGE_NAME
): ActivityResultContract<Set<String>, Set<String>> {
- return HealthDataRequestPermissionsInternal(providerPackageName = providerPackageName)
+ if (VERSION.SDK_INT < VERSION_CODES.UPSIDE_DOWN_CAKE) {
+ return HealthDataRequestPermissionsInternal(
+ providerPackageName = providerPackageName)
+ }
+ return HealthDataRequestPermissionsUpsideDownCake()
}
}
}
diff --git a/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/HealthConnectClientUpsideDownImpl.kt b/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/HealthConnectClientUpsideDownImpl.kt
new file mode 100644
index 0000000..50c33b0
--- /dev/null
+++ b/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/HealthConnectClientUpsideDownImpl.kt
@@ -0,0 +1,294 @@
+/*
+ * 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 androidx.health.connect.client.impl
+
+import android.content.Context
+import android.content.pm.PackageInfo.REQUESTED_PERMISSION_GRANTED
+import android.content.pm.PackageManager.GET_PERMISSIONS
+import android.content.pm.PackageManager.PackageInfoFlags
+import android.healthconnect.ChangeLogsRequest
+import android.healthconnect.HealthConnectException
+import android.healthconnect.HealthConnectManager
+import android.healthconnect.ReadRecordsRequestUsingIds
+import android.healthconnect.RecordIdFilter
+import android.os.Build
+import android.os.RemoteException
+import androidx.annotation.RequiresApi
+import androidx.core.os.asOutcomeReceiver
+import androidx.health.connect.client.HealthConnectClient
+import androidx.health.connect.client.PermissionController
+import androidx.health.connect.client.aggregate.AggregationResult
+import androidx.health.connect.client.aggregate.AggregationResultGroupedByDuration
+import androidx.health.connect.client.aggregate.AggregationResultGroupedByPeriod
+import androidx.health.connect.client.changes.DeletionChange
+import androidx.health.connect.client.changes.UpsertionChange
+import androidx.health.connect.client.impl.platform.records.toPlatformChangeLogTokenRequest
+import androidx.health.connect.client.impl.platform.records.toPlatformReadRecordsRequestUsingFilters
+import androidx.health.connect.client.impl.platform.records.toPlatformRecord
+import androidx.health.connect.client.impl.platform.records.toPlatformRecordClass
+import androidx.health.connect.client.impl.platform.records.toPlatformTimeRangeFilter
+import androidx.health.connect.client.impl.platform.records.toSdkRecord
+import androidx.health.connect.client.impl.platform.response.toKtResponse
+import androidx.health.connect.client.impl.platform.time.SystemDefaultTimeSource
+import androidx.health.connect.client.impl.platform.time.TimeSource
+import androidx.health.connect.client.impl.platform.toKtException
+import androidx.health.connect.client.permission.HealthPermission
+import androidx.health.connect.client.permission.HealthPermission.Companion.PERMISSION_PREFIX
+import androidx.health.connect.client.records.Record
+import androidx.health.connect.client.request.AggregateGroupByDurationRequest
+import androidx.health.connect.client.request.AggregateGroupByPeriodRequest
+import androidx.health.connect.client.request.AggregateRequest
+import androidx.health.connect.client.request.ChangesTokenRequest
+import androidx.health.connect.client.request.ReadRecordsRequest
+import androidx.health.connect.client.response.ChangesResponse
+import androidx.health.connect.client.response.InsertRecordsResponse
+import androidx.health.connect.client.response.ReadRecordResponse
+import androidx.health.connect.client.response.ReadRecordsResponse
+import androidx.health.connect.client.time.TimeRangeFilter
+import kotlin.reflect.KClass
+import kotlinx.coroutines.suspendCancellableCoroutine
+
+/**
+ * Implements the [HealthConnectClient] with APIs in UpsideDownCake.
+ *
+ * @suppress
+ */
+@RequiresApi(api = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
+class HealthConnectClientUpsideDownImpl : HealthConnectClient, PermissionController {
+
+ private val context: Context
+ private val timeSource: TimeSource
+ private val healthConnectManager: HealthConnectManager
+
+ constructor(context: Context) : this(context, SystemDefaultTimeSource)
+
+ internal constructor(context: Context, timeSource: TimeSource) {
+ this.context = context
+ this.timeSource = timeSource
+ this.healthConnectManager =
+ context.getSystemService(Context.HEALTHCONNECT_SERVICE) as HealthConnectManager
+ }
+
+ override val permissionController: PermissionController
+ get() = this
+
+ override suspend fun insertRecords(records: List<Record>): InsertRecordsResponse {
+ val response = wrapPlatformException {
+ suspendCancellableCoroutine { continuation ->
+ healthConnectManager.insertRecords(
+ records.map { it.toPlatformRecord() },
+ Runnable::run,
+ continuation.asOutcomeReceiver()
+ )
+ }
+ }
+ return response.toKtResponse()
+ }
+
+ override suspend fun updateRecords(records: List<Record>) {
+ wrapPlatformException {
+ suspendCancellableCoroutine { continuation ->
+ healthConnectManager.updateRecords(
+ records.map { it.toPlatformRecord() },
+ Runnable::run,
+ continuation.asOutcomeReceiver()
+ )
+ }
+ }
+ }
+
+ override suspend fun deleteRecords(
+ recordType: KClass<out Record>,
+ recordIdsList: List<String>,
+ clientRecordIdsList: List<String>
+ ) {
+ wrapPlatformException {
+ suspendCancellableCoroutine { continuation ->
+ healthConnectManager.deleteRecords(
+ buildList {
+ recordIdsList.forEach {
+ add(
+ RecordIdFilter.fromId(recordType.toPlatformRecordClass(), it)
+ )
+ }
+ clientRecordIdsList.forEach {
+ add(
+ RecordIdFilter.fromClientRecordId(
+ recordType.toPlatformRecordClass(),
+ it
+ )
+ )
+ }
+ },
+ Runnable::run,
+ continuation.asOutcomeReceiver()
+ )
+ }
+ }
+ }
+
+ override suspend fun deleteRecords(
+ recordType: KClass<out Record>,
+ timeRangeFilter: TimeRangeFilter
+ ) {
+ wrapPlatformException {
+ suspendCancellableCoroutine { continuation ->
+ healthConnectManager.deleteRecords(
+ recordType.toPlatformRecordClass(),
+ timeRangeFilter.toPlatformTimeRangeFilter(timeSource),
+ Runnable::run,
+ continuation.asOutcomeReceiver()
+ )
+ }
+ }
+ }
+
+ @Suppress("UNCHECKED_CAST") // Safe to cast as the type should match
+ override suspend fun <T : Record> readRecord(
+ recordType: KClass<T>,
+ recordId: String
+ ): ReadRecordResponse<T> {
+ val response = wrapPlatformException {
+ suspendCancellableCoroutine { continuation ->
+ healthConnectManager.readRecords(
+ ReadRecordsRequestUsingIds.Builder(recordType.toPlatformRecordClass())
+ .addId(recordId)
+ .build(),
+ Runnable::run,
+ continuation.asOutcomeReceiver()
+ )
+ }
+ }
+ if (response.records.isEmpty()) {
+ throw RemoteException("No records")
+ }
+ return ReadRecordResponse(response.records[0].toSdkRecord() as T)
+ }
+
+ @Suppress("UNCHECKED_CAST") // Safe to cast as the type should match
+ override suspend fun <T : Record> readRecords(
+ request: ReadRecordsRequest<T>
+ ): ReadRecordsResponse<T> {
+ val response = wrapPlatformException {
+ suspendCancellableCoroutine { continuation ->
+ healthConnectManager.readRecords(
+ request.toPlatformReadRecordsRequestUsingFilters(timeSource),
+ Runnable::run,
+ continuation.asOutcomeReceiver()
+ )
+ }
+ }
+ // TODO(b/262573513): pass page token
+ return ReadRecordsResponse(response.records.map { it.toSdkRecord() as T }, null)
+ }
+
+ override suspend fun aggregate(request: AggregateRequest): AggregationResult {
+ throw UnsupportedOperationException("Method not supported yet")
+ }
+
+ override suspend fun aggregateGroupByDuration(
+ request: AggregateGroupByDurationRequest
+ ): List<AggregationResultGroupedByDuration> {
+ throw UnsupportedOperationException("Method not supported yet")
+ }
+
+ override suspend fun aggregateGroupByPeriod(
+ request: AggregateGroupByPeriodRequest
+ ): List<AggregationResultGroupedByPeriod> {
+ throw UnsupportedOperationException("Method not supported yet")
+ }
+
+ override suspend fun getChangesToken(request: ChangesTokenRequest): String {
+ return wrapPlatformException {
+ suspendCancellableCoroutine { continuation ->
+ healthConnectManager.getChangeLogToken(
+ request.toPlatformChangeLogTokenRequest(),
+ Runnable::run,
+ continuation.asOutcomeReceiver()
+ )
+ }
+ }.token
+ }
+
+ override suspend fun registerForDataNotifications(
+ notificationIntentAction: String,
+ recordTypes: Iterable<KClass<out Record>>
+ ) {
+ throw UnsupportedOperationException("Method not supported yet")
+ }
+
+ override suspend fun unregisterFromDataNotifications(notificationIntentAction: String) {
+ throw UnsupportedOperationException("Method not supported yet")
+ }
+
+ override suspend fun getChanges(changesToken: String): ChangesResponse {
+ val response = wrapPlatformException {
+ suspendCancellableCoroutine { continuation ->
+ healthConnectManager.getChangeLogs(
+ ChangeLogsRequest.Builder(changesToken).build(),
+ Runnable::run,
+ continuation.asOutcomeReceiver()
+ )
+ }
+ }
+ // TODO(b/263472286) revisit changesTokenExpired field in the constructor
+ return ChangesResponse(
+ buildList {
+ response.upsertedRecords.forEach { add(UpsertionChange(it.toSdkRecord())) }
+ response.deletedRecordIds.forEach { add(DeletionChange(it)) }
+ },
+ response.nextChangesToken,
+ response.hasMorePages(),
+ changesTokenExpired = true
+ )
+ }
+
+ override suspend fun getGrantedPermissionsLegacy(
+ permissions: Set<HealthPermission>
+ ): Set<HealthPermission> {
+ throw UnsupportedOperationException("Method not supported yet")
+ }
+
+ override suspend fun getGrantedPermissions(): Set<String> {
+ context.packageManager
+ .getPackageInfo(context.packageName, PackageInfoFlags.of(GET_PERMISSIONS.toLong()))
+ .let {
+ return buildSet {
+ for (i in it.requestedPermissions.indices) {
+ if (
+ it.requestedPermissions[i].startsWith(PERMISSION_PREFIX) &&
+ it.requestedPermissionsFlags[i] and REQUESTED_PERMISSION_GRANTED > 0
+ ) {
+ add(it.requestedPermissions[i])
+ }
+ }
+ }
+ }
+ }
+
+ override suspend fun revokeAllPermissions() {
+ throw UnsupportedOperationException("Method not supported yet")
+ }
+
+ private suspend fun <T> wrapPlatformException(function: suspend () -> T): T {
+ return try {
+ function()
+ } catch (e: HealthConnectException) {
+ throw e.toKtException()
+ }
+ }
+}
diff --git a/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/ExceptionConverter.kt b/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/ExceptionConverter.kt
new file mode 100644
index 0000000..ae79c6f
--- /dev/null
+++ b/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/ExceptionConverter.kt
@@ -0,0 +1,38 @@
+/*
+ * 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.
+ */
+
+@file:RequiresApi(api = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
+
+package androidx.health.connect.client.impl.platform
+
+import android.healthconnect.HealthConnectException
+import android.os.Build
+import android.os.RemoteException
+import androidx.annotation.RequiresApi
+import java.io.IOException
+import java.lang.IllegalArgumentException
+import java.lang.IllegalStateException
+
+/** Converts exception returned by the platform to one of standard exception class hierarchy. */
+internal fun HealthConnectException.toKtException(): Exception {
+ return when (errorCode) {
+ HealthConnectException.ERROR_IO -> IOException(message)
+ HealthConnectException.ERROR_REMOTE -> RemoteException(message)
+ HealthConnectException.ERROR_SECURITY -> SecurityException(message)
+ HealthConnectException.ERROR_INVALID_ARGUMENT -> IllegalArgumentException(message)
+ else -> IllegalStateException(message)
+ }
+}
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityA.kt b/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/package-info.java
similarity index 67%
copy from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityA.kt
copy to health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/package-info.java
index 7053e2d..dc32f56 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityA.kt
+++ b/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/package-info.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2022 The Android Open Source Project
+ * 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.
@@ -14,6 +14,12 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+/**
+ * Helps with conversions to the platform record and API objects.
+ *
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY)
+package androidx.health.connect.client.impl.platform;
-open class SplitPipActivityA : SplitPipActivityBase()
\ No newline at end of file
+import androidx.annotation.RestrictTo;
diff --git a/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/records/RecordsConverters.kt b/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/records/RecordsConverters.kt
new file mode 100644
index 0000000..023aa24e
--- /dev/null
+++ b/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/records/RecordsConverters.kt
@@ -0,0 +1,131 @@
+/*
+ * 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.
+ */
+
+@file:RestrictTo(RestrictTo.Scope.LIBRARY)
+@file:RequiresApi(api = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
+
+package androidx.health.connect.client.impl.platform.records
+
+import android.healthconnect.datatypes.DataOrigin as PlatformDataOrigin
+import android.healthconnect.datatypes.Device as PlatformDevice
+import android.healthconnect.datatypes.Metadata as PlatformMetadata
+import android.healthconnect.datatypes.Record as PlatformRecord
+import android.healthconnect.datatypes.StepsRecord as PlatformStepsRecord
+import android.healthconnect.datatypes.HeartRateRecord as PlatformHeartRateRecord
+import android.os.Build
+import androidx.annotation.RequiresApi
+import androidx.annotation.RestrictTo
+import androidx.health.connect.client.records.HeartRateRecord
+import androidx.health.connect.client.records.Record
+import androidx.health.connect.client.records.StepsRecord
+import androidx.health.connect.client.records.metadata.DataOrigin
+import androidx.health.connect.client.records.metadata.Device
+import androidx.health.connect.client.records.metadata.Metadata
+import kotlin.reflect.KClass
+
+fun KClass<out Record>.toPlatformRecordClass():
+ Class<out PlatformRecord> {
+ return when (this) {
+ StepsRecord::class -> PlatformStepsRecord::class.java
+ HeartRateRecord::class -> PlatformHeartRateRecord::class.java
+ else -> throw IllegalArgumentException("Unsupported record type $this")
+ }
+}
+
+fun Record.toPlatformRecord(): PlatformRecord {
+ return when (this) {
+ is StepsRecord ->
+ PlatformStepsRecord.Builder(
+ metadata.toPlatformMetadata(),
+ startTime,
+ endTime,
+ count
+ )
+ .apply {
+ startZoneOffset?.let { setStartZoneOffset(it) }
+ endZoneOffset?.let { setEndZoneOffset(it) }
+ }
+ .build()
+
+ else -> throw IllegalArgumentException("Unsupported record $this")
+ }
+}
+
+fun PlatformRecord.toSdkRecord(): Record {
+ return when (this) {
+ is PlatformStepsRecord ->
+ StepsRecord(
+ startTime,
+ startZoneOffset,
+ endTime,
+ endZoneOffset,
+ count,
+ metadata.toSdkMetadata()
+ )
+
+ else -> throw IllegalArgumentException("Unsupported record $this")
+ }
+}
+
+fun Metadata.toPlatformMetadata(): PlatformMetadata {
+ return PlatformMetadata.Builder()
+ .apply {
+ device?.toPlatformDevice()?.let { setDevice(it) }
+ setLastModifiedTime(lastModifiedTime)
+ setId(id)
+ setDataOrigin(dataOrigin.toPlatformDataOrigin())
+ setClientRecordId(clientRecordId)
+ setClientRecordVersion(clientRecordVersion)
+ }
+ .build()
+}
+
+fun PlatformMetadata.toSdkMetadata(): Metadata {
+ return Metadata(
+ id,
+ dataOrigin.toSdkDataOrigin(),
+ lastModifiedTime,
+ clientRecordId,
+ clientRecordVersion,
+ device.toSdkDevice()
+ )
+}
+
+fun Device.toPlatformDevice(): PlatformDevice {
+ @Suppress("WrongConstant") // Platform intdef and jetpack intdef match in value.
+ return PlatformDevice.Builder()
+ .apply {
+ setType(type)
+ manufacturer?.let { setManufacturer(it) }
+ model?.let { setModel(it) }
+ }
+ .build()
+}
+
+fun PlatformDevice.toSdkDevice(): Device {
+ @Suppress("WrongConstant") // Platform intdef and jetpack intdef match in value.
+ return Device(manufacturer, model, type)
+}
+
+fun DataOrigin.toPlatformDataOrigin(): PlatformDataOrigin {
+ return PlatformDataOrigin.Builder()
+ .apply { setPackageName(packageName) }
+ .build()
+}
+
+fun PlatformDataOrigin.toSdkDataOrigin(): DataOrigin {
+ return DataOrigin(packageName)
+}
diff --git a/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/records/RequestConverters.kt b/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/records/RequestConverters.kt
new file mode 100644
index 0000000..1cbce0d
--- /dev/null
+++ b/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/records/RequestConverters.kt
@@ -0,0 +1,67 @@
+/*
+ * 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.
+ */
+
+@file:RestrictTo(RestrictTo.Scope.LIBRARY)
+@file:RequiresApi(api = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
+
+package androidx.health.connect.client.impl.platform.records
+
+import android.healthconnect.TimeRangeFilter as PlatformTimeRangeFilter
+import android.healthconnect.datatypes.Record as PlatformRecord
+import android.healthconnect.ChangeLogTokenRequest
+import android.healthconnect.ReadRecordsRequestUsingFilters
+import android.os.Build
+import androidx.annotation.RequiresApi
+import androidx.annotation.RestrictTo
+import androidx.health.connect.client.impl.platform.time.TimeSource
+import androidx.health.connect.client.records.Record
+import androidx.health.connect.client.request.ChangesTokenRequest
+import androidx.health.connect.client.request.ReadRecordsRequest
+import androidx.health.connect.client.time.TimeRangeFilter
+import java.time.Instant
+
+fun ReadRecordsRequest<out Record>.toPlatformReadRecordsRequestUsingFilters(
+ timeSource: TimeSource
+):
+ ReadRecordsRequestUsingFilters<out PlatformRecord> {
+ return ReadRecordsRequestUsingFilters
+ .Builder(recordType.toPlatformRecordClass())
+ .setTimeRangeFilter(timeRangeFilter.toPlatformTimeRangeFilter(timeSource))
+ .apply {
+ // TODO(b/262691771): revisit data origin filter once privacy decision is finalized
+ dataOriginFilter.forEach { addDataOrigins(it.toPlatformDataOrigin()) }
+ }
+ .build()
+}
+
+fun TimeRangeFilter.toPlatformTimeRangeFilter(
+ timeSource: TimeSource
+): PlatformTimeRangeFilter {
+ // TODO(b/262571990): pass nullable Instant start/end
+ // TODO(b/262571990): pass nullable LocalDateTime start/end
+ return PlatformTimeRangeFilter.Builder(startTime ?: Instant.EPOCH, endTime ?: timeSource.now)
+ .build()
+}
+
+fun ChangesTokenRequest.toPlatformChangeLogTokenRequest(): ChangeLogTokenRequest {
+ return ChangeLogTokenRequest.Builder()
+ .apply {
+ // TODO(b/262691771): revisit data origin filter once privacy decision is finalized
+ dataOriginFilters.forEach { addDataOriginFilter(it.toPlatformDataOrigin()) }
+ recordTypes.forEach { addRecordType(it.toPlatformRecordClass()) }
+ }
+ .build()
+}
\ No newline at end of file
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityA.kt b/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/records/package-info.java
similarity index 66%
copy from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityA.kt
copy to health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/records/package-info.java
index 7053e2d..c5b8a8e 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityA.kt
+++ b/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/records/package-info.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2022 The Android Open Source Project
+ * 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.
@@ -14,6 +14,12 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+/**
+ * Helps with conversions to the platform record and API objects.
+ *
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY)
+package androidx.health.connect.client.impl.platform.records;
-open class SplitPipActivityA : SplitPipActivityBase()
\ No newline at end of file
+import androidx.annotation.RestrictTo;
diff --git a/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/response/InsertRecordsResponseConverter.kt b/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/response/InsertRecordsResponseConverter.kt
new file mode 100644
index 0000000..348173e
--- /dev/null
+++ b/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/response/InsertRecordsResponseConverter.kt
@@ -0,0 +1,30 @@
+/*
+ * 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.
+ */
+
+@file:RequiresApi(api = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
+
+package androidx.health.connect.client.impl.platform.response
+
+import android.healthconnect.InsertRecordsResponse
+import android.os.Build
+import androidx.annotation.RequiresApi
+
+internal fun InsertRecordsResponse.toKtResponse():
+ androidx.health.connect.client.response.InsertRecordsResponse {
+ return androidx.health.connect.client.response.InsertRecordsResponse(
+ recordIdsList = records.map { record -> record.metadata.id }
+ )
+}
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityA.kt b/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/response/package-info.java
similarity index 66%
copy from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityA.kt
copy to health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/response/package-info.java
index 7053e2d..f8b9cb7 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityA.kt
+++ b/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/response/package-info.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2022 The Android Open Source Project
+ * 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.
@@ -14,6 +14,12 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+/**
+ * Helps with conversions to the platform record and API objects.
+ *
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY)
+package androidx.health.connect.client.impl.platform.response;
-open class SplitPipActivityA : SplitPipActivityBase()
\ No newline at end of file
+import androidx.annotation.RestrictTo;
diff --git a/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/time/TimeSource.kt b/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/time/TimeSource.kt
new file mode 100644
index 0000000..b0385c6
--- /dev/null
+++ b/health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/platform/time/TimeSource.kt
@@ -0,0 +1,34 @@
+/*
+ * 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.
+ */
+
+@file:RestrictTo(RestrictTo.Scope.LIBRARY)
+@file:RequiresApi(api = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
+
+package androidx.health.connect.client.impl.platform.time
+
+import android.os.Build
+import androidx.annotation.RequiresApi
+import androidx.annotation.RestrictTo
+import java.time.Instant
+
+interface TimeSource {
+ val now: Instant
+}
+
+object SystemDefaultTimeSource : TimeSource {
+ override val now: Instant
+ get() = Instant.now()
+}
\ No newline at end of file
diff --git a/health/connect/connect-client/src/main/java/androidx/health/connect/client/permission/HealthPermission.kt b/health/connect/connect-client/src/main/java/androidx/health/connect/client/permission/HealthPermission.kt
index 463f45f..bc0ac626 100644
--- a/health/connect/connect-client/src/main/java/androidx/health/connect/client/permission/HealthPermission.kt
+++ b/health/connect/connect-client/src/main/java/androidx/health/connect/client/permission/HealthPermission.kt
@@ -129,137 +129,127 @@
return WRITE_PERMISSION_PREFIX + RECORD_TYPE_TO_PERMISSION.getOrDefault(recordType, "")
}
+ internal const val PERMISSION_PREFIX = "android.permission.health."
+
// Read permissions for ACTIVITY.
internal const val READ_ACTIVE_CALORIES_BURNED =
- "android.permission.health.READ_ACTIVE_CALORIES_BURNED"
- internal const val READ_DISTANCE = "android.permission.health.READ_DISTANCE"
- internal const val READ_ELEVATION_GAINED = "android.permission.health.READ_ELEVATION_GAINED"
- internal const val READ_EXERCISE = "android.permission.health.READ_EXERCISE"
- internal const val READ_FLOORS_CLIMBED = "android.permission.health.READ_FLOORS_CLIMBED"
- internal const val READ_STEPS = "android.permission.health.READ_STEPS"
+ PERMISSION_PREFIX + "READ_ACTIVE_CALORIES_BURNED"
+ internal const val READ_DISTANCE = PERMISSION_PREFIX + "READ_DISTANCE"
+ internal const val READ_ELEVATION_GAINED = PERMISSION_PREFIX + "READ_ELEVATION_GAINED"
+ internal const val READ_EXERCISE = PERMISSION_PREFIX + "READ_EXERCISE"
+ internal const val READ_FLOORS_CLIMBED = PERMISSION_PREFIX + "READ_FLOORS_CLIMBED"
+ internal const val READ_STEPS = PERMISSION_PREFIX + "READ_STEPS"
internal const val READ_TOTAL_CALORIES_BURNED =
- "android.permission.health.READ_TOTAL_CALORIES_BURNED"
- internal const val READ_VO2_MAX = "android.permission.health.READ_VO2_MAX"
- internal const val READ_WHEELCHAIR_PUSHES =
- "android.permission.health.READ_WHEELCHAIR_PUSHES"
- internal const val READ_POWER = "android.permission.health.READ_POWER"
- internal const val READ_SPEED = "android.permission.health.READ_SPEED"
+ PERMISSION_PREFIX + "READ_TOTAL_CALORIES_BURNED"
+ internal const val READ_VO2_MAX = PERMISSION_PREFIX + "READ_VO2_MAX"
+ internal const val READ_WHEELCHAIR_PUSHES = PERMISSION_PREFIX + "READ_WHEELCHAIR_PUSHES"
+ internal const val READ_POWER = PERMISSION_PREFIX + "READ_POWER"
+ internal const val READ_SPEED = PERMISSION_PREFIX + "READ_SPEED"
// Read permissions for BODY_MEASUREMENTS.
internal const val READ_BASAL_METABOLIC_RATE =
- "android.permission.health.READ_BASAL_METABOLIC_RATE"
- internal const val READ_BODY_FAT = "android.permission.health.READ_BODY_FAT"
- internal const val READ_BODY_WATER_MASS = "android.permission.health.READ_BODY_WATER_MASS"
- internal const val READ_BONE_MASS = "android.permission.health.READ_BONE_MASS"
- internal const val READ_HEIGHT = "android.permission.health.READ_HEIGHT"
+ PERMISSION_PREFIX + "READ_BASAL_METABOLIC_RATE"
+ internal const val READ_BODY_FAT = PERMISSION_PREFIX + "READ_BODY_FAT"
+ internal const val READ_BODY_WATER_MASS = PERMISSION_PREFIX + "READ_BODY_WATER_MASS"
+ internal const val READ_BONE_MASS = PERMISSION_PREFIX + "READ_BONE_MASS"
+ internal const val READ_HEIGHT = PERMISSION_PREFIX + "READ_HEIGHT"
@RestrictTo(RestrictTo.Scope.LIBRARY)
- internal const val READ_HIP_CIRCUMFERENCE =
- "android.permission.health.READ_HIP_CIRCUMFERENCE"
- internal const val READ_LEAN_BODY_MASS = "android.permission.health.READ_LEAN_BODY_MASS"
+ internal const val READ_HIP_CIRCUMFERENCE = PERMISSION_PREFIX + "READ_HIP_CIRCUMFERENCE"
+ internal const val READ_LEAN_BODY_MASS = PERMISSION_PREFIX + "READ_LEAN_BODY_MASS"
@RestrictTo(RestrictTo.Scope.LIBRARY)
- internal const val READ_WAIST_CIRCUMFERENCE =
- "android.permission.health.READ_WAIST_CIRCUMFERENCE"
- internal const val READ_WEIGHT = "android.permission.health.READ_WEIGHT"
+ internal const val READ_WAIST_CIRCUMFERENCE = PERMISSION_PREFIX + "READ_WAIST_CIRCUMFERENCE"
+ internal const val READ_WEIGHT = PERMISSION_PREFIX + "READ_WEIGHT"
// Read permissions for CYCLE_TRACKING.
- internal const val READ_CERVICAL_MUCUS = "android.permission.health.READ_CERVICAL_MUCUS"
+ internal const val READ_CERVICAL_MUCUS = PERMISSION_PREFIX + "READ_CERVICAL_MUCUS"
@RestrictTo(RestrictTo.Scope.LIBRARY)
internal const val READ_INTERMENSTRUAL_BLEEDING =
- "android.permission.health.READ_INTERMENSTRUAL_BLEEDING"
- internal const val READ_MENSTRUATION = "android.permission.health.READ_MENSTRUATION"
- internal const val READ_OVULATION_TEST = "android.permission.health.READ_OVULATION_TEST"
- internal const val READ_SEXUAL_ACTIVITY = "android.permission.health.READ_SEXUAL_ACTIVITY"
+ PERMISSION_PREFIX + "READ_INTERMENSTRUAL_BLEEDING"
+ internal const val READ_MENSTRUATION = PERMISSION_PREFIX + "READ_MENSTRUATION"
+ internal const val READ_OVULATION_TEST = PERMISSION_PREFIX + "READ_OVULATION_TEST"
+ internal const val READ_SEXUAL_ACTIVITY = PERMISSION_PREFIX + "READ_SEXUAL_ACTIVITY"
// Read permissions for NUTRITION.
- internal const val READ_HYDRATION = "android.permission.health.READ_HYDRATION"
- internal const val READ_NUTRITION = "android.permission.health.READ_NUTRITION"
+ internal const val READ_HYDRATION = PERMISSION_PREFIX + "READ_HYDRATION"
+ internal const val READ_NUTRITION = PERMISSION_PREFIX + "READ_NUTRITION"
// Read permissions for SLEEP.
- internal const val READ_SLEEP = "android.permission.health.READ_SLEEP"
+ internal const val READ_SLEEP = PERMISSION_PREFIX + "READ_SLEEP"
// Read permissions for VITALS.
internal const val READ_BASAL_BODY_TEMPERATURE =
- "android.permission.health.READ_BASAL_BODY_TEMPERATURE"
- internal const val READ_BLOOD_GLUCOSE = "android.permission.health.READ_BLOOD_GLUCOSE"
- internal const val READ_BLOOD_PRESSURE = "android.permission.health.READ_BLOOD_PRESSURE"
- internal const val READ_BODY_TEMPERATURE = "android.permission.health.READ_BODY_TEMPERATURE"
- internal const val READ_HEART_RATE = "android.permission.health.READ_HEART_RATE"
+ PERMISSION_PREFIX + "READ_BASAL_BODY_TEMPERATURE"
+ internal const val READ_BLOOD_GLUCOSE = PERMISSION_PREFIX + "READ_BLOOD_GLUCOSE"
+ internal const val READ_BLOOD_PRESSURE = PERMISSION_PREFIX + "READ_BLOOD_PRESSURE"
+ internal const val READ_BODY_TEMPERATURE = PERMISSION_PREFIX + "READ_BODY_TEMPERATURE"
+ internal const val READ_HEART_RATE = PERMISSION_PREFIX + "READ_HEART_RATE"
internal const val READ_HEART_RATE_VARIABILITY =
- "android.permission.health.READ_HEART_RATE_VARIABILITY"
- internal const val READ_OXYGEN_SATURATION =
- "android.permission.health.READ_OXYGEN_SATURATION"
- internal const val READ_RESPIRATORY_RATE = "android.permission.health.READ_RESPIRATORY_RATE"
- internal const val READ_RESTING_HEART_RATE =
- "android.permission.health.READ_RESTING_HEART_RATE"
+ PERMISSION_PREFIX + "READ_HEART_RATE_VARIABILITY"
+ internal const val READ_OXYGEN_SATURATION = PERMISSION_PREFIX + "READ_OXYGEN_SATURATION"
+ internal const val READ_RESPIRATORY_RATE = PERMISSION_PREFIX + "READ_RESPIRATORY_RATE"
+ internal const val READ_RESTING_HEART_RATE = PERMISSION_PREFIX + "READ_RESTING_HEART_RATE"
// Write permissions for ACTIVITY.
internal const val WRITE_ACTIVE_CALORIES_BURNED =
- "android.permission.health.WRITE_ACTIVE_CALORIES_BURNED"
- internal const val WRITE_DISTANCE = "android.permission.health.WRITE_DISTANCE"
- internal const val WRITE_ELEVATION_GAINED =
- "android.permission.health.WRITE_ELEVATION_GAINED"
- internal const val WRITE_EXERCISE = "android.permission.health.WRITE_EXERCISE"
- internal const val WRITE_FLOORS_CLIMBED = "android.permission.health.WRITE_FLOORS_CLIMBED"
- internal const val WRITE_STEPS = "android.permission.health.WRITE_STEPS"
+ PERMISSION_PREFIX + "WRITE_ACTIVE_CALORIES_BURNED"
+ internal const val WRITE_DISTANCE = PERMISSION_PREFIX + "WRITE_DISTANCE"
+ internal const val WRITE_ELEVATION_GAINED = PERMISSION_PREFIX + "WRITE_ELEVATION_GAINED"
+ internal const val WRITE_EXERCISE = PERMISSION_PREFIX + "WRITE_EXERCISE"
+ internal const val WRITE_FLOORS_CLIMBED = PERMISSION_PREFIX + "WRITE_FLOORS_CLIMBED"
+ internal const val WRITE_STEPS = PERMISSION_PREFIX + "WRITE_STEPS"
internal const val WRITE_TOTAL_CALORIES_BURNED =
- "android.permission.health.WRITE_TOTAL_CALORIES_BURNED"
- internal const val WRITE_VO2_MAX = "android.permission.health.WRITE_VO2_MAX"
- internal const val WRITE_WHEELCHAIR_PUSHES =
- "android.permission.health.WRITE_WHEELCHAIR_PUSHES"
- internal const val WRITE_POWER = "android.permission.health.WRITE_POWER"
- internal const val WRITE_SPEED = "android.permission.health.WRITE_SPEED"
+ PERMISSION_PREFIX + "WRITE_TOTAL_CALORIES_BURNED"
+ internal const val WRITE_VO2_MAX = PERMISSION_PREFIX + "WRITE_VO2_MAX"
+ internal const val WRITE_WHEELCHAIR_PUSHES = PERMISSION_PREFIX + "WRITE_WHEELCHAIR_PUSHES"
+ internal const val WRITE_POWER = PERMISSION_PREFIX + "WRITE_POWER"
+ internal const val WRITE_SPEED = PERMISSION_PREFIX + "WRITE_SPEED"
// Write permissions for BODY_MEASUREMENTS.
internal const val WRITE_BASAL_METABOLIC_RATE =
- "android.permission.health.WRITE_BASAL_METABOLIC_RATE"
- internal const val WRITE_BODY_FAT = "android.permission.health.WRITE_BODY_FAT"
- internal const val WRITE_BODY_WATER_MASS = "android.permission.health.WRITE_BODY_WATER_MASS"
- internal const val WRITE_BONE_MASS = "android.permission.health.WRITE_BONE_MASS"
- internal const val WRITE_HEIGHT = "android.permission.health.WRITE_HEIGHT"
+ PERMISSION_PREFIX + "WRITE_BASAL_METABOLIC_RATE"
+ internal const val WRITE_BODY_FAT = PERMISSION_PREFIX + "WRITE_BODY_FAT"
+ internal const val WRITE_BODY_WATER_MASS = PERMISSION_PREFIX + "WRITE_BODY_WATER_MASS"
+ internal const val WRITE_BONE_MASS = PERMISSION_PREFIX + "WRITE_BONE_MASS"
+ internal const val WRITE_HEIGHT = PERMISSION_PREFIX + "WRITE_HEIGHT"
@RestrictTo(RestrictTo.Scope.LIBRARY)
- internal const val WRITE_HIP_CIRCUMFERENCE =
- "android.permission.health.WRITE_HIP_CIRCUMFERENCE"
- internal const val WRITE_LEAN_BODY_MASS = "android.permission.health.WRITE_LEAN_BODY_MASS"
+ internal const val WRITE_HIP_CIRCUMFERENCE = PERMISSION_PREFIX + "WRITE_HIP_CIRCUMFERENCE"
+ internal const val WRITE_LEAN_BODY_MASS = PERMISSION_PREFIX + "WRITE_LEAN_BODY_MASS"
@RestrictTo(RestrictTo.Scope.LIBRARY)
internal const val WRITE_WAIST_CIRCUMFERENCE =
- "android.permission.health.WRITE_WAIST_CIRCUMFERENCE"
- internal const val WRITE_WEIGHT = "android.permission.health.WRITE_WEIGHT"
+ PERMISSION_PREFIX + "WRITE_WAIST_CIRCUMFERENCE"
+ internal const val WRITE_WEIGHT = PERMISSION_PREFIX + "WRITE_WEIGHT"
// Write permissions for CYCLE_TRACKING.
- internal const val WRITE_CERVICAL_MUCUS = "android.permission.health.WRITE_CERVICAL_MUCUS"
+ internal const val WRITE_CERVICAL_MUCUS = PERMISSION_PREFIX + "WRITE_CERVICAL_MUCUS"
@RestrictTo(RestrictTo.Scope.LIBRARY)
internal const val WRITE_INTERMENSTRUAL_BLEEDING =
- "android.permission.health.WRITE_INTERMENSTRUAL_BLEEDING"
- internal const val WRITE_MENSTRUATION = "android.permission.health.WRITE_MENSTRUATION"
- internal const val WRITE_OVULATION_TEST = "android.permission.health.WRITE_OVULATION_TEST"
- internal const val WRITE_SEXUAL_ACTIVITY = "android.permission.health.WRITE_SEXUAL_ACTIVITY"
+ PERMISSION_PREFIX + "WRITE_INTERMENSTRUAL_BLEEDING"
+ internal const val WRITE_MENSTRUATION = PERMISSION_PREFIX + "WRITE_MENSTRUATION"
+ internal const val WRITE_OVULATION_TEST = PERMISSION_PREFIX + "WRITE_OVULATION_TEST"
+ internal const val WRITE_SEXUAL_ACTIVITY = PERMISSION_PREFIX + "WRITE_SEXUAL_ACTIVITY"
// Write permissions for NUTRITION.
- internal const val WRITE_HYDRATION = "android.permission.health.WRITE_HYDRATION"
- internal const val WRITE_NUTRITION = "android.permission.health.WRITE_NUTRITION"
+ internal const val WRITE_HYDRATION = PERMISSION_PREFIX + "WRITE_HYDRATION"
+ internal const val WRITE_NUTRITION = PERMISSION_PREFIX + "WRITE_NUTRITION"
// Write permissions for SLEEP.
- internal const val WRITE_SLEEP = "android.permission.health.WRITE_SLEEP"
+ internal const val WRITE_SLEEP = PERMISSION_PREFIX + "WRITE_SLEEP"
// Write permissions for VITALS.
internal const val WRITE_BASAL_BODY_TEMPERATURE =
- "android.permission.health.WRITE_BASAL_BODY_TEMPERATURE"
- internal const val WRITE_BLOOD_GLUCOSE = "android.permission.health.WRITE_BLOOD_GLUCOSE"
- internal const val WRITE_BLOOD_PRESSURE = "android.permission.health.WRITE_BLOOD_PRESSURE"
- internal const val WRITE_BODY_TEMPERATURE =
- "android.permission.health.WRITE_BODY_TEMPERATURE"
- internal const val WRITE_HEART_RATE = "android.permission.health.WRITE_HEART_RATE"
+ PERMISSION_PREFIX + "WRITE_BASAL_BODY_TEMPERATURE"
+ internal const val WRITE_BLOOD_GLUCOSE = PERMISSION_PREFIX + "WRITE_BLOOD_GLUCOSE"
+ internal const val WRITE_BLOOD_PRESSURE = PERMISSION_PREFIX + "WRITE_BLOOD_PRESSURE"
+ internal const val WRITE_BODY_TEMPERATURE = PERMISSION_PREFIX + "WRITE_BODY_TEMPERATURE"
+ internal const val WRITE_HEART_RATE = PERMISSION_PREFIX + "WRITE_HEART_RATE"
internal const val WRITE_HEART_RATE_VARIABILITY =
- "android.permission.health.WRITE_HEART_RATE_VARIABILITY"
- internal const val WRITE_OXYGEN_SATURATION =
- "android.permission.health.WRITE_OXYGEN_SATURATION"
- internal const val WRITE_RESPIRATORY_RATE =
- "android.permission.health.WRITE_RESPIRATORY_RATE"
- internal const val WRITE_RESTING_HEART_RATE =
- "android.permission.health.WRITE_RESTING_HEART_RATE"
+ PERMISSION_PREFIX + "WRITE_HEART_RATE_VARIABILITY"
+ internal const val WRITE_OXYGEN_SATURATION = PERMISSION_PREFIX + "WRITE_OXYGEN_SATURATION"
+ internal const val WRITE_RESPIRATORY_RATE = PERMISSION_PREFIX + "WRITE_RESPIRATORY_RATE"
+ internal const val WRITE_RESTING_HEART_RATE = PERMISSION_PREFIX + "WRITE_RESTING_HEART_RATE"
- internal const val READ_PERMISSION_PREFIX = "android.permission.health.READ_"
- internal const val WRITE_PERMISSION_PREFIX = "android.permission.health.WRITE_"
+ internal const val READ_PERMISSION_PREFIX = PERMISSION_PREFIX + "READ_"
+ internal const val WRITE_PERMISSION_PREFIX = PERMISSION_PREFIX + "WRITE_"
internal val RECORD_TYPE_TO_PERMISSION =
mapOf<KClass<out Record>, String>(
diff --git a/health/connect/connect-client/src/main/java/androidx/health/connect/client/permission/platform/HealthDataRequestPermissionsUpsideDownCake.kt b/health/connect/connect-client/src/main/java/androidx/health/connect/client/permission/platform/HealthDataRequestPermissionsUpsideDownCake.kt
new file mode 100644
index 0000000..e6994c5
--- /dev/null
+++ b/health/connect/connect-client/src/main/java/androidx/health/connect/client/permission/platform/HealthDataRequestPermissionsUpsideDownCake.kt
@@ -0,0 +1,53 @@
+/*
+ * 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 androidx.health.connect.client.permission.platform
+
+import android.content.Context
+import android.content.Intent
+import androidx.activity.result.contract.ActivityResultContract
+import androidx.activity.result.contract.ActivityResultContracts.RequestMultiplePermissions
+import androidx.annotation.RestrictTo
+import androidx.health.connect.client.permission.HealthPermission.Companion.PERMISSION_PREFIX
+
+/**
+ * An [ActivityResultContract] to request Health Connect system permissions.
+ *
+ * @see androidx.activity.ComponentActivity.registerForActivityResult
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY)
+internal class HealthDataRequestPermissionsUpsideDownCake :
+ ActivityResultContract<Set<String>, Set<String>>() {
+
+ private val requestPermissions = RequestMultiplePermissions()
+
+ override fun createIntent(context: Context, input: Set<String>): Intent {
+ require(input.all { it.startsWith(PERMISSION_PREFIX) }) {
+ "Unsupported health connect permission"
+ }
+ return requestPermissions.createIntent(context, input.toTypedArray())
+ }
+
+ override fun parseResult(resultCode: Int, intent: Intent?): Set<String> =
+ requestPermissions.parseResult(resultCode, intent).filterValues { it }.keys
+
+ override fun getSynchronousResult(
+ context: Context,
+ input: Set<String>,
+ ): SynchronousResult<Set<String>>? =
+ requestPermissions.getSynchronousResult(context, input.toTypedArray())?.let { result ->
+ SynchronousResult(result.value.filterValues { it }.keys)
+ }
+}
diff --git a/health/connect/connect-client/src/test/java/androidx/health/connect/client/PermissionControllerTest.kt b/health/connect/connect-client/src/test/java/androidx/health/connect/client/PermissionControllerTest.kt
index f73d84e..4f24393 100644
--- a/health/connect/connect-client/src/test/java/androidx/health/connect/client/PermissionControllerTest.kt
+++ b/health/connect/connect-client/src/test/java/androidx/health/connect/client/PermissionControllerTest.kt
@@ -17,14 +17,17 @@
package androidx.health.connect.client
import android.content.Context
+import android.os.Build.VERSION_CODES
+import androidx.activity.result.contract.ActivityResultContracts.RequestMultiplePermissions
import androidx.health.connect.client.permission.HealthPermission
import androidx.health.connect.client.records.StepsRecord
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
-import com.google.common.truth.Truth
+import com.google.common.truth.Truth.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
+import org.robolectric.annotation.Config
private const val PROVIDER_PACKAGE_NAME = "com.example.fake.provider"
@@ -39,30 +42,42 @@
}
@Test
- fun createIntentTest() {
+ fun createIntent_legacy() {
val requestPermissionContract =
PermissionController.createRequestPermissionResultContractLegacy(PROVIDER_PACKAGE_NAME)
val intent =
requestPermissionContract.createIntent(
- context,
- setOf(HealthPermission.createReadPermissionLegacy(StepsRecord::class))
- )
+ context, setOf(HealthPermission.createReadPermissionLegacy(StepsRecord::class)))
- Truth.assertThat(intent.action).isEqualTo("androidx.health.ACTION_REQUEST_PERMISSIONS")
- Truth.assertThat(intent.`package`).isEqualTo(PROVIDER_PACKAGE_NAME)
+ assertThat(intent.action).isEqualTo("androidx.health.ACTION_REQUEST_PERMISSIONS")
+ assertThat(intent.`package`).isEqualTo(PROVIDER_PACKAGE_NAME)
}
@Test
- fun createIntentTest_permissionStrings() {
+ fun createIntent_permissionStrings() {
val requestPermissionContract =
PermissionController.createRequestPermissionResultContract(PROVIDER_PACKAGE_NAME)
val intent =
requestPermissionContract.createIntent(
- context,
- setOf(HealthPermission.READ_ACTIVE_CALORIES_BURNED)
- )
+ context, setOf(HealthPermission.READ_ACTIVE_CALORIES_BURNED))
- Truth.assertThat(intent.action).isEqualTo("androidx.health.ACTION_REQUEST_PERMISSIONS")
- Truth.assertThat(intent.`package`).isEqualTo(PROVIDER_PACKAGE_NAME)
+ assertThat(intent.action).isEqualTo("androidx.health.ACTION_REQUEST_PERMISSIONS")
+ assertThat(intent.`package`).isEqualTo(PROVIDER_PACKAGE_NAME)
+ }
+
+ @Test
+ @Config(minSdk = VERSION_CODES.UPSIDE_DOWN_CAKE)
+ fun createIntent_UpsideDownCake() {
+ val requestPermissionContract =
+ PermissionController.createRequestPermissionResultContract(PROVIDER_PACKAGE_NAME)
+ val intent =
+ requestPermissionContract.createIntent(
+ context, setOf(HealthPermission.WRITE_STEPS, HealthPermission.READ_DISTANCE))
+
+ assertThat(intent.action).isEqualTo(RequestMultiplePermissions.ACTION_REQUEST_PERMISSIONS)
+ assertThat(intent.getStringArrayExtra(RequestMultiplePermissions.EXTRA_PERMISSIONS))
+ .asList()
+ .containsExactly(HealthPermission.WRITE_STEPS, HealthPermission.READ_DISTANCE)
+ assertThat(intent.`package`).isNull()
}
}
diff --git a/health/connect/connect-client/src/test/java/androidx/health/connect/client/permission/platform/HealthDataRequestPermissionsUpsideDownCakeTest.kt b/health/connect/connect-client/src/test/java/androidx/health/connect/client/permission/platform/HealthDataRequestPermissionsUpsideDownCakeTest.kt
new file mode 100644
index 0000000..2bbd4f4
--- /dev/null
+++ b/health/connect/connect-client/src/test/java/androidx/health/connect/client/permission/platform/HealthDataRequestPermissionsUpsideDownCakeTest.kt
@@ -0,0 +1,90 @@
+/*
+ * Copyright 2023 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 androidx.health.connect.client.permission.platform
+
+import android.app.Activity
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import androidx.activity.result.contract.ActivityResultContracts.RequestMultiplePermissions
+import androidx.health.connect.client.permission.HealthPermission
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import com.google.common.truth.Truth.assertThat
+import kotlin.test.assertFailsWith
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@RunWith(AndroidJUnit4::class)
+class HealthDataRequestPermissionsUpsideDownCakeTest {
+
+ private lateinit var context: Context
+
+ @Before
+ fun setUp() {
+ context = ApplicationProvider.getApplicationContext()
+ }
+
+ @Test
+ fun createIntent() {
+ val requestPermissionContract = HealthDataRequestPermissionsUpsideDownCake()
+ val intent =
+ requestPermissionContract.createIntent(
+ context, setOf(HealthPermission.READ_STEPS, HealthPermission.WRITE_DISTANCE))
+
+ assertThat(intent.action).isEqualTo(RequestMultiplePermissions.ACTION_REQUEST_PERMISSIONS)
+ assertThat(intent.getStringArrayExtra(RequestMultiplePermissions.EXTRA_PERMISSIONS))
+ .asList()
+ .containsExactly(HealthPermission.READ_STEPS, HealthPermission.WRITE_DISTANCE)
+ }
+
+ @Test
+ fun createIntent_nonHealthPermission_throwsIAE() {
+ val requestPermissionContract = HealthDataRequestPermissionsUpsideDownCake()
+ assertFailsWith<IllegalArgumentException> {
+ requestPermissionContract.createIntent(
+ context, setOf(HealthPermission.READ_STEPS, "NON_HEALTH_PERMISSION"))
+ }
+ }
+
+ @Test
+ fun parseIntent() {
+ val requestPermissionContract = HealthDataRequestPermissionsUpsideDownCake()
+
+ val intent = Intent()
+ intent.putExtra(
+ RequestMultiplePermissions.EXTRA_PERMISSIONS,
+ arrayOf(
+ HealthPermission.READ_STEPS,
+ HealthPermission.WRITE_STEPS,
+ HealthPermission.WRITE_DISTANCE,
+ HealthPermission.READ_HEART_RATE))
+ intent.putExtra(
+ RequestMultiplePermissions.EXTRA_PERMISSION_GRANT_RESULTS,
+ intArrayOf(
+ PackageManager.PERMISSION_GRANTED,
+ PackageManager.PERMISSION_DENIED,
+ PackageManager.PERMISSION_GRANTED,
+ PackageManager.PERMISSION_DENIED))
+
+ val result = requestPermissionContract.parseResult(Activity.RESULT_OK, intent)
+
+ assertThat(result)
+ .containsExactly(HealthPermission.READ_STEPS, HealthPermission.WRITE_DISTANCE)
+ }
+}
diff --git a/heifwriter/heifwriter/api/api_lint.ignore b/heifwriter/heifwriter/api/api_lint.ignore
index a93261a..d3c7e43 100644
--- a/heifwriter/heifwriter/api/api_lint.ignore
+++ b/heifwriter/heifwriter/api/api_lint.ignore
@@ -1,42 +1,24 @@
// Baseline format: 1.0
+GenericException: androidx.heifwriter.AvifWriter#stop(long):
+ Methods must not throw generic exceptions (`java.lang.Exception`)
GenericException: androidx.heifwriter.HeifWriter#stop(long):
Methods must not throw generic exceptions (`java.lang.Exception`)
-MissingGetterMatchingBuilder: androidx.heifwriter.HeifWriter.Builder#setGridEnabled(boolean):
- androidx.heifwriter.HeifWriter does not declare a `isGridEnabled()` method matching method androidx.heifwriter.HeifWriter.Builder.setGridEnabled(boolean)
-MissingGetterMatchingBuilder: androidx.heifwriter.HeifWriter.Builder#setHandler(android.os.Handler):
- androidx.heifwriter.HeifWriter does not declare a `getHandler()` method matching method androidx.heifwriter.HeifWriter.Builder.setHandler(android.os.Handler)
-MissingGetterMatchingBuilder: androidx.heifwriter.HeifWriter.Builder#setMaxImages(int):
- androidx.heifwriter.HeifWriter does not declare a `getMaxImages()` method matching method androidx.heifwriter.HeifWriter.Builder.setMaxImages(int)
-MissingGetterMatchingBuilder: androidx.heifwriter.HeifWriter.Builder#setPrimaryIndex(int):
- androidx.heifwriter.HeifWriter does not declare a `getPrimaryIndex()` method matching method androidx.heifwriter.HeifWriter.Builder.setPrimaryIndex(int)
-MissingGetterMatchingBuilder: androidx.heifwriter.HeifWriter.Builder#setQuality(int):
- androidx.heifwriter.HeifWriter does not declare a `getQuality()` method matching method androidx.heifwriter.HeifWriter.Builder.setQuality(int)
-MissingGetterMatchingBuilder: androidx.heifwriter.HeifWriter.Builder#setRotation(int):
- androidx.heifwriter.HeifWriter does not declare a `getRotation()` method matching method androidx.heifwriter.HeifWriter.Builder.setRotation(int)
-
-
-MissingNullability: androidx.heifwriter.HeifWriter.Builder#build():
- Missing nullability on method `build` return
-MissingNullability: androidx.heifwriter.HeifWriter.Builder#setGridEnabled(boolean):
- Missing nullability on method `setGridEnabled` return
-MissingNullability: androidx.heifwriter.HeifWriter.Builder#setHandler(android.os.Handler):
- Missing nullability on method `setHandler` return
-MissingNullability: androidx.heifwriter.HeifWriter.Builder#setMaxImages(int):
- Missing nullability on method `setMaxImages` return
-MissingNullability: androidx.heifwriter.HeifWriter.Builder#setPrimaryIndex(int):
- Missing nullability on method `setPrimaryIndex` return
-MissingNullability: androidx.heifwriter.HeifWriter.Builder#setQuality(int):
- Missing nullability on method `setQuality` return
-MissingNullability: androidx.heifwriter.HeifWriter.Builder#setRotation(int):
- Missing nullability on method `setRotation` return
-
-
+UseParcelFileDescriptor: androidx.heifwriter.AvifWriter.Builder#Builder(java.io.FileDescriptor, int, int, int) parameter #0:
+ Must use ParcelFileDescriptor instead of FileDescriptor in parameter fd in androidx.heifwriter.AvifWriter.Builder(java.io.FileDescriptor fd, int width, int height, int inputMode)
UseParcelFileDescriptor: androidx.heifwriter.HeifWriter.Builder#Builder(java.io.FileDescriptor, int, int, int) parameter #0:
Must use ParcelFileDescriptor instead of FileDescriptor in parameter fd in androidx.heifwriter.HeifWriter.Builder(java.io.FileDescriptor fd, int width, int height, int inputMode)
+VisiblySynchronized: androidx.heifwriter.AvifWriter#addBitmap(android.graphics.Bitmap):
+ Internal locks must not be exposed (synchronizing on this or class is still externally observable): method androidx.heifwriter.AvifWriter.addBitmap(android.graphics.Bitmap)
+VisiblySynchronized: androidx.heifwriter.AvifWriter#addYuvBuffer(int, byte[]):
+ Internal locks must not be exposed (synchronizing on this or class is still externally observable): method androidx.heifwriter.AvifWriter.addYuvBuffer(int,byte[])
+VisiblySynchronized: androidx.heifwriter.AvifWriter#setInputEndOfStreamTimestamp(long):
+ Internal locks must not be exposed (synchronizing on this or class is still externally observable): method androidx.heifwriter.AvifWriter.setInputEndOfStreamTimestamp(long)
+VisiblySynchronized: androidx.heifwriter.AvifWriter#stop(long):
+ Internal locks must not be exposed (synchronizing on this or class is still externally observable): method androidx.heifwriter.AvifWriter.stop(long)
VisiblySynchronized: androidx.heifwriter.HeifWriter#addBitmap(android.graphics.Bitmap):
Internal locks must not be exposed (synchronizing on this or class is still externally observable): method androidx.heifwriter.HeifWriter.addBitmap(android.graphics.Bitmap)
VisiblySynchronized: androidx.heifwriter.HeifWriter#addYuvBuffer(int, byte[]):
diff --git a/heifwriter/heifwriter/api/current.txt b/heifwriter/heifwriter/api/current.txt
index 8a45d85..90c95a4 100644
--- a/heifwriter/heifwriter/api/current.txt
+++ b/heifwriter/heifwriter/api/current.txt
@@ -1,30 +1,71 @@
// Signature format: 4.0
package androidx.heifwriter {
+ public final class AvifWriter implements java.lang.AutoCloseable {
+ method public void addBitmap(android.graphics.Bitmap);
+ method public void addExifData(int, byte[], int, int);
+ method public void addYuvBuffer(int, byte[]);
+ method public void close();
+ method public android.os.Handler? getHandler();
+ method public android.view.Surface getInputSurface();
+ method public int getMaxImages();
+ method public int getPrimaryIndex();
+ method public int getQuality();
+ method public int getRotation();
+ method public boolean isGridEnabled();
+ method public boolean isHighBitDepthEnabled();
+ method public void setInputEndOfStreamTimestamp(@IntRange(from=0) long);
+ method public void start();
+ method public void stop(@IntRange(from=0) long) throws java.lang.Exception;
+ field public static final int INPUT_MODE_BITMAP = 2; // 0x2
+ field public static final int INPUT_MODE_BUFFER = 0; // 0x0
+ field public static final int INPUT_MODE_SURFACE = 1; // 0x1
+ }
+
+ public static final class AvifWriter.Builder {
+ ctor public AvifWriter.Builder(String, @IntRange(from=1) int, @IntRange(from=1) int, int);
+ ctor public AvifWriter.Builder(java.io.FileDescriptor, @IntRange(from=1) int, @IntRange(from=1) int, int);
+ method public androidx.heifwriter.AvifWriter build() throws java.io.IOException;
+ method public androidx.heifwriter.AvifWriter.Builder setGridEnabled(boolean);
+ method public androidx.heifwriter.AvifWriter.Builder setHandler(android.os.Handler?);
+ method public androidx.heifwriter.AvifWriter.Builder setHighBitDepthEnabled(boolean);
+ method public androidx.heifwriter.AvifWriter.Builder setMaxImages(@IntRange(from=1) int);
+ method public androidx.heifwriter.AvifWriter.Builder setPrimaryIndex(@IntRange(from=0) int);
+ method public androidx.heifwriter.AvifWriter.Builder setQuality(@IntRange(from=0, to=100) int);
+ method public androidx.heifwriter.AvifWriter.Builder setRotation(@IntRange(from=0) int);
+ }
+
public final class HeifWriter implements java.lang.AutoCloseable {
method public void addBitmap(android.graphics.Bitmap);
method public void addExifData(int, byte[], int, int);
method public void addYuvBuffer(int, byte[]);
method public void close();
+ method public android.os.Handler? getHandler();
method public android.view.Surface getInputSurface();
- method public void setInputEndOfStreamTimestamp(long);
+ method public int getMaxImages();
+ method public int getPrimaryIndex();
+ method public int getQuality();
+ method public int getRotation();
+ method public boolean isGridEnabled();
+ method public boolean isHighBitDepthEnabled();
+ method public void setInputEndOfStreamTimestamp(@IntRange(from=0) long);
method public void start();
- method public void stop(long) throws java.lang.Exception;
+ method public void stop(@IntRange(from=0) long) throws java.lang.Exception;
field public static final int INPUT_MODE_BITMAP = 2; // 0x2
field public static final int INPUT_MODE_BUFFER = 0; // 0x0
field public static final int INPUT_MODE_SURFACE = 1; // 0x1
}
public static final class HeifWriter.Builder {
- ctor public HeifWriter.Builder(String, int, int, int);
- ctor public HeifWriter.Builder(java.io.FileDescriptor, int, int, int);
- method public androidx.heifwriter.HeifWriter! build() throws java.io.IOException;
- method public androidx.heifwriter.HeifWriter.Builder! setGridEnabled(boolean);
- method public androidx.heifwriter.HeifWriter.Builder! setHandler(android.os.Handler?);
- method public androidx.heifwriter.HeifWriter.Builder! setMaxImages(int);
- method public androidx.heifwriter.HeifWriter.Builder! setPrimaryIndex(int);
- method public androidx.heifwriter.HeifWriter.Builder! setQuality(int);
- method public androidx.heifwriter.HeifWriter.Builder! setRotation(int);
+ ctor public HeifWriter.Builder(String, @IntRange(from=1) int, @IntRange(from=1) int, int);
+ ctor public HeifWriter.Builder(java.io.FileDescriptor, @IntRange(from=1) int, @IntRange(from=1) int, int);
+ method public androidx.heifwriter.HeifWriter build() throws java.io.IOException;
+ method public androidx.heifwriter.HeifWriter.Builder setGridEnabled(boolean);
+ method public androidx.heifwriter.HeifWriter.Builder setHandler(android.os.Handler?);
+ method public androidx.heifwriter.HeifWriter.Builder setMaxImages(@IntRange(from=1) int);
+ method public androidx.heifwriter.HeifWriter.Builder setPrimaryIndex(@IntRange(from=0) int);
+ method public androidx.heifwriter.HeifWriter.Builder setQuality(@IntRange(from=0, to=100) int);
+ method public androidx.heifwriter.HeifWriter.Builder setRotation(@IntRange(from=0) int);
}
}
diff --git a/heifwriter/heifwriter/api/public_plus_experimental_current.txt b/heifwriter/heifwriter/api/public_plus_experimental_current.txt
index 8a45d85..90c95a4 100644
--- a/heifwriter/heifwriter/api/public_plus_experimental_current.txt
+++ b/heifwriter/heifwriter/api/public_plus_experimental_current.txt
@@ -1,30 +1,71 @@
// Signature format: 4.0
package androidx.heifwriter {
+ public final class AvifWriter implements java.lang.AutoCloseable {
+ method public void addBitmap(android.graphics.Bitmap);
+ method public void addExifData(int, byte[], int, int);
+ method public void addYuvBuffer(int, byte[]);
+ method public void close();
+ method public android.os.Handler? getHandler();
+ method public android.view.Surface getInputSurface();
+ method public int getMaxImages();
+ method public int getPrimaryIndex();
+ method public int getQuality();
+ method public int getRotation();
+ method public boolean isGridEnabled();
+ method public boolean isHighBitDepthEnabled();
+ method public void setInputEndOfStreamTimestamp(@IntRange(from=0) long);
+ method public void start();
+ method public void stop(@IntRange(from=0) long) throws java.lang.Exception;
+ field public static final int INPUT_MODE_BITMAP = 2; // 0x2
+ field public static final int INPUT_MODE_BUFFER = 0; // 0x0
+ field public static final int INPUT_MODE_SURFACE = 1; // 0x1
+ }
+
+ public static final class AvifWriter.Builder {
+ ctor public AvifWriter.Builder(String, @IntRange(from=1) int, @IntRange(from=1) int, int);
+ ctor public AvifWriter.Builder(java.io.FileDescriptor, @IntRange(from=1) int, @IntRange(from=1) int, int);
+ method public androidx.heifwriter.AvifWriter build() throws java.io.IOException;
+ method public androidx.heifwriter.AvifWriter.Builder setGridEnabled(boolean);
+ method public androidx.heifwriter.AvifWriter.Builder setHandler(android.os.Handler?);
+ method public androidx.heifwriter.AvifWriter.Builder setHighBitDepthEnabled(boolean);
+ method public androidx.heifwriter.AvifWriter.Builder setMaxImages(@IntRange(from=1) int);
+ method public androidx.heifwriter.AvifWriter.Builder setPrimaryIndex(@IntRange(from=0) int);
+ method public androidx.heifwriter.AvifWriter.Builder setQuality(@IntRange(from=0, to=100) int);
+ method public androidx.heifwriter.AvifWriter.Builder setRotation(@IntRange(from=0) int);
+ }
+
public final class HeifWriter implements java.lang.AutoCloseable {
method public void addBitmap(android.graphics.Bitmap);
method public void addExifData(int, byte[], int, int);
method public void addYuvBuffer(int, byte[]);
method public void close();
+ method public android.os.Handler? getHandler();
method public android.view.Surface getInputSurface();
- method public void setInputEndOfStreamTimestamp(long);
+ method public int getMaxImages();
+ method public int getPrimaryIndex();
+ method public int getQuality();
+ method public int getRotation();
+ method public boolean isGridEnabled();
+ method public boolean isHighBitDepthEnabled();
+ method public void setInputEndOfStreamTimestamp(@IntRange(from=0) long);
method public void start();
- method public void stop(long) throws java.lang.Exception;
+ method public void stop(@IntRange(from=0) long) throws java.lang.Exception;
field public static final int INPUT_MODE_BITMAP = 2; // 0x2
field public static final int INPUT_MODE_BUFFER = 0; // 0x0
field public static final int INPUT_MODE_SURFACE = 1; // 0x1
}
public static final class HeifWriter.Builder {
- ctor public HeifWriter.Builder(String, int, int, int);
- ctor public HeifWriter.Builder(java.io.FileDescriptor, int, int, int);
- method public androidx.heifwriter.HeifWriter! build() throws java.io.IOException;
- method public androidx.heifwriter.HeifWriter.Builder! setGridEnabled(boolean);
- method public androidx.heifwriter.HeifWriter.Builder! setHandler(android.os.Handler?);
- method public androidx.heifwriter.HeifWriter.Builder! setMaxImages(int);
- method public androidx.heifwriter.HeifWriter.Builder! setPrimaryIndex(int);
- method public androidx.heifwriter.HeifWriter.Builder! setQuality(int);
- method public androidx.heifwriter.HeifWriter.Builder! setRotation(int);
+ ctor public HeifWriter.Builder(String, @IntRange(from=1) int, @IntRange(from=1) int, int);
+ ctor public HeifWriter.Builder(java.io.FileDescriptor, @IntRange(from=1) int, @IntRange(from=1) int, int);
+ method public androidx.heifwriter.HeifWriter build() throws java.io.IOException;
+ method public androidx.heifwriter.HeifWriter.Builder setGridEnabled(boolean);
+ method public androidx.heifwriter.HeifWriter.Builder setHandler(android.os.Handler?);
+ method public androidx.heifwriter.HeifWriter.Builder setMaxImages(@IntRange(from=1) int);
+ method public androidx.heifwriter.HeifWriter.Builder setPrimaryIndex(@IntRange(from=0) int);
+ method public androidx.heifwriter.HeifWriter.Builder setQuality(@IntRange(from=0, to=100) int);
+ method public androidx.heifwriter.HeifWriter.Builder setRotation(@IntRange(from=0) int);
}
}
diff --git a/heifwriter/heifwriter/api/restricted_current.txt b/heifwriter/heifwriter/api/restricted_current.txt
index 8a45d85..90c95a4 100644
--- a/heifwriter/heifwriter/api/restricted_current.txt
+++ b/heifwriter/heifwriter/api/restricted_current.txt
@@ -1,30 +1,71 @@
// Signature format: 4.0
package androidx.heifwriter {
+ public final class AvifWriter implements java.lang.AutoCloseable {
+ method public void addBitmap(android.graphics.Bitmap);
+ method public void addExifData(int, byte[], int, int);
+ method public void addYuvBuffer(int, byte[]);
+ method public void close();
+ method public android.os.Handler? getHandler();
+ method public android.view.Surface getInputSurface();
+ method public int getMaxImages();
+ method public int getPrimaryIndex();
+ method public int getQuality();
+ method public int getRotation();
+ method public boolean isGridEnabled();
+ method public boolean isHighBitDepthEnabled();
+ method public void setInputEndOfStreamTimestamp(@IntRange(from=0) long);
+ method public void start();
+ method public void stop(@IntRange(from=0) long) throws java.lang.Exception;
+ field public static final int INPUT_MODE_BITMAP = 2; // 0x2
+ field public static final int INPUT_MODE_BUFFER = 0; // 0x0
+ field public static final int INPUT_MODE_SURFACE = 1; // 0x1
+ }
+
+ public static final class AvifWriter.Builder {
+ ctor public AvifWriter.Builder(String, @IntRange(from=1) int, @IntRange(from=1) int, int);
+ ctor public AvifWriter.Builder(java.io.FileDescriptor, @IntRange(from=1) int, @IntRange(from=1) int, int);
+ method public androidx.heifwriter.AvifWriter build() throws java.io.IOException;
+ method public androidx.heifwriter.AvifWriter.Builder setGridEnabled(boolean);
+ method public androidx.heifwriter.AvifWriter.Builder setHandler(android.os.Handler?);
+ method public androidx.heifwriter.AvifWriter.Builder setHighBitDepthEnabled(boolean);
+ method public androidx.heifwriter.AvifWriter.Builder setMaxImages(@IntRange(from=1) int);
+ method public androidx.heifwriter.AvifWriter.Builder setPrimaryIndex(@IntRange(from=0) int);
+ method public androidx.heifwriter.AvifWriter.Builder setQuality(@IntRange(from=0, to=100) int);
+ method public androidx.heifwriter.AvifWriter.Builder setRotation(@IntRange(from=0) int);
+ }
+
public final class HeifWriter implements java.lang.AutoCloseable {
method public void addBitmap(android.graphics.Bitmap);
method public void addExifData(int, byte[], int, int);
method public void addYuvBuffer(int, byte[]);
method public void close();
+ method public android.os.Handler? getHandler();
method public android.view.Surface getInputSurface();
- method public void setInputEndOfStreamTimestamp(long);
+ method public int getMaxImages();
+ method public int getPrimaryIndex();
+ method public int getQuality();
+ method public int getRotation();
+ method public boolean isGridEnabled();
+ method public boolean isHighBitDepthEnabled();
+ method public void setInputEndOfStreamTimestamp(@IntRange(from=0) long);
method public void start();
- method public void stop(long) throws java.lang.Exception;
+ method public void stop(@IntRange(from=0) long) throws java.lang.Exception;
field public static final int INPUT_MODE_BITMAP = 2; // 0x2
field public static final int INPUT_MODE_BUFFER = 0; // 0x0
field public static final int INPUT_MODE_SURFACE = 1; // 0x1
}
public static final class HeifWriter.Builder {
- ctor public HeifWriter.Builder(String, int, int, int);
- ctor public HeifWriter.Builder(java.io.FileDescriptor, int, int, int);
- method public androidx.heifwriter.HeifWriter! build() throws java.io.IOException;
- method public androidx.heifwriter.HeifWriter.Builder! setGridEnabled(boolean);
- method public androidx.heifwriter.HeifWriter.Builder! setHandler(android.os.Handler?);
- method public androidx.heifwriter.HeifWriter.Builder! setMaxImages(int);
- method public androidx.heifwriter.HeifWriter.Builder! setPrimaryIndex(int);
- method public androidx.heifwriter.HeifWriter.Builder! setQuality(int);
- method public androidx.heifwriter.HeifWriter.Builder! setRotation(int);
+ ctor public HeifWriter.Builder(String, @IntRange(from=1) int, @IntRange(from=1) int, int);
+ ctor public HeifWriter.Builder(java.io.FileDescriptor, @IntRange(from=1) int, @IntRange(from=1) int, int);
+ method public androidx.heifwriter.HeifWriter build() throws java.io.IOException;
+ method public androidx.heifwriter.HeifWriter.Builder setGridEnabled(boolean);
+ method public androidx.heifwriter.HeifWriter.Builder setHandler(android.os.Handler?);
+ method public androidx.heifwriter.HeifWriter.Builder setMaxImages(@IntRange(from=1) int);
+ method public androidx.heifwriter.HeifWriter.Builder setPrimaryIndex(@IntRange(from=0) int);
+ method public androidx.heifwriter.HeifWriter.Builder setQuality(@IntRange(from=0, to=100) int);
+ method public androidx.heifwriter.HeifWriter.Builder setRotation(@IntRange(from=0) int);
}
}
diff --git a/heifwriter/heifwriter/lint-baseline.xml b/heifwriter/heifwriter/lint-baseline.xml
index 3a578ac..b2f2806 100644
--- a/heifwriter/heifwriter/lint-baseline.xml
+++ b/heifwriter/heifwriter/lint-baseline.xml
@@ -7,7 +7,7 @@
errorLine1=" synchronized void updateInputEOSTime(long timestampNs) {"
errorLine2=" ^">
<location
- file="src/main/java/androidx/heifwriter/HeifEncoder.java"/>
+ file="src/main/java/androidx/heifwriter/EncoderBase.java"/>
</issue>
<issue
@@ -16,7 +16,7 @@
errorLine1=" synchronized boolean updateLastInputAndEncoderTime(long inputTimeNs, long encoderTimeUs) {"
errorLine2=" ^">
<location
- file="src/main/java/androidx/heifwriter/HeifEncoder.java"/>
+ file="src/main/java/androidx/heifwriter/EncoderBase.java"/>
</issue>
<issue
@@ -25,7 +25,7 @@
errorLine1=" synchronized void updateLastOutputTime(long outputTimeUs) {"
errorLine2=" ^">
<location
- file="src/main/java/androidx/heifwriter/HeifEncoder.java"/>
+ file="src/main/java/androidx/heifwriter/EncoderBase.java"/>
</issue>
<issue
@@ -34,7 +34,7 @@
errorLine1=" synchronized void waitForResult(long timeoutMs) throws Exception {"
errorLine2=" ^">
<location
- file="src/main/java/androidx/heifwriter/HeifWriter.java"/>
+ file="src/main/java/androidx/heifwriter/WriterBase.java"/>
</issue>
<issue
@@ -43,7 +43,7 @@
errorLine1=" synchronized void signalResult(@Nullable Exception e) {"
errorLine2=" ^">
<location
- file="src/main/java/androidx/heifwriter/HeifWriter.java"/>
+ file="src/main/java/androidx/heifwriter/WriterBase.java"/>
</issue>
<issue
@@ -121,6 +121,24 @@
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
+ errorLine1=" protected static String findHevcFallback() {"
+ errorLine2=" ~~~~~~~">
+ <location
+ file="src/main/java/androidx/heifwriter/HeifEncoder.java"/>
+ </issue>
+
+ <issue
+ id="UnknownNullness"
+ message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
+ errorLine1=" protected static String findAv1Fallback() {"
+ errorLine2=" ~~~~~~~">
+ <location
+ file="src/main/java/androidx/heifwriter/AvifEncoder.java"/>
+ </issue>
+
+ <issue
+ id="UnknownNullness"
+ message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Builder setRotation(int rotation) {"
errorLine2=" ~~~~~~~">
<location
@@ -184,6 +202,69 @@
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
+ errorLine1=" public Builder setRotation(int rotation) {"
+ errorLine2=" ~~~~~~~">
+ <location
+ file="src/main/java/androidx/heifwriter/AvifWriter.java"/>
+ </issue>
+
+ <issue
+ id="UnknownNullness"
+ message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
+ errorLine1=" public Builder setGridEnabled(boolean gridEnabled) {"
+ errorLine2=" ~~~~~~~">
+ <location
+ file="src/main/java/androidx/heifwriter/AvifWriter.java"/>
+ </issue>
+
+ <issue
+ id="UnknownNullness"
+ message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
+ errorLine1=" public Builder setQuality(int quality) {"
+ errorLine2=" ~~~~~~~">
+ <location
+ file="src/main/java/androidx/heifwriter/AvifWriter.java"/>
+ </issue>
+
+ <issue
+ id="UnknownNullness"
+ message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
+ errorLine1=" public Builder setMaxImages(int maxImages) {"
+ errorLine2=" ~~~~~~~">
+ <location
+ file="src/main/java/androidx/heifwriter/AvifWriter.java"/>
+ </issue>
+
+ <issue
+ id="UnknownNullness"
+ message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
+ errorLine1=" public Builder setPrimaryIndex(int primaryIndex) {"
+ errorLine2=" ~~~~~~~">
+ <location
+ file="src/main/java/androidx/heifwriter/AvifWriter.java"/>
+ </issue>
+
+ <issue
+ id="UnknownNullness"
+ message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
+ errorLine1=" public Builder setHandler(@Nullable Handler handler) {"
+ errorLine2=" ~~~~~~~">
+ <location
+ file="src/main/java/androidx/heifwriter/AvifWriter.java"/>
+ </issue>
+
+ <issue
+ id="UnknownNullness"
+ message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
+ errorLine1=" public HeifWriter build() throws IOException {"
+ errorLine2=" ~~~~~~~~~~">
+ <location
+ file="src/main/java/androidx/heifwriter/AvifWriter.java"/>
+ </issue>
+
+ <issue
+ id="UnknownNullness"
+ message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public void loadTexture(int texId, Bitmap bitmap) {"
errorLine2=" ~~~~~~">
<location
diff --git a/heifwriter/heifwriter/src/androidTest/java/androidx/heifwriter/AvifWriterTest.java b/heifwriter/heifwriter/src/androidTest/java/androidx/heifwriter/AvifWriterTest.java
new file mode 100644
index 0000000..5aadb65
--- /dev/null
+++ b/heifwriter/heifwriter/src/androidTest/java/androidx/heifwriter/AvifWriterTest.java
@@ -0,0 +1,425 @@
+/*
+ * 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 androidx.heifwriter;
+
+import static androidx.heifwriter.AvifWriter.INPUT_MODE_BITMAP;
+import static androidx.heifwriter.AvifWriter.INPUT_MODE_BUFFER;
+import static androidx.heifwriter.AvifWriter.INPUT_MODE_SURFACE;
+import static androidx.test.core.app.ApplicationProvider.getApplicationContext;
+
+import android.Manifest;
+import android.graphics.Bitmap;
+import android.graphics.ImageFormat;
+import android.media.MediaFormat;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.Process;
+import android.util.Log;
+
+import androidx.heifwriter.test.R;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.filters.FlakyTest;
+import androidx.test.filters.LargeTest;
+import androidx.test.filters.SdkSuppress;
+import androidx.test.filters.SmallTest;
+import androidx.test.rule.GrantPermissionRule;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+/**
+ * Test {@link AvifWriter}.
+ */
+@RunWith(AndroidJUnit4.class)
+@FlakyTest
+public class AvifWriterTest extends TestBase {
+ private static final String TAG = AvifWriterTest.class.getSimpleName();
+
+ @Rule
+ public GrantPermissionRule mRuntimePermissionRule1 =
+ GrantPermissionRule.grant(Manifest.permission.READ_EXTERNAL_STORAGE);
+
+ @Rule
+ public GrantPermissionRule mRuntimePermissionRule =
+ GrantPermissionRule.grant(Manifest.permission.WRITE_EXTERNAL_STORAGE);
+
+ private static final boolean DEBUG = true;
+ private static final boolean DUMP_YUV_INPUT = false;
+
+ private static final String AVIFWRITER_INPUT = "heifwriter_input.heic";
+ private static final int[] IMAGE_RESOURCES = new int[] {
+ R.raw.heifwriter_input
+ };
+ private static final String[] IMAGE_FILENAMES = new String[] {
+ AVIFWRITER_INPUT
+ };
+ private static final String OUTPUT_FILENAME = "output.avif";
+
+ private EglWindowSurface mInputEglSurface;
+ private Handler mHandler;
+ private int mInputIndex;
+
+ @Before
+ public void setUp() throws Exception {
+ for (int i = 0; i < IMAGE_RESOURCES.length; ++i) {
+ String outputPath = new File(getApplicationContext().getExternalFilesDir(null),
+ IMAGE_FILENAMES[i]).getAbsolutePath();
+
+ InputStream inputStream = null;
+ FileOutputStream outputStream = null;
+ try {
+ inputStream = getApplicationContext()
+ .getResources().openRawResource(IMAGE_RESOURCES[i]);
+ outputStream = new FileOutputStream(outputPath);
+ copy(inputStream, outputStream);
+ } finally {
+ closeQuietly(inputStream);
+ closeQuietly(outputStream);
+ }
+ }
+
+ HandlerThread handlerThread = new HandlerThread(
+ "AvifEncoderThread", Process.THREAD_PRIORITY_FOREGROUND);
+ handlerThread.start();
+ mHandler = new Handler(handlerThread.getLooper());
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ for (int i = 0; i < IMAGE_RESOURCES.length; ++i) {
+ String imageFilePath = new File(getApplicationContext().getExternalFilesDir(null),
+ IMAGE_FILENAMES[i]).getAbsolutePath();
+ File imageFile = new File(imageFilePath);
+ if (imageFile.exists()) {
+ imageFile.delete();
+ }
+ }
+ }
+
+ @Test
+ @LargeTest
+ public void testInputBuffer_NoGrid_NoHandler() throws Throwable {
+ if (shouldSkip()) return;
+
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_BUFFER, false, false, OUTPUT_FILENAME);
+ doTestForVariousNumberImages(builder);
+ }
+
+ @Test
+ @LargeTest
+ public void testInputBuffer_Grid_NoHandler() throws Throwable {
+ if (shouldSkip()) return;
+
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_BUFFER, true, false, OUTPUT_FILENAME);
+ doTestForVariousNumberImages(builder);
+ }
+
+ @Test
+ @LargeTest
+ public void testInputBuffer_NoGrid_Handler() throws Throwable {
+ if (shouldSkip()) return;
+
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_BUFFER, false, true, OUTPUT_FILENAME);
+ doTestForVariousNumberImages(builder);
+ }
+
+ @Test
+ @LargeTest
+ public void testInputBuffer_Grid_Handler() throws Throwable {
+ if (shouldSkip()) return;
+
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_BUFFER, true, true, OUTPUT_FILENAME);
+ doTestForVariousNumberImages(builder);
+ }
+
+ @SdkSuppress(maxSdkVersion = 29) // b/192261638
+ @Test
+ @LargeTest
+ public void testInputSurface_NoGrid_NoHandler() throws Throwable {
+ if (shouldSkip()) return;
+
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_SURFACE, false, false, OUTPUT_FILENAME);
+ doTestForVariousNumberImages(builder);
+ }
+ //
+ @SdkSuppress(maxSdkVersion = 29) // b/192261638
+ @Test
+ @LargeTest
+ public void testInputSurface_Grid_NoHandler() throws Throwable {
+ if (shouldSkip()) return;
+
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_SURFACE, true, false, OUTPUT_FILENAME);
+ doTestForVariousNumberImages(builder);
+ }
+
+ @SdkSuppress(maxSdkVersion = 29) // b/192261638
+ @Test
+ @LargeTest
+ public void testInputSurface_NoGrid_Handler() throws Throwable {
+ if (shouldSkip()) return;
+
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_SURFACE, false, true, OUTPUT_FILENAME);
+ doTestForVariousNumberImages(builder);
+ }
+
+ @SdkSuppress(maxSdkVersion = 29) // b/192261638
+ @Test
+ @LargeTest
+ public void testInputSurface_Grid_Handler() throws Throwable {
+ if (shouldSkip()) return;
+
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_SURFACE, true, true, OUTPUT_FILENAME);
+ doTestForVariousNumberImages(builder);
+ }
+
+
+ @Test
+ @LargeTest
+ public void testInputBitmap_NoGrid_NoHandler() throws Throwable {
+ if (shouldSkip()) return;
+
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_BITMAP, false, false, OUTPUT_FILENAME);
+ for (int i = 0; i < IMAGE_RESOURCES.length; ++i) {
+ String inputPath = new File(getApplicationContext().getExternalFilesDir(null),
+ IMAGE_FILENAMES[i]).getAbsolutePath();
+ doTestForVariousNumberImages(builder.setInputPath(inputPath));
+ }
+ }
+
+ @SdkSuppress(maxSdkVersion = 29) // b/192261638
+ @Test
+ @LargeTest
+ public void testInputBitmap_Grid_NoHandler() throws Throwable {
+ if (shouldSkip()) return;
+
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_BITMAP, true, false, OUTPUT_FILENAME);
+ for (int i = 0; i < IMAGE_RESOURCES.length; ++i) {
+ String inputPath = new File(getApplicationContext().getExternalFilesDir(null),
+ IMAGE_FILENAMES[i]).getAbsolutePath();
+ doTestForVariousNumberImages(builder.setInputPath(inputPath));
+ }
+ }
+
+ @SdkSuppress(maxSdkVersion = 29) // b/192261638
+ @Test
+ @LargeTest
+ public void testInputBitmap_NoGrid_Handler() throws Throwable {
+ if (shouldSkip()) return;
+
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_BITMAP, false, true, OUTPUT_FILENAME);
+ for (int i = 0; i < IMAGE_RESOURCES.length; ++i) {
+ String inputPath = new File(getApplicationContext().getExternalFilesDir(null),
+ IMAGE_FILENAMES[i]).getAbsolutePath();
+ doTestForVariousNumberImages(builder.setInputPath(inputPath));
+ }
+ }
+
+ @SdkSuppress(maxSdkVersion = 29) // b/192261638
+ @Test
+ @LargeTest
+ public void testInputBitmap_Grid_Handler() throws Throwable {
+ if (shouldSkip()) return;
+
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_BITMAP, true, true, OUTPUT_FILENAME);
+ for (int i = 0; i < IMAGE_RESOURCES.length; ++i) {
+ String inputPath = new File(getApplicationContext().getExternalFilesDir(null),
+ IMAGE_FILENAMES[i]).getAbsolutePath();
+ doTestForVariousNumberImages(builder.setInputPath(inputPath));
+ }
+ }
+
+ @SdkSuppress(maxSdkVersion = 29) // b/192261638
+ @Test
+ @SmallTest
+ public void testCloseWithoutStart() throws Throwable {
+ if (shouldSkip()) return;
+
+ final String outputPath = new File(getApplicationContext().getExternalFilesDir(null),
+ OUTPUT_FILENAME).getAbsolutePath();
+ AvifWriter avifWriter = new AvifWriter.Builder(
+ outputPath, 1920, 1080, INPUT_MODE_SURFACE)
+ .setGridEnabled(true)
+ .setMaxImages(4)
+ .setQuality(90)
+ .setPrimaryIndex(0)
+ .setHandler(mHandler)
+ .build();
+
+ avifWriter.close();
+ }
+
+ private void drawFrame(int width, int height) {
+ mInputEglSurface.makeCurrent();
+ generateSurfaceFrame(mInputIndex, width, height);
+ mInputEglSurface.setPresentationTime(1000 * computePresentationTime(mInputIndex));
+ mInputEglSurface.swapBuffers();
+ mInputIndex++;
+ }
+
+ private void doTestForVariousNumberImages(TestConfig.Builder builder) throws Exception {
+ builder.setNumImages(4);
+ doTest(builder.setRotation(270).build());
+ doTest(builder.setRotation(180).build());
+ doTest(builder.setRotation(90).build());
+ doTest(builder.setRotation(0).build());
+ doTest(builder.setNumImages(1).build());
+ doTest(builder.setNumImages(8).build());
+ }
+
+ private boolean shouldSkip() {
+ return !hasEncoderForMime(MediaFormat.MIMETYPE_VIDEO_AV1);
+ }
+
+ private static byte[] mYuvData;
+ private void doTest(final TestConfig config) throws Exception {
+ final int width = config.mWidth;
+ final int height = config.mHeight;
+ final int actualNumImages = config.mActualNumImages;
+
+ mInputIndex = 0;
+ AvifWriter avifWriter = null;
+ FileInputStream inputStream = null;
+ FileOutputStream outputStream = null;
+ try {
+ if (DEBUG)
+ Log.d(TAG, "started: " + config);
+
+ avifWriter = new AvifWriter.Builder(
+ new File(getApplicationContext().getExternalFilesDir(null),
+ OUTPUT_FILENAME).getAbsolutePath(), width, height, config.mInputMode)
+ .setRotation(config.mRotation)
+ .setGridEnabled(config.mUseGrid)
+ .setMaxImages(config.mMaxNumImages)
+ .setQuality(config.mQuality)
+ .setPrimaryIndex(config.mMaxNumImages - 1)
+ .setHandler(config.mUseHandler ? mHandler : null)
+ .build();
+
+ if (config.mInputMode == INPUT_MODE_SURFACE) {
+ mInputEglSurface = new EglWindowSurface(avifWriter.getInputSurface());
+ }
+
+ avifWriter.start();
+
+ if (config.mInputMode == INPUT_MODE_BUFFER) {
+ if (mYuvData == null || mYuvData.length != width * height * 3 / 2) {
+ mYuvData = new byte[width * height * 3 / 2];
+ }
+
+ if (config.mInputPath != null) {
+ inputStream = new FileInputStream(config.mInputPath);
+ }
+
+ if (DUMP_YUV_INPUT) {
+ File outputFile = new File("/sdcard/input.yuv");
+ outputFile.createNewFile();
+ outputStream = new FileOutputStream(outputFile);
+ }
+
+ for (int i = 0; i < actualNumImages; i++) {
+ if (DEBUG)
+ Log.d(TAG, "fillYuvBuffer: " + i);
+ fillYuvBuffer(i, mYuvData, width, height, inputStream);
+ if (DUMP_YUV_INPUT) {
+ Log.d(TAG, "@@@ dumping input YUV");
+ outputStream.write(mYuvData);
+ }
+ avifWriter.addYuvBuffer(ImageFormat.YUV_420_888, mYuvData);
+ }
+ } else if (config.mInputMode == INPUT_MODE_SURFACE) {
+ // The input surface is a surface texture using single buffer mode, draws will be
+ // blocked until onFrameAvailable is done with the buffer, which is dependant on
+ // how fast MediaCodec processes them, which is further dependent on how fast the
+ // MediaCodec callbacks are handled. We can't put draws on the same looper that
+ // handles MediaCodec callback, it will cause deadlock.
+ for (int i = 0; i < actualNumImages; i++) {
+ if (DEBUG)
+ Log.d(TAG, "drawFrame: " + i);
+ drawFrame(width, height);
+ }
+ avifWriter.setInputEndOfStreamTimestamp(
+ 1000 * computePresentationTime(actualNumImages - 1));
+ } else if (config.mInputMode == INPUT_MODE_BITMAP) {
+ Bitmap[] bitmaps = config.mBitmaps;
+ for (int i = 0; i < Math.min(bitmaps.length, actualNumImages); i++) {
+ if (DEBUG)
+ Log.d(TAG, "addBitmap: " + i);
+ avifWriter.addBitmap(bitmaps[i]);
+ bitmaps[i].recycle();
+ }
+ }
+
+ avifWriter.stop(10000);
+ // The test sets the primary index to the last image.
+ // However, if we're testing early abort, the last image will not be
+ // present and the muxer is supposed to set it to 0 by default.
+ int expectedPrimary = config.mMaxNumImages - 1;
+ int expectedImageCount = config.mMaxNumImages;
+ if (actualNumImages < config.mMaxNumImages) {
+ expectedPrimary = 0;
+ expectedImageCount = actualNumImages;
+ }
+ verifyResult(config.mOutputPath, width, height, config.mRotation,
+ expectedImageCount, expectedPrimary, config.mUseGrid,
+ config.mInputMode == INPUT_MODE_SURFACE);
+ if (DEBUG)
+ Log.d(TAG, "finished: PASS");
+ } finally {
+ try {
+ if (outputStream != null) {
+ outputStream.close();
+ }
+ if (inputStream != null) {
+ inputStream.close();
+ }
+ } catch (IOException e) {
+ }
+
+ if (avifWriter != null) {
+ avifWriter.close();
+ avifWriter = null;
+ }
+ if (mInputEglSurface != null) {
+ // This also releases the surface from encoder.
+ mInputEglSurface.release();
+ mInputEglSurface = null;
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/heifwriter/heifwriter/src/androidTest/java/androidx/heifwriter/HeifWriterTest.java b/heifwriter/heifwriter/src/androidTest/java/androidx/heifwriter/HeifWriterTest.java
index b8e3752..f1f65ab 100644
--- a/heifwriter/heifwriter/src/androidTest/java/androidx/heifwriter/HeifWriterTest.java
+++ b/heifwriter/heifwriter/src/androidTest/java/androidx/heifwriter/HeifWriterTest.java
@@ -21,28 +21,15 @@
import static androidx.heifwriter.HeifWriter.INPUT_MODE_SURFACE;
import static androidx.test.core.app.ApplicationProvider.getApplicationContext;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
import android.Manifest;
import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.graphics.Color;
import android.graphics.ImageFormat;
-import android.graphics.Rect;
-import android.media.MediaCodecInfo;
-import android.media.MediaCodecList;
-import android.media.MediaExtractor;
import android.media.MediaFormat;
-import android.media.MediaMetadataRetriever;
-import android.opengl.GLES20;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Process;
import android.util.Log;
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
import androidx.heifwriter.test.R;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.FlakyTest;
@@ -58,62 +45,38 @@
import org.junit.Test;
import org.junit.runner.RunWith;
-import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-import java.util.Arrays;
/**
* Test {@link HeifWriter}.
*/
@RunWith(AndroidJUnit4.class)
@FlakyTest
-public class HeifWriterTest {
+public class HeifWriterTest extends TestBase {
private static final String TAG = HeifWriterTest.class.getSimpleName();
- private static final MediaCodecList sMCL = new MediaCodecList(MediaCodecList.REGULAR_CODECS);
-
@Rule
public GrantPermissionRule mRuntimePermissionRule1 =
- GrantPermissionRule.grant(Manifest.permission.READ_EXTERNAL_STORAGE);
+ GrantPermissionRule.grant(Manifest.permission.READ_EXTERNAL_STORAGE);
@Rule
public GrantPermissionRule mRuntimePermissionRule =
- GrantPermissionRule.grant(Manifest.permission.WRITE_EXTERNAL_STORAGE);
+ GrantPermissionRule.grant(Manifest.permission.WRITE_EXTERNAL_STORAGE);
- private static final boolean DEBUG = false;
+ private static final boolean DEBUG = true;
private static final boolean DUMP_YUV_INPUT = false;
- private static final byte[][] TEST_YUV_COLORS = {
- {(byte) 255, (byte) 0, (byte) 0},
- {(byte) 255, (byte) 0, (byte) 255},
- {(byte) 255, (byte) 255, (byte) 255},
- {(byte) 255, (byte) 255, (byte) 0},
- };
- private static final Color COLOR_BLOCK =
- Color.valueOf(1.0f, 1.0f, 1.0f);
- private static final Color[] COLOR_BARS = {
- Color.valueOf(0.0f, 0.0f, 0.0f),
- Color.valueOf(0.0f, 0.0f, 0.64f),
- Color.valueOf(0.0f, 0.64f, 0.0f),
- Color.valueOf(0.0f, 0.64f, 0.64f),
- Color.valueOf(0.64f, 0.0f, 0.0f),
- Color.valueOf(0.64f, 0.0f, 0.64f),
- Color.valueOf(0.64f, 0.64f, 0.0f),
- };
- private static final float MAX_DELTA = 0.025f;
- private static final int BORDER_WIDTH = 16;
-
private static final String HEIFWRITER_INPUT = "heifwriter_input.heic";
private static final int[] IMAGE_RESOURCES = new int[] {
- R.raw.heifwriter_input
+ R.raw.heifwriter_input
};
private static final String[] IMAGE_FILENAMES = new String[] {
- HEIFWRITER_INPUT
+ HEIFWRITER_INPUT
};
private static final String OUTPUT_FILENAME = "output.heic";
@@ -125,13 +88,13 @@
public void setUp() throws Exception {
for (int i = 0; i < IMAGE_RESOURCES.length; ++i) {
String outputPath = new File(getApplicationContext().getExternalFilesDir(null),
- IMAGE_FILENAMES[i]).getAbsolutePath();
+ IMAGE_FILENAMES[i]).getAbsolutePath();
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = getApplicationContext()
- .getResources().openRawResource(IMAGE_RESOURCES[i]);
+ .getResources().openRawResource(IMAGE_RESOURCES[i]);
outputStream = new FileOutputStream(outputPath);
copy(inputStream, outputStream);
} finally {
@@ -141,7 +104,7 @@
}
HandlerThread handlerThread = new HandlerThread(
- "HeifEncoderThread", Process.THREAD_PRIORITY_FOREGROUND);
+ "HeifEncoderThread", Process.THREAD_PRIORITY_FOREGROUND);
handlerThread.start();
mHandler = new Handler(handlerThread.getLooper());
}
@@ -150,7 +113,7 @@
public void tearDown() throws Exception {
for (int i = 0; i < IMAGE_RESOURCES.length; ++i) {
String imageFilePath = new File(getApplicationContext().getExternalFilesDir(null),
- IMAGE_FILENAMES[i]).getAbsolutePath();
+ IMAGE_FILENAMES[i]).getAbsolutePath();
File imageFile = new File(imageFilePath);
if (imageFile.exists()) {
imageFile.delete();
@@ -164,7 +127,8 @@
public void testInputBuffer_NoGrid_NoHandler() throws Throwable {
if (shouldSkip()) return;
- TestConfig.Builder builder = new TestConfig.Builder(INPUT_MODE_BUFFER, false, false);
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_BUFFER, false, false, OUTPUT_FILENAME);
doTestForVariousNumberImages(builder);
}
@@ -174,7 +138,8 @@
public void testInputBuffer_Grid_NoHandler() throws Throwable {
if (shouldSkip()) return;
- TestConfig.Builder builder = new TestConfig.Builder(INPUT_MODE_BUFFER, true, false);
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_BUFFER, true, false, OUTPUT_FILENAME);
doTestForVariousNumberImages(builder);
}
@@ -184,7 +149,8 @@
public void testInputBuffer_NoGrid_Handler() throws Throwable {
if (shouldSkip()) return;
- TestConfig.Builder builder = new TestConfig.Builder(INPUT_MODE_BUFFER, false, true);
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_BUFFER, false, true, OUTPUT_FILENAME);
doTestForVariousNumberImages(builder);
}
@@ -194,7 +160,8 @@
public void testInputBuffer_Grid_Handler() throws Throwable {
if (shouldSkip()) return;
- TestConfig.Builder builder = new TestConfig.Builder(INPUT_MODE_BUFFER, true, true);
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_BUFFER, true, true, OUTPUT_FILENAME);
doTestForVariousNumberImages(builder);
}
@@ -204,17 +171,19 @@
public void testInputSurface_NoGrid_NoHandler() throws Throwable {
if (shouldSkip()) return;
- TestConfig.Builder builder = new TestConfig.Builder(INPUT_MODE_SURFACE, false, false);
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_SURFACE, false, false, OUTPUT_FILENAME);
doTestForVariousNumberImages(builder);
}
-
+ //
@SdkSuppress(maxSdkVersion = 29) // b/192261638
@Test
@LargeTest
public void testInputSurface_Grid_NoHandler() throws Throwable {
if (shouldSkip()) return;
- TestConfig.Builder builder = new TestConfig.Builder(INPUT_MODE_SURFACE, true, false);
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_SURFACE, true, false, OUTPUT_FILENAME);
doTestForVariousNumberImages(builder);
}
@@ -224,7 +193,8 @@
public void testInputSurface_NoGrid_Handler() throws Throwable {
if (shouldSkip()) return;
- TestConfig.Builder builder = new TestConfig.Builder(INPUT_MODE_SURFACE, false, true);
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_SURFACE, false, true, OUTPUT_FILENAME);
doTestForVariousNumberImages(builder);
}
@@ -234,20 +204,23 @@
public void testInputSurface_Grid_Handler() throws Throwable {
if (shouldSkip()) return;
- TestConfig.Builder builder = new TestConfig.Builder(INPUT_MODE_SURFACE, true, true);
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_SURFACE, true, true, OUTPUT_FILENAME);
doTestForVariousNumberImages(builder);
}
+
@SdkSuppress(maxSdkVersion = 29) // b/192261638
@Test
@LargeTest
public void testInputBitmap_NoGrid_NoHandler() throws Throwable {
if (shouldSkip()) return;
- TestConfig.Builder builder = new TestConfig.Builder(INPUT_MODE_BITMAP, false, false);
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_BITMAP, false, false, OUTPUT_FILENAME);
for (int i = 0; i < IMAGE_RESOURCES.length; ++i) {
String inputPath = new File(getApplicationContext().getExternalFilesDir(null),
- IMAGE_FILENAMES[i]).getAbsolutePath();
+ IMAGE_FILENAMES[i]).getAbsolutePath();
doTestForVariousNumberImages(builder.setInputPath(inputPath));
}
}
@@ -258,10 +231,11 @@
public void testInputBitmap_Grid_NoHandler() throws Throwable {
if (shouldSkip()) return;
- TestConfig.Builder builder = new TestConfig.Builder(INPUT_MODE_BITMAP, true, false);
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_BITMAP, true, false, OUTPUT_FILENAME);
for (int i = 0; i < IMAGE_RESOURCES.length; ++i) {
String inputPath = new File(getApplicationContext().getExternalFilesDir(null),
- IMAGE_FILENAMES[i]).getAbsolutePath();
+ IMAGE_FILENAMES[i]).getAbsolutePath();
doTestForVariousNumberImages(builder.setInputPath(inputPath));
}
}
@@ -272,10 +246,11 @@
public void testInputBitmap_NoGrid_Handler() throws Throwable {
if (shouldSkip()) return;
- TestConfig.Builder builder = new TestConfig.Builder(INPUT_MODE_BITMAP, false, true);
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_BITMAP, false, true, OUTPUT_FILENAME);
for (int i = 0; i < IMAGE_RESOURCES.length; ++i) {
String inputPath = new File(getApplicationContext().getExternalFilesDir(null),
- IMAGE_FILENAMES[i]).getAbsolutePath();
+ IMAGE_FILENAMES[i]).getAbsolutePath();
doTestForVariousNumberImages(builder.setInputPath(inputPath));
}
}
@@ -286,10 +261,11 @@
public void testInputBitmap_Grid_Handler() throws Throwable {
if (shouldSkip()) return;
- TestConfig.Builder builder = new TestConfig.Builder(INPUT_MODE_BITMAP, true, true);
+ TestConfig.Builder builder =
+ new TestConfig.Builder(INPUT_MODE_BITMAP, true, true, OUTPUT_FILENAME);
for (int i = 0; i < IMAGE_RESOURCES.length; ++i) {
String inputPath = new File(getApplicationContext().getExternalFilesDir(null),
- IMAGE_FILENAMES[i]).getAbsolutePath();
+ IMAGE_FILENAMES[i]).getAbsolutePath();
doTestForVariousNumberImages(builder.setInputPath(inputPath));
}
}
@@ -301,19 +277,27 @@
if (shouldSkip()) return;
final String outputPath = new File(getApplicationContext().getExternalFilesDir(null),
- OUTPUT_FILENAME).getAbsolutePath();
+ OUTPUT_FILENAME).getAbsolutePath();
HeifWriter heifWriter = new HeifWriter.Builder(
- outputPath, 1920, 1080, INPUT_MODE_SURFACE)
- .setGridEnabled(true)
- .setMaxImages(4)
- .setQuality(90)
- .setPrimaryIndex(0)
- .setHandler(mHandler)
- .build();
+ outputPath, 1920, 1080, INPUT_MODE_SURFACE)
+ .setGridEnabled(true)
+ .setMaxImages(4)
+ .setQuality(90)
+ .setPrimaryIndex(0)
+ .setHandler(mHandler)
+ .build();
heifWriter.close();
}
+ private void drawFrame(int width, int height) {
+ mInputEglSurface.makeCurrent();
+ generateSurfaceFrame(mInputIndex, width, height);
+ mInputEglSurface.setPresentationTime(1000 * computePresentationTime(mInputIndex));
+ mInputEglSurface.swapBuffers();
+ mInputIndex++;
+ }
+
private void doTestForVariousNumberImages(TestConfig.Builder builder) throws Exception {
builder.setNumImages(4);
doTest(builder.setRotation(270).build());
@@ -324,186 +308,11 @@
doTest(builder.setNumImages(8).build());
}
- private void closeQuietly(Closeable closeable) {
- if (closeable != null) {
- try {
- closeable.close();
- } catch (RuntimeException rethrown) {
- throw rethrown;
- } catch (Exception ignored) {
- }
- }
- }
-
- private int copy(InputStream in, OutputStream out) throws IOException {
- int total = 0;
- byte[] buffer = new byte[8192];
- int c;
- while ((c = in.read(buffer)) != -1) {
- total += c;
- out.write(buffer, 0, c);
- }
- return total;
- }
-
private boolean shouldSkip() {
return !hasEncoderForMime(MediaFormat.MIMETYPE_VIDEO_HEVC)
&& !hasEncoderForMime(MediaFormat.MIMETYPE_IMAGE_ANDROID_HEIC);
}
- private boolean hasEncoderForMime(String mime) {
- for (MediaCodecInfo info : sMCL.getCodecInfos()) {
- if (info.isEncoder()) {
- for (String type : info.getSupportedTypes()) {
- if (type.equalsIgnoreCase(mime)) {
- Log.i(TAG, "found codec " + info.getName() + " for mime " + mime);
- return true;
- }
- }
- }
- }
- return false;
- }
-
- private static class TestConfig {
- final int mInputMode;
- final boolean mUseGrid;
- final boolean mUseHandler;
- final int mMaxNumImages;
- final int mActualNumImages;
- final int mWidth;
- final int mHeight;
- final int mRotation;
- final int mQuality;
- final String mInputPath;
- final String mOutputPath;
- final Bitmap[] mBitmaps;
-
- TestConfig(int inputMode, boolean useGrid, boolean useHandler,
- int maxNumImages, int actualNumImages, int width, int height,
- int rotation, int quality,
- String inputPath, String outputPath, Bitmap[] bitmaps) {
- mInputMode = inputMode;
- mUseGrid = useGrid;
- mUseHandler = useHandler;
- mMaxNumImages = maxNumImages;
- mActualNumImages = actualNumImages;
- mWidth = width;
- mHeight = height;
- mRotation = rotation;
- mQuality = quality;
- mInputPath = inputPath;
- mOutputPath = outputPath;
- mBitmaps = bitmaps;
- }
-
- static class Builder {
- final int mInputMode;
- final boolean mUseGrid;
- final boolean mUseHandler;
- int mMaxNumImages;
- int mNumImages;
- int mWidth;
- int mHeight;
- int mRotation;
- final int mQuality;
- String mInputPath;
- final String mOutputPath;
- Bitmap[] mBitmaps;
- boolean mNumImagesSetExplicitly;
-
-
- Builder(int inputMode, boolean useGrids, boolean useHandler) {
- mInputMode = inputMode;
- mUseGrid = useGrids;
- mUseHandler = useHandler;
- mMaxNumImages = mNumImages = 4;
- mWidth = 1920;
- mHeight = 1080;
- mRotation = 0;
- mQuality = 100;
- mOutputPath = new File(getApplicationContext().getExternalFilesDir(null),
- OUTPUT_FILENAME).getAbsolutePath();
- }
-
- Builder setInputPath(String inputPath) {
- mInputPath = (mInputMode == INPUT_MODE_BITMAP) ? inputPath : null;
- return this;
- }
-
- Builder setNumImages(int numImages) {
- mNumImagesSetExplicitly = true;
- mNumImages = numImages;
- return this;
- }
-
- Builder setRotation(int rotation) {
- mRotation = rotation;
- return this;
- }
-
- private void loadBitmapInputs() {
- if (mInputMode != INPUT_MODE_BITMAP) {
- return;
- }
- MediaMetadataRetriever retriever = new MediaMetadataRetriever();
- retriever.setDataSource(mInputPath);
- String hasImage = retriever.extractMetadata(
- MediaMetadataRetriever.METADATA_KEY_HAS_IMAGE);
- if (!"yes".equals(hasImage)) {
- throw new IllegalArgumentException("no bitmap found!");
- }
- mMaxNumImages = Math.min(mMaxNumImages, Integer.parseInt(retriever.extractMetadata(
- MediaMetadataRetriever.METADATA_KEY_IMAGE_COUNT)));
- if (!mNumImagesSetExplicitly) {
- mNumImages = mMaxNumImages;
- }
- mBitmaps = new Bitmap[mMaxNumImages];
- for (int i = 0; i < mBitmaps.length; i++) {
- mBitmaps[i] = retriever.getImageAtIndex(i);
- }
- mWidth = mBitmaps[0].getWidth();
- mHeight = mBitmaps[0].getHeight();
- try {
- retriever.release();
- } catch (IOException e) {
- // Nothing we can do about it.
- }
- }
-
- private void cleanupStaleOutputs() {
- File outputFile = new File(mOutputPath);
- if (outputFile.exists()) {
- outputFile.delete();
- }
- }
-
- TestConfig build() {
- cleanupStaleOutputs();
- loadBitmapInputs();
-
- return new TestConfig(mInputMode, mUseGrid, mUseHandler, mMaxNumImages, mNumImages,
- mWidth, mHeight, mRotation, mQuality, mInputPath, mOutputPath, mBitmaps);
- }
- }
-
- @Override
- public String toString() {
- return "TestConfig"
- + ": mInputMode " + mInputMode
- + ", mUseGrid " + mUseGrid
- + ", mUseHandler " + mUseHandler
- + ", mMaxNumImages " + mMaxNumImages
- + ", mNumImages " + mActualNumImages
- + ", mWidth " + mWidth
- + ", mHeight " + mHeight
- + ", mRotation " + mRotation
- + ", mQuality " + mQuality
- + ", mInputPath " + mInputPath
- + ", mOutputPath " + mOutputPath;
- }
- }
-
private static byte[] mYuvData;
private void doTest(final TestConfig config) throws Exception {
final int width = config.mWidth;
@@ -515,17 +324,19 @@
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
- if (DEBUG) Log.d(TAG, "started: " + config);
+ if (DEBUG)
+ Log.d(TAG, "started: " + config);
heifWriter = new HeifWriter.Builder(
- config.mOutputPath, width, height, config.mInputMode)
- .setRotation(config.mRotation)
- .setGridEnabled(config.mUseGrid)
- .setMaxImages(config.mMaxNumImages)
- .setQuality(config.mQuality)
- .setPrimaryIndex(config.mMaxNumImages - 1)
- .setHandler(config.mUseHandler ? mHandler : null)
- .build();
+ new File(getApplicationContext().getExternalFilesDir(null),
+ OUTPUT_FILENAME).getAbsolutePath(), width, height, config.mInputMode)
+ .setRotation(config.mRotation)
+ .setGridEnabled(config.mUseGrid)
+ .setMaxImages(config.mMaxNumImages)
+ .setQuality(config.mQuality)
+ .setPrimaryIndex(config.mMaxNumImages - 1)
+ .setHandler(config.mUseHandler ? mHandler : null)
+ .build();
if (config.mInputMode == INPUT_MODE_SURFACE) {
mInputEglSurface = new EglWindowSurface(heifWriter.getInputSurface());
@@ -549,7 +360,8 @@
}
for (int i = 0; i < actualNumImages; i++) {
- if (DEBUG) Log.d(TAG, "fillYuvBuffer: " + i);
+ if (DEBUG)
+ Log.d(TAG, "fillYuvBuffer: " + i);
fillYuvBuffer(i, mYuvData, width, height, inputStream);
if (DUMP_YUV_INPUT) {
Log.d(TAG, "@@@ dumping input YUV");
@@ -564,15 +376,17 @@
// MediaCodec callbacks are handled. We can't put draws on the same looper that
// handles MediaCodec callback, it will cause deadlock.
for (int i = 0; i < actualNumImages; i++) {
- if (DEBUG) Log.d(TAG, "drawFrame: " + i);
+ if (DEBUG)
+ Log.d(TAG, "drawFrame: " + i);
drawFrame(width, height);
}
heifWriter.setInputEndOfStreamTimestamp(
- 1000 * computePresentationTime(actualNumImages - 1));
+ 1000 * computePresentationTime(actualNumImages - 1));
} else if (config.mInputMode == INPUT_MODE_BITMAP) {
Bitmap[] bitmaps = config.mBitmaps;
for (int i = 0; i < Math.min(bitmaps.length, actualNumImages); i++) {
- if (DEBUG) Log.d(TAG, "addBitmap: " + i);
+ if (DEBUG)
+ Log.d(TAG, "addBitmap: " + i);
heifWriter.addBitmap(bitmaps[i]);
bitmaps[i].recycle();
}
@@ -589,9 +403,10 @@
expectedImageCount = actualNumImages;
}
verifyResult(config.mOutputPath, width, height, config.mRotation,
- expectedImageCount, expectedPrimary, config.mUseGrid,
- config.mInputMode == INPUT_MODE_SURFACE);
- if (DEBUG) Log.d(TAG, "finished: PASS");
+ expectedImageCount, expectedPrimary, config.mUseGrid,
+ config.mInputMode == INPUT_MODE_SURFACE);
+ if (DEBUG)
+ Log.d(TAG, "finished: PASS");
} finally {
try {
if (outputStream != null) {
@@ -600,7 +415,8 @@
if (inputStream != null) {
inputStream.close();
}
- } catch (IOException e) {}
+ } catch (IOException e) {
+ }
if (heifWriter != null) {
heifWriter.close();
@@ -613,139 +429,4 @@
}
}
}
-
- private long computePresentationTime(int frameIndex) {
- return 132 + (long)frameIndex * 1000000;
- }
-
- private void fillYuvBuffer(int frameIndex, @NonNull byte[] data, int width, int height,
- @Nullable FileInputStream inputStream) throws IOException {
- if (inputStream != null) {
- inputStream.read(data);
- } else {
- byte[] color = TEST_YUV_COLORS[frameIndex % TEST_YUV_COLORS.length];
- int sizeY = width * height;
- Arrays.fill(data, 0, sizeY, color[0]);
- Arrays.fill(data, sizeY, sizeY * 5 / 4, color[1]);
- Arrays.fill(data, sizeY * 5 / 4, sizeY * 3 / 2, color[2]);
- }
- }
-
- private void drawFrame(int width, int height) {
- mInputEglSurface.makeCurrent();
- generateSurfaceFrame(mInputIndex, width, height);
- mInputEglSurface.setPresentationTime(1000 * computePresentationTime(mInputIndex));
- mInputEglSurface.swapBuffers();
- mInputIndex++;
- }
-
- private static Rect getColorBarRect(int index, int width, int height) {
- int barWidth = (width - BORDER_WIDTH * 2) / COLOR_BARS.length;
- return new Rect(BORDER_WIDTH + barWidth * index, BORDER_WIDTH,
- BORDER_WIDTH + barWidth * (index + 1), height - BORDER_WIDTH);
- }
-
- private static Rect getColorBlockRect(int index, int width, int height) {
- int blockCenterX = (width / 5) * (index % 4 + 1);
- return new Rect(blockCenterX - width / 10, height / 6,
- blockCenterX + width / 10, height / 3);
- }
-
- private void generateSurfaceFrame(int frameIndex, int width, int height) {
- GLES20.glViewport(0, 0, width, height);
- GLES20.glDisable(GLES20.GL_SCISSOR_TEST);
- GLES20.glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
- GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
- GLES20.glEnable(GLES20.GL_SCISSOR_TEST);
-
- for (int i = 0; i < COLOR_BARS.length; i++) {
- Rect r = getColorBarRect(i, width, height);
-
- GLES20.glScissor(r.left, r.top, r.width(), r.height());
- final Color color = COLOR_BARS[i];
- GLES20.glClearColor(color.red(), color.green(), color.blue(), 1.0f);
- GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
- }
-
- Rect r = getColorBlockRect(frameIndex, width, height);
- GLES20.glScissor(r.left, r.top, r.width(), r.height());
- GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
- GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
- r.inset(BORDER_WIDTH, BORDER_WIDTH);
- GLES20.glScissor(r.left, r.top, r.width(), r.height());
- GLES20.glClearColor(COLOR_BLOCK.red(), COLOR_BLOCK.green(), COLOR_BLOCK.blue(), 1.0f);
- GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
- }
-
- /**
- * Determines if two color values are approximately equal.
- */
- private static boolean approxEquals(Color expected, Color actual) {
- return (Math.abs(expected.red() - actual.red()) <= MAX_DELTA)
- && (Math.abs(expected.green() - actual.green()) <= MAX_DELTA)
- && (Math.abs(expected.blue() - actual.blue()) <= MAX_DELTA);
- }
-
- private void verifyResult(
- String filename, int width, int height, int rotation,
- int imageCount, int primary, boolean useGrid, boolean checkColor)
- throws Exception {
- MediaMetadataRetriever retriever = new MediaMetadataRetriever();
- retriever.setDataSource(filename);
- String hasImage = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_IMAGE);
- if (!"yes".equals(hasImage)) {
- throw new Exception("No images found in file " + filename);
- }
- assertEquals("Wrong width", width,
- Integer.parseInt(retriever.extractMetadata(
- MediaMetadataRetriever.METADATA_KEY_IMAGE_WIDTH)));
- assertEquals("Wrong height", height,
- Integer.parseInt(retriever.extractMetadata(
- MediaMetadataRetriever.METADATA_KEY_IMAGE_HEIGHT)));
- assertEquals("Wrong rotation", rotation,
- Integer.parseInt(retriever.extractMetadata(
- MediaMetadataRetriever.METADATA_KEY_IMAGE_ROTATION)));
- assertEquals("Wrong image count", imageCount,
- Integer.parseInt(retriever.extractMetadata(
- MediaMetadataRetriever.METADATA_KEY_IMAGE_COUNT)));
- assertEquals("Wrong primary index", primary,
- Integer.parseInt(retriever.extractMetadata(
- MediaMetadataRetriever.METADATA_KEY_IMAGE_PRIMARY)));
- try {
- retriever.release();
- } catch (IOException e) {
- // Nothing we can do about it.
- }
-
- if (useGrid) {
- MediaExtractor extractor = new MediaExtractor();
- extractor.setDataSource(filename);
- MediaFormat format = extractor.getTrackFormat(0);
- int tileWidth = format.getInteger(MediaFormat.KEY_TILE_WIDTH);
- int tileHeight = format.getInteger(MediaFormat.KEY_TILE_HEIGHT);
- int gridRows = format.getInteger(MediaFormat.KEY_GRID_ROWS);
- int gridCols = format.getInteger(MediaFormat.KEY_GRID_COLUMNS);
- assertTrue("Wrong tile width or grid cols",
- ((width + tileWidth - 1) / tileWidth) == gridCols);
- assertTrue("Wrong tile height or grid rows",
- ((height + tileHeight - 1) / tileHeight) == gridRows);
- extractor.release();
- }
-
- if (checkColor) {
- Bitmap bitmap = BitmapFactory.decodeFile(filename);
-
- for (int i = 0; i < COLOR_BARS.length; i++) {
- Rect r = getColorBarRect(i, width, height);
- assertTrue("Color bar " + i + " doesn't match", approxEquals(COLOR_BARS[i],
- Color.valueOf(bitmap.getPixel(r.centerX(), r.centerY()))));
- }
-
- Rect r = getColorBlockRect(primary, width, height);
- assertTrue("Color block doesn't match", approxEquals(COLOR_BLOCK,
- Color.valueOf(bitmap.getPixel(r.centerX(), height - r.centerY()))));
-
- bitmap.recycle();
- }
- }
-}
+}
\ No newline at end of file
diff --git a/heifwriter/heifwriter/src/androidTest/java/androidx/heifwriter/TestBase.java b/heifwriter/heifwriter/src/androidTest/java/androidx/heifwriter/TestBase.java
new file mode 100644
index 0000000..83938e4
--- /dev/null
+++ b/heifwriter/heifwriter/src/androidTest/java/androidx/heifwriter/TestBase.java
@@ -0,0 +1,377 @@
+/*
+ * 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 androidx.heifwriter;
+
+import static androidx.heifwriter.HeifWriter.INPUT_MODE_BITMAP;
+import static androidx.test.core.app.ApplicationProvider.getApplicationContext;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.Color;
+import android.graphics.Rect;
+import android.media.MediaCodecInfo;
+import android.media.MediaCodecList;
+import android.media.MediaExtractor;
+import android.media.MediaFormat;
+import android.media.MediaMetadataRetriever;
+import android.opengl.GLES20;
+import android.util.Log;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+
+import java.io.Closeable;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Arrays;
+
+/**
+ * Base class holding common utilities for {@link HeifWriterTest} and {@link AvifWriterTest}.
+ */
+public class TestBase {
+ private static final String TAG = HeifWriterTest.class.getSimpleName();
+
+ private static final MediaCodecList sMCL = new MediaCodecList(MediaCodecList.REGULAR_CODECS);
+
+ private static final byte[][] TEST_YUV_COLORS = {
+ {(byte) 255, (byte) 0, (byte) 0},
+ {(byte) 255, (byte) 0, (byte) 255},
+ {(byte) 255, (byte) 255, (byte) 255},
+ {(byte) 255, (byte) 255, (byte) 0},
+ };
+ private static final Color COLOR_BLOCK =
+ Color.valueOf(1.0f, 1.0f, 1.0f);
+ private static final Color[] COLOR_BARS = {
+ Color.valueOf(0.0f, 0.0f, 0.0f),
+ Color.valueOf(0.0f, 0.0f, 0.64f),
+ Color.valueOf(0.0f, 0.64f, 0.0f),
+ Color.valueOf(0.0f, 0.64f, 0.64f),
+ Color.valueOf(0.64f, 0.0f, 0.0f),
+ Color.valueOf(0.64f, 0.0f, 0.64f),
+ Color.valueOf(0.64f, 0.64f, 0.0f),
+ };
+ private static final float MAX_DELTA = 0.025f;
+ private static final int BORDER_WIDTH = 16;
+
+ protected long computePresentationTime(int frameIndex) {
+ return 132 + (long)frameIndex * 1000000;
+ }
+
+ protected void fillYuvBuffer(int frameIndex, @NonNull byte[] data, int width, int height,
+ @Nullable FileInputStream inputStream) throws IOException {
+ if (inputStream != null) {
+ inputStream.read(data);
+ } else {
+ byte[] color = TEST_YUV_COLORS[frameIndex % TEST_YUV_COLORS.length];
+ int sizeY = width * height;
+ Arrays.fill(data, 0, sizeY, color[0]);
+ Arrays.fill(data, sizeY, sizeY * 5 / 4, color[1]);
+ Arrays.fill(data, sizeY * 5 / 4, sizeY * 3 / 2, color[2]);
+ }
+ }
+
+ protected static Rect getColorBarRect(int index, int width, int height) {
+ int barWidth = (width - BORDER_WIDTH * 2) / COLOR_BARS.length;
+ return new Rect(BORDER_WIDTH + barWidth * index, BORDER_WIDTH,
+ BORDER_WIDTH + barWidth * (index + 1), height - BORDER_WIDTH);
+ }
+
+ protected static Rect getColorBlockRect(int index, int width, int height) {
+ int blockCenterX = (width / 5) * (index % 4 + 1);
+ return new Rect(blockCenterX - width / 10, height / 6,
+ blockCenterX + width / 10, height / 3);
+ }
+
+ protected void generateSurfaceFrame(int frameIndex, int width, int height) {
+ GLES20.glViewport(0, 0, width, height);
+ GLES20.glDisable(GLES20.GL_SCISSOR_TEST);
+ GLES20.glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
+ GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
+ GLES20.glEnable(GLES20.GL_SCISSOR_TEST);
+
+ for (int i = 0; i < COLOR_BARS.length; i++) {
+ Rect r = getColorBarRect(i, width, height);
+
+ GLES20.glScissor(r.left, r.top, r.width(), r.height());
+ final Color color = COLOR_BARS[i];
+ GLES20.glClearColor(color.red(), color.green(), color.blue(), 1.0f);
+ GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
+ }
+
+ Rect r = getColorBlockRect(frameIndex, width, height);
+ GLES20.glScissor(r.left, r.top, r.width(), r.height());
+ GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
+ GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
+ r.inset(BORDER_WIDTH, BORDER_WIDTH);
+ GLES20.glScissor(r.left, r.top, r.width(), r.height());
+ GLES20.glClearColor(COLOR_BLOCK.red(), COLOR_BLOCK.green(), COLOR_BLOCK.blue(), 1.0f);
+ GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
+ }
+
+ /**
+ * Determines if two color values are approximately equal.
+ */
+ protected static boolean approxEquals(Color expected, Color actual) {
+ return (Math.abs(expected.red() - actual.red()) <= MAX_DELTA)
+ && (Math.abs(expected.green() - actual.green()) <= MAX_DELTA)
+ && (Math.abs(expected.blue() - actual.blue()) <= MAX_DELTA);
+ }
+
+ protected void verifyResult(
+ String filename, int width, int height, int rotation,
+ int imageCount, int primary, boolean useGrid, boolean checkColor)
+ throws Exception {
+ MediaMetadataRetriever retriever = new MediaMetadataRetriever();
+ retriever.setDataSource(filename);
+ String hasImage = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_IMAGE);
+ if (!"yes".equals(hasImage)) {
+ throw new Exception("No images found in file " + filename);
+ }
+ assertEquals("Wrong width", width,
+ Integer.parseInt(retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_IMAGE_WIDTH)));
+ assertEquals("Wrong height", height,
+ Integer.parseInt(retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_IMAGE_HEIGHT)));
+ assertEquals("Wrong rotation", rotation,
+ Integer.parseInt(retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_IMAGE_ROTATION)));
+ assertEquals("Wrong image count", imageCount,
+ Integer.parseInt(retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_IMAGE_COUNT)));
+ assertEquals("Wrong primary index", primary,
+ Integer.parseInt(retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_IMAGE_PRIMARY)));
+ try {
+ retriever.release();
+ } catch (IOException e) {
+ // Nothing we can do about it.
+ }
+
+ if (useGrid) {
+ MediaExtractor extractor = new MediaExtractor();
+ extractor.setDataSource(filename);
+ MediaFormat format = extractor.getTrackFormat(0);
+ int tileWidth = format.getInteger(MediaFormat.KEY_TILE_WIDTH);
+ int tileHeight = format.getInteger(MediaFormat.KEY_TILE_HEIGHT);
+ int gridRows = format.getInteger(MediaFormat.KEY_GRID_ROWS);
+ int gridCols = format.getInteger(MediaFormat.KEY_GRID_COLUMNS);
+ assertTrue("Wrong tile width or grid cols",
+ ((width + tileWidth - 1) / tileWidth) == gridCols);
+ assertTrue("Wrong tile height or grid rows",
+ ((height + tileHeight - 1) / tileHeight) == gridRows);
+ extractor.release();
+ }
+
+ if (checkColor) {
+ Bitmap bitmap = BitmapFactory.decodeFile(filename);
+
+ for (int i = 0; i < COLOR_BARS.length; i++) {
+ Rect r = getColorBarRect(i, width, height);
+ assertTrue("Color bar " + i + " doesn't match", approxEquals(COLOR_BARS[i],
+ Color.valueOf(bitmap.getPixel(r.centerX(), r.centerY()))));
+ }
+
+ Rect r = getColorBlockRect(primary, width, height);
+ assertTrue("Color block doesn't match", approxEquals(COLOR_BLOCK,
+ Color.valueOf(bitmap.getPixel(r.centerX(), height - r.centerY()))));
+
+ bitmap.recycle();
+ }
+ }
+
+ protected void closeQuietly(Closeable closeable) {
+ if (closeable != null) {
+ try {
+ closeable.close();
+ } catch (RuntimeException rethrown) {
+ throw rethrown;
+ } catch (Exception ignored) {
+ }
+ }
+ }
+
+ protected int copy(InputStream in, OutputStream out) throws IOException {
+ int total = 0;
+ byte[] buffer = new byte[8192];
+ int c;
+ while ((c = in.read(buffer)) != -1) {
+ total += c;
+ out.write(buffer, 0, c);
+ }
+ return total;
+ }
+
+ protected boolean hasEncoderForMime(String mime) {
+ for (MediaCodecInfo info : sMCL.getCodecInfos()) {
+ if (info.isEncoder()) {
+ for (String type : info.getSupportedTypes()) {
+ if (type.equalsIgnoreCase(mime)) {
+ Log.i(TAG, "found codec " + info.getName() + " for mime " + mime);
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ protected static class TestConfig {
+ final int mInputMode;
+ final boolean mUseGrid;
+ final boolean mUseHandler;
+ final int mMaxNumImages;
+ final int mActualNumImages;
+ final int mWidth;
+ final int mHeight;
+ final int mRotation;
+ final int mQuality;
+ final String mInputPath;
+ final String mOutputPath;
+ final Bitmap[] mBitmaps;
+
+ TestConfig(int inputMode, boolean useGrid, boolean useHandler,
+ int maxNumImages, int actualNumImages, int width, int height,
+ int rotation, int quality,
+ String inputPath, String outputPath, Bitmap[] bitmaps) {
+ mInputMode = inputMode;
+ mUseGrid = useGrid;
+ mUseHandler = useHandler;
+ mMaxNumImages = maxNumImages;
+ mActualNumImages = actualNumImages;
+ mWidth = width;
+ mHeight = height;
+ mRotation = rotation;
+ mQuality = quality;
+ mInputPath = inputPath;
+ mOutputPath = outputPath;
+ mBitmaps = bitmaps;
+ }
+
+ static class Builder {
+ final int mInputMode;
+ final boolean mUseGrid;
+ final boolean mUseHandler;
+ int mMaxNumImages;
+ int mNumImages;
+ int mWidth;
+ int mHeight;
+ int mRotation;
+ final int mQuality;
+ String mInputPath;
+ final String mOutputPath;
+ Bitmap[] mBitmaps;
+ boolean mNumImagesSetExplicitly;
+
+
+ Builder(int inputMode, boolean useGrids, boolean useHandler, String outputFileName) {
+ mInputMode = inputMode;
+ mUseGrid = useGrids;
+ mUseHandler = useHandler;
+ mMaxNumImages = mNumImages = 4;
+ mWidth = 1920;
+ mHeight = 1080;
+ mRotation = 0;
+ mQuality = 100;
+ mOutputPath = new File(getApplicationContext().getExternalFilesDir(null),
+ outputFileName).getAbsolutePath();
+ }
+
+ Builder setInputPath(String inputPath) {
+ mInputPath = (mInputMode == INPUT_MODE_BITMAP) ? inputPath : null;
+ return this;
+ }
+
+ Builder setNumImages(int numImages) {
+ mNumImagesSetExplicitly = true;
+ mNumImages = numImages;
+ return this;
+ }
+
+ Builder setRotation(int rotation) {
+ mRotation = rotation;
+ return this;
+ }
+
+ private void loadBitmapInputs() {
+ if (mInputMode != INPUT_MODE_BITMAP) {
+ return;
+ }
+ MediaMetadataRetriever retriever = new MediaMetadataRetriever();
+ retriever.setDataSource(mInputPath);
+ String hasImage = retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_HAS_IMAGE);
+ if (!"yes".equals(hasImage)) {
+ throw new IllegalArgumentException("no bitmap found!");
+ }
+ mMaxNumImages = Math.min(mMaxNumImages, Integer.parseInt(retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_IMAGE_COUNT)));
+ if (!mNumImagesSetExplicitly) {
+ mNumImages = mMaxNumImages;
+ }
+ mBitmaps = new Bitmap[mMaxNumImages];
+ for (int i = 0; i < mBitmaps.length; i++) {
+ mBitmaps[i] = retriever.getImageAtIndex(i);
+ }
+ mWidth = mBitmaps[0].getWidth();
+ mHeight = mBitmaps[0].getHeight();
+ try {
+ retriever.release();
+ } catch (IOException e) {
+ // Nothing we can do about it.
+ }
+ }
+
+ private void cleanupStaleOutputs() {
+ File outputFile = new File(mOutputPath);
+ if (outputFile.exists()) {
+ outputFile.delete();
+ }
+ }
+
+ TestConfig build() {
+ cleanupStaleOutputs();
+ loadBitmapInputs();
+
+ return new TestConfig(mInputMode, mUseGrid, mUseHandler, mMaxNumImages, mNumImages,
+ mWidth, mHeight, mRotation, mQuality, mInputPath, mOutputPath, mBitmaps);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "TestConfig"
+ + ": mInputMode " + mInputMode
+ + ", mUseGrid " + mUseGrid
+ + ", mUseHandler " + mUseHandler
+ + ", mMaxNumImages " + mMaxNumImages
+ + ", mNumImages " + mActualNumImages
+ + ", mWidth " + mWidth
+ + ", mHeight " + mHeight
+ + ", mRotation " + mRotation
+ + ", mQuality " + mQuality
+ + ", mInputPath " + mInputPath
+ + ", mOutputPath " + mOutputPath;
+ }
+ }
+}
\ No newline at end of file
diff --git a/heifwriter/heifwriter/src/main/java/androidx/heifwriter/AvifEncoder.java b/heifwriter/heifwriter/src/main/java/androidx/heifwriter/AvifEncoder.java
new file mode 100644
index 0000000..561e0b2
--- /dev/null
+++ b/heifwriter/heifwriter/src/main/java/androidx/heifwriter/AvifEncoder.java
@@ -0,0 +1,144 @@
+/*
+ * Copyright 2022 Google Inc. All rights reserved.
+ *
+ * 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 androidx.heifwriter;
+
+import android.media.MediaCodec;
+import android.media.MediaCodecInfo;
+import android.media.MediaCodecInfo.CodecCapabilities;
+import android.media.MediaCodecList;
+import android.media.MediaFormat;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.util.Log;
+import android.util.Range;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+
+import java.io.IOException;
+
+/**
+ * This class encodes images into HEIF-compatible samples using AV1 encoder.
+ *
+ * It currently supports three input modes: {@link #INPUT_MODE_BUFFER},
+ * {@link #INPUT_MODE_SURFACE}, or {@link #INPUT_MODE_BITMAP}.
+ *
+ * The output format and samples are sent back in {@link
+ * Callback#onOutputFormatChanged(HeifEncoder, MediaFormat)} and {@link
+ * Callback#onDrainOutputBuffer(HeifEncoder, ByteBuffer)}. If the client
+ * requests to use grid, each tile will be sent back individually.
+ *
+ * HeifEncoder is made a separate class from {@link HeifWriter}, as some more
+ * advanced use cases might want to build solutions on top of the HeifEncoder directly.
+ * (eg. mux still images and video tracks into a single container).
+ *
+ * @hide
+ */
+public final class AvifEncoder extends EncoderBase {
+ private static final String TAG = "AvifEncoder";
+ private static final boolean DEBUG = false;
+
+ protected static final int GRID_WIDTH = 512;
+ protected static final int GRID_HEIGHT = 512;
+ protected static final double MAX_COMPRESS_RATIO = 0.25f;
+
+ private static final MediaCodecList sMCL =
+ new MediaCodecList(MediaCodecList.REGULAR_CODECS);
+
+ /**
+ * Configure the avif encoding session. Should only be called once.
+ *
+ * @param width Width of the image.
+ * @param height Height of the image.
+ * @param useGrid Whether to encode image into tiles. If enabled, tile size will be
+ * automatically chosen.
+ * @param quality A number between 0 and 100 (inclusive), with 100 indicating the best quality
+ * supported by this implementation (which often results in larger file size).
+ * @param inputMode The input type of this encoding session.
+ * @param handler If not null, client will receive all callbacks on the handler's looper.
+ * Otherwise, client will receive callbacks on a looper created by us.
+ * @param cb The callback to receive various messages from the avif encoder.
+ */
+ public AvifEncoder(int width, int height, boolean useGrid,
+ int quality, @InputMode int inputMode,
+ @Nullable Handler handler, @NonNull Callback cb,
+ boolean useBitDepth10) throws IOException {
+ super("AVIF", width, height, useGrid, quality, inputMode, handler, cb, useBitDepth10);
+ mEncoder.setCallback(new Av1EncoderCallback(), mHandler);
+ finishSettingUpEncoder(useBitDepth10);
+ }
+
+ protected static String findAv1Fallback() {
+ String av1 = null; // first AV1 encoder
+ for (MediaCodecInfo info : sMCL.getCodecInfos()) {
+ if (!info.isEncoder()) {
+ continue;
+ }
+ MediaCodecInfo.CodecCapabilities caps = null;
+ try {
+ caps = info.getCapabilitiesForType(MediaFormat.MIMETYPE_VIDEO_AV1);
+ } catch (IllegalArgumentException e) { // mime is not supported
+ continue;
+ }
+ if (!caps.getVideoCapabilities().isSizeSupported(GRID_WIDTH, GRID_HEIGHT)) {
+ continue;
+ }
+ if (caps.getEncoderCapabilities().isBitrateModeSupported(
+ MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CQ)) {
+ // Encoder that supports CQ mode is preferred over others,
+ // return the first encoder that supports CQ mode.
+ // (No need to check if it's hw based, it's already listed in
+ // order of preference.)
+ return info.getName();
+ }
+ if (av1 == null) {
+ av1 = info.getName();
+ }
+ }
+ // If no encoders support CQ, return the first AV1 encoder.
+ return av1;
+ }
+
+ /**
+ * MediaCodec callback for AV1 encoding.
+ */
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ protected class Av1EncoderCallback extends EncoderCallback {
+ @Override
+ public void onOutputFormatChanged(MediaCodec codec, MediaFormat format) {
+ if (codec != mEncoder) return;
+
+ if (DEBUG) Log.d(TAG, "onOutputFormatChanged: " + format);
+
+ // TODO(b/252835975) replace "image/avif" with MIMETYPE_IMAGE_AVIF.
+ if (!format.getString(MediaFormat.KEY_MIME).equals("image/avif")) {
+ format.setString(MediaFormat.KEY_MIME, "image/avif");
+ format.setInteger(MediaFormat.KEY_WIDTH, mWidth);
+ format.setInteger(MediaFormat.KEY_HEIGHT, mHeight);
+
+ if (mUseGrid) {
+ format.setInteger(MediaFormat.KEY_TILE_WIDTH, mGridWidth);
+ format.setInteger(MediaFormat.KEY_TILE_HEIGHT, mGridHeight);
+ format.setInteger(MediaFormat.KEY_GRID_ROWS, mGridRows);
+ format.setInteger(MediaFormat.KEY_GRID_COLUMNS, mGridCols);
+ }
+ }
+
+ mCallback.onOutputFormatChanged(AvifEncoder.this, format);
+ }
+ }
+}
\ No newline at end of file
diff --git a/heifwriter/heifwriter/src/main/java/androidx/heifwriter/AvifWriter.java b/heifwriter/heifwriter/src/main/java/androidx/heifwriter/AvifWriter.java
new file mode 100644
index 0000000..706f9dfd
--- /dev/null
+++ b/heifwriter/heifwriter/src/main/java/androidx/heifwriter/AvifWriter.java
@@ -0,0 +1,330 @@
+/*
+ * Copyright 2022 Google Inc. All rights reserved.
+ *
+ * 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 androidx.heifwriter;
+
+import static android.media.MediaMuxer.OutputFormat.MUXER_OUTPUT_HEIF;
+
+import android.annotation.SuppressLint;
+import android.graphics.Bitmap;
+import android.media.MediaCodec;
+import android.media.MediaFormat;
+import android.media.MediaMuxer;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.Looper;
+import android.os.Process;
+import android.util.Log;
+import android.util.Pair;
+import android.view.Surface;
+
+import androidx.annotation.IntDef;
+import androidx.annotation.IntRange;
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+
+import java.io.FileDescriptor;
+import java.io.IOException;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * This class writes one or more still images (of the same dimensions) into
+ * an AVIF file.
+ *
+ * It currently supports three input modes: {@link #INPUT_MODE_BUFFER},
+ * {@link #INPUT_MODE_SURFACE}, or {@link #INPUT_MODE_BITMAP}.
+ *
+ * The general sequence (in pseudo-code) to write a avif file using this class is as follows:
+ *
+ * 1) Construct the writer:
+ * AvifWriter avifwriter = new AvifWriter(...);
+ *
+ * 2) If using surface input mode, obtain the input surface:
+ * Surface surface = avifwriter.getInputSurface();
+ *
+ * 3) Call start:
+ * avifwriter.start();
+ *
+ * 4) Depending on the chosen input mode, add one or more images using one of these methods:
+ * avifwriter.addYuvBuffer(...); Or
+ * avifwriter.addBitmap(...); Or
+ * render to the previously obtained surface
+ *
+ * 5) Call stop:
+ * avifwriter.stop(...);
+ *
+ * 6) Close the writer:
+ * avifwriter.close();
+ *
+ * Please refer to the documentations on individual methods for the exact usage.
+ */
+@SuppressWarnings("HiddenSuperclass")
+public final class AvifWriter extends WriterBase {
+
+ private static final String TAG = "AvifWriter";
+ private static final boolean DEBUG = false;
+
+ /**
+ * The input mode where the client adds input buffers with YUV data.
+ *
+ * @see #addYuvBuffer(int, byte[])
+ */
+ public static final int INPUT_MODE_BUFFER = WriterBase.INPUT_MODE_BUFFER;
+
+ /**
+ * The input mode where the client renders the images to an input Surface created by the writer.
+ *
+ * The input surface operates in single buffer mode. As a result, for use case where camera
+ * directly outputs to the input surface, this mode will not work because camera framework
+ * requires multiple buffers to operate in a pipeline fashion.
+ *
+ * @see #getInputSurface()
+ */
+ public static final int INPUT_MODE_SURFACE = WriterBase.INPUT_MODE_SURFACE;
+
+ /**
+ * The input mode where the client adds bitmaps.
+ *
+ * @see #addBitmap(Bitmap)
+ */
+ public static final int INPUT_MODE_BITMAP = WriterBase.INPUT_MODE_BITMAP;
+
+ /**
+ * @hide
+ */
+ @IntDef({
+ INPUT_MODE_BUFFER, INPUT_MODE_SURFACE, INPUT_MODE_BITMAP,
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface InputMode {
+
+ }
+
+ /**
+ * Builder class for constructing a AvifWriter object from specified parameters.
+ */
+ public static final class Builder {
+ private final String mPath;
+ private final FileDescriptor mFd;
+ private final int mWidth;
+ private final int mHeight;
+ private final @InputMode int mInputMode;
+ private boolean mGridEnabled = true;
+ private int mQuality = 100;
+ private int mMaxImages = 1;
+ private int mPrimaryIndex = 0;
+ private int mRotation = 0;
+ private Handler mHandler;
+ private boolean mHighBitDepthEnabled = false;
+
+ /**
+ * Construct a Builder with output specified by its path.
+ *
+ * @param path Path of the file to be written.
+ * @param width Width of the image in number of pixels.
+ * @param height Height of the image in number of pixels.
+ * @param inputMode Input mode for this writer, must be one of {@link #INPUT_MODE_BUFFER},
+ * {@link #INPUT_MODE_SURFACE}, or {@link #INPUT_MODE_BITMAP}.
+ */
+ public Builder(@NonNull String path,
+ @IntRange(from = 1) int width,
+ @IntRange(from = 1) int height,
+ @InputMode int inputMode) {
+ this(path, null, width, height, inputMode);
+ }
+
+ /**
+ * Construct a Builder with output specified by its file descriptor.
+ *
+ * @param fd File descriptor of the file to be written.
+ * @param width Width of the image in number of pixels.
+ * @param height Height of the image in number of pixels.
+ * @param inputMode Input mode for this writer, must be one of {@link #INPUT_MODE_BUFFER},
+ * {@link #INPUT_MODE_SURFACE}, or {@link #INPUT_MODE_BITMAP}.
+ */
+ public Builder(@NonNull FileDescriptor fd,
+ @IntRange(from = 1) int width,
+ @IntRange(from = 1) int height,
+ @InputMode int inputMode) {
+ this(null, fd, width, height, inputMode);
+ }
+
+ private Builder(String path, FileDescriptor fd,
+ @IntRange(from = 1) int width,
+ @IntRange(from = 1) int height,
+ @InputMode int inputMode) {
+ mPath = path;
+ mFd = fd;
+ mWidth = width;
+ mHeight = height;
+ mInputMode = inputMode;
+ }
+
+ /**
+ * Set the image rotation in degrees.
+ *
+ * @param rotation Rotation angle in degrees (clockwise) of the image, must be 0, 90,
+ * 180 or 270. Default is 0.
+ * @return this Builder object.
+ */
+ public @NonNull Builder setRotation(@IntRange(from = 0) int rotation) {
+ if (rotation != 0 && rotation != 90 && rotation != 180 && rotation != 270) {
+ throw new IllegalArgumentException("Invalid rotation angle: " + rotation);
+ }
+ mRotation = rotation;
+ return this;
+ }
+
+ /**
+ * Set whether to enable grid option.
+ *
+ * @param gridEnabled Whether to enable grid option. If enabled, the tile size will be
+ * automatically chosen. Default is to enable.
+ * @return this Builder object.
+ */
+ public @NonNull Builder setGridEnabled(boolean gridEnabled) {
+ mGridEnabled = gridEnabled;
+ return this;
+ }
+
+ /**
+ * Set the quality for encoding images.
+ *
+ * @param quality A number between 0 and 100 (inclusive), with 100 indicating the best
+ * quality supported by this implementation. Default is 100.
+ * @return this Builder object.
+ */
+ public @NonNull Builder setQuality(@IntRange(from = 0, to = 100) int quality) {
+ if (quality < 0 || quality > 100) {
+ throw new IllegalArgumentException("Invalid quality: " + quality);
+ }
+ mQuality = quality;
+ return this;
+ }
+
+ /**
+ * Set the maximum number of images to write.
+ *
+ * @param maxImages Max number of images to write. Frames exceeding this number will not be
+ * written to file. The writing can be stopped earlier before this number
+ * of images are written by {@link #stop(long)}, except for the input mode
+ * of {@link #INPUT_MODE_SURFACE}, where the EOS timestamp must be
+ * specified (via {@link #setInputEndOfStreamTimestamp(long)} and reached.
+ * Default is 1.
+ * @return this Builder object.
+ */
+ public @NonNull Builder setMaxImages(@IntRange(from = 1) int maxImages) {
+ if (maxImages <= 0) {
+ throw new IllegalArgumentException("Invalid maxImage: " + maxImages);
+ }
+ mMaxImages = maxImages;
+ return this;
+ }
+
+ /**
+ * Set the primary image index.
+ *
+ * @param primaryIndex Index of the image that should be marked as primary, must be within
+ * range [0, maxImages - 1] inclusive. Default is 0.
+ * @return this Builder object.
+ */
+ public @NonNull Builder setPrimaryIndex(@IntRange(from = 0) int primaryIndex) {
+ mPrimaryIndex = primaryIndex;
+ return this;
+ }
+
+ /**
+ * Provide a handler for the AvifWriter to use.
+ *
+ * @param handler If not null, client will receive all callbacks on the handler's looper.
+ * Otherwise, client will receive callbacks on a looper created by the
+ * writer. Default is null.
+ * @return this Builder object.
+ */
+ public @NonNull Builder setHandler(@Nullable Handler handler) {
+ mHandler = handler;
+ return this;
+ }
+
+ /**
+ * Provide a setting for the AvifWriter to use high bit-depth or not.
+ *
+ * @param highBitDepthEnabled Whether to enable high bit-depth mode. Default is false, if
+ * true, AvifWriter will encode with high bit-depth.
+ * @return this Builder object.
+ */
+ public @NonNull Builder setHighBitDepthEnabled(boolean highBitDepthEnabled) {
+ mHighBitDepthEnabled = highBitDepthEnabled;
+ return this;
+ }
+
+ /**
+ * Build a AvifWriter object.
+ *
+ * @return a AvifWriter object built according to the specifications.
+ * @throws IOException if failed to create the writer, possibly due to failure to create
+ * {@link android.media.MediaMuxer} or {@link android.media.MediaCodec}.
+ */
+ public @NonNull AvifWriter build() throws IOException {
+ return new AvifWriter(mPath, mFd, mWidth, mHeight, mRotation, mGridEnabled, mQuality,
+ mMaxImages, mPrimaryIndex, mInputMode, mHandler, mHighBitDepthEnabled);
+ }
+ }
+
+ @SuppressLint("WrongConstant")
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ AvifWriter(@NonNull String path,
+ @NonNull FileDescriptor fd,
+ int width,
+ int height,
+ int rotation,
+ boolean gridEnabled,
+ int quality,
+ int maxImages,
+ int primaryIndex,
+ @InputMode int inputMode,
+ @Nullable Handler handler,
+ boolean highBitDepthEnabled) throws IOException {
+ super(rotation, inputMode, maxImages, primaryIndex, gridEnabled, quality,
+ handler, highBitDepthEnabled);
+
+ if (DEBUG) {
+ Log.d(TAG, "width: " + width
+ + ", height: " + height
+ + ", rotation: " + rotation
+ + ", gridEnabled: " + gridEnabled
+ + ", quality: " + quality
+ + ", maxImages: " + maxImages
+ + ", primaryIndex: " + primaryIndex
+ + ", inputMode: " + inputMode);
+ }
+
+ // set to 1 initially, and wait for output format to know for sure
+ mNumTiles = 1;
+
+ mMuxer = (path != null) ? new MediaMuxer(path, MUXER_OUTPUT_HEIF)
+ : new MediaMuxer(fd, MUXER_OUTPUT_HEIF);
+
+ mEncoder = new AvifEncoder(width, height, gridEnabled, quality,
+ mInputMode, mHandler, new WriterCallback(), highBitDepthEnabled);
+ }
+}
\ No newline at end of file
diff --git a/heifwriter/heifwriter/src/main/java/androidx/heifwriter/EglWindowSurface.java b/heifwriter/heifwriter/src/main/java/androidx/heifwriter/EglWindowSurface.java
index 35d34d4..c69e002 100644
--- a/heifwriter/heifwriter/src/main/java/androidx/heifwriter/EglWindowSurface.java
+++ b/heifwriter/heifwriter/src/main/java/androidx/heifwriter/EglWindowSurface.java
@@ -25,6 +25,8 @@
import android.util.Log;
import android.view.Surface;
+import androidx.annotation.NonNull;
+
import java.util.Objects;
/**
@@ -52,18 +54,22 @@
* Creates an EglWindowSurface from a Surface.
*/
public EglWindowSurface(Surface surface) {
+ this(surface, false);
+ }
+
+ public EglWindowSurface(Surface surface, boolean useHighBitDepth) {
if (surface == null) {
throw new NullPointerException();
}
mSurface = surface;
- eglSetup();
+ eglSetup(useHighBitDepth);
}
/**
* Prepares EGL. We want a GLES 2.0 context and a surface that supports recording.
*/
- private void eglSetup() {
+ private void eglSetup(boolean useHighBitDepth) {
mEGLDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY);
if (Objects.equals(mEGLDisplay, EGL14.EGL_NO_DISPLAY)) {
throw new RuntimeException("unable to get EGL14 display");
@@ -76,27 +82,31 @@
// Configure EGL for recordable and OpenGL ES 2.0. We want enough RGB bits
// to minimize artifacts from possible YUV conversion.
- int[] attribList = {
- EGL14.EGL_RED_SIZE, 8,
- EGL14.EGL_GREEN_SIZE, 8,
- EGL14.EGL_BLUE_SIZE, 8,
- EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT,
- EGLExt.EGL_RECORDABLE_ANDROID, 1,
- EGL14.EGL_NONE
+ int eglColorSize = useHighBitDepth ? 10: 8;
+ int eglAlphaSize = useHighBitDepth ? 2: 0;
+ int recordable = useHighBitDepth ? 0: 1;
+ int[] configAttribList = {
+ EGL14.EGL_RED_SIZE, eglColorSize,
+ EGL14.EGL_GREEN_SIZE, eglColorSize,
+ EGL14.EGL_BLUE_SIZE, eglColorSize,
+ EGL14.EGL_ALPHA_SIZE, eglAlphaSize,
+ EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT,
+ EGLExt.EGL_RECORDABLE_ANDROID, recordable,
+ EGL14.EGL_NONE
};
int[] numConfigs = new int[1];
- if (!EGL14.eglChooseConfig(mEGLDisplay, attribList, 0, mConfigs, 0, mConfigs.length,
- numConfigs, 0)) {
+ if (!EGL14.eglChooseConfig(mEGLDisplay, configAttribList, 0, mConfigs, 0, mConfigs.length,
+ numConfigs, 0)) {
throw new RuntimeException("unable to find RGB888+recordable ES2 EGL config");
}
// Configure context for OpenGL ES 2.0.
- int[] attrib_list = {
- EGL14.EGL_CONTEXT_CLIENT_VERSION, 2,
- EGL14.EGL_NONE
+ int[] contextAttribList = {
+ EGL14.EGL_CONTEXT_CLIENT_VERSION, 2,
+ EGL14.EGL_NONE
};
mEGLContext = EGL14.eglCreateContext(mEGLDisplay, mConfigs[0], EGL14.EGL_NO_CONTEXT,
- attrib_list, 0);
+ contextAttribList, 0);
checkEglError("eglCreateContext");
if (mEGLContext == null) {
throw new RuntimeException("null context");
@@ -188,7 +198,7 @@
/**
* Returns the Surface that the MediaCodec receives buffers from.
*/
- public Surface getSurface() {
+ public @NonNull Surface getSurface() {
return mSurface;
}
diff --git a/heifwriter/heifwriter/src/main/java/androidx/heifwriter/EncoderBase.java b/heifwriter/heifwriter/src/main/java/androidx/heifwriter/EncoderBase.java
new file mode 100644
index 0000000..5a30454
--- /dev/null
+++ b/heifwriter/heifwriter/src/main/java/androidx/heifwriter/EncoderBase.java
@@ -0,0 +1,1058 @@
+/*
+ * Copyright 2022 Google Inc. All rights reserved.
+ *
+ * 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 androidx.heifwriter;
+
+import android.graphics.Bitmap;
+import android.graphics.ImageFormat;
+import android.graphics.Rect;
+import android.graphics.SurfaceTexture;
+import android.media.Image;
+import android.media.MediaCodec;
+import android.media.MediaCodec.BufferInfo;
+import android.media.MediaCodec.CodecException;
+import android.media.MediaCodecInfo;
+import android.media.MediaCodecInfo.CodecCapabilities;
+import android.media.MediaCodecList;
+import android.media.MediaFormat;
+import android.opengl.GLES20;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.Looper;
+import android.os.Process;
+import android.util.Log;
+import android.util.Range;
+import android.view.Surface;
+
+import androidx.annotation.IntDef;
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+
+import java.io.IOException;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * This class holds common utilities for {@link HeifEncoder} and {@link AvifEncoder}, and
+ * calls media framework and encodes images into HEIF- or AVIF- compatible samples using
+ * HEVC or AV1 encoder.
+ *
+ * It currently supports three input modes: {@link #INPUT_MODE_BUFFER},
+ * {@link #INPUT_MODE_SURFACE}, or {@link #INPUT_MODE_BITMAP}.
+ *
+ * Callback#onOutputFormatChanged(MediaCodec, MediaFormat)} and {@link
+ * Callback#onDrainOutputBuffer(MediaCodec, ByteBuffer)}. If the client
+ * requests to use grid, each tile will be sent back individually.
+ *
+ *
+ * * HeifEncoder is made a separate class from {@link HeifWriter}, as some more
+ * * advanced use cases might want to build solutions on top of the HeifEncoder directly.
+ * * (eg. mux still images and video tracks into a single container).
+ *
+ *
+ * @hide
+ */
+public class EncoderBase implements AutoCloseable,
+ SurfaceTexture.OnFrameAvailableListener {
+ private static final String TAG = "EncoderBase";
+ private static final boolean DEBUG = false;
+
+ private String MIME;
+ private int GRID_WIDTH;
+ private int GRID_HEIGHT;
+ private double MAX_COMPRESS_RATIO;
+ private int INPUT_BUFFER_POOL_SIZE = 2;
+
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ MediaCodec mEncoder;
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ final MediaFormat mCodecFormat;
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ protected final Callback mCallback;
+ private final HandlerThread mHandlerThread;
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ final Handler mHandler;
+ private final @InputMode int mInputMode;
+ private final boolean mUseBitDepth10;
+
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ final int mWidth;
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ protected final int mHeight;
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ protected final int mGridWidth;
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ protected final int mGridHeight;
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ protected final int mGridRows;
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ protected final int mGridCols;
+ private final int mNumTiles;
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ final boolean mUseGrid;
+
+ private int mInputIndex;
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ boolean mInputEOS;
+ private final Rect mSrcRect;
+ private final Rect mDstRect;
+ private ByteBuffer mCurrentBuffer;
+ private final ArrayList<ByteBuffer> mEmptyBuffers = new ArrayList<>();
+ private final ArrayList<ByteBuffer> mFilledBuffers = new ArrayList<>();
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ final ArrayList<Integer> mCodecInputBuffers = new ArrayList<>();
+ private final boolean mCopyTiles;
+
+ // Helper for tracking EOS when surface is used
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ SurfaceEOSTracker mEOSTracker;
+
+ // Below variables are to handle GL copy from client's surface
+ // to encoder surface when tiles are used.
+ private SurfaceTexture mInputTexture;
+ private Surface mInputSurface;
+ private Surface mEncoderSurface;
+ private EglWindowSurface mEncoderEglSurface;
+ private EglRectBlt mRectBlt;
+ private int mTextureId;
+ private final float[] mTmpMatrix = new float[16];
+ private final AtomicBoolean mStopping = new AtomicBoolean(false);
+
+ public static final int INPUT_MODE_BUFFER = HeifWriter.INPUT_MODE_BUFFER;
+ public static final int INPUT_MODE_SURFACE = HeifWriter.INPUT_MODE_SURFACE;
+ public static final int INPUT_MODE_BITMAP = HeifWriter.INPUT_MODE_BITMAP;
+ @IntDef({
+ INPUT_MODE_BUFFER,
+ INPUT_MODE_SURFACE,
+ INPUT_MODE_BITMAP,
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface InputMode {}
+
+ public static abstract class Callback {
+ /**
+ * Called when the output format has changed.
+ *
+ * @param encoder The EncoderBase object.
+ * @param format The new output format.
+ */
+ public abstract void onOutputFormatChanged(
+ @NonNull EncoderBase encoder, @NonNull MediaFormat format);
+
+ /**
+ * Called when an output buffer becomes available.
+ *
+ * @param encoder The EncoderBase object.
+ * @param byteBuffer the available output buffer.
+ */
+ public abstract void onDrainOutputBuffer(
+ @NonNull EncoderBase encoder, @NonNull ByteBuffer byteBuffer);
+
+ /**
+ * Called when encoding reached the end of stream without error.
+ *
+ * @param encoder The EncoderBase object.
+ */
+ public abstract void onComplete(@NonNull EncoderBase encoder);
+
+ /**
+ * Called when encoding hits an error.
+ *
+ * @param encoder The EncoderBase object.
+ * @param e The exception that the codec reported.
+ */
+ public abstract void onError(@NonNull EncoderBase encoder, @NonNull CodecException e);
+ }
+
+ /**
+ * Configure the encoder. Should only be called once.
+ *
+ * @param mimeType mime type. Currently it supports "HEIC" and "AVIF".
+ * @param width Width of the image.
+ * @param height Height of the image.
+ * @param useGrid Whether to encode image into tiles. If enabled, tile size will be
+ * automatically chosen.
+ * @param quality A number between 0 and 100 (inclusive), with 100 indicating the best quality
+ * supported by this implementation (which often results in larger file size).
+ * @param inputMode The input type of this encoding session.
+ * @param handler If not null, client will receive all callbacks on the handler's looper.
+ * Otherwise, client will receive callbacks on a looper created by us.
+ * @param cb The callback to receive various messages from the heif encoder.
+ */
+ protected EncoderBase(@NonNull String mimeType, int width, int height, boolean useGrid,
+ int quality, @InputMode int inputMode,
+ @Nullable Handler handler, @NonNull Callback cb,
+ boolean useBitDepth10) throws IOException {
+ if (DEBUG)
+ Log.d(TAG, "width: " + width + ", height: " + height +
+ ", useGrid: " + useGrid + ", quality: " + quality +
+ ", inputMode: " + inputMode +
+ ", useBitDepth10: " + String.valueOf(useBitDepth10));
+
+ if (width < 0 || height < 0 || quality < 0 || quality > 100) {
+ throw new IllegalArgumentException("invalid encoder inputs");
+ }
+
+ switch (mimeType) {
+ case "HEIC":
+ MIME = mimeType;
+ GRID_WIDTH = HeifEncoder.GRID_WIDTH;
+ GRID_HEIGHT = HeifEncoder.GRID_HEIGHT;
+ MAX_COMPRESS_RATIO = HeifEncoder.MAX_COMPRESS_RATIO;
+ break;
+ case "AVIF":
+ MIME = mimeType;
+ GRID_WIDTH = AvifEncoder.GRID_WIDTH;
+ GRID_HEIGHT = AvifEncoder.GRID_HEIGHT;
+ MAX_COMPRESS_RATIO = AvifEncoder.MAX_COMPRESS_RATIO;
+ break;
+ default:
+ Log.e(TAG, "Not supported mime type: " + mimeType);
+ }
+
+ boolean useHeicEncoder = false;
+ MediaCodecInfo.CodecCapabilities caps = null;
+ switch (MIME) {
+ case "HEIC":
+ try {
+ mEncoder = MediaCodec.createEncoderByType(
+ MediaFormat.MIMETYPE_IMAGE_ANDROID_HEIC);
+ caps = mEncoder.getCodecInfo().getCapabilitiesForType(
+ MediaFormat.MIMETYPE_IMAGE_ANDROID_HEIC);
+ // If the HEIC encoder can't support the size, fall back to HEVC encoder.
+ if (!caps.getVideoCapabilities().isSizeSupported(width, height)) {
+ mEncoder.release();
+ mEncoder = null;
+ throw new Exception();
+ }
+ useHeicEncoder = true;
+ } catch (Exception e) {
+ mEncoder = MediaCodec.createByCodecName(HeifEncoder.findHevcFallback());
+ caps = mEncoder.getCodecInfo()
+ .getCapabilitiesForType(MediaFormat.MIMETYPE_VIDEO_HEVC);
+ // Disable grid if the image is too small
+ useGrid &= (width > GRID_WIDTH || height > GRID_HEIGHT);
+ // Always enable grid if the size is too large for the HEVC encoder
+ useGrid |= !caps.getVideoCapabilities().isSizeSupported(width, height);
+ }
+ break;
+ case "AVIF":
+ mEncoder = MediaCodec.createByCodecName(AvifEncoder.findAv1Fallback());
+ caps = mEncoder.getCodecInfo()
+ .getCapabilitiesForType(MediaFormat.MIMETYPE_VIDEO_AV1);
+ // Disable grid if the image is too small
+ useGrid &= (width > GRID_WIDTH || height > GRID_HEIGHT);
+ // Always enable grid if the size is too large for the AV1 encoder
+ useGrid |= !caps.getVideoCapabilities().isSizeSupported(width, height);
+ break;
+ default:
+ Log.e(TAG, "Not supported mime type: " + MIME);
+ }
+
+ mInputMode = inputMode;
+ mUseBitDepth10 = useBitDepth10;
+ mCallback = cb;
+
+ Looper looper = (handler != null) ? handler.getLooper() : null;
+ if (looper == null) {
+ mHandlerThread = new HandlerThread("HeifEncoderThread",
+ Process.THREAD_PRIORITY_FOREGROUND);
+ mHandlerThread.start();
+ looper = mHandlerThread.getLooper();
+ } else {
+ mHandlerThread = null;
+ }
+ mHandler = new Handler(looper);
+ boolean useSurfaceInternally =
+ (inputMode == INPUT_MODE_SURFACE) || (inputMode == INPUT_MODE_BITMAP);
+ int colorFormat = useSurfaceInternally ? CodecCapabilities.COLOR_FormatSurface :
+ (useBitDepth10 ? CodecCapabilities.COLOR_FormatYUVP010 :
+ CodecCapabilities.COLOR_FormatYUV420Flexible);
+ mCopyTiles = (useGrid && !useHeicEncoder) || (inputMode == INPUT_MODE_BITMAP);
+
+ mWidth = width;
+ mHeight = height;
+ mUseGrid = useGrid;
+
+ int gridWidth, gridHeight, gridRows, gridCols;
+
+ if (useGrid) {
+ gridWidth = GRID_WIDTH;
+ gridHeight = GRID_HEIGHT;
+ gridRows = (height + GRID_HEIGHT - 1) / GRID_HEIGHT;
+ gridCols = (width + GRID_WIDTH - 1) / GRID_WIDTH;
+ } else {
+ gridWidth = mWidth;
+ gridHeight = mHeight;
+ gridRows = 1;
+ gridCols = 1;
+ }
+
+ MediaFormat codecFormat;
+ if (useHeicEncoder) {
+ codecFormat = MediaFormat.createVideoFormat(
+ MediaFormat.MIMETYPE_IMAGE_ANDROID_HEIC, mWidth, mHeight);
+ } else {
+ codecFormat = MediaFormat.createVideoFormat(
+ MediaFormat.MIMETYPE_VIDEO_HEVC, gridWidth, gridHeight);
+ }
+
+ if (useGrid) {
+ codecFormat.setInteger(MediaFormat.KEY_TILE_WIDTH, gridWidth);
+ codecFormat.setInteger(MediaFormat.KEY_TILE_HEIGHT, gridHeight);
+ codecFormat.setInteger(MediaFormat.KEY_GRID_COLUMNS, gridCols);
+ codecFormat.setInteger(MediaFormat.KEY_GRID_ROWS, gridRows);
+ }
+
+ if (useHeicEncoder) {
+ mGridWidth = width;
+ mGridHeight = height;
+ mGridRows = 1;
+ mGridCols = 1;
+ } else {
+ mGridWidth = gridWidth;
+ mGridHeight = gridHeight;
+ mGridRows = gridRows;
+ mGridCols = gridCols;
+ }
+ mNumTiles = mGridRows * mGridCols;
+
+ codecFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 0);
+ codecFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, colorFormat);
+ codecFormat.setInteger(MediaFormat.KEY_FRAME_RATE, mNumTiles);
+
+ // When we're doing tiles, set the operating rate higher as the size
+ // is small, otherwise set to the normal 30fps.
+ if (mNumTiles > 1) {
+ codecFormat.setInteger(MediaFormat.KEY_OPERATING_RATE, 120);
+ } else {
+ codecFormat.setInteger(MediaFormat.KEY_OPERATING_RATE, 30);
+ }
+
+ if (useSurfaceInternally && !mCopyTiles) {
+ // Use fixed PTS gap and disable backward frame drop
+ Log.d(TAG, "Setting fixed pts gap");
+ codecFormat.setLong(MediaFormat.KEY_MAX_PTS_GAP_TO_ENCODER, -1000000);
+ }
+
+ MediaCodecInfo.EncoderCapabilities encoderCaps = caps.getEncoderCapabilities();
+
+ if (encoderCaps.isBitrateModeSupported(
+ MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CQ)) {
+ Log.d(TAG, "Setting bitrate mode to constant quality");
+ Range<Integer> qualityRange = encoderCaps.getQualityRange();
+ Log.d(TAG, "Quality range: " + qualityRange);
+ codecFormat.setInteger(MediaFormat.KEY_BITRATE_MODE,
+ MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CQ);
+ codecFormat.setInteger(MediaFormat.KEY_QUALITY, (int) (qualityRange.getLower() +
+ (qualityRange.getUpper() - qualityRange.getLower()) * quality / 100.0));
+ } else {
+ if (encoderCaps.isBitrateModeSupported(
+ MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CBR)) {
+ Log.d(TAG, "Setting bitrate mode to constant bitrate");
+ codecFormat.setInteger(MediaFormat.KEY_BITRATE_MODE,
+ MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CBR);
+ } else { // assume VBR
+ Log.d(TAG, "Setting bitrate mode to variable bitrate");
+ codecFormat.setInteger(MediaFormat.KEY_BITRATE_MODE,
+ MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_VBR);
+ }
+ // Calculate the bitrate based on image dimension, max compression ratio and quality.
+ // Note that we set the frame rate to the number of tiles, so the bitrate would be the
+ // intended bits for one image.
+ int bitrate = caps.getVideoCapabilities().getBitrateRange().clamp(
+ (int) (width * height * 1.5 * 8 * MAX_COMPRESS_RATIO * quality / 100.0f));
+ codecFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitrate);
+ }
+
+ mCodecFormat = codecFormat;
+
+ mDstRect = new Rect(0, 0, mGridWidth, mGridHeight);
+ mSrcRect = new Rect();
+ }
+
+ /**
+ * Finish setting up the encoder.
+ * Call MediaCodec.configure() method so that mEncoder enters configured stage, then add input
+ * surface or add input buffers if needed.
+ *
+ * Note: this method must be called after the constructor.
+ */
+ protected void finishSettingUpEncoder(boolean useBitDepth10) {
+ boolean useSurfaceInternally =
+ (mInputMode == INPUT_MODE_SURFACE) || (mInputMode == INPUT_MODE_BITMAP);
+
+ mEncoder.configure(mCodecFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
+
+ if (useSurfaceInternally) {
+ mEncoderSurface = mEncoder.createInputSurface();
+
+ mEOSTracker = new SurfaceEOSTracker(mCopyTiles);
+
+ if (mCopyTiles) {
+ mEncoderEglSurface = new EglWindowSurface(mEncoderSurface, useBitDepth10);
+ mEncoderEglSurface.makeCurrent();
+
+ mRectBlt = new EglRectBlt(
+ new Texture2dProgram((mInputMode == INPUT_MODE_BITMAP)
+ ? Texture2dProgram.TEXTURE_2D
+ : Texture2dProgram.TEXTURE_EXT),
+ mWidth, mHeight);
+
+ mTextureId = mRectBlt.createTextureObject();
+
+ if (mInputMode == INPUT_MODE_SURFACE) {
+ // use single buffer mode to block on input
+ mInputTexture = new SurfaceTexture(mTextureId, true);
+ mInputTexture.setOnFrameAvailableListener(this);
+ mInputTexture.setDefaultBufferSize(mWidth, mHeight);
+ mInputSurface = new Surface(mInputTexture);
+ }
+
+ // make uncurrent since onFrameAvailable could be called on arbituray thread.
+ // making the context current on a different thread will cause error.
+ mEncoderEglSurface.makeUnCurrent();
+ } else {
+ mInputSurface = mEncoderSurface;
+ }
+ } else {
+ for (int i = 0; i < INPUT_BUFFER_POOL_SIZE; i++) {
+ int bufferSize = mUseBitDepth10 ? mWidth * mHeight * 3 : mWidth * mHeight * 3 / 2;
+ mEmptyBuffers.add(ByteBuffer.allocateDirect(bufferSize));
+ }
+ }
+ }
+
+ /**
+ * Copies from source frame to encoder inputs using GL. The source could be either
+ * client's input surface, or the input bitmap loaded to texture.
+ */
+ private void copyTilesGL() {
+ GLES20.glViewport(0, 0, mGridWidth, mGridHeight);
+
+ for (int row = 0; row < mGridRows; row++) {
+ for (int col = 0; col < mGridCols; col++) {
+ int left = col * mGridWidth;
+ int top = row * mGridHeight;
+ mSrcRect.set(left, top, left + mGridWidth, top + mGridHeight);
+ try {
+ mRectBlt.copyRect(mTextureId, Texture2dProgram.V_FLIP_MATRIX, mSrcRect);
+ } catch (RuntimeException e) {
+ // EGL copy could throw if the encoder input surface is no longer valid
+ // after encoder is released. This is not an error because we're already
+ // stopping (either after EOS is received or requested by client).
+ if (mStopping.get()) {
+ return;
+ }
+ throw e;
+ }
+ mEncoderEglSurface.setPresentationTime(
+ 1000 * computePresentationTime(mInputIndex++));
+ mEncoderEglSurface.swapBuffers();
+ }
+ }
+ }
+
+ @Override
+ public void onFrameAvailable(SurfaceTexture surfaceTexture) {
+ synchronized (this) {
+ if (mEncoderEglSurface == null) {
+ return;
+ }
+
+ mEncoderEglSurface.makeCurrent();
+
+ surfaceTexture.updateTexImage();
+ surfaceTexture.getTransformMatrix(mTmpMatrix);
+
+ long timestampNs = surfaceTexture.getTimestamp();
+
+ if (DEBUG) Log.d(TAG, "onFrameAvailable: timestampUs " + (timestampNs / 1000));
+
+ boolean takeFrame = mEOSTracker.updateLastInputAndEncoderTime(timestampNs,
+ computePresentationTime(mInputIndex + mNumTiles - 1));
+
+ if (takeFrame) {
+ copyTilesGL();
+ }
+
+ surfaceTexture.releaseTexImage();
+
+ // make uncurrent since the onFrameAvailable could be called on arbituray thread.
+ // making the context current on a different thread will cause error.
+ mEncoderEglSurface.makeUnCurrent();
+ }
+ }
+
+ /**
+ * Start the encoding process.
+ */
+ public void start() {
+ mEncoder.start();
+ }
+
+ /**
+ * Add one YUV buffer to be encoded. This might block if the encoder can't process the input
+ * buffers fast enough.
+ *
+ * After the call returns, the client can reuse the data array.
+ *
+ * @param format The YUV format as defined in {@link android.graphics.ImageFormat}, currently
+ * only support YUV_420_888.
+ *
+ * @param data byte array containing the YUV data. If the format has more than one planes,
+ * they must be concatenated.
+ */
+ public void addYuvBuffer(int format, @NonNull byte[] data) {
+ if (mInputMode != INPUT_MODE_BUFFER) {
+ throw new IllegalStateException(
+ "addYuvBuffer is only allowed in buffer input mode");
+ }
+ if ((mUseBitDepth10 && format != ImageFormat.YCBCR_P010)
+ || (!mUseBitDepth10 && format != ImageFormat.YUV_420_888)) {
+ throw new IllegalStateException("Wrong color format.");
+ }
+ if (data == null
+ || (mUseBitDepth10 && data.length != mWidth * mHeight * 3)
+ || (!mUseBitDepth10 && data.length != mWidth * mHeight * 3 / 2)) {
+ throw new IllegalArgumentException("invalid data");
+ }
+ addYuvBufferInternal(data);
+ }
+
+ /**
+ * Retrieves the input surface for encoding.
+ *
+ * Will only return valid value if configured to use surface input.
+ */
+ public @NonNull Surface getInputSurface() {
+ if (mInputMode != INPUT_MODE_SURFACE) {
+ throw new IllegalStateException(
+ "getInputSurface is only allowed in surface input mode");
+ }
+ return mInputSurface;
+ }
+
+ /**
+ * Sets the timestamp (in nano seconds) of the last input frame to encode. Frames with
+ * timestamps larger than the specified value will not be encoded. However, if a frame
+ * already started encoding when this is set, all tiles within that frame will be encoded.
+ *
+ * This method only applies when surface is used.
+ */
+ public void setEndOfInputStreamTimestamp(long timestampNs) {
+ if (mInputMode != INPUT_MODE_SURFACE) {
+ throw new IllegalStateException(
+ "setEndOfInputStreamTimestamp is only allowed in surface input mode");
+ }
+ if (mEOSTracker != null) {
+ mEOSTracker.updateInputEOSTime(timestampNs);
+ }
+ }
+
+ /**
+ * Adds one bitmap to be encoded.
+ */
+ public void addBitmap(@NonNull Bitmap bitmap) {
+ if (mInputMode != INPUT_MODE_BITMAP) {
+ throw new IllegalStateException("addBitmap is only allowed in bitmap input mode");
+ }
+
+ boolean takeFrame = mEOSTracker.updateLastInputAndEncoderTime(
+ computePresentationTime(mInputIndex) * 1000,
+ computePresentationTime(mInputIndex + mNumTiles - 1));
+
+ if (!takeFrame) return;
+
+ synchronized (this) {
+ if (mEncoderEglSurface == null) {
+ return;
+ }
+
+ mEncoderEglSurface.makeCurrent();
+
+ mRectBlt.loadTexture(mTextureId, bitmap);
+
+ copyTilesGL();
+
+ // make uncurrent since the onFrameAvailable could be called on arbituray thread.
+ // making the context current on a different thread will cause error.
+ mEncoderEglSurface.makeUnCurrent();
+ }
+ }
+
+ /**
+ * Sends input EOS to the encoder. Result will be notified asynchronously via
+ * {@link Callback#onComplete(EncoderBase)} if encoder reaches EOS without error, or
+ * {@link Callback#onError(EncoderBase, CodecException)} otherwise.
+ */
+ public void stopAsync() {
+ if (mInputMode == INPUT_MODE_BITMAP) {
+ // here we simply set the EOS timestamp to 0, so that the cut off will be the last
+ // bitmap ever added.
+ mEOSTracker.updateInputEOSTime(0);
+ } else if (mInputMode == INPUT_MODE_BUFFER) {
+ addYuvBufferInternal(null);
+ }
+ }
+
+ /**
+ * Generates the presentation time for input frame N, in microseconds.
+ * The timestamp advances 1 sec for every whole frame.
+ */
+ private long computePresentationTime(int frameIndex) {
+ return 132 + (long)frameIndex * 1000000 / mNumTiles;
+ }
+
+ /**
+ * Obtains one empty input buffer and copies the data into it. Before input
+ * EOS is sent, this would block until the data is copied. After input EOS
+ * is sent, this would return immediately.
+ */
+ private void addYuvBufferInternal(@Nullable byte[] data) {
+ ByteBuffer buffer = acquireEmptyBuffer();
+ if (buffer == null) {
+ return;
+ }
+ buffer.clear();
+ if (data != null) {
+ buffer.put(data);
+ }
+ buffer.flip();
+ synchronized (mFilledBuffers) {
+ mFilledBuffers.add(buffer);
+ }
+ mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ maybeCopyOneTileYUV();
+ }
+ });
+ }
+
+ /**
+ * Routine to copy one tile if we have both input and codec buffer available.
+ *
+ * Must be called on the handler looper that also handles the MediaCodec callback.
+ */
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ void maybeCopyOneTileYUV() {
+ ByteBuffer currentBuffer;
+ while ((currentBuffer = getCurrentBuffer()) != null && !mCodecInputBuffers.isEmpty()) {
+ int index = mCodecInputBuffers.remove(0);
+
+ // 0-length input means EOS.
+ boolean inputEOS = (mInputIndex % mNumTiles == 0) && (currentBuffer.remaining() == 0);
+
+ if (!inputEOS) {
+ Image image = mEncoder.getInputImage(index);
+ int left = mGridWidth * (mInputIndex % mGridCols);
+ int top = mGridHeight * (mInputIndex / mGridCols % mGridRows);
+ mSrcRect.set(left, top, left + mGridWidth, top + mGridHeight);
+ copyOneTileYUV(currentBuffer, image, mWidth, mHeight, mSrcRect, mDstRect,
+ mUseBitDepth10);
+ }
+
+ mEncoder.queueInputBuffer(index, 0,
+ inputEOS ? 0 : mEncoder.getInputBuffer(index).capacity(),
+ computePresentationTime(mInputIndex++),
+ inputEOS ? MediaCodec.BUFFER_FLAG_END_OF_STREAM : 0);
+
+ if (inputEOS || mInputIndex % mNumTiles == 0) {
+ returnEmptyBufferAndNotify(inputEOS);
+ }
+ }
+ }
+
+ /**
+ * Copies from a rect from src buffer to dst image.
+ * TOOD: This will be replaced by JNI.
+ */
+ private static void copyOneTileYUV(ByteBuffer srcBuffer, Image dstImage,
+ int srcWidth, int srcHeight, Rect srcRect, Rect dstRect, boolean useBitDepth10) {
+ if (srcRect.width() != dstRect.width() || srcRect.height() != dstRect.height()) {
+ throw new IllegalArgumentException("src and dst rect size are different!");
+ }
+ if (srcWidth % 2 != 0 || srcHeight % 2 != 0 ||
+ srcRect.left % 2 != 0 || srcRect.top % 2 != 0 ||
+ srcRect.right % 2 != 0 || srcRect.bottom % 2 != 0 ||
+ dstRect.left % 2 != 0 || dstRect.top % 2 != 0 ||
+ dstRect.right % 2 != 0 || dstRect.bottom % 2 != 0) {
+ throw new IllegalArgumentException("src or dst are not aligned!");
+ }
+
+ Image.Plane[] planes = dstImage.getPlanes();
+ if (useBitDepth10) {
+ for (int n = 0; n < planes.length; n++) {
+ ByteBuffer dstBuffer = planes[n].getBuffer();
+ int colStride = planes[n].getPixelStride();
+ int copyWidth = Math.min(srcRect.width(), srcWidth - srcRect.left);
+ int copyHeight = Math.min(srcRect.height(), srcHeight - srcRect.top);
+ int srcPlanePos = 0, div = 1;
+ if (n > 0) {
+ div = 2;
+ srcPlanePos = srcWidth * srcHeight;
+ }
+ for (int i = 0; i < copyHeight / div; i++) {
+ srcBuffer.position(srcPlanePos +
+ (i + srcRect.top / div) * srcWidth + srcRect.left / div);
+ dstBuffer.position((i + dstRect.top / div) * planes[n].getRowStride()
+ + dstRect.left * colStride / div);
+
+ for (int j = 0; j < copyWidth; j++) {
+ dstBuffer.put(srcBuffer.get());
+ if (colStride > 1 && j != copyWidth - 1) {
+ dstBuffer.position(dstBuffer.position() + colStride - 1);
+ }
+ }
+ }
+ }
+ } else {
+ for (int n = 0; n < planes.length; n++) {
+ ByteBuffer dstBuffer = planes[n].getBuffer();
+ int colStride = planes[n].getPixelStride();
+ int copyWidth = Math.min(srcRect.width(), srcWidth - srcRect.left);
+ int copyHeight = Math.min(srcRect.height(), srcHeight - srcRect.top);
+ int srcPlanePos = 0, div = 1;
+ if (n > 0) {
+ div = 2;
+ srcPlanePos = srcWidth * srcHeight * (n + 3) / 4;
+ }
+ for (int i = 0; i < copyHeight / div; i++) {
+ srcBuffer.position(srcPlanePos +
+ (i + srcRect.top / div) * srcWidth / div + srcRect.left / div);
+ dstBuffer.position((i + dstRect.top / div) * planes[n].getRowStride()
+ + dstRect.left * colStride / div);
+
+ for (int j = 0; j < copyWidth / div; j++) {
+ dstBuffer.put(srcBuffer.get());
+ if (colStride > 1 && j != copyWidth / div - 1) {
+ dstBuffer.position(dstBuffer.position() + colStride - 1);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private ByteBuffer acquireEmptyBuffer() {
+ synchronized (mEmptyBuffers) {
+ // wait for an empty input buffer first
+ while (!mInputEOS && mEmptyBuffers.isEmpty()) {
+ try {
+ mEmptyBuffers.wait();
+ } catch (InterruptedException e) {}
+ }
+
+ // if already EOS, return null to stop further encoding.
+ return mInputEOS ? null : mEmptyBuffers.remove(0);
+ }
+ }
+
+ /**
+ * Routine to get the current input buffer to copy from.
+ * Only called on callback handler thread.
+ */
+ private ByteBuffer getCurrentBuffer() {
+ if (!mInputEOS && mCurrentBuffer == null) {
+ synchronized (mFilledBuffers) {
+ mCurrentBuffer = mFilledBuffers.isEmpty() ?
+ null : mFilledBuffers.remove(0);
+ }
+ }
+ return mInputEOS ? null : mCurrentBuffer;
+ }
+
+ /**
+ * Routine to put the consumed input buffer back into the empty buffer pool.
+ * Only called on callback handler thread.
+ */
+ private void returnEmptyBufferAndNotify(boolean inputEOS) {
+ synchronized (mEmptyBuffers) {
+ mInputEOS |= inputEOS;
+ mEmptyBuffers.add(mCurrentBuffer);
+ mEmptyBuffers.notifyAll();
+ }
+ mCurrentBuffer = null;
+ }
+
+ /**
+ * Routine to release all resources. Must be run on the same looper that
+ * handles the MediaCodec callbacks.
+ */
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ void stopInternal() {
+ if (DEBUG) Log.d(TAG, "stopInternal");
+
+ // set stopping, so that the tile copy would bail out
+ // if it hits failure after this point.
+ mStopping.set(true);
+
+ // after start, mEncoder is only accessed on handler, so no need to sync.
+ try {
+ if (mEncoder != null) {
+ mEncoder.stop();
+ mEncoder.release();
+ }
+ } catch (Exception e) {
+ } finally {
+ mEncoder = null;
+ }
+
+ // unblock the addBuffer() if we're tearing down before EOS is sent.
+ synchronized (mEmptyBuffers) {
+ mInputEOS = true;
+ mEmptyBuffers.notifyAll();
+ }
+
+ // Clean up surface and Egl related refs. This lock must come after encoder
+ // release. When we're closing, we insert stopInternal() at the front of queue
+ // so that the shutdown can be processed promptly, this means there might be
+ // some output available requests queued after this. As the tile copies trying
+ // to finish the current frame, there is a chance is might get stuck because
+ // those outputs were not returned. Shutting down the encoder will make break
+ // the tile copier out of that.
+ synchronized(this) {
+ try {
+ if (mRectBlt != null) {
+ mRectBlt.release(false);
+ }
+ } catch (Exception e) {
+ } finally {
+ mRectBlt = null;
+ }
+
+ try {
+ if (mEncoderEglSurface != null) {
+ // Note that this frees mEncoderSurface too. If mEncoderEglSurface is not
+ // there, client is responsible to release the input surface it got from us,
+ // we don't release mEncoderSurface here.
+ mEncoderEglSurface.release();
+ }
+ } catch (Exception e) {
+ } finally {
+ mEncoderEglSurface = null;
+ }
+
+ try {
+ if (mInputTexture != null) {
+ mInputTexture.release();
+ }
+ } catch (Exception e) {
+ } finally {
+ mInputTexture = null;
+ }
+ }
+ }
+
+ /**
+ * This class handles EOS for surface or bitmap inputs.
+ *
+ * When encoding from surface or bitmap, we can't call
+ * {@link MediaCodec#signalEndOfInputStream()} immediately after input is drawn, since this
+ * could drop all pending frames in the buffer queue. When there are tiles, this could leave
+ * us a partially encoded image.
+ *
+ * So here we track the EOS status by timestamps, and only signal EOS to the encoder
+ * when we collected all images we need.
+ *
+ * Since this is updated from multiple threads ({@link #setEndOfInputStreamTimestamp(long)},
+ * {@link EncoderCallback#onOutputBufferAvailable(MediaCodec, int, BufferInfo)},
+ * {@link #addBitmap(Bitmap)} and {@link #onFrameAvailable(SurfaceTexture)}), it must be fully
+ * synchronized.
+ *
+ * Note that when buffer input is used, the EOS flag is set in
+ * {@link EncoderCallback#onInputBufferAvailable(MediaCodec, int)} and this class is not used.
+ */
+ private class SurfaceEOSTracker {
+ private static final boolean DEBUG_EOS = false;
+
+ final boolean mCopyTiles;
+ long mInputEOSTimeNs = -1;
+ long mLastInputTimeNs = -1;
+ long mEncoderEOSTimeUs = -1;
+ long mLastEncoderTimeUs = -1;
+ long mLastOutputTimeUs = -1;
+ boolean mSignaled;
+
+ SurfaceEOSTracker(boolean copyTiles) {
+ mCopyTiles = copyTiles;
+ }
+
+ synchronized void updateInputEOSTime(long timestampNs) {
+ if (DEBUG_EOS) Log.d(TAG, "updateInputEOSTime: " + timestampNs);
+
+ if (mCopyTiles) {
+ if (mInputEOSTimeNs < 0) {
+ mInputEOSTimeNs = timestampNs;
+ }
+ } else {
+ if (mEncoderEOSTimeUs < 0) {
+ mEncoderEOSTimeUs = timestampNs / 1000;
+ }
+ }
+ updateEOSLocked();
+ }
+
+ synchronized boolean updateLastInputAndEncoderTime(long inputTimeNs, long encoderTimeUs) {
+ if (DEBUG_EOS) Log.d(TAG,
+ "updateLastInputAndEncoderTime: " + inputTimeNs + ", " + encoderTimeUs);
+
+ boolean shouldTakeFrame = mInputEOSTimeNs < 0 || inputTimeNs <= mInputEOSTimeNs;
+ if (shouldTakeFrame) {
+ mLastEncoderTimeUs = encoderTimeUs;
+ }
+ mLastInputTimeNs = inputTimeNs;
+ updateEOSLocked();
+ return shouldTakeFrame;
+ }
+
+ synchronized void updateLastOutputTime(long outputTimeUs) {
+ if (DEBUG_EOS) Log.d(TAG, "updateLastOutputTime: " + outputTimeUs);
+
+ mLastOutputTimeUs = outputTimeUs;
+ updateEOSLocked();
+ }
+
+ private void updateEOSLocked() {
+ if (mSignaled) {
+ return;
+ }
+ if (mEncoderEOSTimeUs < 0) {
+ if (mInputEOSTimeNs >= 0 && mLastInputTimeNs >= mInputEOSTimeNs) {
+ if (mLastEncoderTimeUs < 0) {
+ doSignalEOSLocked();
+ return;
+ }
+ // mEncoderEOSTimeUs tracks the timestamp of the last output buffer we
+ // will wait for. When that buffer arrives, encoder will be signalled EOS.
+ mEncoderEOSTimeUs = mLastEncoderTimeUs;
+ if (DEBUG_EOS) Log.d(TAG,
+ "updateEOSLocked: mEncoderEOSTimeUs " + mEncoderEOSTimeUs);
+ }
+ }
+ if (mEncoderEOSTimeUs >= 0 && mEncoderEOSTimeUs <= mLastOutputTimeUs) {
+ doSignalEOSLocked();
+ }
+ }
+
+ private void doSignalEOSLocked() {
+ if (DEBUG_EOS) Log.d(TAG, "doSignalEOSLocked");
+
+ mHandler.post(new Runnable() {
+ @Override public void run() {
+ if (mEncoder != null) {
+ mEncoder.signalEndOfInputStream();
+ }
+ }
+ });
+
+ mSignaled = true;
+ }
+ }
+
+
+ /**
+ * MediaCodec callback for HEVC/AV1 encoding.
+ */
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ abstract class EncoderCallback extends MediaCodec.Callback {
+ private boolean mOutputEOS;
+
+ @Override
+ public void onInputBufferAvailable(MediaCodec codec, int index) {
+ if (codec != mEncoder || mInputEOS) return;
+
+ if (DEBUG) Log.d(TAG, "onInputBufferAvailable: " + index);
+ mCodecInputBuffers.add(index);
+ maybeCopyOneTileYUV();
+ }
+
+ @Override
+ public void onOutputBufferAvailable(MediaCodec codec, int index, BufferInfo info) {
+ if (codec != mEncoder || mOutputEOS) return;
+
+ if (DEBUG) {
+ Log.d(TAG, "onOutputBufferAvailable: " + index
+ + ", time " + info.presentationTimeUs
+ + ", size " + info.size
+ + ", flags " + info.flags);
+ }
+
+ if ((info.size > 0) && ((info.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) == 0)) {
+ ByteBuffer outputBuffer = codec.getOutputBuffer(index);
+
+ // reset position as addBuffer() modifies it
+ outputBuffer.position(info.offset);
+ outputBuffer.limit(info.offset + info.size);
+
+ if (mEOSTracker != null) {
+ mEOSTracker.updateLastOutputTime(info.presentationTimeUs);
+ }
+
+ mCallback.onDrainOutputBuffer(EncoderBase.this, outputBuffer);
+ }
+
+ mOutputEOS |= ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0);
+
+ codec.releaseOutputBuffer(index, false);
+
+ if (mOutputEOS) {
+ stopAndNotify(null);
+ }
+ }
+
+ @Override
+ public void onError(MediaCodec codec, CodecException e) {
+ if (codec != mEncoder) return;
+
+ Log.e(TAG, "onError: " + e);
+ stopAndNotify(e);
+ }
+
+ private void stopAndNotify(@Nullable CodecException e) {
+ stopInternal();
+ if (e == null) {
+ mCallback.onComplete(EncoderBase.this);
+ } else {
+ mCallback.onError(EncoderBase.this, e);
+ }
+ }
+ }
+
+ @Override
+ public void close() {
+ // unblock the addBuffer() if we're tearing down before EOS is sent.
+ synchronized (mEmptyBuffers) {
+ mInputEOS = true;
+ mEmptyBuffers.notifyAll();
+ }
+
+ mHandler.postAtFrontOfQueue(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ stopInternal();
+ } catch (Exception e) {
+ // We don't want to crash when closing.
+ }
+ }
+ });
+ }
+}
\ No newline at end of file
diff --git a/heifwriter/heifwriter/src/main/java/androidx/heifwriter/HeifEncoder.java b/heifwriter/heifwriter/src/main/java/androidx/heifwriter/HeifEncoder.java
index 5e08a73..6ab3111 100644
--- a/heifwriter/heifwriter/src/main/java/androidx/heifwriter/HeifEncoder.java
+++ b/heifwriter/heifwriter/src/main/java/androidx/heifwriter/HeifEncoder.java
@@ -16,36 +16,20 @@
package androidx.heifwriter;
-import android.graphics.Bitmap;
-import android.graphics.Rect;
-import android.graphics.SurfaceTexture;
-import android.media.Image;
import android.media.MediaCodec;
-import android.media.MediaCodec.BufferInfo;
-import android.media.MediaCodec.CodecException;
import android.media.MediaCodecInfo;
import android.media.MediaCodecInfo.CodecCapabilities;
import android.media.MediaCodecList;
import android.media.MediaFormat;
-import android.opengl.GLES20;
import android.os.Handler;
import android.os.HandlerThread;
-import android.os.Looper;
-import android.os.Process;
import android.util.Log;
import android.util.Range;
-import android.view.Surface;
-import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.io.IOException;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.concurrent.atomic.AtomicBoolean;
/**
* This class encodes images into HEIF-compatible samples using HEVC encoder.
@@ -64,115 +48,16 @@
*
* @hide
*/
-public final class HeifEncoder implements AutoCloseable,
- SurfaceTexture.OnFrameAvailableListener {
+public final class HeifEncoder extends EncoderBase {
private static final String TAG = "HeifEncoder";
private static final boolean DEBUG = false;
- private static final int GRID_WIDTH = 512;
- private static final int GRID_HEIGHT = 512;
- private static final double MAX_COMPRESS_RATIO = 0.25f;
- private static final int INPUT_BUFFER_POOL_SIZE = 2;
+ protected static final int GRID_WIDTH = 512;
+ protected static final int GRID_HEIGHT = 512;
+ protected static final double MAX_COMPRESS_RATIO = 0.25f;
private static final MediaCodecList sMCL =
- new MediaCodecList(MediaCodecList.REGULAR_CODECS);
-
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- MediaCodec mEncoder;
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- final Callback mCallback;
- private final HandlerThread mHandlerThread;
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- final Handler mHandler;
- private final @InputMode int mInputMode;
-
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- final int mWidth;
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- final int mHeight;
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- final int mGridWidth;
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- final int mGridHeight;
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- final int mGridRows;
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- final int mGridCols;
- private final int mNumTiles;
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- final boolean mUseGrid;
-
- private int mInputIndex;
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- boolean mInputEOS;
- private final Rect mSrcRect;
- private final Rect mDstRect;
- private ByteBuffer mCurrentBuffer;
- private final ArrayList<ByteBuffer> mEmptyBuffers = new ArrayList<>();
- private final ArrayList<ByteBuffer> mFilledBuffers = new ArrayList<>();
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- final ArrayList<Integer> mCodecInputBuffers = new ArrayList<>();
-
- // Helper for tracking EOS when surface is used
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- SurfaceEOSTracker mEOSTracker;
-
- // Below variables are to handle GL copy from client's surface
- // to encoder surface when tiles are used.
- private SurfaceTexture mInputTexture;
- private Surface mInputSurface;
- private Surface mEncoderSurface;
- private EglWindowSurface mEncoderEglSurface;
- private EglRectBlt mRectBlt;
- private int mTextureId;
- private final float[] mTmpMatrix = new float[16];
- private final AtomicBoolean mStopping = new AtomicBoolean(false);
-
- public static final int INPUT_MODE_BUFFER = HeifWriter.INPUT_MODE_BUFFER;
- public static final int INPUT_MODE_SURFACE = HeifWriter.INPUT_MODE_SURFACE;
- public static final int INPUT_MODE_BITMAP = HeifWriter.INPUT_MODE_BITMAP;
- @IntDef({
- INPUT_MODE_BUFFER,
- INPUT_MODE_SURFACE,
- INPUT_MODE_BITMAP,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface InputMode {}
-
- public static abstract class Callback {
- /**
- * Called when the output format has changed.
- *
- * @param encoder The HeifEncoder object.
- * @param format The new output format.
- */
- public abstract void onOutputFormatChanged(
- @NonNull HeifEncoder encoder, @NonNull MediaFormat format);
-
- /**
- * Called when an output buffer becomes available.
- *
- * @param encoder The HeifEncoder object.
- * @param byteBuffer the available output buffer.
- */
- public abstract void onDrainOutputBuffer(
- @NonNull HeifEncoder encoder, @NonNull ByteBuffer byteBuffer);
-
- /**
- * Called when encoding reached the end of stream without error.
- *
- * @param encoder The HeifEncoder object.
- */
- public abstract void onComplete(@NonNull HeifEncoder encoder);
-
- /**
- * Called when encoding hits an error.
- *
- * @param encoder The HeifEncoder object.
- * @param e The exception that the codec reported.
- */
- public abstract void onError(@NonNull HeifEncoder encoder, @NonNull CodecException e);
- }
+ new MediaCodecList(MediaCodecList.REGULAR_CODECS);
/**
* Configure the heif encoding session. Should only be called once.
@@ -189,198 +74,15 @@
* @param cb The callback to receive various messages from the heif encoder.
*/
public HeifEncoder(int width, int height, boolean useGrid,
- int quality, @InputMode int inputMode,
- @Nullable Handler handler, @NonNull Callback cb) throws IOException {
- if (DEBUG) Log.d(TAG, "width: " + width + ", height: " + height +
- ", useGrid: " + useGrid + ", quality: " + quality + ", inputMode: " + inputMode);
-
- if (width < 0 || height < 0 || quality < 0 || quality > 100) {
- throw new IllegalArgumentException("invalid encoder inputs");
- }
-
- // Disable grid if the image is too small
- useGrid &= (width > GRID_WIDTH || height > GRID_HEIGHT);
-
- boolean useHeicEncoder = false;
- MediaCodecInfo.CodecCapabilities caps = null;
- try {
- mEncoder = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_IMAGE_ANDROID_HEIC);
- caps = mEncoder.getCodecInfo().getCapabilitiesForType(
- MediaFormat.MIMETYPE_IMAGE_ANDROID_HEIC);
- // If the HEIC encoder can't support the size, fall back to HEVC encoder.
- if (!caps.getVideoCapabilities().isSizeSupported(width, height)) {
- mEncoder.release();
- mEncoder = null;
- throw new Exception();
- }
- useHeicEncoder = true;
- } catch (Exception e) {
- mEncoder = MediaCodec.createByCodecName(findHevcFallback());
- caps = mEncoder.getCodecInfo().getCapabilitiesForType(MediaFormat.MIMETYPE_VIDEO_HEVC);
- // Always enable grid if the size is too large for the HEVC encoder
- useGrid |= !caps.getVideoCapabilities().isSizeSupported(width, height);
- }
-
- mInputMode = inputMode;
-
- mCallback = cb;
-
- Looper looper = (handler != null) ? handler.getLooper() : null;
- if (looper == null) {
- mHandlerThread = new HandlerThread("HeifEncoderThread",
- Process.THREAD_PRIORITY_FOREGROUND);
- mHandlerThread.start();
- looper = mHandlerThread.getLooper();
- } else {
- mHandlerThread = null;
- }
- mHandler = new Handler(looper);
- boolean useSurfaceInternally =
- (inputMode == INPUT_MODE_SURFACE) || (inputMode == INPUT_MODE_BITMAP);
- int colorFormat = useSurfaceInternally ? CodecCapabilities.COLOR_FormatSurface :
- CodecCapabilities.COLOR_FormatYUV420Flexible;
- boolean copyTiles = (useGrid && !useHeicEncoder) || (inputMode == INPUT_MODE_BITMAP);
-
- mWidth = width;
- mHeight = height;
- mUseGrid = useGrid;
-
- int gridWidth, gridHeight, gridRows, gridCols;
-
- if (useGrid) {
- gridWidth = GRID_WIDTH;
- gridHeight = GRID_HEIGHT;
- gridRows = (height + GRID_HEIGHT - 1) / GRID_HEIGHT;
- gridCols = (width + GRID_WIDTH - 1) / GRID_WIDTH;
- } else {
- gridWidth = mWidth;
- gridHeight = mHeight;
- gridRows = 1;
- gridCols = 1;
- }
-
- MediaFormat codecFormat;
- if (useHeicEncoder) {
- codecFormat = MediaFormat.createVideoFormat(
- MediaFormat.MIMETYPE_IMAGE_ANDROID_HEIC, mWidth, mHeight);
- } else {
- codecFormat = MediaFormat.createVideoFormat(
- MediaFormat.MIMETYPE_VIDEO_HEVC, gridWidth, gridHeight);
- }
-
- if (useGrid) {
- codecFormat.setInteger(MediaFormat.KEY_TILE_WIDTH, gridWidth);
- codecFormat.setInteger(MediaFormat.KEY_TILE_HEIGHT, gridHeight);
- codecFormat.setInteger(MediaFormat.KEY_GRID_COLUMNS, gridCols);
- codecFormat.setInteger(MediaFormat.KEY_GRID_ROWS, gridRows);
- }
-
- if (useHeicEncoder) {
- mGridWidth = width;
- mGridHeight = height;
- mGridRows = 1;
- mGridCols = 1;
- } else {
- mGridWidth = gridWidth;
- mGridHeight = gridHeight;
- mGridRows = gridRows;
- mGridCols = gridCols;
- }
- mNumTiles = mGridRows * mGridCols;
-
- codecFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 0);
- codecFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, colorFormat);
- codecFormat.setInteger(MediaFormat.KEY_FRAME_RATE, mNumTiles);
-
- // When we're doing tiles, set the operating rate higher as the size
- // is small, otherwise set to the normal 30fps.
- if (mNumTiles > 1) {
- codecFormat.setInteger(MediaFormat.KEY_OPERATING_RATE, 120);
- } else {
- codecFormat.setInteger(MediaFormat.KEY_OPERATING_RATE, 30);
- }
-
- if (useSurfaceInternally && !copyTiles) {
- // Use fixed PTS gap and disable backward frame drop
- Log.d(TAG, "Setting fixed pts gap");
- codecFormat.setLong(MediaFormat.KEY_MAX_PTS_GAP_TO_ENCODER, -1000000);
- }
-
- MediaCodecInfo.EncoderCapabilities encoderCaps = caps.getEncoderCapabilities();
-
- if (encoderCaps.isBitrateModeSupported(
- MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CQ)) {
- Log.d(TAG, "Setting bitrate mode to constant quality");
- Range<Integer> qualityRange = encoderCaps.getQualityRange();
- Log.d(TAG, "Quality range: " + qualityRange);
- codecFormat.setInteger(MediaFormat.KEY_BITRATE_MODE,
- MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CQ);
- codecFormat.setInteger(MediaFormat.KEY_QUALITY, (int) (qualityRange.getLower() +
- (qualityRange.getUpper() - qualityRange.getLower()) * quality / 100.0));
- } else {
- if (encoderCaps.isBitrateModeSupported(
- MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CBR)) {
- Log.d(TAG, "Setting bitrate mode to constant bitrate");
- codecFormat.setInteger(MediaFormat.KEY_BITRATE_MODE,
- MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CBR);
- } else { // assume VBR
- Log.d(TAG, "Setting bitrate mode to variable bitrate");
- codecFormat.setInteger(MediaFormat.KEY_BITRATE_MODE,
- MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_VBR);
- }
- // Calculate the bitrate based on image dimension, max compression ratio and quality.
- // Note that we set the frame rate to the number of tiles, so the bitrate would be the
- // intended bits for one image.
- int bitrate = caps.getVideoCapabilities().getBitrateRange().clamp(
- (int) (width * height * 1.5 * 8 * MAX_COMPRESS_RATIO * quality / 100.0f));
- codecFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitrate);
- }
-
- mEncoder.setCallback(new EncoderCallback(), mHandler);
- mEncoder.configure(codecFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
-
- if (useSurfaceInternally) {
- mEncoderSurface = mEncoder.createInputSurface();
-
- mEOSTracker = new SurfaceEOSTracker(copyTiles);
-
- if (copyTiles) {
- mEncoderEglSurface = new EglWindowSurface(mEncoderSurface);
- mEncoderEglSurface.makeCurrent();
-
- mRectBlt = new EglRectBlt(
- new Texture2dProgram((inputMode == INPUT_MODE_BITMAP)
- ? Texture2dProgram.TEXTURE_2D
- : Texture2dProgram.TEXTURE_EXT),
- mWidth, mHeight);
-
- mTextureId = mRectBlt.createTextureObject();
-
- if (inputMode == INPUT_MODE_SURFACE) {
- // use single buffer mode to block on input
- mInputTexture = new SurfaceTexture(mTextureId, true);
- mInputTexture.setOnFrameAvailableListener(this);
- mInputTexture.setDefaultBufferSize(mWidth, mHeight);
- mInputSurface = new Surface(mInputTexture);
- }
-
- // make uncurrent since onFrameAvailable could be called on arbituray thread.
- // making the context current on a different thread will cause error.
- mEncoderEglSurface.makeUnCurrent();
- } else {
- mInputSurface = mEncoderSurface;
- }
- } else {
- for (int i = 0; i < INPUT_BUFFER_POOL_SIZE; i++) {
- mEmptyBuffers.add(ByteBuffer.allocateDirect(mWidth * mHeight * 3 / 2));
- }
- }
-
- mDstRect = new Rect(0, 0, mGridWidth, mGridHeight);
- mSrcRect = new Rect();
+ int quality, @InputMode int inputMode,
+ @Nullable Handler handler, @NonNull Callback cb) throws IOException {
+ super("HEIC", width, height, useGrid, quality, inputMode, handler, cb,
+ /* useBitDepth10 */ false);
+ mEncoder.setCallback(new HevcEncoderCallback(), mHandler);
+ finishSettingUpEncoder(/* useBitDepth10 */ false);
}
- private String findHevcFallback() {
+ protected static String findHevcFallback() {
String hevc = null; // first HEVC encoder
for (MediaCodecInfo info : sMCL.getCodecInfos()) {
if (!info.isEncoder()) {
@@ -396,7 +98,7 @@
continue;
}
if (caps.getEncoderCapabilities().isBitrateModeSupported(
- MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CQ)) {
+ MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CQ)) {
// Encoder that supports CQ mode is preferred over others,
// return the first encoder that supports CQ mode.
// (No need to check if it's hw based, it's already listed in
@@ -410,508 +112,12 @@
// If no encoders support CQ, return the first HEVC encoder.
return hevc;
}
- /**
- * Copies from source frame to encoder inputs using GL. The source could be either
- * client's input surface, or the input bitmap loaded to texture.
- */
- private void copyTilesGL() {
- GLES20.glViewport(0, 0, mGridWidth, mGridHeight);
-
- for (int row = 0; row < mGridRows; row++) {
- for (int col = 0; col < mGridCols; col++) {
- int left = col * mGridWidth;
- int top = row * mGridHeight;
- mSrcRect.set(left, top, left + mGridWidth, top + mGridHeight);
- try {
- mRectBlt.copyRect(mTextureId, Texture2dProgram.V_FLIP_MATRIX, mSrcRect);
- } catch (RuntimeException e) {
- // EGL copy could throw if the encoder input surface is no longer valid
- // after encoder is released. This is not an error because we're already
- // stopping (either after EOS is received or requested by client).
- if (mStopping.get()) {
- return;
- }
- throw e;
- }
- mEncoderEglSurface.setPresentationTime(
- 1000 * computePresentationTime(mInputIndex++));
- mEncoderEglSurface.swapBuffers();
- }
- }
- }
-
- @Override
- public void onFrameAvailable(SurfaceTexture surfaceTexture) {
- synchronized (this) {
- if (mEncoderEglSurface == null) {
- return;
- }
-
- mEncoderEglSurface.makeCurrent();
-
- surfaceTexture.updateTexImage();
- surfaceTexture.getTransformMatrix(mTmpMatrix);
-
- long timestampNs = surfaceTexture.getTimestamp();
-
- if (DEBUG) Log.d(TAG, "onFrameAvailable: timestampUs " + (timestampNs / 1000));
-
- boolean takeFrame = mEOSTracker.updateLastInputAndEncoderTime(timestampNs,
- computePresentationTime(mInputIndex + mNumTiles - 1));
-
- if (takeFrame) {
- copyTilesGL();
- }
-
- surfaceTexture.releaseTexImage();
-
- // make uncurrent since the onFrameAvailable could be called on arbituray thread.
- // making the context current on a different thread will cause error.
- mEncoderEglSurface.makeUnCurrent();
- }
- }
-
- /**
- * Start the encoding process.
- */
- public void start() {
- mEncoder.start();
- }
-
- /**
- * Add one YUV buffer to be encoded. This might block if the encoder can't process the input
- * buffers fast enough.
- *
- * After the call returns, the client can reuse the data array.
- *
- * @param format The YUV format as defined in {@link android.graphics.ImageFormat}, currently
- * only support YUV_420_888.
- *
- * @param data byte array containing the YUV data. If the format has more than one planes,
- * they must be concatenated.
- */
- public void addYuvBuffer(int format, @NonNull byte[] data) {
- if (mInputMode != INPUT_MODE_BUFFER) {
- throw new IllegalStateException(
- "addYuvBuffer is only allowed in buffer input mode");
- }
- if (data == null || data.length != mWidth * mHeight * 3 / 2) {
- throw new IllegalArgumentException("invalid data");
- }
- addYuvBufferInternal(data);
- }
-
- /**
- * Retrieves the input surface for encoding.
- *
- * Will only return valid value if configured to use surface input.
- */
- public @NonNull Surface getInputSurface() {
- if (mInputMode != INPUT_MODE_SURFACE) {
- throw new IllegalStateException(
- "getInputSurface is only allowed in surface input mode");
- }
- return mInputSurface;
- }
-
- /**
- * Sets the timestamp (in nano seconds) of the last input frame to encode. Frames with
- * timestamps larger than the specified value will not be encoded. However, if a frame
- * already started encoding when this is set, all tiles within that frame will be encoded.
- *
- * This method only applies when surface is used.
- */
- public void setEndOfInputStreamTimestamp(long timestampNs) {
- if (mInputMode != INPUT_MODE_SURFACE) {
- throw new IllegalStateException(
- "setEndOfInputStreamTimestamp is only allowed in surface input mode");
- }
- if (mEOSTracker != null) {
- mEOSTracker.updateInputEOSTime(timestampNs);
- }
- }
-
- /**
- * Adds one bitmap to be encoded.
- */
- public void addBitmap(@NonNull Bitmap bitmap) {
- if (mInputMode != INPUT_MODE_BITMAP) {
- throw new IllegalStateException("addBitmap is only allowed in bitmap input mode");
- }
-
- boolean takeFrame = mEOSTracker.updateLastInputAndEncoderTime(
- computePresentationTime(mInputIndex) * 1000,
- computePresentationTime(mInputIndex + mNumTiles - 1));
-
- if (!takeFrame) return;
-
- synchronized (this) {
- if (mEncoderEglSurface == null) {
- return;
- }
-
- mEncoderEglSurface.makeCurrent();
-
- mRectBlt.loadTexture(mTextureId, bitmap);
-
- copyTilesGL();
-
- // make uncurrent since the onFrameAvailable could be called on arbituray thread.
- // making the context current on a different thread will cause error.
- mEncoderEglSurface.makeUnCurrent();
- }
- }
-
- /**
- * Sends input EOS to the encoder. Result will be notified asynchronously via
- * {@link Callback#onComplete(HeifEncoder)} if encoder reaches EOS without error, or
- * {@link Callback#onError(HeifEncoder, CodecException)} otherwise.
- */
- public void stopAsync() {
- if (mInputMode == INPUT_MODE_BITMAP) {
- // here we simply set the EOS timestamp to 0, so that the cut off will be the last
- // bitmap ever added.
- mEOSTracker.updateInputEOSTime(0);
- } else if (mInputMode == INPUT_MODE_BUFFER) {
- addYuvBufferInternal(null);
- }
- }
-
- /**
- * Generates the presentation time for input frame N, in microseconds.
- * The timestamp advances 1 sec for every whole frame.
- */
- private long computePresentationTime(int frameIndex) {
- return 132 + (long)frameIndex * 1000000 / mNumTiles;
- }
-
- /**
- * Obtains one empty input buffer and copies the data into it. Before input
- * EOS is sent, this would block until the data is copied. After input EOS
- * is sent, this would return immediately.
- */
- private void addYuvBufferInternal(@Nullable byte[] data) {
- ByteBuffer buffer = acquireEmptyBuffer();
- if (buffer == null) {
- return;
- }
- buffer.clear();
- if (data != null) {
- buffer.put(data);
- }
- buffer.flip();
- synchronized (mFilledBuffers) {
- mFilledBuffers.add(buffer);
- }
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- maybeCopyOneTileYUV();
- }
- });
- }
-
- /**
- * Routine to copy one tile if we have both input and codec buffer available.
- *
- * Must be called on the handler looper that also handles the MediaCodec callback.
- */
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- void maybeCopyOneTileYUV() {
- ByteBuffer currentBuffer;
- while ((currentBuffer = getCurrentBuffer()) != null && !mCodecInputBuffers.isEmpty()) {
- int index = mCodecInputBuffers.remove(0);
-
- // 0-length input means EOS.
- boolean inputEOS = (mInputIndex % mNumTiles == 0) && (currentBuffer.remaining() == 0);
-
- if (!inputEOS) {
- Image image = mEncoder.getInputImage(index);
- int left = mGridWidth * (mInputIndex % mGridCols);
- int top = mGridHeight * (mInputIndex / mGridCols % mGridRows);
- mSrcRect.set(left, top, left + mGridWidth, top + mGridHeight);
- copyOneTileYUV(currentBuffer, image, mWidth, mHeight, mSrcRect, mDstRect);
- }
-
- mEncoder.queueInputBuffer(index, 0,
- inputEOS ? 0 : mEncoder.getInputBuffer(index).capacity(),
- computePresentationTime(mInputIndex++),
- inputEOS ? MediaCodec.BUFFER_FLAG_END_OF_STREAM : 0);
-
- if (inputEOS || mInputIndex % mNumTiles == 0) {
- returnEmptyBufferAndNotify(inputEOS);
- }
- }
- }
-
- /**
- * Copies from a rect from src buffer to dst image.
- * TOOD: This will be replaced by JNI.
- */
- private static void copyOneTileYUV(
- ByteBuffer srcBuffer, Image dstImage,
- int srcWidth, int srcHeight,
- Rect srcRect, Rect dstRect) {
- if (srcRect.width() != dstRect.width() || srcRect.height() != dstRect.height()) {
- throw new IllegalArgumentException("src and dst rect size are different!");
- }
- if (srcWidth % 2 != 0 || srcHeight % 2 != 0 ||
- srcRect.left % 2 != 0 || srcRect.top % 2 != 0 ||
- srcRect.right % 2 != 0 || srcRect.bottom % 2 != 0 ||
- dstRect.left % 2 != 0 || dstRect.top % 2 != 0 ||
- dstRect.right % 2 != 0 || dstRect.bottom % 2 != 0) {
- throw new IllegalArgumentException("src or dst are not aligned!");
- }
-
- Image.Plane[] planes = dstImage.getPlanes();
- for (int n = 0; n < planes.length; n++) {
- ByteBuffer dstBuffer = planes[n].getBuffer();
- int colStride = planes[n].getPixelStride();
- int copyWidth = Math.min(srcRect.width(), srcWidth - srcRect.left);
- int copyHeight = Math.min(srcRect.height(), srcHeight - srcRect.top);
- int srcPlanePos = 0, div = 1;
- if (n > 0) {
- div = 2;
- srcPlanePos = srcWidth * srcHeight * (n + 3) / 4;
- }
- for (int i = 0; i < copyHeight / div; i++) {
- srcBuffer.position(srcPlanePos +
- (i + srcRect.top / div) * srcWidth / div + srcRect.left / div);
- dstBuffer.position((i + dstRect.top / div) * planes[n].getRowStride()
- + dstRect.left * colStride / div);
-
- for (int j = 0; j < copyWidth / div; j++) {
- dstBuffer.put(srcBuffer.get());
- if (colStride > 1 && j != copyWidth / div - 1) {
- dstBuffer.position(dstBuffer.position() + colStride - 1);
- }
- }
- }
- }
- }
-
- private ByteBuffer acquireEmptyBuffer() {
- synchronized (mEmptyBuffers) {
- // wait for an empty input buffer first
- while (!mInputEOS && mEmptyBuffers.isEmpty()) {
- try {
- mEmptyBuffers.wait();
- } catch (InterruptedException e) {}
- }
-
- // if already EOS, return null to stop further encoding.
- return mInputEOS ? null : mEmptyBuffers.remove(0);
- }
- }
-
- /**
- * Routine to get the current input buffer to copy from.
- * Only called on callback handler thread.
- */
- private ByteBuffer getCurrentBuffer() {
- if (!mInputEOS && mCurrentBuffer == null) {
- synchronized (mFilledBuffers) {
- mCurrentBuffer = mFilledBuffers.isEmpty() ?
- null : mFilledBuffers.remove(0);
- }
- }
- return mInputEOS ? null : mCurrentBuffer;
- }
-
- /**
- * Routine to put the consumed input buffer back into the empty buffer pool.
- * Only called on callback handler thread.
- */
- private void returnEmptyBufferAndNotify(boolean inputEOS) {
- synchronized (mEmptyBuffers) {
- mInputEOS |= inputEOS;
- mEmptyBuffers.add(mCurrentBuffer);
- mEmptyBuffers.notifyAll();
- }
- mCurrentBuffer = null;
- }
-
- /**
- * Routine to release all resources. Must be run on the same looper that
- * handles the MediaCodec callbacks.
- */
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- void stopInternal() {
- if (DEBUG) Log.d(TAG, "stopInternal");
-
- // set stopping, so that the tile copy would bail out
- // if it hits failure after this point.
- mStopping.set(true);
-
- // after start, mEncoder is only accessed on handler, so no need to sync.
- try {
- if (mEncoder != null) {
- mEncoder.stop();
- mEncoder.release();
- }
- } catch (Exception e) {
- } finally {
- mEncoder = null;
- }
-
- // unblock the addBuffer() if we're tearing down before EOS is sent.
- synchronized (mEmptyBuffers) {
- mInputEOS = true;
- mEmptyBuffers.notifyAll();
- }
-
- // Clean up surface and Egl related refs. This lock must come after encoder
- // release. When we're closing, we insert stopInternal() at the front of queue
- // so that the shutdown can be processed promptly, this means there might be
- // some output available requests queued after this. As the tile copies trying
- // to finish the current frame, there is a chance is might get stuck because
- // those outputs were not returned. Shutting down the encoder will make break
- // the tile copier out of that.
- synchronized(this) {
- try {
- if (mRectBlt != null) {
- mRectBlt.release(false);
- }
- } catch (Exception e) {
- } finally {
- mRectBlt = null;
- }
-
- try {
- if (mEncoderEglSurface != null) {
- // Note that this frees mEncoderSurface too. If mEncoderEglSurface is not
- // there, client is responsible to release the input surface it got from us,
- // we don't release mEncoderSurface here.
- mEncoderEglSurface.release();
- }
- } catch (Exception e) {
- } finally {
- mEncoderEglSurface = null;
- }
-
- try {
- if (mInputTexture != null) {
- mInputTexture.release();
- }
- } catch (Exception e) {
- } finally {
- mInputTexture = null;
- }
- }
- }
-
- /**
- * This class handles EOS for surface or bitmap inputs.
- *
- * When encoding from surface or bitmap, we can't call {@link MediaCodec#signalEndOfInputStream()}
- * immediately after input is drawn, since this could drop all pending frames in the
- * buffer queue. When there are tiles, this could leave us a partially encoded image.
- *
- * So here we track the EOS status by timestamps, and only signal EOS to the encoder
- * when we collected all images we need.
- *
- * Since this is updated from multiple threads ({@link #setEndOfInputStreamTimestamp(long)},
- * {@link EncoderCallback#onOutputBufferAvailable(MediaCodec, int, BufferInfo)},
- * {@link #addBitmap(Bitmap)} and {@link #onFrameAvailable(SurfaceTexture)}), it must be fully
- * synchronized.
- *
- * Note that when buffer input is used, the EOS flag is set in
- * {@link EncoderCallback#onInputBufferAvailable(MediaCodec, int)} and this class is not used.
- */
- private class SurfaceEOSTracker {
- private static final boolean DEBUG_EOS = false;
-
- final boolean mCopyTiles;
- long mInputEOSTimeNs = -1;
- long mLastInputTimeNs = -1;
- long mEncoderEOSTimeUs = -1;
- long mLastEncoderTimeUs = -1;
- long mLastOutputTimeUs = -1;
- boolean mSignaled;
-
- SurfaceEOSTracker(boolean copyTiles) {
- mCopyTiles = copyTiles;
- }
-
- synchronized void updateInputEOSTime(long timestampNs) {
- if (DEBUG_EOS) Log.d(TAG, "updateInputEOSTime: " + timestampNs);
-
- if (mCopyTiles) {
- if (mInputEOSTimeNs < 0) {
- mInputEOSTimeNs = timestampNs;
- }
- } else {
- if (mEncoderEOSTimeUs < 0) {
- mEncoderEOSTimeUs = timestampNs / 1000;
- }
- }
- updateEOSLocked();
- }
-
- synchronized boolean updateLastInputAndEncoderTime(long inputTimeNs, long encoderTimeUs) {
- if (DEBUG_EOS) Log.d(TAG,
- "updateLastInputAndEncoderTime: " + inputTimeNs + ", " + encoderTimeUs);
-
- boolean shouldTakeFrame = mInputEOSTimeNs < 0 || inputTimeNs <= mInputEOSTimeNs;
- if (shouldTakeFrame) {
- mLastEncoderTimeUs = encoderTimeUs;
- }
- mLastInputTimeNs = inputTimeNs;
- updateEOSLocked();
- return shouldTakeFrame;
- }
-
- synchronized void updateLastOutputTime(long outputTimeUs) {
- if (DEBUG_EOS) Log.d(TAG, "updateLastOutputTime: " + outputTimeUs);
-
- mLastOutputTimeUs = outputTimeUs;
- updateEOSLocked();
- }
-
- private void updateEOSLocked() {
- if (mSignaled) {
- return;
- }
- if (mEncoderEOSTimeUs < 0) {
- if (mInputEOSTimeNs >= 0 && mLastInputTimeNs >= mInputEOSTimeNs) {
- if (mLastEncoderTimeUs < 0) {
- doSignalEOSLocked();
- return;
- }
- // mEncoderEOSTimeUs tracks the timestamp of the last output buffer we
- // will wait for. When that buffer arrives, encoder will be signalled EOS.
- mEncoderEOSTimeUs = mLastEncoderTimeUs;
- if (DEBUG_EOS) Log.d(TAG,
- "updateEOSLocked: mEncoderEOSTimeUs " + mEncoderEOSTimeUs);
- }
- }
- if (mEncoderEOSTimeUs >= 0 && mEncoderEOSTimeUs <= mLastOutputTimeUs) {
- doSignalEOSLocked();
- }
- }
-
- private void doSignalEOSLocked() {
- if (DEBUG_EOS) Log.d(TAG, "doSignalEOSLocked");
-
- mHandler.post(new Runnable() {
- @Override public void run() {
- if (mEncoder != null) {
- mEncoder.signalEndOfInputStream();
- }
- }
- });
-
- mSignaled = true;
- }
- }
/**
* MediaCodec callback for HEVC encoding.
*/
@SuppressWarnings("WeakerAccess") /* synthetic access */
- class EncoderCallback extends MediaCodec.Callback {
- private boolean mOutputEOS;
-
+ protected class HevcEncoderCallback extends EncoderCallback {
@Override
public void onOutputFormatChanged(MediaCodec codec, MediaFormat format) {
if (codec != mEncoder) return;
@@ -919,7 +125,7 @@
if (DEBUG) Log.d(TAG, "onOutputFormatChanged: " + format);
if (!MediaFormat.MIMETYPE_IMAGE_ANDROID_HEIC.equals(
- format.getString(MediaFormat.KEY_MIME))) {
+ format.getString(MediaFormat.KEY_MIME))) {
format.setString(MediaFormat.KEY_MIME, MediaFormat.MIMETYPE_IMAGE_ANDROID_HEIC);
format.setInteger(MediaFormat.KEY_WIDTH, mWidth);
format.setInteger(MediaFormat.KEY_HEIGHT, mHeight);
@@ -934,85 +140,5 @@
mCallback.onOutputFormatChanged(HeifEncoder.this, format);
}
-
- @Override
- public void onInputBufferAvailable(MediaCodec codec, int index) {
- if (codec != mEncoder || mInputEOS) return;
-
- if (DEBUG) Log.d(TAG, "onInputBufferAvailable: " + index);
- mCodecInputBuffers.add(index);
- maybeCopyOneTileYUV();
- }
-
- @Override
- public void onOutputBufferAvailable(MediaCodec codec, int index, BufferInfo info) {
- if (codec != mEncoder || mOutputEOS) return;
-
- if (DEBUG) {
- Log.d(TAG, "onOutputBufferAvailable: " + index
- + ", time " + info.presentationTimeUs
- + ", size " + info.size
- + ", flags " + info.flags);
- }
-
- if ((info.size > 0) && ((info.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) == 0)) {
- ByteBuffer outputBuffer = codec.getOutputBuffer(index);
-
- // reset position as addBuffer() modifies it
- outputBuffer.position(info.offset);
- outputBuffer.limit(info.offset + info.size);
-
- if (mEOSTracker != null) {
- mEOSTracker.updateLastOutputTime(info.presentationTimeUs);
- }
-
- mCallback.onDrainOutputBuffer(HeifEncoder.this, outputBuffer);
- }
-
- mOutputEOS |= ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0);
-
- codec.releaseOutputBuffer(index, false);
-
- if (mOutputEOS) {
- stopAndNotify(null);
- }
- }
-
- @Override
- public void onError(MediaCodec codec, CodecException e) {
- if (codec != mEncoder) return;
-
- Log.e(TAG, "onError: " + e);
- stopAndNotify(e);
- }
-
- private void stopAndNotify(@Nullable CodecException e) {
- stopInternal();
- if (e == null) {
- mCallback.onComplete(HeifEncoder.this);
- } else {
- mCallback.onError(HeifEncoder.this, e);
- }
- }
}
-
- @Override
- public void close() {
- // unblock the addBuffer() if we're tearing down before EOS is sent.
- synchronized (mEmptyBuffers) {
- mInputEOS = true;
- mEmptyBuffers.notifyAll();
- }
-
- mHandler.postAtFrontOfQueue(new Runnable() {
- @Override
- public void run() {
- try {
- stopInternal();
- } catch (Exception e) {
- // We don't want to crash when closing.
- }
- }
- });
- }
-}
+}
\ No newline at end of file
diff --git a/heifwriter/heifwriter/src/main/java/androidx/heifwriter/HeifWriter.java b/heifwriter/heifwriter/src/main/java/androidx/heifwriter/HeifWriter.java
index 978654a..878b1ac 100644
--- a/heifwriter/heifwriter/src/main/java/androidx/heifwriter/HeifWriter.java
+++ b/heifwriter/heifwriter/src/main/java/androidx/heifwriter/HeifWriter.java
@@ -32,6 +32,7 @@
import android.view.Surface;
import androidx.annotation.IntDef;
+import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
@@ -77,42 +78,17 @@
*
* <p>Please refer to the documentations on individual methods for the exact usage.
*/
-public final class HeifWriter implements AutoCloseable {
+@SuppressWarnings("HiddenSuperclass")
+public final class HeifWriter extends WriterBase {
private static final String TAG = "HeifWriter";
private static final boolean DEBUG = false;
- private static final int MUXER_DATA_FLAG = 16;
-
- private final @InputMode int mInputMode;
- private final HandlerThread mHandlerThread;
- private final Handler mHandler;
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- int mNumTiles;
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- final int mRotation;
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- final int mMaxImages;
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- final int mPrimaryIndex;
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- final ResultWaiter mResultWaiter = new ResultWaiter();
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- MediaMuxer mMuxer;
- private HeifEncoder mHeifEncoder;
- final AtomicBoolean mMuxerStarted = new AtomicBoolean(false);
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- int[] mTrackIndexArray;
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- int mOutputIndex;
- private boolean mStarted;
-
- private final List<Pair<Integer, ByteBuffer>> mExifList = new ArrayList<>();
/**
* The input mode where the client adds input buffers with YUV data.
*
* @see #addYuvBuffer(int, byte[])
*/
- public static final int INPUT_MODE_BUFFER = 0;
+ public static final int INPUT_MODE_BUFFER = WriterBase.INPUT_MODE_BUFFER;
/**
* The input mode where the client renders the images to an input Surface
@@ -125,18 +101,18 @@
*
* @see #getInputSurface()
*/
- public static final int INPUT_MODE_SURFACE = 1;
+ public static final int INPUT_MODE_SURFACE = WriterBase.INPUT_MODE_SURFACE;
/**
* The input mode where the client adds bitmaps.
*
* @see #addBitmap(Bitmap)
*/
- public static final int INPUT_MODE_BITMAP = 2;
+ public static final int INPUT_MODE_BITMAP = WriterBase.INPUT_MODE_BITMAP;
/** @hide */
@IntDef({
- INPUT_MODE_BUFFER, INPUT_MODE_SURFACE, INPUT_MODE_BITMAP,
+ INPUT_MODE_BUFFER, INPUT_MODE_SURFACE, INPUT_MODE_BITMAP,
})
@Retention(RetentionPolicy.SOURCE)
public @interface InputMode {}
@@ -161,13 +137,15 @@
* Construct a Builder with output specified by its path.
*
* @param path Path of the file to be written.
- * @param width Width of the image.
- * @param height Height of the image.
+ * @param width Width of the image in number of pixels.
+ * @param height Height of the image in number of pixels.
* @param inputMode Input mode for this writer, must be one of {@link #INPUT_MODE_BUFFER},
* {@link #INPUT_MODE_SURFACE}, or {@link #INPUT_MODE_BITMAP}.
*/
public Builder(@NonNull String path,
- int width, int height, @InputMode int inputMode) {
+ @IntRange(from = 1) int width,
+ @IntRange(from = 1) int height,
+ @InputMode int inputMode) {
this(path, null, width, height, inputMode);
}
@@ -175,21 +153,22 @@
* Construct a Builder with output specified by its file descriptor.
*
* @param fd File descriptor of the file to be written.
- * @param width Width of the image.
- * @param height Height of the image.
+ * @param width Width of the image in number of pixels.
+ * @param height Height of the image in number of pixels.
* @param inputMode Input mode for this writer, must be one of {@link #INPUT_MODE_BUFFER},
* {@link #INPUT_MODE_SURFACE}, or {@link #INPUT_MODE_BITMAP}.
*/
public Builder(@NonNull FileDescriptor fd,
- int width, int height, @InputMode int inputMode) {
+ @IntRange(from = 1) int width,
+ @IntRange(from = 1) int height,
+ @InputMode int inputMode) {
this(null, fd, width, height, inputMode);
}
private Builder(String path, FileDescriptor fd,
- int width, int height, @InputMode int inputMode) {
- if (width <= 0 || height <= 0) {
- throw new IllegalArgumentException("Invalid image size: " + width + "x" + height);
- }
+ @IntRange(from = 1) int width,
+ @IntRange(from = 1) int height,
+ @InputMode int inputMode) {
mPath = path;
mFd = fd;
mWidth = width;
@@ -200,11 +179,11 @@
/**
* Set the image rotation in degrees.
*
- * @param rotation Rotation angle (clockwise) of the image, must be 0, 90, 180 or 270.
- * Default is 0.
+ * @param rotation Rotation angle in degrees (clockwise) of the image, must be 0, 90,
+ * 180 or 270. Default is 0.
* @return this Builder object.
*/
- public Builder setRotation(int rotation) {
+ public @NonNull Builder setRotation(@IntRange(from = 0) int rotation) {
if (rotation != 0 && rotation != 90 && rotation != 180 && rotation != 270) {
throw new IllegalArgumentException("Invalid rotation angle: " + rotation);
}
@@ -219,7 +198,7 @@
* automatically chosen. Default is to enable.
* @return this Builder object.
*/
- public Builder setGridEnabled(boolean gridEnabled) {
+ public @NonNull Builder setGridEnabled(boolean gridEnabled) {
mGridEnabled = gridEnabled;
return this;
}
@@ -231,7 +210,7 @@
* quality supported by this implementation. Default is 100.
* @return this Builder object.
*/
- public Builder setQuality(int quality) {
+ public @NonNull Builder setQuality(@IntRange(from = 0, to = 100) int quality) {
if (quality < 0 || quality > 100) {
throw new IllegalArgumentException("Invalid quality: " + quality);
}
@@ -250,7 +229,7 @@
* Default is 1.
* @return this Builder object.
*/
- public Builder setMaxImages(int maxImages) {
+ public @NonNull Builder setMaxImages(@IntRange(from = 1) int maxImages) {
if (maxImages <= 0) {
throw new IllegalArgumentException("Invalid maxImage: " + maxImages);
}
@@ -265,10 +244,7 @@
* range [0, maxImages - 1] inclusive. Default is 0.
* @return this Builder object.
*/
- public Builder setPrimaryIndex(int primaryIndex) {
- if (primaryIndex < 0) {
- throw new IllegalArgumentException("Invalid primaryIndex: " + primaryIndex);
- }
+ public @NonNull Builder setPrimaryIndex(@IntRange(from = 0) int primaryIndex) {
mPrimaryIndex = primaryIndex;
return this;
}
@@ -281,7 +257,7 @@
* writer. Default is null.
* @return this Builder object.
*/
- public Builder setHandler(@Nullable Handler handler) {
+ public @NonNull Builder setHandler(@Nullable Handler handler) {
mHandler = handler;
return this;
}
@@ -293,428 +269,46 @@
* @throws IOException if failed to create the writer, possibly due to failure to create
* {@link android.media.MediaMuxer} or {@link android.media.MediaCodec}.
*/
- public HeifWriter build() throws IOException {
+ public @NonNull HeifWriter build() throws IOException {
return new HeifWriter(mPath, mFd, mWidth, mHeight, mRotation, mGridEnabled, mQuality,
- mMaxImages, mPrimaryIndex, mInputMode, mHandler);
+ mMaxImages, mPrimaryIndex, mInputMode, mHandler);
}
}
@SuppressLint("WrongConstant")
@SuppressWarnings("WeakerAccess") /* synthetic access */
HeifWriter(@NonNull String path,
- @NonNull FileDescriptor fd,
- int width,
- int height,
- int rotation,
- boolean gridEnabled,
- int quality,
- int maxImages,
- int primaryIndex,
- @InputMode int inputMode,
- @Nullable Handler handler) throws IOException {
- if (primaryIndex >= maxImages) {
- throw new IllegalArgumentException(
- "Invalid maxImages (" + maxImages + ") or primaryIndex (" + primaryIndex + ")");
- }
+ @NonNull FileDescriptor fd,
+ int width,
+ int height,
+ int rotation,
+ boolean gridEnabled,
+ int quality,
+ int maxImages,
+ int primaryIndex,
+ @InputMode int inputMode,
+ @Nullable Handler handler) throws IOException {
+ super(rotation, inputMode, maxImages, primaryIndex, gridEnabled, quality,
+ handler, /* highBitDepthEnabled */ false);
if (DEBUG) {
Log.d(TAG, "width: " + width
- + ", height: " + height
- + ", rotation: " + rotation
- + ", gridEnabled: " + gridEnabled
- + ", quality: " + quality
- + ", maxImages: " + maxImages
- + ", primaryIndex: " + primaryIndex
- + ", inputMode: " + inputMode);
+ + ", height: " + height
+ + ", rotation: " + rotation
+ + ", gridEnabled: " + gridEnabled
+ + ", quality: " + quality
+ + ", maxImages: " + maxImages
+ + ", primaryIndex: " + primaryIndex
+ + ", inputMode: " + inputMode);
}
// set to 1 initially, and wait for output format to know for sure
mNumTiles = 1;
- mRotation = rotation;
- mInputMode = inputMode;
- mMaxImages = maxImages;
- mPrimaryIndex = primaryIndex;
-
- Looper looper = (handler != null) ? handler.getLooper() : null;
- if (looper == null) {
- mHandlerThread = new HandlerThread("HeifEncoderThread",
- Process.THREAD_PRIORITY_FOREGROUND);
- mHandlerThread.start();
- looper = mHandlerThread.getLooper();
- } else {
- mHandlerThread = null;
- }
- mHandler = new Handler(looper);
-
mMuxer = (path != null) ? new MediaMuxer(path, MUXER_OUTPUT_HEIF)
- : new MediaMuxer(fd, MUXER_OUTPUT_HEIF);
+ : new MediaMuxer(fd, MUXER_OUTPUT_HEIF);
- mHeifEncoder = new HeifEncoder(width, height, gridEnabled, quality,
- mInputMode, mHandler, new HeifCallback());
+ mEncoder = new HeifEncoder(width, height, gridEnabled, quality,
+ mInputMode, mHandler, new WriterCallback());
}
-
- /**
- * Start the heif writer. Can only be called once.
- *
- * @throws IllegalStateException if called more than once.
- */
- public void start() {
- checkStarted(false);
- mStarted = true;
- mHeifEncoder.start();
- }
-
- /**
- * Add one YUV buffer to the heif file.
- *
- * @param format The YUV format as defined in {@link android.graphics.ImageFormat}, currently
- * only support YUV_420_888.
- *
- * @param data byte array containing the YUV data. If the format has more than one planes,
- * they must be concatenated.
- *
- * @throws IllegalStateException if not started or not configured to use buffer input.
- */
- public void addYuvBuffer(int format, @NonNull byte[] data) {
- checkStartedAndMode(INPUT_MODE_BUFFER);
- synchronized (this) {
- if (mHeifEncoder != null) {
- mHeifEncoder.addYuvBuffer(format, data);
- }
- }
- }
-
- /**
- * Retrieves the input surface for encoding.
- *
- * @return the input surface if configured to use surface input.
- *
- * @throws IllegalStateException if called after start or not configured to use surface input.
- */
- public @NonNull Surface getInputSurface() {
- checkStarted(false);
- checkMode(INPUT_MODE_SURFACE);
- return mHeifEncoder.getInputSurface();
- }
-
- /**
- * Set the timestamp (in nano seconds) of the last input frame to encode.
- *
- * This call is only valid for surface input. Client can use this to stop the heif writer
- * earlier before the maximum number of images are written. If not called, the writer will
- * only stop when the maximum number of images are written.
- *
- * @param timestampNs timestamp (in nano seconds) of the last frame that will be written to the
- * heif file. Frames with timestamps larger than the specified value will not
- * be written. However, if a frame already started encoding when this is set,
- * all tiles within that frame will be encoded.
- *
- * @throws IllegalStateException if not started or not configured to use surface input.
- */
- public void setInputEndOfStreamTimestamp(long timestampNs) {
- checkStartedAndMode(INPUT_MODE_SURFACE);
- synchronized (this) {
- if (mHeifEncoder != null) {
- mHeifEncoder.setEndOfInputStreamTimestamp(timestampNs);
- }
- }
- }
-
- /**
- * Add one bitmap to the heif file.
- *
- * @param bitmap the bitmap to be added to the file.
- * @throws IllegalStateException if not started or not configured to use bitmap input.
- */
- public void addBitmap(@NonNull Bitmap bitmap) {
- checkStartedAndMode(INPUT_MODE_BITMAP);
- synchronized (this) {
- if (mHeifEncoder != null) {
- mHeifEncoder.addBitmap(bitmap);
- }
- }
- }
-
- /**
- * Add Exif data for the specified image. The data must be a valid Exif data block,
- * starting with "Exif\0\0" followed by the TIFF header (See JEITA CP-3451C Section 4.5.2.)
- *
- * @param imageIndex index of the image, must be a valid index for the max number of image
- * specified by {@link Builder#setMaxImages(int)}.
- * @param exifData byte buffer containing a Exif data block.
- * @param offset offset of the Exif data block within exifData.
- * @param length length of the Exif data block.
- */
- public void addExifData(int imageIndex, @NonNull byte[] exifData, int offset, int length) {
- checkStarted(true);
-
- ByteBuffer buffer = ByteBuffer.allocateDirect(length);
- buffer.put(exifData, offset, length);
- buffer.flip();
- // Put it in a queue, as we might not be able to process it at this time.
- synchronized (mExifList) {
- mExifList.add(new Pair<Integer, ByteBuffer>(imageIndex, buffer));
- }
- processExifData();
- }
-
- @SuppressLint("WrongConstant")
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- void processExifData() {
- if (!mMuxerStarted.get()) {
- return;
- }
-
- while (true) {
- Pair<Integer, ByteBuffer> entry;
- synchronized (mExifList) {
- if (mExifList.isEmpty()) {
- return;
- }
- entry = mExifList.remove(0);
- }
- MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
- info.set(entry.second.position(), entry.second.remaining(), 0, MUXER_DATA_FLAG);
- mMuxer.writeSampleData(mTrackIndexArray[entry.first], entry.second, info);
- }
- }
-
- /**
- * Stop the heif writer synchronously. Throws exception if the writer didn't finish writing
- * successfully. Upon a success return:
- *
- * - For buffer and bitmap inputs, all images sent before stop will be written.
- *
- * - For surface input, images with timestamp on or before that specified in
- * {@link #setInputEndOfStreamTimestamp(long)} will be written. In case where
- * {@link #setInputEndOfStreamTimestamp(long)} was never called, stop will block
- * until maximum number of images are received.
- *
- * @param timeoutMs Maximum time (in microsec) to wait for the writer to complete, with zero
- * indicating waiting indefinitely.
- * @see #setInputEndOfStreamTimestamp(long)
- * @throws Exception if encountered error, in which case the output file may not be valid. In
- * particular, {@link TimeoutException} is thrown when timed out, and {@link
- * MediaCodec.CodecException} is thrown when encountered codec error.
- */
- public void stop(long timeoutMs) throws Exception {
- checkStarted(true);
- synchronized (this) {
- if (mHeifEncoder != null) {
- mHeifEncoder.stopAsync();
- }
- }
- mResultWaiter.waitForResult(timeoutMs);
- processExifData();
- closeInternal();
- }
-
- private void checkStarted(boolean requiredStarted) {
- if (mStarted != requiredStarted) {
- throw new IllegalStateException("Already started");
- }
- }
-
- private void checkMode(@InputMode int requiredMode) {
- if (mInputMode != requiredMode) {
- throw new IllegalStateException("Not valid in input mode " + mInputMode);
- }
- }
-
- private void checkStartedAndMode(@InputMode int requiredMode) {
- checkStarted(true);
- checkMode(requiredMode);
- }
-
- /**
- * Routine to stop and release writer, must be called on the same looper
- * that receives heif encoder callbacks.
- */
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- void closeInternal() {
- if (DEBUG) Log.d(TAG, "closeInternal");
- // We don't want to crash when closing, catch all exceptions.
- try {
- // Muxer could throw exceptions if stop is called without samples.
- // Don't crash in that case.
- if (mMuxer != null) {
- mMuxer.stop();
- mMuxer.release();
- }
- } catch (Exception e) {
- } finally {
- mMuxer = null;
- }
- try {
- if (mHeifEncoder != null) {
- mHeifEncoder.close();
- }
- } catch (Exception e) {
- } finally {
- synchronized (this) {
- mHeifEncoder = null;
- }
- }
- }
-
- /**
- * Callback from the heif encoder.
- */
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- class HeifCallback extends HeifEncoder.Callback {
- private boolean mEncoderStopped;
- /**
- * Upon receiving output format from the encoder, add the requested number of
- * image tracks to the muxer and start the muxer.
- */
- @Override
- public void onOutputFormatChanged(
- @NonNull HeifEncoder encoder, @NonNull MediaFormat format) {
- if (mEncoderStopped) return;
-
- if (DEBUG) {
- Log.d(TAG, "onOutputFormatChanged: " + format);
- }
- if (mTrackIndexArray != null) {
- stopAndNotify(new IllegalStateException(
- "Output format changed after muxer started"));
- return;
- }
-
- try {
- int gridRows = format.getInteger(MediaFormat.KEY_GRID_ROWS);
- int gridCols = format.getInteger(MediaFormat.KEY_GRID_COLUMNS);
- mNumTiles = gridRows * gridCols;
- } catch (NullPointerException | ClassCastException e) {
- mNumTiles = 1;
- }
-
- // add mMaxImages image tracks of the same format
- mTrackIndexArray = new int[mMaxImages];
-
- // set rotation angle
- if (mRotation > 0) {
- Log.d(TAG, "setting rotation: " + mRotation);
- mMuxer.setOrientationHint(mRotation);
- }
- for (int i = 0; i < mTrackIndexArray.length; i++) {
- // mark primary
- format.setInteger(MediaFormat.KEY_IS_DEFAULT, (i == mPrimaryIndex) ? 1 : 0);
- mTrackIndexArray[i] = mMuxer.addTrack(format);
- }
- mMuxer.start();
- mMuxerStarted.set(true);
- processExifData();
- }
-
- /**
- * Upon receiving an output buffer from the encoder (which is one image when
- * grid is not used, or one tile if grid is used), add that sample to the muxer.
- */
- @Override
- public void onDrainOutputBuffer(
- @NonNull HeifEncoder encoder, @NonNull ByteBuffer byteBuffer) {
- if (mEncoderStopped) return;
-
- if (DEBUG) {
- Log.d(TAG, "onDrainOutputBuffer: " + mOutputIndex);
- }
- if (mTrackIndexArray == null) {
- stopAndNotify(new IllegalStateException(
- "Output buffer received before format info"));
- return;
- }
-
- if (mOutputIndex < mMaxImages * mNumTiles) {
- MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
- info.set(byteBuffer.position(), byteBuffer.remaining(), 0, 0);
- mMuxer.writeSampleData(
- mTrackIndexArray[mOutputIndex / mNumTiles], byteBuffer, info);
- }
-
- mOutputIndex++;
-
- // post EOS if reached max number of images allowed.
- if (mOutputIndex == mMaxImages * mNumTiles) {
- stopAndNotify(null);
- }
- }
-
- @Override
- public void onComplete(@NonNull HeifEncoder encoder) {
- stopAndNotify(null);
- }
-
- @Override
- public void onError(@NonNull HeifEncoder encoder, @NonNull MediaCodec.CodecException e) {
- stopAndNotify(e);
- }
-
- private void stopAndNotify(@Nullable Exception error) {
- if (mEncoderStopped) return;
-
- mEncoderStopped = true;
- mResultWaiter.signalResult(error);
- }
- }
-
- @SuppressWarnings("WeakerAccess") /* synthetic access */
- static class ResultWaiter {
- private boolean mDone;
- private Exception mException;
-
- synchronized void waitForResult(long timeoutMs) throws Exception {
- if (timeoutMs < 0) {
- throw new IllegalArgumentException("timeoutMs is negative");
- }
- if (timeoutMs == 0) {
- while (!mDone) {
- try {
- wait();
- } catch (InterruptedException ex) {}
- }
- } else {
- final long startTimeMs = System.currentTimeMillis();
- long remainingWaitTimeMs = timeoutMs;
- // avoid early termination by "spurious" wakeup.
- while (!mDone && remainingWaitTimeMs > 0) {
- try {
- wait(remainingWaitTimeMs);
- } catch (InterruptedException ex) {}
- remainingWaitTimeMs -= (System.currentTimeMillis() - startTimeMs);
- }
- }
- if (!mDone) {
- mDone = true;
- mException = new TimeoutException("timed out waiting for result");
- }
- if (mException != null) {
- throw mException;
- }
- }
-
- synchronized void signalResult(@Nullable Exception e) {
- if (!mDone) {
- mDone = true;
- mException = e;
- notifyAll();
- }
- }
- }
-
- @Override
- public void close() {
- mHandler.postAtFrontOfQueue(new Runnable() {
- @Override
- public void run() {
- try {
- closeInternal();
- } catch (Exception e) {
- // If the client called stop() properly, any errors would have been
- // reported there. We don't want to crash when closing.
- }
- }
- });
- }
-}
+}
\ No newline at end of file
diff --git a/heifwriter/heifwriter/src/main/java/androidx/heifwriter/WriterBase.java b/heifwriter/heifwriter/src/main/java/androidx/heifwriter/WriterBase.java
new file mode 100644
index 0000000..7f283edf
--- /dev/null
+++ b/heifwriter/heifwriter/src/main/java/androidx/heifwriter/WriterBase.java
@@ -0,0 +1,572 @@
+/*
+ * Copyright 2022 Google Inc. All rights reserved.
+ *
+ * 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 androidx.heifwriter;
+
+import static android.media.MediaMuxer.OutputFormat.MUXER_OUTPUT_HEIF;
+
+import android.annotation.SuppressLint;
+import android.graphics.Bitmap;
+import android.media.MediaCodec;
+import android.media.MediaFormat;
+import android.media.MediaMuxer;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.Looper;
+import android.os.Process;
+import android.util.Log;
+import android.util.Pair;
+import android.view.Surface;
+
+import androidx.annotation.IntDef;
+import androidx.annotation.IntRange;
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+
+import java.io.FileDescriptor;
+import java.io.IOException;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * This class holds common utliities for {@link HeifWriter} and {@link AvifWriter}.
+ *
+ * @hide
+ */
+public class WriterBase implements AutoCloseable {
+ private static final String TAG = "WriterBase";
+ private static final boolean DEBUG = false;
+ private static final int MUXER_DATA_FLAG = 16;
+
+ /**
+ * The input mode where the client adds input buffers with YUV data.
+ *
+ * @see #addYuvBuffer(int, byte[])
+ */
+ protected static final int INPUT_MODE_BUFFER = 0;
+
+ /**
+ * The input mode where the client renders the images to an input Surface
+ * created by the writer.
+ *
+ * The input surface operates in single buffer mode. As a result, for use case
+ * where camera directly outputs to the input surface, this mode will not work
+ * because camera framework requires multiple buffers to operate in a pipeline
+ * fashion.
+ *
+ * @see #getInputSurface()
+ */
+ protected static final int INPUT_MODE_SURFACE = 1;
+
+ /**
+ * The input mode where the client adds bitmaps.
+ *
+ * @see #addBitmap(Bitmap)
+ */
+ protected static final int INPUT_MODE_BITMAP = 2;
+
+ /** @hide */
+ @IntDef({
+ INPUT_MODE_BUFFER, INPUT_MODE_SURFACE, INPUT_MODE_BITMAP,
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface InputMode {}
+
+ protected final @InputMode int mInputMode;
+ protected final boolean mHighBitDepthEnabled;
+ protected final HandlerThread mHandlerThread;
+ protected final Handler mHandler;
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ protected int mNumTiles;
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ protected final int mRotation;
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ protected final int mMaxImages;
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ protected final int mPrimaryIndex;
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ final ResultWaiter mResultWaiter = new ResultWaiter();
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ @NonNull protected MediaMuxer mMuxer;
+ @NonNull protected EncoderBase mEncoder;
+ final AtomicBoolean mMuxerStarted = new AtomicBoolean(false);
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ int[] mTrackIndexArray;
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ int mOutputIndex;
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ boolean mGridEnabled;
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ int mQuality;
+ private boolean mStarted;
+
+ private final List<Pair<Integer, ByteBuffer>> mExifList = new ArrayList<>();
+
+ protected WriterBase(int rotation,
+ @InputMode int inputMode,
+ int maxImages,
+ int primaryIndex,
+ boolean gridEnabled,
+ int quality,
+ @Nullable Handler handler,
+ boolean highBitDepthEnabled) throws IOException {
+ if (primaryIndex >= maxImages) {
+ throw new IllegalArgumentException(
+ "Invalid maxImages (" + maxImages + ") or primaryIndex (" + primaryIndex + ")");
+ }
+
+ mRotation = rotation;
+ mInputMode = inputMode;
+ mMaxImages = maxImages;
+ mPrimaryIndex = primaryIndex;
+ mGridEnabled = gridEnabled;
+ mQuality = quality;
+ mHighBitDepthEnabled = highBitDepthEnabled;
+
+ Looper looper = (handler != null) ? handler.getLooper() : null;
+ if (looper == null) {
+ mHandlerThread = new HandlerThread("HeifEncoderThread",
+ Process.THREAD_PRIORITY_FOREGROUND);
+ mHandlerThread.start();
+ looper = mHandlerThread.getLooper();
+ } else {
+ mHandlerThread = null;
+ }
+ mHandler = new Handler(looper);
+ }
+
+ /**
+ * Start the heif writer. Can only be called once.
+ *
+ * @throws IllegalStateException if called more than once.
+ */
+ public void start() {
+ checkStarted(false);
+ mStarted = true;
+ mEncoder.start();
+ }
+
+ /**
+ * Add one YUV buffer to the heif file.
+ *
+ * @param format The YUV format as defined in {@link android.graphics.ImageFormat}, currently
+ * only support YUV_420_888.
+ *
+ * @param data byte array containing the YUV data. If the format has more than one planes,
+ * they must be concatenated.
+ *
+ * @throws IllegalStateException if not started or not configured to use buffer input.
+ */
+ public void addYuvBuffer(int format, @NonNull byte[] data) {
+ checkStartedAndMode(INPUT_MODE_BUFFER);
+ synchronized (this) {
+ if (mEncoder != null) {
+ mEncoder.addYuvBuffer(format, data);
+ }
+ }
+ }
+
+ /**
+ * Retrieves the input surface for encoding.
+ *
+ * @return the input surface if configured to use surface input.
+ *
+ * @throws IllegalStateException if called after start or not configured to use surface input.
+ */
+ public @NonNull Surface getInputSurface() {
+ checkStarted(false);
+ checkMode(INPUT_MODE_SURFACE);
+ return mEncoder.getInputSurface();
+ }
+
+ /**
+ * Set the timestamp (in nano seconds) of the last input frame to encode.
+ *
+ * This call is only valid for surface input. Client can use this to stop the heif writer
+ * earlier before the maximum number of images are written. If not called, the writer will
+ * only stop when the maximum number of images are written.
+ *
+ * @param timestampNs timestamp (in nano seconds) of the last frame that will be written to the
+ * heif file. Frames with timestamps larger than the specified value will not
+ * be written. However, if a frame already started encoding when this is set,
+ * all tiles within that frame will be encoded.
+ *
+ * @throws IllegalStateException if not started or not configured to use surface input.
+ */
+ public void setInputEndOfStreamTimestamp(@IntRange(from = 0) long timestampNs) {
+ checkStartedAndMode(INPUT_MODE_SURFACE);
+ synchronized (this) {
+ if (mEncoder != null) {
+ mEncoder.setEndOfInputStreamTimestamp(timestampNs);
+ }
+ }
+ }
+
+ /**
+ * Add one bitmap to the heif file.
+ *
+ * @param bitmap the bitmap to be added to the file.
+ * @throws IllegalStateException if not started or not configured to use bitmap input.
+ */
+ public void addBitmap(@NonNull Bitmap bitmap) {
+ checkStartedAndMode(INPUT_MODE_BITMAP);
+ synchronized (this) {
+ if (mEncoder != null) {
+ mEncoder.addBitmap(bitmap);
+ }
+ }
+ }
+
+ /**
+ * Add Exif data for the specified image. The data must be a valid Exif data block,
+ * starting with "Exif\0\0" followed by the TIFF header (See JEITA CP-3451C Section 4.5.2.)
+ *
+ * @param imageIndex index of the image, must be a valid index for the max number of image
+ * specified by {@link Builder#setMaxImages(int)}.
+ * @param exifData byte buffer containing a Exif data block.
+ * @param offset offset of the Exif data block within exifData.
+ * @param length length of the Exif data block.
+ */
+ public void addExifData(int imageIndex, @NonNull byte[] exifData, int offset, int length) {
+ checkStarted(true);
+
+ ByteBuffer buffer = ByteBuffer.allocateDirect(length);
+ buffer.put(exifData, offset, length);
+ buffer.flip();
+ // Put it in a queue, as we might not be able to process it at this time.
+ synchronized (mExifList) {
+ mExifList.add(new Pair<Integer, ByteBuffer>(imageIndex, buffer));
+ }
+ processExifData();
+ }
+
+ @SuppressLint("WrongConstant")
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ void processExifData() {
+ if (!mMuxerStarted.get()) {
+ return;
+ }
+
+ while (true) {
+ Pair<Integer, ByteBuffer> entry;
+ synchronized (mExifList) {
+ if (mExifList.isEmpty()) {
+ return;
+ }
+ entry = mExifList.remove(0);
+ }
+ MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
+ info.set(entry.second.position(), entry.second.remaining(), 0, MUXER_DATA_FLAG);
+ mMuxer.writeSampleData(mTrackIndexArray[entry.first], entry.second, info);
+ }
+ }
+
+ /**
+ * Stop the heif writer synchronously. Throws exception if the writer didn't finish writing
+ * successfully. Upon a success return:
+ *
+ * - For buffer and bitmap inputs, all images sent before stop will be written.
+ *
+ * - For surface input, images with timestamp on or before that specified in
+ * {@link #setInputEndOfStreamTimestamp(long)} will be written. In case where
+ * {@link #setInputEndOfStreamTimestamp(long)} was never called, stop will block
+ * until maximum number of images are received.
+ *
+ * @param timeoutMs Maximum time (in microsec) to wait for the writer to complete, with zero
+ * indicating waiting indefinitely.
+ * @see #setInputEndOfStreamTimestamp(long)
+ * @throws Exception if encountered error, in which case the output file may not be valid. In
+ * particular, {@link TimeoutException} is thrown when timed out, and {@link
+ * MediaCodec.CodecException} is thrown when encountered codec error.
+ */
+ public void stop(@IntRange(from = 0) long timeoutMs) throws Exception {
+ checkStarted(true);
+ synchronized (this) {
+ if (mEncoder != null) {
+ mEncoder.stopAsync();
+ }
+ }
+ mResultWaiter.waitForResult(timeoutMs);
+ processExifData();
+ closeInternal();
+ }
+
+ private void checkStarted(boolean requiredStarted) {
+ if (mStarted != requiredStarted) {
+ throw new IllegalStateException("Already started");
+ }
+ }
+
+ private void checkMode(@InputMode int requiredMode) {
+ if (mInputMode != requiredMode) {
+ throw new IllegalStateException("Not valid in input mode " + mInputMode);
+ }
+ }
+
+ private void checkStartedAndMode(@InputMode int requiredMode) {
+ checkStarted(true);
+ checkMode(requiredMode);
+ }
+
+ /**
+ * Routine to stop and release writer, must be called on the same looper
+ * that receives heif encoder callbacks.
+ */
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ void closeInternal() {
+ if (DEBUG) Log.d(TAG, "closeInternal");
+ // We don't want to crash when closing, catch all exceptions.
+ try {
+ // Muxer could throw exceptions if stop is called without samples.
+ // Don't crash in that case.
+ if (mMuxer != null) {
+ mMuxer.stop();
+ mMuxer.release();
+ }
+ } catch (Exception e) {
+ } finally {
+ mMuxer = null;
+ }
+ try {
+ if (mEncoder != null) {
+ mEncoder.close();
+ }
+ } catch (Exception e) {
+ } finally {
+ synchronized (this) {
+ mEncoder = null;
+ }
+ }
+ }
+
+ /**
+ * Callback from the encoder.
+ */
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ protected class WriterCallback extends EncoderBase.Callback {
+ private boolean mEncoderStopped;
+ /**
+ * Upon receiving output format from the encoder, add the requested number of
+ * image tracks to the muxer and start the muxer.
+ */
+ @Override
+ public void onOutputFormatChanged(
+ @NonNull EncoderBase encoder, @NonNull MediaFormat format) {
+ if (mEncoderStopped) return;
+
+ if (DEBUG) {
+ Log.d(TAG, "onOutputFormatChanged: " + format);
+ }
+ if (mTrackIndexArray != null) {
+ stopAndNotify(new IllegalStateException(
+ "Output format changed after muxer started"));
+ return;
+ }
+
+ try {
+ int gridRows = format.getInteger(MediaFormat.KEY_GRID_ROWS);
+ int gridCols = format.getInteger(MediaFormat.KEY_GRID_COLUMNS);
+ mNumTiles = gridRows * gridCols;
+ } catch (NullPointerException | ClassCastException e) {
+ mNumTiles = 1;
+ }
+
+ // add mMaxImages image tracks of the same format
+ mTrackIndexArray = new int[mMaxImages];
+
+ // set rotation angle
+ if (mRotation > 0) {
+ Log.d(TAG, "setting rotation: " + mRotation);
+ mMuxer.setOrientationHint(mRotation);
+ }
+ for (int i = 0; i < mTrackIndexArray.length; i++) {
+ // mark primary
+ format.setInteger(MediaFormat.KEY_IS_DEFAULT, (i == mPrimaryIndex) ? 1 : 0);
+ mTrackIndexArray[i] = mMuxer.addTrack(format);
+ }
+ mMuxer.start();
+ mMuxerStarted.set(true);
+ processExifData();
+ }
+
+ /**
+ * Upon receiving an output buffer from the encoder (which is one image when
+ * grid is not used, or one tile if grid is used), add that sample to the muxer.
+ */
+ @Override
+ public void onDrainOutputBuffer(
+ @NonNull EncoderBase encoder, @NonNull ByteBuffer byteBuffer) {
+ if (mEncoderStopped) return;
+
+ if (DEBUG) {
+ Log.d(TAG, "onDrainOutputBuffer: " + mOutputIndex);
+ }
+ if (mTrackIndexArray == null) {
+ stopAndNotify(new IllegalStateException(
+ "Output buffer received before format info"));
+ return;
+ }
+
+ if (mOutputIndex < mMaxImages * mNumTiles) {
+ MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
+ info.set(byteBuffer.position(), byteBuffer.remaining(), 0, 0);
+ mMuxer.writeSampleData(
+ mTrackIndexArray[mOutputIndex / mNumTiles], byteBuffer, info);
+ }
+
+ mOutputIndex++;
+
+ // post EOS if reached max number of images allowed.
+ if (mOutputIndex == mMaxImages * mNumTiles) {
+ stopAndNotify(null);
+ }
+ }
+
+ @Override
+ public void onComplete(@NonNull EncoderBase encoder) {
+ stopAndNotify(null);
+ }
+
+ @Override
+ public void onError(@NonNull EncoderBase encoder, @NonNull MediaCodec.CodecException e) {
+ stopAndNotify(e);
+ }
+
+ private void stopAndNotify(@Nullable Exception error) {
+ if (mEncoderStopped) return;
+
+ mEncoderStopped = true;
+ mResultWaiter.signalResult(error);
+ }
+ }
+
+ @SuppressWarnings("WeakerAccess") /* synthetic access */
+ static class ResultWaiter {
+ private boolean mDone;
+ private Exception mException;
+
+ synchronized void waitForResult(long timeoutMs) throws Exception {
+ if (timeoutMs < 0) {
+ throw new IllegalArgumentException("timeoutMs is negative");
+ }
+ if (timeoutMs == 0) {
+ while (!mDone) {
+ try {
+ wait();
+ } catch (InterruptedException ex) {}
+ }
+ } else {
+ final long startTimeMs = System.currentTimeMillis();
+ long remainingWaitTimeMs = timeoutMs;
+ // avoid early termination by "spurious" wakeup.
+ while (!mDone && remainingWaitTimeMs > 0) {
+ try {
+ wait(remainingWaitTimeMs);
+ } catch (InterruptedException ex) {}
+ remainingWaitTimeMs -= (System.currentTimeMillis() - startTimeMs);
+ }
+ }
+ if (!mDone) {
+ mDone = true;
+ mException = new TimeoutException("timed out waiting for result");
+ }
+ if (mException != null) {
+ throw mException;
+ }
+ }
+
+ synchronized void signalResult(@Nullable Exception e) {
+ if (!mDone) {
+ mDone = true;
+ mException = e;
+ notifyAll();
+ }
+ }
+ }
+
+ @Override
+ public void close() {
+ mHandler.postAtFrontOfQueue(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ closeInternal();
+ } catch (Exception e) {
+ // If the client called stop() properly, any errors would have been
+ // reported there. We don't want to crash when closing.
+ }
+ }
+ });
+ }
+
+ /*
+ * Gets rotation.
+ */
+ public int getRotation() {
+ return mRotation;
+ }
+
+ /*
+ * Returns true if grid is enabled.
+ */
+ public boolean isGridEnabled() {
+ return mGridEnabled;
+ }
+
+ /*
+ * Gets configured quality.
+ */
+ public int getQuality() {
+ return mQuality;
+ }
+
+ /*
+ * Gets number of maximum images.
+ */
+ public int getMaxImages() {
+ return mMaxImages;
+ }
+
+ /*
+ * Gets index of the primary image.
+ */
+ public int getPrimaryIndex() {
+ return mPrimaryIndex;
+ }
+
+ /*
+ * Gets handler.
+ *
+ * The result is the same as clients' input from setHandler() method.
+ * If not null, client will receive all callbacks on the handler's looper.
+ * Otherwise, client will receive callbacks on the current looper.
+ */
+ public @Nullable Handler getHandler() {
+ return mHandler;
+ }
+
+ /*
+ * Returns true if high bit-depth is enabled.
+ */
+ public boolean isHighBitDepthEnabled() {
+ return mHighBitDepthEnabled;
+ }
+}
\ No newline at end of file
diff --git a/leanback/leanback/api/api_lint.ignore b/leanback/leanback/api/api_lint.ignore
index a72d2ae..a568a48 100644
--- a/leanback/leanback/api/api_lint.ignore
+++ b/leanback/leanback/api/api_lint.ignore
@@ -147,8 +147,6 @@
Invalid nullability on parameter `view` in method `onViewCreated`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
InvalidNullabilityOverride: androidx.leanback.widget.GuidedActionEditText#onTouchEvent(android.view.MotionEvent) parameter #0:
Invalid nullability on parameter `event` in method `onTouchEvent`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
-InvalidNullabilityOverride: androidx.leanback.widget.ShadowOverlayContainer#draw(android.graphics.Canvas) parameter #0:
- Invalid nullability on parameter `canvas` in method `draw`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
KotlinOperator: androidx.leanback.widget.ObjectAdapter#get(int):
@@ -1135,6 +1133,8 @@
Missing nullability on field `TOP_FRACTION` in class `class androidx.leanback.graphics.CompositeDrawable.ChildDrawable`
MissingNullability: androidx.leanback.graphics.FitWidthBitmapDrawable#PROPERTY_VERTICAL_OFFSET:
Missing nullability on field `PROPERTY_VERTICAL_OFFSET` in class `class androidx.leanback.graphics.FitWidthBitmapDrawable`
+MissingNullability: androidx.leanback.graphics.FitWidthBitmapDrawable#draw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `canvas` in method `draw`
MissingNullability: androidx.leanback.graphics.FitWidthBitmapDrawable#getBitmap():
Missing nullability on method `getBitmap` return
MissingNullability: androidx.leanback.graphics.FitWidthBitmapDrawable#getConstantState():
@@ -2189,6 +2189,8 @@
Missing nullability on parameter `context` in method `ShadowOverlayContainer`
MissingNullability: androidx.leanback.widget.ShadowOverlayContainer#ShadowOverlayContainer(android.content.Context, android.util.AttributeSet, int) parameter #1:
Missing nullability on parameter `attrs` in method `ShadowOverlayContainer`
+MissingNullability: androidx.leanback.widget.ShadowOverlayContainer#draw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `canvas` in method `draw`
MissingNullability: androidx.leanback.widget.ShadowOverlayContainer#getWrappedView():
Missing nullability on method `getWrappedView` return
MissingNullability: androidx.leanback.widget.ShadowOverlayContainer#prepareParentForShadow(android.view.ViewGroup) parameter #0:
diff --git a/libraryversions.toml b/libraryversions.toml
index c22b486..83e4c5e1 100644
--- a/libraryversions.toml
+++ b/libraryversions.toml
@@ -1,5 +1,5 @@
[versions]
-ACTIVITY = "1.7.0-alpha05"
+ACTIVITY = "1.8.0-alpha01"
ADS_IDENTIFIER = "1.0.0-alpha05"
ANNOTATION = "1.6.0-beta01"
ANNOTATION_EXPERIMENTAL = "1.4.0-alpha01"
@@ -29,7 +29,7 @@
CONSTRAINTLAYOUT_CORE = "1.1.0-alpha07"
CONTENTPAGER = "1.1.0-alpha01"
COORDINATORLAYOUT = "1.3.0-alpha01"
-CORE = "1.10.0-alpha03"
+CORE = "1.12.0-alpha01"
CORE_ANIMATION = "1.0.0-beta02"
CORE_ANIMATION_TESTING = "1.0.0-beta01"
CORE_APPDIGEST = "1.0.0-alpha01"
@@ -41,7 +41,7 @@
CORE_ROLE = "1.2.0-alpha01"
CORE_SPLASHSCREEN = "1.1.0-alpha01"
CORE_UWB = "1.0.0-alpha05"
-CREDENTIALS = "1.0.0-alpha02"
+CREDENTIALS = "1.2.0-alpha01"
CURSORADAPTER = "1.1.0-alpha01"
CUSTOMVIEW = "1.2.0-alpha03"
CUSTOMVIEW_POOLINGCONTAINER = "1.1.0-alpha01"
diff --git a/mediarouter/mediarouter/api/current.txt b/mediarouter/mediarouter/api/current.txt
index b1cf094..e1077a5 100644
--- a/mediarouter/mediarouter/api/current.txt
+++ b/mediarouter/mediarouter/api/current.txt
@@ -172,6 +172,7 @@
method public static androidx.mediarouter.media.MediaRouteDescriptor? fromBundle(android.os.Bundle?);
method public int getConnectionState();
method public java.util.List<android.content.IntentFilter!> getControlFilters();
+ method public java.util.Set<java.lang.String!> getDeduplicationIds();
method public String? getDescription();
method public int getDeviceType();
method public android.os.Bundle? getExtras();
@@ -201,6 +202,7 @@
method public androidx.mediarouter.media.MediaRouteDescriptor.Builder setCanDisconnect(boolean);
method @Deprecated public androidx.mediarouter.media.MediaRouteDescriptor.Builder setConnecting(boolean);
method public androidx.mediarouter.media.MediaRouteDescriptor.Builder setConnectionState(int);
+ method public androidx.mediarouter.media.MediaRouteDescriptor.Builder setDeduplicationIds(java.util.Set<java.lang.String!>);
method public androidx.mediarouter.media.MediaRouteDescriptor.Builder setDescription(String?);
method public androidx.mediarouter.media.MediaRouteDescriptor.Builder setDeviceType(int);
method public androidx.mediarouter.media.MediaRouteDescriptor.Builder setEnabled(boolean);
diff --git a/mediarouter/mediarouter/api/public_plus_experimental_current.txt b/mediarouter/mediarouter/api/public_plus_experimental_current.txt
index b1cf094..e1077a5 100644
--- a/mediarouter/mediarouter/api/public_plus_experimental_current.txt
+++ b/mediarouter/mediarouter/api/public_plus_experimental_current.txt
@@ -172,6 +172,7 @@
method public static androidx.mediarouter.media.MediaRouteDescriptor? fromBundle(android.os.Bundle?);
method public int getConnectionState();
method public java.util.List<android.content.IntentFilter!> getControlFilters();
+ method public java.util.Set<java.lang.String!> getDeduplicationIds();
method public String? getDescription();
method public int getDeviceType();
method public android.os.Bundle? getExtras();
@@ -201,6 +202,7 @@
method public androidx.mediarouter.media.MediaRouteDescriptor.Builder setCanDisconnect(boolean);
method @Deprecated public androidx.mediarouter.media.MediaRouteDescriptor.Builder setConnecting(boolean);
method public androidx.mediarouter.media.MediaRouteDescriptor.Builder setConnectionState(int);
+ method public androidx.mediarouter.media.MediaRouteDescriptor.Builder setDeduplicationIds(java.util.Set<java.lang.String!>);
method public androidx.mediarouter.media.MediaRouteDescriptor.Builder setDescription(String?);
method public androidx.mediarouter.media.MediaRouteDescriptor.Builder setDeviceType(int);
method public androidx.mediarouter.media.MediaRouteDescriptor.Builder setEnabled(boolean);
diff --git a/mediarouter/mediarouter/api/restricted_current.txt b/mediarouter/mediarouter/api/restricted_current.txt
index b1cf094..e1077a5 100644
--- a/mediarouter/mediarouter/api/restricted_current.txt
+++ b/mediarouter/mediarouter/api/restricted_current.txt
@@ -172,6 +172,7 @@
method public static androidx.mediarouter.media.MediaRouteDescriptor? fromBundle(android.os.Bundle?);
method public int getConnectionState();
method public java.util.List<android.content.IntentFilter!> getControlFilters();
+ method public java.util.Set<java.lang.String!> getDeduplicationIds();
method public String? getDescription();
method public int getDeviceType();
method public android.os.Bundle? getExtras();
@@ -201,6 +202,7 @@
method public androidx.mediarouter.media.MediaRouteDescriptor.Builder setCanDisconnect(boolean);
method @Deprecated public androidx.mediarouter.media.MediaRouteDescriptor.Builder setConnecting(boolean);
method public androidx.mediarouter.media.MediaRouteDescriptor.Builder setConnectionState(int);
+ method public androidx.mediarouter.media.MediaRouteDescriptor.Builder setDeduplicationIds(java.util.Set<java.lang.String!>);
method public androidx.mediarouter.media.MediaRouteDescriptor.Builder setDescription(String?);
method public androidx.mediarouter.media.MediaRouteDescriptor.Builder setDeviceType(int);
method public androidx.mediarouter.media.MediaRouteDescriptor.Builder setEnabled(boolean);
diff --git a/mediarouter/mediarouter/build.gradle b/mediarouter/mediarouter/build.gradle
index fcaf016..e9e3b8d 100644
--- a/mediarouter/mediarouter/build.gradle
+++ b/mediarouter/mediarouter/build.gradle
@@ -25,11 +25,12 @@
api("androidx.media:media:1.4.1")
api(libs.guavaListenableFuture)
- implementation("androidx.core:core:1.6.0")
+ implementation("androidx.core:core:1.8.0")
implementation("androidx.appcompat:appcompat:1.1.0")
implementation("androidx.palette:palette:1.0.0")
implementation("androidx.recyclerview:recyclerview:1.1.0")
implementation("androidx.appcompat:appcompat-resources:1.2.0")
+ implementation "androidx.annotation:annotation-experimental:1.3.0"
testImplementation(libs.junit)
testImplementation(libs.testCore)
diff --git a/mediarouter/mediarouter/src/androidTest/java/androidx/mediarouter/media/MediaRouter2UtilsTest.java b/mediarouter/mediarouter/src/androidTest/java/androidx/mediarouter/media/MediaRouter2UtilsTest.java
index ae769ed..5c524fd 100644
--- a/mediarouter/mediarouter/src/androidTest/java/androidx/mediarouter/media/MediaRouter2UtilsTest.java
+++ b/mediarouter/mediarouter/src/androidTest/java/androidx/mediarouter/media/MediaRouter2UtilsTest.java
@@ -16,11 +16,17 @@
package androidx.mediarouter.media;
+import static androidx.mediarouter.media.MediaRouter2Utils.KEY_CONTROL_FILTERS;
+import static androidx.mediarouter.media.MediaRouter2Utils.KEY_DEVICE_TYPE;
+import static androidx.mediarouter.media.MediaRouter2Utils.KEY_EXTRAS;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import android.media.MediaRoute2Info;
import android.os.Build;
+import android.os.Bundle;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SdkSuppress;
@@ -29,6 +35,9 @@
import org.junit.Test;
import org.junit.runner.RunWith;
+import java.util.ArrayList;
+import java.util.HashSet;
+
/** Test for {@link MediaRouter2Utils}. */
@SmallTest
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.R)
@@ -60,4 +69,45 @@
.build();
assertNull(MediaRouter2Utils.toFwkMediaRoute2Info(descriptorWithEmptyName));
}
+
+ @SdkSuppress(minSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE, codeName = "UpsideDownCake")
+ @Test
+ public void toFwkMediaRoute2Info_withDeduplicationIds() {
+ HashSet<String> dedupIds = new HashSet<>();
+ dedupIds.add("dedup_id1");
+ dedupIds.add("dedup_id2");
+ MediaRouteDescriptor descriptor =
+ new MediaRouteDescriptor.Builder(
+ FAKE_MEDIA_ROUTE_DESCRIPTOR_ID, FAKE_MEDIA_ROUTE_DESCRIPTOR_NAME)
+ .setDeduplicationIds(dedupIds)
+ .build();
+ assertTrue(
+ MediaRouter2Utils.toFwkMediaRoute2Info(descriptor)
+ .getDeduplicationIds()
+ .equals(dedupIds));
+ }
+
+ @SdkSuppress(minSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE, codeName = "UpsideDownCake")
+ @Test
+ public void toMediaRouteDescriptor_withDeduplicationIds() {
+ HashSet<String> dedupIds = new HashSet<>();
+ dedupIds.add("dedup_id1");
+ dedupIds.add("dedup_id2");
+ // Extras needed to make toMediaRouteDescriptor not return null.
+ Bundle extras = new Bundle();
+ extras.putBundle(KEY_EXTRAS, new Bundle());
+ extras.putInt(KEY_DEVICE_TYPE, MediaRouter.RouteInfo.DEVICE_TYPE_UNKNOWN);
+ extras.putParcelableArrayList(KEY_CONTROL_FILTERS, new ArrayList<>());
+ MediaRoute2Info routeInfo =
+ new MediaRoute2Info.Builder(
+ FAKE_MEDIA_ROUTE_DESCRIPTOR_ID, FAKE_MEDIA_ROUTE_DESCRIPTOR_NAME)
+ .addFeature(MediaRoute2Info.FEATURE_REMOTE_PLAYBACK)
+ .setDeduplicationIds(dedupIds)
+ .setExtras(extras)
+ .build();
+ assertTrue(
+ MediaRouter2Utils.toMediaRouteDescriptor(routeInfo)
+ .getDeduplicationIds()
+ .equals(dedupIds));
+ }
}
diff --git a/mediarouter/mediarouter/src/main/java/androidx/mediarouter/media/MediaRoute2Provider.java b/mediarouter/mediarouter/src/main/java/androidx/mediarouter/media/MediaRoute2Provider.java
index e77626e..73a1ddd 100644
--- a/mediarouter/mediarouter/src/main/java/androidx/mediarouter/media/MediaRoute2Provider.java
+++ b/mediarouter/mediarouter/src/main/java/androidx/mediarouter/media/MediaRoute2Provider.java
@@ -46,7 +46,9 @@
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
+import androidx.annotation.OptIn;
import androidx.annotation.RequiresApi;
+import androidx.core.os.BuildCompat;
import androidx.mediarouter.R;
import androidx.mediarouter.media.MediaRouteProvider.DynamicGroupRouteController.DynamicRouteDescriptor;
import androidx.mediarouter.media.MediaRouter.ControlRequestCallback;
@@ -72,7 +74,7 @@
final Callback mCallback;
final Map<MediaRouter2.RoutingController, GroupRouteController> mControllerMap =
new ArrayMap<>();
- private final MediaRouter2.RouteCallback mRouteCallback = new RouteCallback();
+ private final MediaRouter2.RouteCallback mRouteCallback;
private final MediaRouter2.TransferCallback mTransferCallback = new TransferCallback();
private final MediaRouter2.ControllerCallback mControllerCallback = new ControllerCallback();
private final Handler mHandler;
@@ -81,6 +83,8 @@
private List<MediaRoute2Info> mRoutes = new ArrayList<>();
private Map<String, String> mRouteIdToOriginalRouteIdMap = new ArrayMap<>();
+ @OptIn(markerClass = androidx.core.os.BuildCompat.PrereleaseSdkCheck.class)
+ @SuppressWarnings({"SyntheticAccessor"})
MediaRoute2Provider(@NonNull Context context, @NonNull Callback callback) {
super(context);
mMediaRouter2 = MediaRouter2.getInstance(context);
@@ -88,6 +92,12 @@
mHandler = new Handler(Looper.getMainLooper());
mHandlerExecutor = mHandler::post;
+
+ if (BuildCompat.isAtLeastU()) {
+ mRouteCallback = new RouteCallbackUpsideDownCake();
+ } else {
+ mRouteCallback = new RouteCallback();
+ }
}
@Override
@@ -380,6 +390,14 @@
}
}
+ private class RouteCallbackUpsideDownCake extends MediaRouter2.RouteCallback {
+
+ @Override
+ public void onRoutesUpdated(@NonNull List<MediaRoute2Info> routes) {
+ refreshRoutes();
+ }
+ }
+
private class TransferCallback extends MediaRouter2.TransferCallback {
TransferCallback() {}
diff --git a/mediarouter/mediarouter/src/main/java/androidx/mediarouter/media/MediaRouteDescriptor.java b/mediarouter/mediarouter/src/main/java/androidx/mediarouter/media/MediaRouteDescriptor.java
index 314a72f..bc16e9f 100644
--- a/mediarouter/mediarouter/src/main/java/androidx/mediarouter/media/MediaRouteDescriptor.java
+++ b/mediarouter/mediarouter/src/main/java/androidx/mediarouter/media/MediaRouteDescriptor.java
@@ -31,7 +31,9 @@
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
+import java.util.HashSet;
import java.util.List;
+import java.util.Set;
/**
* Describes the properties of a route.
@@ -65,6 +67,7 @@
static final String KEY_SETTINGS_INTENT = "settingsIntent";
static final String KEY_MIN_CLIENT_VERSION = "minClientVersion";
static final String KEY_MAX_CLIENT_VERSION = "maxClientVersion";
+ static final String KEY_DEDUPLICATION_IDS = "deduplicationIds";
final Bundle mBundle;
List<String> mGroupMemberIds;
@@ -299,6 +302,20 @@
}
/**
+ * Gets the route's deduplication ids.
+ *
+ * <p>Two routes are considered to come from the same receiver device if any of their respective
+ * deduplication ids match.
+ */
+ @NonNull
+ public Set<String> getDeduplicationIds() {
+ ArrayList<String> deduplicationIds = mBundle.getStringArrayList(KEY_DEDUPLICATION_IDS);
+ return deduplicationIds != null
+ ? Collections.unmodifiableSet(new HashSet<>(deduplicationIds))
+ : Collections.emptySet();
+ }
+
+ /**
* Gets the route's presentation display id, or -1 if none.
*/
public int getPresentationDisplayId() {
@@ -767,6 +784,21 @@
}
/**
+ * Sets the route's deduplication ids.
+ *
+ * <p>Two routes are considered to come from the same receiver device if any of their
+ * respective deduplication ids match.
+ *
+ * @param deduplicationIds A set of strings that uniquely identify the receiver device that
+ * backs this route.
+ */
+ @NonNull
+ public Builder setDeduplicationIds(@NonNull Set<String> deduplicationIds) {
+ mBundle.putStringArrayList(KEY_DEDUPLICATION_IDS, new ArrayList<>(deduplicationIds));
+ return this;
+ }
+
+ /**
* Sets the route's presentation display id, or -1 if none.
*/
@NonNull
diff --git a/mediarouter/mediarouter/src/main/java/androidx/mediarouter/media/MediaRouter2Utils.java b/mediarouter/mediarouter/src/main/java/androidx/mediarouter/media/MediaRouter2Utils.java
index 5514799..8ac3e5b 100644
--- a/mediarouter/mediarouter/src/main/java/androidx/mediarouter/media/MediaRouter2Utils.java
+++ b/mediarouter/mediarouter/src/main/java/androidx/mediarouter/media/MediaRouter2Utils.java
@@ -35,9 +35,12 @@
import android.text.TextUtils;
import android.util.ArraySet;
+import androidx.annotation.DoNotInline;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
+import androidx.annotation.OptIn;
import androidx.annotation.RequiresApi;
+import androidx.core.os.BuildCompat;
import java.util.ArrayList;
import java.util.Collection;
@@ -65,6 +68,7 @@
private MediaRouter2Utils() {}
+ @OptIn(markerClass = androidx.core.os.BuildCompat.PrereleaseSdkCheck.class)
@Nullable
public static MediaRoute2Info toFwkMediaRoute2Info(@Nullable MediaRouteDescriptor descriptor) {
if (descriptor == null) {
@@ -88,6 +92,10 @@
//.setClientPackageName(clientMap.get(device.getDeviceId()))
;
+ if (BuildCompat.isAtLeastU()) {
+ Api34Impl.setDeduplicationIds(builder, descriptor.getDeduplicationIds());
+ }
+
switch (descriptor.getDeviceType()) {
case DEVICE_TYPE_TV:
builder.addFeature(FEATURE_REMOTE_VIDEO_PLAYBACK);
@@ -118,6 +126,7 @@
return builder.build();
}
+ @OptIn(markerClass = androidx.core.os.BuildCompat.PrereleaseSdkCheck.class)
@Nullable
public static MediaRouteDescriptor toMediaRouteDescriptor(
@Nullable MediaRoute2Info fwkMediaRoute2Info) {
@@ -135,6 +144,10 @@
.setEnabled(true)
.setCanDisconnect(false);
+ if (BuildCompat.isAtLeastU()) {
+ builder.setDeduplicationIds(Api34Impl.getDeduplicationIds(fwkMediaRoute2Info));
+ }
+
CharSequence description = fwkMediaRoute2Info.getDescription();
if (description != null) {
builder.setDescription(description.toString());
@@ -276,4 +289,19 @@
}
return routeFeature;
}
+
+ @RequiresApi(api = 34)
+ private static final class Api34Impl {
+
+ @DoNotInline
+ public static void setDeduplicationIds(
+ MediaRoute2Info.Builder builder, Set<String> deduplicationIds) {
+ builder.setDeduplicationIds(deduplicationIds);
+ }
+
+ @DoNotInline
+ public static Set<String> getDeduplicationIds(MediaRoute2Info fwkMediaRoute2Info) {
+ return fwkMediaRoute2Info.getDeduplicationIds();
+ }
+ }
}
diff --git a/privacysandbox/ads/ads-adservices-java/src/androidTest/java/androidx/privacysandbox/ads/adservices/java/endtoend/TestUtil.java b/privacysandbox/ads/ads-adservices-java/src/androidTest/java/androidx/privacysandbox/ads/adservices/java/endtoend/TestUtil.java
index 8d5d99a..5502ef7 100644
--- a/privacysandbox/ads/ads-adservices-java/src/androidTest/java/androidx/privacysandbox/ads/adservices/java/endtoend/TestUtil.java
+++ b/privacysandbox/ads/ads-adservices-java/src/androidTest/java/androidx/privacysandbox/ads/adservices/java/endtoend/TestUtil.java
@@ -104,6 +104,14 @@
}
}
+ public void overrideAppSetIdKillSwitch(boolean override) {
+ if (override) {
+ runShellCommand("setprop debug.adservices.appsetid_kill_switch " + false);
+ } else {
+ runShellCommand("setprop debug.adservices.appsetid_kill_switch " + null);
+ }
+ }
+
// Override measurement related kill switch to ignore the effect of actual PH values.
// If isOverride = true, override measurement related kill switch to OFF to allow adservices
// If isOverride = false, override measurement related kill switch to meaningless value so that
diff --git a/privacysandbox/ads/ads-adservices-java/src/androidTest/java/androidx/privacysandbox/ads/adservices/java/endtoend/appsetid/AppSetIdManagerTest.java b/privacysandbox/ads/ads-adservices-java/src/androidTest/java/androidx/privacysandbox/ads/adservices/java/endtoend/appsetid/AppSetIdManagerTest.java
new file mode 100644
index 0000000..88973750
--- /dev/null
+++ b/privacysandbox/ads/ads-adservices-java/src/androidTest/java/androidx/privacysandbox/ads/adservices/java/endtoend/appsetid/AppSetIdManagerTest.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright 2023 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 androidx.privacysandbox.ads.adservices.java.endtoend.appsetid;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import androidx.privacysandbox.ads.adservices.appsetid.AppSetId;
+import androidx.privacysandbox.ads.adservices.internal.AdServicesInfo;
+import androidx.privacysandbox.ads.adservices.java.appsetid.AppSetIdManagerFutures;
+import androidx.privacysandbox.ads.adservices.java.endtoend.TestUtil;
+import androidx.test.core.app.ApplicationProvider;
+import androidx.test.platform.app.InstrumentationRegistry;
+
+import org.junit.After;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+// TODO: Consider refactoring so that we're not duplicating code.
+public class AppSetIdManagerTest {
+ private static final String TAG = "AppSetIdManagerTest";
+ TestUtil mTestUtil = new TestUtil(InstrumentationRegistry.getInstrumentation(), TAG);
+
+ @Before
+ public void setup() throws Exception {
+ mTestUtil.overrideAppSetIdKillSwitch(true);
+ mTestUtil.overrideKillSwitches(true);
+ mTestUtil.overrideAllowlists(true);
+ }
+
+ @After
+ public void teardown() {
+ mTestUtil.overrideAppSetIdKillSwitch(false);
+ mTestUtil.overrideKillSwitches(false);
+ mTestUtil.overrideAllowlists(false);
+ }
+
+ @Test
+ public void testAppSetId() throws Exception {
+ // Skip the test if SDK extension 4 is not present.
+ Assume.assumeTrue(AdServicesInfo.INSTANCE.version() >= 4);
+
+ AppSetIdManagerFutures appSetIdManager =
+ AppSetIdManagerFutures.from(ApplicationProvider.getApplicationContext());
+ AppSetId appSetId = appSetIdManager.getAppSetIdAsync().get();
+ assertThat(appSetId.getId()).isNotEmpty();
+ assertThat(appSetId.getScope()).isNotNull();
+ }
+}
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/api/current.txt b/privacysandbox/sdkruntime/sdkruntime-client/api/current.txt
index e6f50d0..aa2ae90 100644
--- a/privacysandbox/sdkruntime/sdkruntime-client/api/current.txt
+++ b/privacysandbox/sdkruntime/sdkruntime-client/api/current.txt
@@ -1 +1,15 @@
// Signature format: 4.0
+package androidx.privacysandbox.sdkruntime.client {
+
+ public final class SdkSandboxManagerCompat {
+ method public static androidx.privacysandbox.sdkruntime.client.SdkSandboxManagerCompat from(android.content.Context context);
+ method @kotlin.jvm.Throws(exceptionClasses=LoadSdkCompatException::class) public suspend Object? loadSdk(String sdkName, android.os.Bundle params, kotlin.coroutines.Continuation<? super androidx.privacysandbox.sdkruntime.core.SandboxedSdkCompat>) throws androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException;
+ field public static final androidx.privacysandbox.sdkruntime.client.SdkSandboxManagerCompat.Companion Companion;
+ }
+
+ public static final class SdkSandboxManagerCompat.Companion {
+ method public androidx.privacysandbox.sdkruntime.client.SdkSandboxManagerCompat from(android.content.Context context);
+ }
+
+}
+
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/api/public_plus_experimental_current.txt b/privacysandbox/sdkruntime/sdkruntime-client/api/public_plus_experimental_current.txt
index e6f50d0..aa2ae90 100644
--- a/privacysandbox/sdkruntime/sdkruntime-client/api/public_plus_experimental_current.txt
+++ b/privacysandbox/sdkruntime/sdkruntime-client/api/public_plus_experimental_current.txt
@@ -1 +1,15 @@
// Signature format: 4.0
+package androidx.privacysandbox.sdkruntime.client {
+
+ public final class SdkSandboxManagerCompat {
+ method public static androidx.privacysandbox.sdkruntime.client.SdkSandboxManagerCompat from(android.content.Context context);
+ method @kotlin.jvm.Throws(exceptionClasses=LoadSdkCompatException::class) public suspend Object? loadSdk(String sdkName, android.os.Bundle params, kotlin.coroutines.Continuation<? super androidx.privacysandbox.sdkruntime.core.SandboxedSdkCompat>) throws androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException;
+ field public static final androidx.privacysandbox.sdkruntime.client.SdkSandboxManagerCompat.Companion Companion;
+ }
+
+ public static final class SdkSandboxManagerCompat.Companion {
+ method public androidx.privacysandbox.sdkruntime.client.SdkSandboxManagerCompat from(android.content.Context context);
+ }
+
+}
+
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/api/restricted_current.txt b/privacysandbox/sdkruntime/sdkruntime-client/api/restricted_current.txt
index e6f50d0..aa2ae90 100644
--- a/privacysandbox/sdkruntime/sdkruntime-client/api/restricted_current.txt
+++ b/privacysandbox/sdkruntime/sdkruntime-client/api/restricted_current.txt
@@ -1 +1,15 @@
// Signature format: 4.0
+package androidx.privacysandbox.sdkruntime.client {
+
+ public final class SdkSandboxManagerCompat {
+ method public static androidx.privacysandbox.sdkruntime.client.SdkSandboxManagerCompat from(android.content.Context context);
+ method @kotlin.jvm.Throws(exceptionClasses=LoadSdkCompatException::class) public suspend Object? loadSdk(String sdkName, android.os.Bundle params, kotlin.coroutines.Continuation<? super androidx.privacysandbox.sdkruntime.core.SandboxedSdkCompat>) throws androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException;
+ field public static final androidx.privacysandbox.sdkruntime.client.SdkSandboxManagerCompat.Companion Companion;
+ }
+
+ public static final class SdkSandboxManagerCompat.Companion {
+ method public androidx.privacysandbox.sdkruntime.client.SdkSandboxManagerCompat from(android.content.Context context);
+ }
+
+}
+
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/build.gradle b/privacysandbox/sdkruntime/sdkruntime-client/build.gradle
index 4ce9b50..8f55312 100644
--- a/privacysandbox/sdkruntime/sdkruntime-client/build.gradle
+++ b/privacysandbox/sdkruntime/sdkruntime-client/build.gradle
@@ -24,9 +24,40 @@
dependencies {
api(libs.kotlinStdlib)
+ api(libs.kotlinCoroutinesCore)
+ implementation("androidx.core:core-ktx:1.8.0")
+
+ api project(path: ':privacysandbox:sdkruntime:sdkruntime-core')
+
+ implementation("androidx.core:core:1.8.0")
+
+ testImplementation(libs.junit)
+ testImplementation(libs.truth)
+ testImplementation project(":room:room-compiler-processing-testing")
+
+ // TODO(b/249982004): cleanup dependencies
+ androidTestImplementation(libs.testCore)
+ androidTestImplementation(libs.testExtJunit)
+ androidTestImplementation(libs.testRunner)
+ androidTestImplementation(libs.testRules)
+ androidTestImplementation(libs.truth)
+ androidTestImplementation(libs.junit)
+ androidTestImplementation(project(":internal-testutils-truth")) // for assertThrows
+
+ androidTestImplementation(libs.mockitoCore, excludes.bytebuddy) // DexMaker has it"s own MockMaker
+ androidTestImplementation(libs.dexmakerMockitoInline, excludes.bytebuddy) // DexMaker has it"s own MockMaker
}
android {
+ sourceSets {
+ androidTest {
+ assets {
+ srcDirs += "src/androidTest/assets"
+ }
+ }
+ }
+ compileSdk = 33
+ compileSdkExtension = 4
namespace "androidx.privacysandbox.sdkruntime.client"
}
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/AndroidManifest.xml b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/AndroidManifest.xml
new file mode 100644
index 0000000..3e3ea90
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/AndroidManifest.xml
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+</manifest>
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdkTable.xml b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdkTable.xml
new file mode 100644
index 0000000..d589762
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdkTable.xml
@@ -0,0 +1,25 @@
+<!--
+ 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.
+ -->
+<runtime-enabled-sdk-table>
+ <runtime-enabled-sdk>
+ <compat-config-path>RuntimeEnabledSdks/V1/CompatSdkConfig.xml</compat-config-path>
+ <package-name>androidx.privacysandbox.sdkruntime.test.v1</package-name>
+ </runtime-enabled-sdk>
+ <runtime-enabled-sdk>
+ <compat-config-path>RuntimeEnabledSdks/InvalidEntryPointSdkConfig.xml</compat-config-path>
+ <package-name>androidx.privacysandbox.sdkruntime.test.invalidEntryPoint</package-name>
+ </runtime-enabled-sdk>
+</runtime-enabled-sdk-table>
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdks/InvalidEntryPointSdkConfig.xml b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdks/InvalidEntryPointSdkConfig.xml
new file mode 100644
index 0000000..d28649c
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdks/InvalidEntryPointSdkConfig.xml
@@ -0,0 +1,19 @@
+<!--
+ 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.
+ -->
+<compat-config>
+ <compat-entrypoint>InvalidEntryPoint</compat-entrypoint>
+ <dex-path>RuntimeEnabledSdks/V1/classes.dex</dex-path>
+</compat-config>
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdks/RPackage.dex b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdks/RPackage.dex
new file mode 100644
index 0000000..d4862a1
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdks/RPackage.dex
Binary files differ
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdks/RPackage.md b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdks/RPackage.md
new file mode 100644
index 0000000..5c1e2a0
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdks/RPackage.md
@@ -0,0 +1,8 @@
+RPackage class for testing SDK resource remapping.
+
+RPackage.dex built from:
+
+1) androidx.privacysandbox.sdkruntime.test.RPackage
+ public class RPackage {
+ public static int packageId = 0;
+ }
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdks/V1/CompatSdkCode.md b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdks/V1/CompatSdkCode.md
new file mode 100644
index 0000000..a2f1cbf
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdks/V1/CompatSdkCode.md
@@ -0,0 +1,125 @@
+Test sdk that was built with V1 library.
+
+DO NOT RECOMPILE WITH ANY CHANGES TO LIBRARY CLASSES.
+Main purpose of that provider is to test that old core versions could be loaded by new client.
+
+classes.dex built from:
+
+1) androidx.privacysandbox.sdkruntime.core.Versions
+@Keep
+object Versions {
+
+ const val API_VERSION = 1
+
+ @JvmField
+ var CLIENT_VERSION = -1
+
+ @JvmStatic
+ fun handShake(clientVersion: Int): Int {
+ CLIENT_VERSION = clientVersion
+ return API_VERSION
+ }
+}
+
+2) androidx.privacysandbox.sdkruntime.core.SandboxedSdkProviderCompat
+abstract class SandboxedSdkProviderCompat {
+ var context: Context? = null
+ private set
+
+ fun attachContext(context: Context) {
+ check(this.context == null) { "Context already set" }
+ this.context = context
+ }
+
+ @Throws(LoadSdkCompatException::class)
+ abstract fun onLoadSdk(params: Bundle): SandboxedSdkCompat
+
+ open fun beforeUnloadSdk() {}
+
+ abstract fun getView(
+ windowContext: Context,
+ params: Bundle,
+ width: Int,
+ height: Int
+ ): View
+}
+
+3) androidx.privacysandbox.sdkruntime.core.SandboxedSdkCompat
+sealed class SandboxedSdkCompat {
+
+ abstract fun getInterface(): IBinder?
+
+ private class CompatImpl(private val mInterface: IBinder) : SandboxedSdkCompat() {
+ override fun getInterface(): IBinder? {
+ return mInterface
+ }
+ }
+
+ companion object {
+ @JvmStatic
+ fun create(binder: IBinder): SandboxedSdkCompat {
+ return CompatImpl(binder)
+ }
+ }
+}
+
+4) androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException
+class LoadSdkCompatException : Exception {
+
+ val loadSdkErrorCode: Int
+
+ val extraInformation: Bundle
+
+ @JvmOverloads
+ constructor(
+ loadSdkErrorCode: Int,
+ message: String?,
+ cause: Throwable?,
+ extraInformation: Bundle = Bundle()
+ ) : super(message, cause) {
+ this.loadSdkErrorCode = loadSdkErrorCode
+ this.extraInformation = extraInformation
+ }
+
+ constructor(
+ cause: Throwable,
+ extraInfo: Bundle
+ ) : this(LOAD_SDK_SDK_DEFINED_ERROR, "", cause, extraInfo)
+
+ companion object {
+ const val LOAD_SDK_SDK_DEFINED_ERROR = 102
+ }
+}
+
+5) androidx.privacysandbox.sdkruntime.test.v1.CompatProvider
+class CompatProvider : SandboxedSdkProviderCompat() {
+
+ @JvmField
+ val onLoadSdkBinder = Binder()
+
+ @JvmField
+ var lastOnLoadSdkParams: Bundle? = null
+
+ @JvmField
+ var isBeforeUnloadSdkCalled = false
+
+ @Throws(LoadSdkCompatException::class)
+ override fun onLoadSdk(params: Bundle): SandboxedSdkCompat {
+ lastOnLoadSdkParams = params
+ if (params.getBoolean("needFail", false)) {
+ throw LoadSdkCompatException(RuntimeException(), params)
+ }
+ return SandboxedSdkCompat.create(onLoadSdkBinder)
+ }
+
+ override fun beforeUnloadSdk() {
+ isBeforeUnloadSdkCalled = true
+ }
+
+ override fun getView(
+ windowContext: Context, params: Bundle, width: Int,
+ height: Int
+ ): View {
+ return View(windowContext)
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdks/V1/CompatSdkConfig.xml b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdks/V1/CompatSdkConfig.xml
new file mode 100644
index 0000000..dfeca90
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdks/V1/CompatSdkConfig.xml
@@ -0,0 +1,20 @@
+<!--
+ 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.
+ -->
+<compat-config>
+ <compat-entrypoint>androidx.privacysandbox.sdkruntime.test.v1.CompatProvider</compat-entrypoint>
+ <dex-path>RuntimeEnabledSdks/V1/classes.dex</dex-path>
+ <java-resources-root-path>RuntimeEnabledSdks/V1/javaresources</java-resources-root-path>
+</compat-config>
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdks/V1/classes.dex b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdks/V1/classes.dex
new file mode 100644
index 0000000..a6da7e9
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdks/V1/classes.dex
Binary files differ
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdks/V1/javaresources/test.txt b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdks/V1/javaresources/test.txt
new file mode 100644
index 0000000..30d74d2
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/assets/RuntimeEnabledSdks/V1/javaresources/test.txt
@@ -0,0 +1 @@
+test
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/SdkSandboxManagerCompatSandboxedTest.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/SdkSandboxManagerCompatSandboxedTest.kt
new file mode 100644
index 0000000..aff7553
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/SdkSandboxManagerCompatSandboxedTest.kt
@@ -0,0 +1,177 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client
+
+import android.annotation.SuppressLint
+import android.app.sdksandbox.LoadSdkException
+import android.app.sdksandbox.SandboxedSdk
+import android.app.sdksandbox.SdkSandboxManager
+import android.content.Context
+import android.os.Binder
+import android.os.Build
+import android.os.Bundle
+import android.os.OutcomeReceiver
+import android.os.ext.SdkExtensions.AD_SERVICES
+import androidx.annotation.RequiresExtension
+import androidx.privacysandbox.sdkruntime.core.AdServicesInfo
+import androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SdkSuppress
+import androidx.test.filters.SmallTest
+import com.google.common.truth.Truth.assertThat
+import kotlinx.coroutines.runBlocking
+import org.junit.Assert.assertThrows
+import org.junit.Assume.assumeTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.ArgumentMatchers.any
+import org.mockito.ArgumentMatchers.eq
+import org.mockito.Mockito
+import org.mockito.Mockito.doAnswer
+import org.mockito.Mockito.verify
+import org.mockito.Mockito.`when`
+import org.mockito.invocation.InvocationOnMock
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+// TODO(b/249982507) Test should be rewritten to use real SDK in sandbox instead of mocking manager
+// TODO(b/249981547) Remove suppress after updating to new lint version (b/262251309)
+@SuppressLint("NewApi")
+// TODO(b/262577044) Remove RequiresExtension after extensions support in @SdkSuppress
+@RequiresExtension(extension = AD_SERVICES, version = 4)
+@SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
+class SdkSandboxManagerCompatSandboxedTest {
+
+ private lateinit var mContext: Context
+
+ @Before
+ fun setUp() {
+ assumeTrue("Requires Sandbox API available", isSandboxApiAvailable())
+ mContext = Mockito.spy(ApplicationProvider.getApplicationContext<Context>())
+ }
+
+ @Test
+ fun loadSdk_whenNoLocalSdkExistsAndSandboxAvailable_delegateToPlatformLoadSdk() {
+ val sdkSandboxManager = mockSandboxManager(mContext)
+ setupLoadSdkAnswer(sdkSandboxManager, SandboxedSdk(Binder()))
+
+ val managerCompat = SdkSandboxManagerCompat.from(mContext)
+ val sdkName = "test"
+ val params = Bundle()
+
+ runBlocking {
+ managerCompat.loadSdk(sdkName, params)
+ }
+
+ verify(sdkSandboxManager).loadSdk(
+ eq(sdkName),
+ eq(params),
+ any(),
+ any()
+ )
+ }
+
+ @Test
+ fun loadSdk_whenNoLocalSdkExistsAndSandboxAvailable_returnResultFromPlatformLoadSdk() {
+ val sdkSandboxManager = mockSandboxManager(mContext)
+
+ val sandboxedSdk = SandboxedSdk(Binder())
+ setupLoadSdkAnswer(sdkSandboxManager, sandboxedSdk)
+
+ val managerCompat = SdkSandboxManagerCompat.from(mContext)
+
+ val result = runBlocking {
+ managerCompat.loadSdk("test", Bundle())
+ }
+
+ assertThat(result.getInterface()).isEqualTo(sandboxedSdk.getInterface())
+ }
+
+ @Test
+ fun loadSdk_whenNoLocalSdkExistsAndSandboxAvailable_rethrowsExceptionFromPlatformLoadSdk() {
+ val sdkSandboxManager = mockSandboxManager(mContext)
+
+ val loadSdkException = LoadSdkException(
+ RuntimeException(),
+ Bundle()
+ )
+ setupLoadSdkAnswer(sdkSandboxManager, loadSdkException)
+
+ val managerCompat = SdkSandboxManagerCompat.from(mContext)
+
+ val result = assertThrows(LoadSdkCompatException::class.java) {
+ runBlocking {
+ managerCompat.loadSdk("test", Bundle())
+ }
+ }
+
+ assertThat(result.cause).isEqualTo(loadSdkException.cause)
+ assertThat(result.extraInformation).isEqualTo(loadSdkException.extraInformation)
+ assertThat(result.loadSdkErrorCode).isEqualTo(loadSdkException.loadSdkErrorCode)
+ }
+
+ companion object SandboxApi {
+
+ private fun isSandboxApiAvailable() =
+ AdServicesInfo.version() >= 4
+
+ private fun mockSandboxManager(spyContext: Context): SdkSandboxManager {
+ val sdkSandboxManager = Mockito.mock(SdkSandboxManager::class.java)
+ `when`(spyContext.getSystemService(SdkSandboxManager::class.java))
+ .thenReturn(sdkSandboxManager)
+ return sdkSandboxManager
+ }
+
+ private fun setupLoadSdkAnswer(
+ sdkSandboxManager: SdkSandboxManager,
+ sandboxedSdk: SandboxedSdk
+ ) {
+ val answer = { args: InvocationOnMock ->
+ val receiver = args.getArgument<OutcomeReceiver<SandboxedSdk, LoadSdkException>>(3)
+ receiver.onResult(sandboxedSdk)
+ null
+ }
+ doAnswer(answer)
+ .`when`(sdkSandboxManager).loadSdk(
+ any(),
+ any(),
+ any(),
+ any()
+ )
+ }
+
+ private fun setupLoadSdkAnswer(
+ sdkSandboxManager: SdkSandboxManager,
+ loadSdkException: LoadSdkException
+ ) {
+ val answer = { args: InvocationOnMock ->
+ val receiver = args.getArgument<OutcomeReceiver<SandboxedSdk, LoadSdkException>>(3)
+ receiver.onError(loadSdkException)
+ null
+ }
+ doAnswer(answer)
+ .`when`(sdkSandboxManager).loadSdk(
+ any(),
+ any(),
+ any(),
+ any()
+ )
+ }
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/SdkSandboxManagerCompatTest.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/SdkSandboxManagerCompatTest.kt
new file mode 100644
index 0000000..fdf6281
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/SdkSandboxManagerCompatTest.kt
@@ -0,0 +1,154 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client
+
+import android.content.Context
+import android.content.ContextWrapper
+import android.os.Build
+import android.os.Bundle
+import androidx.privacysandbox.sdkruntime.core.AdServicesInfo
+import androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException
+import androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException.Companion.LOAD_SDK_INTERNAL_ERROR
+import androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException.Companion.LOAD_SDK_SDK_DEFINED_ERROR
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SdkSuppress
+import androidx.test.filters.SmallTest
+import com.google.common.truth.Truth.assertThat
+import kotlinx.coroutines.runBlocking
+import org.junit.Assert.assertThrows
+import org.junit.Assume.assumeTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.Mockito
+import org.mockito.Mockito.any
+import org.mockito.Mockito.spy
+import org.mockito.Mockito.verify
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class SdkSandboxManagerCompatTest {
+
+ @Test
+ fun from_whenCalledOnSameContext_returnSameManager() {
+ val context = ApplicationProvider.getApplicationContext<Context>()
+
+ val managerCompat = SdkSandboxManagerCompat.from(context)
+ val managerCompat2 = SdkSandboxManagerCompat.from(context)
+
+ assertThat(managerCompat2).isSameInstanceAs(managerCompat)
+ }
+
+ @Test
+ fun from_whenCalledOnDifferentContext_returnDifferentManager() {
+ val context = ApplicationProvider.getApplicationContext<Context>()
+ val context2 = ContextWrapper(context)
+
+ val managerCompat = SdkSandboxManagerCompat.from(context)
+ val managerCompat2 = SdkSandboxManagerCompat.from(context2)
+
+ assertThat(managerCompat2).isNotSameInstanceAs(managerCompat)
+ }
+
+ @Test
+ // TODO(b/249982507) DexmakerMockitoInline requires P+. Rewrite to support P-
+ @SdkSuppress(minSdkVersion = Build.VERSION_CODES.P)
+ fun loadSdk_whenNoLocalSdkExistsAndSandboxNotAvailable_notDelegateToSandbox() {
+ // TODO(b/262577044) Replace with @SdkSuppress after supporting maxExtensionVersion
+ assumeTrue("Requires Sandbox API not available", isSandboxApiNotAvailable())
+
+ val context = spy(ApplicationProvider.getApplicationContext<Context>())
+ val managerCompat = SdkSandboxManagerCompat.from(context)
+
+ assertThrows(LoadSdkCompatException::class.java) {
+ runBlocking {
+ managerCompat.loadSdk("sdk-not-exists", Bundle())
+ }
+ }
+
+ verify(context, Mockito.never()).getSystemService(any())
+ }
+
+ @Test
+ fun loadSdk_whenNoLocalSdkExistsAndSandboxNotAvailable_throwsSdkNotFoundException() {
+ // TODO(b/262577044) Replace with @SdkSuppress after supporting maxExtensionVersion
+ assumeTrue("Requires Sandbox API not available", isSandboxApiNotAvailable())
+
+ val context = ApplicationProvider.getApplicationContext<Context>()
+ val managerCompat = SdkSandboxManagerCompat.from(context)
+
+ val result = assertThrows(LoadSdkCompatException::class.java) {
+ runBlocking {
+ managerCompat.loadSdk("sdk-not-exists", Bundle())
+ }
+ }
+
+ assertThat(result.loadSdkErrorCode)
+ .isEqualTo(LoadSdkCompatException.LOAD_SDK_NOT_FOUND)
+ }
+
+ @Test
+ fun loadSdk_whenLocalSdkExists_returnResultFromCompatLoadSdk() {
+ val context = ApplicationProvider.getApplicationContext<Context>()
+ val managerCompat = SdkSandboxManagerCompat.from(context)
+
+ val result = runBlocking {
+ managerCompat.loadSdk("androidx.privacysandbox.sdkruntime.test.v1", Bundle())
+ }
+
+ assertThat(result.getInterface()!!.javaClass.classLoader)
+ .isNotSameInstanceAs(managerCompat.javaClass.classLoader)
+ }
+
+ @Test
+ fun loadSdk_whenLocalSdkExists_rethrowsExceptionFromCompatLoadSdk() {
+ val context = ApplicationProvider.getApplicationContext<Context>()
+ val managerCompat = SdkSandboxManagerCompat.from(context)
+
+ val params = Bundle()
+ params.putBoolean("needFail", true)
+
+ val result = assertThrows(LoadSdkCompatException::class.java) {
+ runBlocking {
+ managerCompat.loadSdk("androidx.privacysandbox.sdkruntime.test.v1", params)
+ }
+ }
+
+ assertThat(result.extraInformation).isEqualTo(params)
+ assertThat(result.loadSdkErrorCode).isEqualTo(LOAD_SDK_SDK_DEFINED_ERROR)
+ }
+
+ @Test
+ fun loadSdk_whenLocalSdkFailedToLoad_throwsInternalErrorException() {
+ val context = ApplicationProvider.getApplicationContext<Context>()
+ val managerCompat = SdkSandboxManagerCompat.from(context)
+
+ val result = assertThrows(LoadSdkCompatException::class.java) {
+ runBlocking {
+ managerCompat.loadSdk(
+ sdkName = "androidx.privacysandbox.sdkruntime.test.invalidEntryPoint",
+ params = Bundle()
+ )
+ }
+ }
+
+ assertThat(result.loadSdkErrorCode).isEqualTo(LOAD_SDK_INTERNAL_ERROR)
+ assertThat(result.message).isEqualTo("Failed to instantiate local SDK")
+ }
+
+ private fun isSandboxApiNotAvailable() =
+ AdServicesInfo.version() < 4
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/config/LocalSdkConfigParserTest.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/config/LocalSdkConfigParserTest.kt
new file mode 100644
index 0000000..541d137
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/config/LocalSdkConfigParserTest.kt
@@ -0,0 +1,247 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.config
+
+import androidx.privacysandbox.sdkruntime.client.config.LocalSdkConfigParser.Companion.parse
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import androidx.testutils.assertThrows
+import com.google.common.truth.Truth.assertThat
+import java.io.ByteArrayInputStream
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.xmlpull.v1.XmlPullParserException
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class LocalSdkConfigParserTest {
+
+ @Test
+ fun parse_skipUnknownTagsAndReturnParsedResult() {
+ val xml = """
+ <compat-config>
+ <compat-entrypoint>compat.sdk.provider</compat-entrypoint>
+ <unknown-tag>new parameter from future library version</unknown-tag>
+ <dex-path>1.dex</dex-path>
+ <future-version-tag>
+ <unknown-tag>new inner tag</unknown-tag>
+ </future-version-tag>
+ <dex-path>2.dex</dex-path>
+ <java-resources-root-path>javaResPath/</java-resources-root-path>
+ <resource-id-remapping>
+ <unknown-tag>new remapping tag</unknown-tag>
+ <r-package-class>com.test.sdk.RPackage</r-package-class>
+ <resources-package-id>42</resources-package-id>
+ </resource-id-remapping>
+ </compat-config>
+ """.trimIndent()
+
+ val result = tryParse(xml, packageName = "com.test.sdk.package")
+
+ assertThat(result)
+ .isEqualTo(
+ LocalSdkConfig(
+ packageName = "com.test.sdk.package",
+ dexPaths = listOf("1.dex", "2.dex"),
+ entryPoint = "compat.sdk.provider",
+ javaResourcesRoot = "javaResPath/",
+ resourceRemapping = ResourceRemappingConfig(
+ rPackageClassName = "com.test.sdk.RPackage",
+ packageId = 42
+ )
+ )
+ )
+ }
+
+ @Test
+ fun parse_whenOnlyMandatoryElements_returnParsedResult() {
+ val xml = """
+ <compat-config>
+ <compat-entrypoint>compat.sdk.provider</compat-entrypoint>
+ <dex-path>1.dex</dex-path>
+ </compat-config>
+ """.trimIndent()
+
+ val result = tryParse(xml, packageName = "com.test.sdk.package")
+
+ assertThat(result)
+ .isEqualTo(
+ LocalSdkConfig(
+ packageName = "com.test.sdk.package",
+ dexPaths = listOf("1.dex"),
+ entryPoint = "compat.sdk.provider",
+ javaResourcesRoot = null,
+ resourceRemapping = null
+ )
+ )
+ }
+
+ @Test
+ fun parse_whenNoEntryPoint_throwsException() {
+ assertParsingFailWithReason(
+ xml = """
+ <compat-config>
+ <dex-path>1.dex</dex-path>
+ </compat-config>
+ """.trimIndent(),
+ reason = "No compat-entrypoint tag found"
+ )
+ }
+
+ @Test
+ fun parse_whenDuplicateEntryPoint_throwsException() {
+ assertParsingFailWithReason(
+ xml = """
+ <compat-config>
+ <compat-entrypoint>compat.sdk.provider</compat-entrypoint>
+ <compat-entrypoint>compat.sdk.provider2</compat-entrypoint>
+ <dex-path>1.dex</dex-path>
+ </compat-config>
+ """.trimIndent(),
+ reason = "Duplicate compat-entrypoint tag found"
+ )
+ }
+
+ @Test
+ fun parse_whenNoDexPath_throwsException() {
+ assertParsingFailWithReason(
+ xml = """
+ <compat-config>
+ <compat-entrypoint>compat.sdk.provider</compat-entrypoint>
+ </compat-config>
+ """.trimIndent(),
+ reason = "No dex-path tags found"
+ )
+ }
+
+ @Test
+ fun parse_whenDuplicateJavaResourceRoot_throwsException() {
+ assertParsingFailWithReason(
+ xml = """
+ <compat-config>
+ <compat-entrypoint>compat.sdk.provider</compat-entrypoint>
+ <dex-path>1.dex</dex-path>
+ <java-resources-root-path>path1/</java-resources-root-path>
+ <java-resources-root-path>path2/</java-resources-root-path>
+ </compat-config>
+ """.trimIndent(),
+ reason = "Duplicate java-resources-root-path tag found"
+ )
+ }
+
+ @Test
+ fun parse_whenDuplicateResourceRemapping_throwsException() {
+ assertParsingFailWithReason(
+ xml = """
+ <compat-config>
+ <compat-entrypoint>compat.sdk.provider</compat-entrypoint>
+ <dex-path>1.dex</dex-path>
+ <resource-id-remapping>
+ <r-package-class>com.test.sdk.RPackage</r-package-class>
+ <resources-package-id>42</resources-package-id>
+ </resource-id-remapping>
+ <resource-id-remapping>
+ <r-package-class>com.test.sdk.RPackage</r-package-class>
+ <resources-package-id>42</resources-package-id>
+ </resource-id-remapping>
+ </compat-config>
+ """.trimIndent(),
+ reason = "Duplicate resource-id-remapping tag found"
+ )
+ }
+
+ @Test
+ fun parse_whenNoClassInResourceRemapping_throwsException() {
+ assertParsingFailWithReason(
+ xml = """
+ <compat-config>
+ <compat-entrypoint>compat.sdk.provider</compat-entrypoint>
+ <dex-path>1.dex</dex-path>
+ <resource-id-remapping>
+ <resources-package-id>42</resources-package-id>
+ </resource-id-remapping>
+ </compat-config>
+ """.trimIndent(),
+ reason = "No r-package-class tag found"
+ )
+ }
+
+ @Test
+ fun parse_whenDuplicateClassInResourceRemapping_throwsException() {
+ assertParsingFailWithReason(
+ xml = """
+ <compat-config>
+ <compat-entrypoint>compat.sdk.provider</compat-entrypoint>
+ <dex-path>1.dex</dex-path>
+ <resource-id-remapping>
+ <r-package-class>com.test.sdk.RPackage</r-package-class>
+ <r-package-class>com.test.sdk.RPackage</r-package-class>
+ <resources-package-id>42</resources-package-id>
+ </resource-id-remapping>
+ </compat-config>
+ """.trimIndent(),
+ reason = "Duplicate r-package-class tag found"
+ )
+ }
+
+ @Test
+ fun parse_whenNoPackageIdInResourceRemapping_throwsException() {
+ assertParsingFailWithReason(
+ xml = """
+ <compat-config>
+ <compat-entrypoint>compat.sdk.provider</compat-entrypoint>
+ <dex-path>1.dex</dex-path>
+ <resource-id-remapping>
+ <r-package-class>com.test.sdk.RPackage</r-package-class>
+ </resource-id-remapping>
+ </compat-config>
+ """.trimIndent(),
+ reason = "No resources-package-id tag found"
+ )
+ }
+
+ @Test
+ fun parse_whenDuplicatePackageIdInResourceRemapping_throwsException() {
+ assertParsingFailWithReason(
+ xml = """
+ <compat-config>
+ <compat-entrypoint>compat.sdk.provider</compat-entrypoint>
+ <dex-path>1.dex</dex-path>
+ <resource-id-remapping>
+ <r-package-class>com.test.sdk.RPackage</r-package-class>
+ <resources-package-id>42</resources-package-id>
+ <resources-package-id>42</resources-package-id>
+ </resource-id-remapping>
+ </compat-config>
+ """.trimIndent(),
+ reason = "Duplicate resources-package-id tag found"
+ )
+ }
+
+ private fun assertParsingFailWithReason(xml: String, reason: String) {
+ assertThrows<XmlPullParserException> {
+ tryParse(xml)
+ }.hasMessageThat().isEqualTo(
+ reason
+ )
+ }
+
+ private fun tryParse(xml: String, packageName: String = "sdkPackageName"): LocalSdkConfig {
+ ByteArrayInputStream(xml.toByteArray()).use { inputStream ->
+ return parse(inputStream, packageName)
+ }
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/config/LocalSdkConfigsHolderTest.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/config/LocalSdkConfigsHolderTest.kt
new file mode 100644
index 0000000..0b51558
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/config/LocalSdkConfigsHolderTest.kt
@@ -0,0 +1,70 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.config
+
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class LocalSdkConfigsHolderTest {
+
+ @Test
+ fun load_whenSdkTableNotExists_doesNotThrowException() {
+ val configHolder = LocalSdkConfigsHolder.load(
+ ApplicationProvider.getApplicationContext(),
+ sdkTableAssetName = "not-exists"
+ )
+ val result = configHolder.getSdkConfig("sdk")
+ assertThat(result).isNull()
+ }
+
+ @Test
+ fun getSdkConfig_whenSdkExists_returnSdkInfo() {
+ val configHolder = LocalSdkConfigsHolder.load(
+ ApplicationProvider.getApplicationContext()
+ )
+
+ val result = configHolder.getSdkConfig(
+ "androidx.privacysandbox.sdkruntime.test.v1"
+ )
+
+ assertThat(result)
+ .isEqualTo(
+ LocalSdkConfig(
+ packageName = "androidx.privacysandbox.sdkruntime.test.v1",
+ dexPaths = listOf("RuntimeEnabledSdks/V1/classes.dex"),
+ entryPoint = "androidx.privacysandbox.sdkruntime.test.v1.CompatProvider",
+ javaResourcesRoot = "RuntimeEnabledSdks/V1/javaresources"
+ )
+ )
+ }
+
+ @Test
+ fun getSdkConfig_whenSdkNotExists_returnNull() {
+ val configHolder = LocalSdkConfigsHolder.load(
+ ApplicationProvider.getApplicationContext()
+ )
+
+ val result = configHolder.getSdkConfig("not-exists")
+
+ assertThat(result).isNull()
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/config/SdkTableConfigParserTest.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/config/SdkTableConfigParserTest.kt
new file mode 100644
index 0000000..e646377
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/config/SdkTableConfigParserTest.kt
@@ -0,0 +1,173 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.config
+
+import androidx.privacysandbox.sdkruntime.client.config.SdkTableConfigParser.Companion.parse
+import androidx.privacysandbox.sdkruntime.client.config.SdkTableConfigParser.SdkTableEntry
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import androidx.testutils.assertThrows
+import com.google.common.truth.Truth.assertThat
+import java.io.ByteArrayInputStream
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.xmlpull.v1.XmlPullParserException
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class SdkTableConfigParserTest {
+
+ @Test
+ fun parse_skipUnknownTagsAndReturnSetWithSdkTableEntries() {
+ val xml = """
+ <runtime-enabled-sdk-table>
+ <runtime-enabled-sdk>
+ <package-name>sdk1</package-name>
+ <unknown-tag>new parameter from future library version</unknown-tag>
+ <compat-config-path>config1.xml</compat-config-path>
+ </runtime-enabled-sdk>
+ <future-version-runtime-enabled-sdk>
+ <unknown-tag>new sdk type without old tags</unknown-tag>
+ </future-version-runtime-enabled-sdk>
+ <runtime-enabled-sdk>
+ <unknown-tag2>new parameter from future library version</unknown-tag2>
+ <package-name>sdk2</package-name>
+ <compat-config-path>config2.xml</compat-config-path>
+ </runtime-enabled-sdk>
+ </runtime-enabled-sdk-table>
+ """.trimIndent()
+
+ val result = tryParse(xml)
+
+ assertThat(result)
+ .containsExactly(
+ SdkTableEntry("sdk1", "config1.xml"),
+ SdkTableEntry("sdk2", "config2.xml")
+ )
+ }
+
+ @Test
+ fun parse_whenEmptyTable_returnsEmptyMap() {
+ val xml = """
+ <runtime-enabled-sdk-table>
+ </runtime-enabled-sdk-table>
+ """.trimIndent()
+
+ val result = tryParse(xml)
+
+ assertThat(result).isEmpty()
+ }
+
+ @Test
+ fun parse_whenNoPackageName_throwsException() {
+ val xml = """
+ <runtime-enabled-sdk-table>
+ <runtime-enabled-sdk>
+ <compat-config-path>config1.xml</compat-config-path>
+ </runtime-enabled-sdk>
+ </runtime-enabled-sdk-table>
+ """.trimIndent()
+
+ assertThrows<XmlPullParserException> {
+ tryParse(xml)
+ }.hasMessageThat().isEqualTo(
+ "No package-name tag found"
+ )
+ }
+
+ @Test
+ fun parse_whenMultiplePackageNames_throwsException() {
+ val xml = """
+ <runtime-enabled-sdk-table>
+ <runtime-enabled-sdk>
+ <package-name>sdk1</package-name>
+ <package-name>sdk2</package-name>
+ <compat-config-path>config1.xml</compat-config-path>
+ </runtime-enabled-sdk>
+ </runtime-enabled-sdk-table>
+ """.trimIndent()
+
+ assertThrows<XmlPullParserException> {
+ tryParse(xml)
+ }.hasMessageThat().isEqualTo(
+ "Duplicate package-name tag found"
+ )
+ }
+
+ @Test
+ fun parse_whenNoConfigPath_throwsException() {
+ val xml = """
+ <runtime-enabled-sdk-table>
+ <runtime-enabled-sdk>
+ <package-name>sdk1</package-name>
+ </runtime-enabled-sdk>
+ </runtime-enabled-sdk-table>
+ """.trimIndent()
+
+ assertThrows<XmlPullParserException> {
+ tryParse(xml)
+ }.hasMessageThat().isEqualTo(
+ "No compat-config-path tag found"
+ )
+ }
+
+ @Test
+ fun parse_whenMultipleConfigPaths_throwsException() {
+ val xml = """
+ <runtime-enabled-sdk-table>
+ <runtime-enabled-sdk>
+ <package-name>sdk1</package-name>
+ <compat-config-path>config1.xml</compat-config-path>
+ <compat-config-path>config2.xml</compat-config-path>
+ </runtime-enabled-sdk>
+ </runtime-enabled-sdk-table>
+ """.trimIndent()
+
+ assertThrows<XmlPullParserException> {
+ tryParse(xml)
+ }.hasMessageThat().isEqualTo(
+ "Duplicate compat-config-path tag found"
+ )
+ }
+
+ @Test
+ fun parse_whenDuplicatePackageName_throwsException() {
+ val xml = """
+ <runtime-enabled-sdk-table>
+ <runtime-enabled-sdk>
+ <package-name>sdk1</package-name>
+ <compat-config-path>config1.xml</compat-config-path>
+ </runtime-enabled-sdk>
+ <runtime-enabled-sdk>
+ <package-name>sdk1</package-name>
+ <compat-config-path>config2.xml</compat-config-path>
+ </runtime-enabled-sdk>
+ </runtime-enabled-sdk-table>
+ """.trimIndent()
+
+ assertThrows<XmlPullParserException> {
+ tryParse(xml)
+ }.hasMessageThat().isEqualTo(
+ "Duplicate entry for sdk1 found"
+ )
+ }
+
+ private fun tryParse(xml: String): Set<SdkTableEntry> {
+ ByteArrayInputStream(xml.toByteArray()).use { inputStream ->
+ return parse(inputStream)
+ }
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/FileClassLoaderFactoryTest.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/FileClassLoaderFactoryTest.kt
new file mode 100644
index 0000000..31fee55
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/FileClassLoaderFactoryTest.kt
@@ -0,0 +1,145 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.loader
+
+import android.content.Context
+import androidx.privacysandbox.sdkruntime.client.config.LocalSdkConfig
+import androidx.privacysandbox.sdkruntime.client.loader.storage.LocalSdkStorage
+import androidx.privacysandbox.sdkruntime.client.loader.storage.LocalSdkDexFiles
+import androidx.privacysandbox.sdkruntime.client.loader.storage.TestLocalSdkStorage
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.google.common.truth.Truth.assertThat
+import java.io.File
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class FileClassLoaderFactoryTest {
+
+ private lateinit var testSdkConfig: LocalSdkConfig
+
+ @Before
+ fun setUp() {
+ testSdkConfig = LocalSdkConfig(
+ packageName = "androidx.privacysandbox.sdkruntime.test.v1",
+ dexPaths = listOf(
+ "RuntimeEnabledSdks/V1/classes.dex",
+ ),
+ entryPoint = "androidx.privacysandbox.sdkruntime.test.v1.CompatProvider",
+ )
+ }
+
+ @Test
+ fun createClassLoaderFor_whenSdkStorageReturnFiles_returnClassloaderAndNotDelegateToFallback() {
+ val sdkDexFiles = extractTestSdkDexFiles()
+ val fallback = TestFallbackFactory()
+
+ val fileClassLoaderFactory = FileClassLoaderFactory(
+ StubSdkStorage(result = sdkDexFiles),
+ fallback
+ )
+
+ val classLoader = fileClassLoaderFactory.createClassLoaderFor(
+ testSdkConfig,
+ javaClass.classLoader!!.parent!!
+ )
+
+ val loadedEntryPointClass = classLoader.loadClass(testSdkConfig.entryPoint)
+ assertThat(loadedEntryPointClass.classLoader).isEqualTo(classLoader)
+
+ assertThat(fallback.loadSdkCalled).isFalse()
+ }
+
+ @Test
+ fun createClassLoaderFor_whenSdkStorageReturnNull_delegateToFallback() {
+ val fallback = TestFallbackFactory(testSdkConfig, javaClass.classLoader!!.parent)
+ val fileClassLoaderFactory = FileClassLoaderFactory(
+ StubSdkStorage(result = null),
+ fallback
+ )
+
+ fileClassLoaderFactory.createClassLoaderFor(
+ testSdkConfig,
+ javaClass.classLoader!!.parent!!
+ )
+
+ assertThat(fallback.loadSdkCalled).isTrue()
+ }
+
+ @Test
+ fun createClassLoaderFor_whenSdkStorageThrows_delegateToFallback() {
+ val fallback = TestFallbackFactory(testSdkConfig, javaClass.classLoader!!.parent)
+ val fileClassLoaderFactory = FileClassLoaderFactory(
+ ThrowingSdkStorage(exception = Exception("Something wrong")),
+ fallback
+ )
+
+ fileClassLoaderFactory.createClassLoaderFor(
+ testSdkConfig,
+ javaClass.classLoader!!.parent!!
+ )
+
+ assertThat(fallback.loadSdkCalled).isTrue()
+ }
+
+ private class StubSdkStorage(
+ private val result: LocalSdkDexFiles?
+ ) : LocalSdkStorage {
+ override fun dexFilesFor(sdkConfig: LocalSdkConfig) = result
+ }
+
+ private class ThrowingSdkStorage(
+ private val exception: Exception
+ ) : LocalSdkStorage {
+ override fun dexFilesFor(sdkConfig: LocalSdkConfig): LocalSdkDexFiles? {
+ throw exception
+ }
+ }
+
+ private class TestFallbackFactory(
+ private val expectedSdkConfig: LocalSdkConfig? = null,
+ private val expectedParent: ClassLoader? = null,
+ ) : SdkLoader.ClassLoaderFactory {
+
+ var loadSdkCalled: Boolean = false
+
+ override fun createClassLoaderFor(
+ sdkConfig: LocalSdkConfig,
+ parent: ClassLoader
+ ): ClassLoader {
+ assertThat(sdkConfig).isEqualTo(expectedSdkConfig)
+ assertThat(parent).isEqualTo(expectedParent)
+ loadSdkCalled = true
+ return parent
+ }
+ }
+
+ private fun extractTestSdkDexFiles(): LocalSdkDexFiles {
+ val context = ApplicationProvider.getApplicationContext<Context>()
+
+ val testStorage = TestLocalSdkStorage(
+ context,
+ rootFolder = File(context.cacheDir, "FileClassLoaderFactoryTest")
+ )
+
+ return testStorage.dexFilesFor(testSdkConfig)
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/InMemorySdkClassLoaderFactoryTest.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/InMemorySdkClassLoaderFactoryTest.kt
new file mode 100644
index 0000000..93aec37
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/InMemorySdkClassLoaderFactoryTest.kt
@@ -0,0 +1,78 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.loader
+
+import android.os.Build
+import androidx.privacysandbox.sdkruntime.client.config.LocalSdkConfig
+import androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SdkSuppress
+import androidx.test.filters.SmallTest
+import com.google.common.truth.Truth.assertThat
+import org.junit.Assert.assertThrows
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class InMemorySdkClassLoaderFactoryTest {
+
+ private lateinit var factoryUnderTest: InMemorySdkClassLoaderFactory
+ private lateinit var testSdkInfo: LocalSdkConfig
+
+ @Before
+ fun setUp() {
+ factoryUnderTest = InMemorySdkClassLoaderFactory.create(
+ ApplicationProvider.getApplicationContext()
+ )
+ testSdkInfo = LocalSdkConfig(
+ packageName = "androidx.privacysandbox.sdkruntime.test.v1",
+ dexPaths = listOf("RuntimeEnabledSdks/V1/classes.dex"),
+ entryPoint = "androidx.privacysandbox.sdkruntime.test.v1.CompatProvider",
+ javaResourcesRoot = "RuntimeEnabledSdks/V1/"
+ )
+ }
+
+ @Test
+ @SdkSuppress(minSdkVersion = Build.VERSION_CODES.O_MR1)
+ fun createClassLoaderFor_whenApi27_returnClassloader() {
+ val classLoader = factoryUnderTest.createClassLoaderFor(
+ testSdkInfo,
+ javaClass.classLoader!!
+ )
+ val loadedEntryPointClass = classLoader.loadClass(testSdkInfo.entryPoint)
+ assertThat(loadedEntryPointClass.classLoader).isEqualTo(classLoader)
+ }
+
+ @Test
+ @SdkSuppress(maxSdkVersion = Build.VERSION_CODES.O)
+ fun createClassLoaderFor_whenApiPre27_throwsSandboxDisabledException() {
+ val ex = assertThrows(LoadSdkCompatException::class.java) {
+ factoryUnderTest.createClassLoaderFor(
+ testSdkInfo,
+ javaClass.classLoader!!
+ )
+ }
+
+ assertThat(ex.loadSdkErrorCode)
+ .isEqualTo(LoadSdkCompatException.LOAD_SDK_SDK_SANDBOX_DISABLED)
+ assertThat(ex)
+ .hasMessageThat()
+ .isEqualTo("Can't use InMemoryDexClassLoader")
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/JavaResourcesLoadingClassLoaderFactoryTest.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/JavaResourcesLoadingClassLoaderFactoryTest.kt
new file mode 100644
index 0000000..3da2c8b
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/JavaResourcesLoadingClassLoaderFactoryTest.kt
@@ -0,0 +1,114 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.loader
+
+import androidx.privacysandbox.sdkruntime.client.config.LocalSdkConfig
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.google.common.truth.Truth.assertThat
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class JavaResourcesLoadingClassLoaderFactoryTest {
+
+ private lateinit var appClassloader: ClassLoader
+ private lateinit var factoryUnderTest: JavaResourcesLoadingClassLoaderFactory
+ private lateinit var testSdkConfig: LocalSdkConfig
+
+ @Before
+ fun setUp() {
+ appClassloader = javaClass.classLoader!!
+ factoryUnderTest = JavaResourcesLoadingClassLoaderFactory(
+ appClassloader,
+ codeClassLoaderFactory = object : SdkLoader.ClassLoaderFactory {
+ override fun createClassLoaderFor(sdkConfig: LocalSdkConfig, parent: ClassLoader) =
+ parent
+ }
+ )
+ testSdkConfig = LocalSdkConfig(
+ packageName = "androidx.privacysandbox.sdkruntime.test.v1",
+ dexPaths = listOf("RuntimeEnabledSdks/V1/classes.dex"),
+ entryPoint = "androidx.privacysandbox.sdkruntime.test.v1.CompatProvider",
+ javaResourcesRoot = "RuntimeEnabledSdks/V1/javaresources"
+ )
+ }
+
+ @Test
+ fun getResource_delegateToAppClassloaderWithPrefix() {
+ val classLoader = factoryUnderTest.createClassLoaderFor(
+ testSdkConfig,
+ appClassloader.parent!!
+ )
+ val resource = classLoader.getResource("test.txt")
+
+ val appResource = appClassloader.getResource(
+ "assets/RuntimeEnabledSdks/V1/javaresources/test.txt"
+ )
+ assertThat(resource).isNotNull()
+ assertThat(resource).isEqualTo(appResource)
+ }
+
+ @Test
+ fun getResource_whenAppResource_returnNull() {
+ val classLoader = factoryUnderTest.createClassLoaderFor(
+ testSdkConfig,
+ appClassloader.parent!!
+ )
+
+ val resource = classLoader.getResource("assets/RuntimeEnabledSdkTable.xml")
+ val appResource = appClassloader.getResource("assets/RuntimeEnabledSdkTable.xml")
+
+ assertThat(appResource).isNotNull()
+ assertThat(resource).isNull()
+ }
+
+ @Test
+ fun getResources_delegateToAppClassloaderWithPrefix() {
+ val classLoader = factoryUnderTest.createClassLoaderFor(
+ testSdkConfig,
+ appClassloader.parent!!
+ )
+
+ val resources = classLoader
+ .getResources("test.txt")
+ .toList()
+ assertThat(resources.isEmpty()).isFalse()
+
+ val appResources = appClassloader
+ .getResources("assets/RuntimeEnabledSdks/V1/javaresources/test.txt")
+ .toList()
+
+ assertThat(appResources).isEqualTo(resources)
+ }
+
+ @Test
+ fun getResources_whenAppResource_returnEmpty() {
+ val classLoader = factoryUnderTest.createClassLoaderFor(
+ testSdkConfig,
+ appClassloader.parent!!
+ )
+
+ val resources = classLoader.getResources("assets/RuntimeEnabledSdkTable.xml")
+ val appResources = appClassloader.getResources("assets/RuntimeEnabledSdkTable.xml")
+
+ assertThat(appResources.hasMoreElements()).isTrue()
+ assertThat(resources.hasMoreElements()).isFalse()
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/LocalSdkTest.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/LocalSdkTest.kt
new file mode 100644
index 0000000..37635f0
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/LocalSdkTest.kt
@@ -0,0 +1,237 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.loader
+
+import android.content.Context
+import android.os.Binder
+import android.os.Bundle
+import android.view.View
+import androidx.privacysandbox.sdkruntime.client.config.LocalSdkConfig
+import androidx.privacysandbox.sdkruntime.client.loader.impl.SandboxedSdkContextCompat
+import androidx.privacysandbox.sdkruntime.client.loader.storage.TestLocalSdkStorage
+import androidx.privacysandbox.sdkruntime.client.loader.storage.toClassPathString
+import androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException
+import androidx.privacysandbox.sdkruntime.core.SandboxedSdkCompat
+import androidx.privacysandbox.sdkruntime.core.SandboxedSdkProviderCompat
+import androidx.privacysandbox.sdkruntime.core.Versions
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.filters.SmallTest
+import com.google.common.truth.Truth.assertThat
+import dalvik.system.BaseDexClassLoader
+import java.io.File
+import org.junit.Assert.assertThrows
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.Parameterized
+
+@SmallTest
+@RunWith(Parameterized::class)
+internal class LocalSdkTest(
+ @Suppress("unused") private val sdkPath: String,
+ @Suppress("unused") private val sdkVersion: Int,
+ private val loadedSdk: LocalSdk
+) {
+
+ @Test
+ fun loadSdk_attachCorrectContext() {
+ val sdkContext = loadedSdk.extractSdkContext()
+ assertThat(sdkContext.javaClass.name)
+ .isEqualTo(SandboxedSdkContextCompat::class.java.name)
+ }
+
+ @Test
+ fun onLoadSdk_callOnLoadSdkAndReturnResult() {
+ val params = Bundle()
+
+ val sandboxedSdkCompat = loadedSdk.onLoadSdk(params)
+
+ val expectedBinder = loadedSdk.extractSdkProviderFieldValue<Binder>(
+ fieldName = "onLoadSdkBinder",
+ )
+ assertThat(sandboxedSdkCompat.getInterface()).isEqualTo(expectedBinder)
+
+ val lastParams = loadedSdk.extractSdkProviderFieldValue<Bundle>(
+ fieldName = "lastOnLoadSdkParams",
+ )
+ assertThat(lastParams).isEqualTo(params)
+ }
+
+ @Test
+ fun onLoadSdk_callOnLoadSdkAndThrowException() {
+ val params = Bundle()
+ params.putBoolean("needFail", true)
+
+ val ex = assertThrows(LoadSdkCompatException::class.java) {
+ loadedSdk.onLoadSdk(params)
+ }
+
+ assertThat(ex.extraInformation).isEqualTo(params)
+ }
+
+ @Test
+ fun beforeUnloadSdk_callBeforeUnloadSdk() {
+ loadedSdk.beforeUnloadSdk()
+
+ val isBeforeUnloadSdkCalled = loadedSdk.extractSdkProviderFieldValue<Boolean>(
+ fieldName = "isBeforeUnloadSdkCalled"
+ )
+
+ assertThat(isBeforeUnloadSdkCalled).isTrue()
+ }
+
+ class CurrentVersionProviderLoadTest : SandboxedSdkProviderCompat() {
+ @JvmField
+ val onLoadSdkBinder = Binder()
+
+ @JvmField
+ var lastOnLoadSdkParams: Bundle? = null
+
+ @JvmField
+ var isBeforeUnloadSdkCalled = false
+
+ @Throws(LoadSdkCompatException::class)
+ override fun onLoadSdk(params: Bundle): SandboxedSdkCompat {
+ lastOnLoadSdkParams = params
+ if (params.getBoolean("needFail", false)) {
+ throw LoadSdkCompatException(RuntimeException(), params)
+ }
+ return SandboxedSdkCompat(onLoadSdkBinder)
+ }
+
+ override fun beforeUnloadSdk() {
+ isBeforeUnloadSdkCalled = true
+ }
+
+ override fun getView(
+ windowContext: Context,
+ params: Bundle,
+ width: Int,
+ height: Int
+ ): View {
+ return View(windowContext)
+ }
+ }
+
+ internal class TestClassLoaderFactory(
+ private val testStorage: TestLocalSdkStorage
+ ) : SdkLoader.ClassLoaderFactory {
+ override fun createClassLoaderFor(
+ sdkConfig: LocalSdkConfig,
+ parent: ClassLoader
+ ): ClassLoader {
+ val sdkDexFiles = testStorage.dexFilesFor(sdkConfig)
+
+ val optimizedDirectory = File(sdkDexFiles.files[0].parentFile, "DexOpt")
+ if (!optimizedDirectory.exists()) {
+ optimizedDirectory.mkdirs()
+ }
+
+ return BaseDexClassLoader(
+ sdkDexFiles.toClassPathString(),
+ optimizedDirectory,
+ /* librarySearchPath = */ null,
+ parent
+ )
+ }
+ }
+
+ internal class TestSdkInfo internal constructor(
+ val apiVersion: Int,
+ dexPath: String,
+ sdkProviderClass: String
+ ) {
+ val localSdkConfig = LocalSdkConfig(
+ packageName = "test.$apiVersion.$sdkProviderClass",
+ dexPaths = listOf(dexPath),
+ entryPoint = sdkProviderClass
+ )
+ }
+
+ companion object {
+ private val SDKS = arrayOf(
+ TestSdkInfo(
+ 1,
+ "RuntimeEnabledSdks/V1/classes.dex",
+ "androidx.privacysandbox.sdkruntime.test.v1.CompatProvider"
+ )
+ )
+
+ @Parameterized.Parameters(name = "sdk: {0}, version: {1}")
+ @JvmStatic
+ fun params(): List<Array<Any>> = buildList {
+ assertThat(SDKS.size).isEqualTo(Versions.API_VERSION)
+
+ val assetsSdkLoader = createAssetsSdkLoader()
+ for (i in SDKS.indices) {
+ val sdk = SDKS[i]
+ assertThat(sdk.apiVersion).isEqualTo(i + 1)
+
+ val loadedSdk = assetsSdkLoader.loadSdk(sdk.localSdkConfig)
+ assertThat(loadedSdk.extractApiVersion())
+ .isEqualTo(sdk.apiVersion)
+
+ add(
+ arrayOf(
+ sdk.localSdkConfig.dexPaths[0],
+ sdk.apiVersion,
+ loadedSdk
+ )
+ )
+ }
+
+ // add SDK loaded from test sources
+ add(
+ arrayOf(
+ "BuiltFromSource",
+ Versions.API_VERSION,
+ loadTestSdkFromSource(),
+ )
+ )
+ }
+
+ private fun loadTestSdkFromSource(): LocalSdk {
+ val sdkLoader = SdkLoader(
+ object : SdkLoader.ClassLoaderFactory {
+ override fun createClassLoaderFor(
+ sdkConfig: LocalSdkConfig,
+ parent: ClassLoader
+ ): ClassLoader = javaClass.classLoader!!
+ },
+ ApplicationProvider.getApplicationContext()
+ )
+
+ return sdkLoader.loadSdk(
+ LocalSdkConfig(
+ packageName = "test.CurrentVersionProviderLoadTest",
+ dexPaths = emptyList(),
+ entryPoint = CurrentVersionProviderLoadTest::class.java.name
+ )
+ )
+ }
+
+ private fun createAssetsSdkLoader(): SdkLoader {
+ val context = ApplicationProvider.getApplicationContext<Context>()
+ val testStorage = TestLocalSdkStorage(
+ context,
+ rootFolder = File(context.cacheDir, "LocalSdkTest")
+ )
+ return SdkLoader(
+ TestClassLoaderFactory(testStorage),
+ context
+ )
+ }
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/LocalSdkTestUtils.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/LocalSdkTestUtils.kt
new file mode 100644
index 0000000..0cfa817
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/LocalSdkTestUtils.kt
@@ -0,0 +1,72 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.loader
+
+import android.content.Context
+import androidx.privacysandbox.sdkruntime.core.Versions
+import androidx.privacysandbox.sdkruntime.core.SandboxedSdkProviderCompat
+import kotlin.reflect.cast
+
+/**
+ * Extract value of [Versions.API_VERSION] from loaded SDK.
+ */
+internal fun LocalSdk.extractApiVersion(): Int =
+ extractVersionValue("API_VERSION")
+
+/**
+ * Extract value of [Versions.CLIENT_VERSION] from loaded SDK.
+ */
+internal fun LocalSdk.extractClientVersion(): Int =
+ extractVersionValue("CLIENT_VERSION")
+
+/**
+ * Extract [SandboxedSdkProviderCompat.context] from loaded SDK.
+ */
+internal fun LocalSdk.extractSdkContext(): Context {
+ val getContextMethod = sdkProvider
+ .javaClass
+ .getMethod("getContext")
+
+ val rawContext = getContextMethod.invoke(sdkProvider)
+
+ return Context::class.cast(rawContext)
+}
+
+/**
+ * Extract field value from [SandboxedSdkProviderCompat]
+ */
+internal inline fun <reified T> LocalSdk.extractSdkProviderFieldValue(fieldName: String): T {
+ return sdkProvider
+ .javaClass
+ .getField(fieldName)
+ .get(sdkProvider)!! as T
+}
+
+/**
+ * Extract classloader that was used for loading of [SandboxedSdkProviderCompat].
+ */
+internal fun LocalSdk.extractSdkProviderClassloader(): ClassLoader =
+ sdkProvider.javaClass.classLoader!!
+
+private fun LocalSdk.extractVersionValue(versionFieldName: String): Int {
+ val versionsClass = Class.forName(
+ Versions::class.java.name,
+ false,
+ extractSdkProviderClassloader()
+ )
+ return versionsClass.getDeclaredField(versionFieldName).get(null) as Int
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/SandboxedSdkContextCompatTest.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/SandboxedSdkContextCompatTest.kt
new file mode 100644
index 0000000..11c62973
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/SandboxedSdkContextCompatTest.kt
@@ -0,0 +1,41 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.loader
+
+import androidx.privacysandbox.sdkruntime.client.loader.impl.SandboxedSdkContextCompat
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class SandboxedSdkContextCompatTest {
+
+ @Test
+ fun getClassloader_returnSdkClassloader() {
+ val sdkClassLoader = javaClass.classLoader!!.parent!!
+
+ val sdkContextCompat = SandboxedSdkContextCompat(
+ ApplicationProvider.getApplicationContext(),
+ sdkClassLoader
+ )
+ assertThat(sdkContextCompat.classLoader)
+ .isEqualTo(sdkClassLoader)
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/SdkLoaderTest.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/SdkLoaderTest.kt
new file mode 100644
index 0000000..2c2b15d
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/SdkLoaderTest.kt
@@ -0,0 +1,142 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.loader
+
+import android.content.Context
+import android.os.Build
+import androidx.privacysandbox.sdkruntime.client.config.LocalSdkConfig
+import androidx.privacysandbox.sdkruntime.client.config.ResourceRemappingConfig
+import androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException
+import androidx.privacysandbox.sdkruntime.core.Versions
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SdkSuppress
+import androidx.test.filters.SmallTest
+import androidx.testutils.assertThrows
+import com.google.common.truth.Truth.assertThat
+import java.io.File
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class SdkLoaderTest {
+
+ private lateinit var sdkLoader: SdkLoader
+
+ private lateinit var testSdkConfig: LocalSdkConfig
+
+ @Before
+ fun setUp() {
+ val context = ApplicationProvider.getApplicationContext<Context>()
+ sdkLoader = SdkLoader.create(
+ context
+ )
+ testSdkConfig = LocalSdkConfig(
+ packageName = "androidx.privacysandbox.sdkruntime.test.v1",
+ dexPaths = listOf(
+ "RuntimeEnabledSdks/V1/classes.dex",
+ "RuntimeEnabledSdks/RPackage.dex"
+ ),
+ entryPoint = "androidx.privacysandbox.sdkruntime.test.v1.CompatProvider",
+ javaResourcesRoot = "RuntimeEnabledSdks/V1/javaresources",
+ resourceRemapping = ResourceRemappingConfig(
+ rPackageClassName = "androidx.privacysandbox.sdkruntime.test.RPackage",
+ packageId = 42
+ )
+ )
+
+ // Clean extracted SDKs between tests
+ File(context.cacheDir, "RuntimeEnabledSdk").deleteRecursively()
+ }
+
+ @Test
+ fun loadSdk_callVersionsHandShake() {
+ val loadedSdk = sdkLoader.loadSdk(testSdkConfig)
+
+ assertThat(loadedSdk.extractClientVersion())
+ .isEqualTo(Versions.API_VERSION)
+ }
+
+ @Test
+ fun testContextClassloader() {
+ val loadedSdk = sdkLoader.loadSdk(testSdkConfig)
+
+ val classLoader = loadedSdk.extractSdkProviderClassloader()
+ val sdkContext = loadedSdk.extractSdkContext()
+
+ assertThat(sdkContext.classLoader)
+ .isSameInstanceAs(classLoader)
+ }
+
+ @Test
+ fun testJavaResources() {
+ val loadedSdk = sdkLoader.loadSdk(testSdkConfig)
+
+ val classLoader = loadedSdk.extractSdkProviderClassloader()
+ val content = classLoader.getResourceAsStream("test.txt").use { inputStream ->
+ inputStream.bufferedReader().readLine()
+ }
+
+ assertThat(content)
+ .isEqualTo("test")
+ }
+
+ @Test
+ fun testRPackageUpdate() {
+ val loadedSdk = sdkLoader.loadSdk(testSdkConfig)
+
+ val classLoader = loadedSdk.extractSdkProviderClassloader()
+
+ val rPackageClass =
+ classLoader.loadClass("androidx.privacysandbox.sdkruntime.test.RPackage")
+
+ val packageIdField = rPackageClass.getDeclaredField("packageId")
+ val value = packageIdField.get(null)
+
+ assertThat(value).isEqualTo(42)
+ }
+
+ @Test
+ @SdkSuppress(maxSdkVersion = Build.VERSION_CODES.O)
+ fun testLowSpace_failPreApi27() {
+ val context = ApplicationProvider.getApplicationContext<Context>()
+ val sdkLoaderWithLowSpaceMode = SdkLoader.create(
+ context,
+ lowSpaceThreshold = Long.MAX_VALUE
+ )
+
+ assertThrows(LoadSdkCompatException::class.java) {
+ sdkLoaderWithLowSpaceMode.loadSdk(testSdkConfig)
+ }.hasMessageThat().isEqualTo("Can't use InMemoryDexClassLoader")
+ }
+
+ @Test
+ @SdkSuppress(minSdkVersion = Build.VERSION_CODES.O_MR1)
+ fun testLowSpace_notFailApi27() {
+ val sdkLoaderWithLowSpaceMode = SdkLoader.create(
+ ApplicationProvider.getApplicationContext(),
+ lowSpaceThreshold = Long.MAX_VALUE
+ )
+
+ val loadedSdk = sdkLoaderWithLowSpaceMode.loadSdk(testSdkConfig)
+ val classLoader = loadedSdk.extractSdkProviderClassloader()
+
+ val entryPointClass = classLoader.loadClass(testSdkConfig.entryPoint)
+ assertThat(entryPointClass).isNotNull()
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/storage/CachedLocalSdkStorageTest.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/storage/CachedLocalSdkStorageTest.kt
new file mode 100644
index 0000000..428c85f
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/storage/CachedLocalSdkStorageTest.kt
@@ -0,0 +1,192 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.loader.storage
+
+import android.content.Context
+import android.os.Environment
+import android.os.StatFs
+import androidx.privacysandbox.sdkruntime.client.config.LocalSdkConfig
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import androidx.testutils.assertThrows
+import com.google.common.truth.Truth.assertThat
+import java.io.File
+import java.io.FileNotFoundException
+import java.io.InputStream
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class CachedLocalSdkStorageTest {
+
+ private lateinit var context: Context
+
+ private lateinit var storageUnderTest: CachedLocalSdkStorage
+
+ private lateinit var testSdkConfig: LocalSdkConfig
+
+ private lateinit var sdkFolder: File
+
+ @Before
+ fun setUp() {
+ context = ApplicationProvider.getApplicationContext()
+
+ storageUnderTest = CachedLocalSdkStorage.create(
+ context,
+ lowSpaceThreshold = disabledLowSpaceModeThreshold()
+ )
+
+ testSdkConfig = LocalSdkConfig(
+ packageName = "androidx.privacysandbox.sdkruntime.test.v1",
+ dexPaths = listOf(
+ "RuntimeEnabledSdks/V1/classes.dex",
+ "RuntimeEnabledSdks/RPackage.dex"
+ ),
+ entryPoint = "androidx.privacysandbox.sdkruntime.test.v1.CompatProvider",
+ )
+
+ sdkFolder = LocalSdkFolderProvider
+ .create(context)
+ .dexFolderFor(testSdkConfig)
+
+ // Clean up between tests
+ sdkFolder.deleteRecursively()
+ sdkFolder.deleteOnExit()
+ }
+
+ @Test
+ fun dexFilesFor_extractSdkDexFilesAndMakeThemReadOnly() {
+ val dexFiles = storageUnderTest.dexFilesFor(testSdkConfig)
+ assertThat(dexFiles).isNotNull()
+ val dexList = dexFiles!!.files
+
+ assertThat(dexList.size).isEqualTo(testSdkConfig.dexPaths.size)
+ for (index in testSdkConfig.dexPaths.indices) {
+ assertAssetExtractedToReadOnlyFile(testSdkConfig.dexPaths[index], dexList[index])
+ }
+ }
+
+ @Test
+ fun dexFilesFor_whenAlreadyExtracted_returnExistingFilesWithoutModification() {
+ val firstResult = storageUnderTest.dexFilesFor(testSdkConfig)!!.files
+ val lastModifiedBefore = firstResult[0].lastModified()
+
+ // Wait some time to check that no new files will be created (same lastModified)
+ Thread.sleep(100)
+
+ val secondResult = storageUnderTest.dexFilesFor(testSdkConfig)!!.files
+ val lastModifiedAfter = secondResult[0].lastModified()
+
+ assertThat(secondResult).isEqualTo(firstResult)
+ assertThat(lastModifiedAfter).isEqualTo(lastModifiedBefore)
+ }
+
+ @Test
+ fun dexFilesFor_whenFileMissing_extractOnlyThisFile() {
+ val firstResult = storageUnderTest.dexFilesFor(testSdkConfig)!!.files
+ val fileToDelete = firstResult[0]
+ val fileToKeep = firstResult[1]
+
+ fileToDelete.delete()
+ val fileToKeepLastModified = fileToKeep.lastModified()
+
+ // Wait some time to check that existing file will not be modified (same lastModified)
+ Thread.sleep(100)
+
+ val secondResult = storageUnderTest.dexFilesFor(testSdkConfig)!!.files
+ val extractedFile = secondResult[0]
+ val notModifiedFile = secondResult[1]
+
+ assertThat(secondResult).isEqualTo(firstResult)
+ assertAssetExtractedToReadOnlyFile(testSdkConfig.dexPaths[0], extractedFile)
+ assertThat(notModifiedFile.lastModified()).isEqualTo(fileToKeepLastModified)
+ }
+
+ @Test
+ fun dexFilesFor_whenLowSpaceAndNoExtractedFiles_returnNull() {
+ val storageWithLowSpaceEnabled = CachedLocalSdkStorage.create(
+ context,
+ lowSpaceThreshold = enabledLowSpaceModeThreshold()
+ )
+ val result = storageWithLowSpaceEnabled.dexFilesFor(testSdkConfig)
+ assertThat(result).isNull()
+ }
+
+ @Test
+ fun dexFilesFor_whenLowSpaceAndFilesExtractedBefore_returnExistingFiles() {
+ val extractedFiles = storageUnderTest.dexFilesFor(testSdkConfig)
+ assertThat(extractedFiles).isNotNull()
+
+ val storageWithLowSpaceEnabled = CachedLocalSdkStorage.create(
+ context,
+ lowSpaceThreshold = enabledLowSpaceModeThreshold()
+ )
+ val result = storageWithLowSpaceEnabled.dexFilesFor(testSdkConfig)
+ assertThat(result).isEqualTo(extractedFiles)
+ }
+
+ @Test
+ fun dexFilesFor_whenFailedToExtract_deleteFolderAndThrowException() {
+ val invalidConfig = LocalSdkConfig(
+ packageName = "storage.test.invalid.dexPath",
+ dexPaths = listOf("NOT_EXISTS"),
+ entryPoint = "EntryPoint"
+ )
+
+ val rootFolder = LocalSdkFolderProvider
+ .create(context)
+ .dexFolderFor(invalidConfig)
+
+ val fileToDelete = File(rootFolder, "toDelete")
+ fileToDelete.createNewFile()
+ assertThat(fileToDelete.exists()).isTrue()
+
+ assertThrows<FileNotFoundException> {
+ storageUnderTest.dexFilesFor(invalidConfig)
+ }.hasMessageThat().contains("NOT_EXISTS")
+
+ assertThat(fileToDelete.exists()).isFalse()
+ }
+
+ private fun assertAssetExtractedToReadOnlyFile(assetPath: String, outputFile: File) {
+ assertThat(outputFile.exists()).isTrue()
+ assertThat(outputFile.parentFile).isEqualTo(sdkFolder)
+ assertThat(outputFile.canWrite()).isFalse()
+
+ val assetContent = context.assets.open(assetPath).use(InputStream::readBytes)
+ val fileContent = outputFile.inputStream().use(InputStream::readBytes)
+ assertThat(fileContent).isEqualTo(assetContent)
+ }
+
+ private fun enabledLowSpaceModeThreshold(): Long =
+ availableBytes() + 10_000_000
+
+ private fun disabledLowSpaceModeThreshold(): Long =
+ availableBytes() - 10_000_000
+
+ @Suppress("DEPRECATION")
+ private fun availableBytes(): Long {
+ val path = Environment.getDataDirectory()
+ val stat = StatFs(path.path)
+ val blockSize = stat.blockSize.toLong()
+ val availableBlocks = stat.availableBlocks.toLong()
+ return availableBlocks * blockSize
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/storage/LocalSdkFolderProviderTest.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/storage/LocalSdkFolderProviderTest.kt
new file mode 100644
index 0000000..8e06bf7
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/storage/LocalSdkFolderProviderTest.kt
@@ -0,0 +1,186 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.loader.storage
+
+import android.content.Context
+import androidx.privacysandbox.sdkruntime.client.config.LocalSdkConfig
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.google.common.truth.Truth.assertThat
+import java.io.DataInputStream
+import java.io.DataOutputStream
+import java.io.File
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class LocalSdkFolderProviderTest {
+
+ private lateinit var context: Context
+
+ private lateinit var sdkRootFolder: File
+ private lateinit var versionFile: File
+
+ private var appLastUpdateTime = 0L
+
+ @Before
+ fun setUp() {
+ context = ApplicationProvider.getApplicationContext()
+
+ sdkRootFolder = File(context.cacheDir, "RuntimeEnabledSdk")
+ versionFile = File(sdkRootFolder, "Folder.version")
+
+ @Suppress("DEPRECATION")
+ appLastUpdateTime =
+ context.packageManager.getPackageInfo(context.packageName, 0).lastUpdateTime
+
+ sdkRootFolder.deleteRecursively()
+ }
+
+ @Test
+ fun create_whenNoSdkRootFolder_createSdkRootFolderAndVersionFile() {
+ LocalSdkFolderProvider.create(context)
+
+ assertThat(sdkRootFolder.exists()).isTrue()
+ val version = readVersionFromFile()
+ assertThat(version).isEqualTo(appLastUpdateTime)
+ }
+
+ @Test
+ fun create_whenVersionNotChanged_doNotRemoveContents() {
+ // Initial create
+ LocalSdkFolderProvider.create(context)
+ val fileToKeep = File(sdkRootFolder, "file")
+ fileToKeep.createNewFile()
+
+ LocalSdkFolderProvider.create(context)
+
+ assertThat(fileToKeep.exists()).isTrue()
+ }
+
+ @Test
+ fun create_whenVersionChanged_deleteSdkRootFolderContentAndCreateVersionFile() {
+ val fileToDelete = createFileToDeleteInSdkRootFolder()
+ createVersionFile {
+ it.writeLong(42)
+ }
+
+ LocalSdkFolderProvider.create(context)
+
+ assertThat(fileToDelete.exists()).isFalse()
+ val version = readVersionFromFile()
+ assertThat(version).isEqualTo(appLastUpdateTime)
+ }
+
+ @Test
+ fun create_whenNoVersionFile_deleteSdkRootFolderContentAndCreateVersionFile() {
+ val fileToDelete = createFileToDeleteInSdkRootFolder()
+
+ LocalSdkFolderProvider.create(context)
+
+ assertThat(sdkRootFolder.exists()).isTrue()
+ assertThat(fileToDelete.exists()).isFalse()
+
+ val version = readVersionFromFile()
+ assertThat(version).isEqualTo(appLastUpdateTime)
+ }
+
+ @Test
+ fun create_whenInvalidVersionFile_deleteSdkRootFolderContentAndCreateVersionFile() {
+ val fileToDelete = createFileToDeleteInSdkRootFolder()
+ createVersionFile {
+ // Version is long type, byte is not enough
+ it.writeByte(1)
+ }
+
+ LocalSdkFolderProvider.create(context)
+
+ assertThat(fileToDelete.exists()).isFalse()
+ val version = readVersionFromFile()
+ assertThat(version).isEqualTo(appLastUpdateTime)
+ }
+
+ @Test
+ fun dexFolderFor_returnPathToSdkDexFolder() {
+ val sdkFolderProvider = LocalSdkFolderProvider.create(context)
+ val dexFolder = sdkFolderProvider.dexFolderFor(
+ LocalSdkConfig(
+ packageName = "com.test.sdk.package",
+ dexPaths = listOf("1.dex", "2.dex"),
+ entryPoint = "compat.sdk.provider",
+ )
+ )
+ assertThat(dexFolder.exists()).isTrue()
+ assertThat(dexFolder).isEqualTo(
+ File(sdkRootFolder, "com.test.sdk.package")
+ )
+ }
+
+ @Test
+ fun dexFolderFor_doNotRemoveExistingFiles() {
+ val sdkFolderProvider = LocalSdkFolderProvider.create(context)
+
+ val sdkConfig = LocalSdkConfig(
+ packageName = "com.test.sdk.package",
+ dexPaths = listOf("1.dex", "2.dex"),
+ entryPoint = "compat.sdk.provider",
+ )
+
+ val dexFolder = sdkFolderProvider.dexFolderFor(sdkConfig)
+
+ val fileToKeep = File(dexFolder, "testFile")
+ fileToKeep.createNewFile()
+
+ val dexFolder2 = sdkFolderProvider.dexFolderFor(sdkConfig)
+ assertThat(dexFolder).isEqualTo(dexFolder2)
+
+ assertThat(fileToKeep.exists()).isTrue()
+ }
+
+ private fun createFileToDeleteInSdkRootFolder(): File {
+ val folder = File(sdkRootFolder, "folder")
+ folder.mkdirs()
+ val file = File(folder, "file")
+ file.createNewFile()
+ file.setReadOnly()
+ assertThat(file.exists()).isTrue()
+ return file
+ }
+
+ private fun readVersionFromFile(): Long {
+ return versionFile.inputStream().use { inputStream ->
+ DataInputStream(inputStream).use { dataStream ->
+ dataStream.readLong()
+ }
+ }
+ }
+
+ private fun createVersionFile(versionWriter: (DataOutputStream) -> Unit) {
+ if (!sdkRootFolder.exists()) {
+ sdkRootFolder.mkdirs()
+ }
+ versionFile.createNewFile()
+ versionFile.outputStream().use { outputStream ->
+ DataOutputStream(outputStream).use { dataStream ->
+ versionWriter(dataStream)
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/storage/TestLocalSdkStorage.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/storage/TestLocalSdkStorage.kt
new file mode 100644
index 0000000..22cf607
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/loader/storage/TestLocalSdkStorage.kt
@@ -0,0 +1,51 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.loader.storage
+
+import android.content.Context
+import androidx.privacysandbox.sdkruntime.client.config.LocalSdkConfig
+import java.io.File
+
+/**
+ * Extract SDK DEX files in [rootFolder] / <packageName>.
+ */
+internal class TestLocalSdkStorage(
+ private val context: Context,
+ private val rootFolder: File
+) : LocalSdkStorage {
+ override fun dexFilesFor(sdkConfig: LocalSdkConfig): LocalSdkDexFiles {
+ val outputFolder = File(rootFolder, sdkConfig.packageName)
+ outputFolder.deleteRecursively()
+ outputFolder.mkdirs()
+
+ val fileList = buildList {
+ for (index in sdkConfig.dexPaths.indices) {
+ val dexFile = File(outputFolder, "$index.dex")
+ dexFile.createNewFile()
+ context.assets.open(sdkConfig.dexPaths[index]).use { inputStream ->
+ dexFile.outputStream().use { outputStream ->
+ inputStream.copyTo(outputStream)
+ }
+ }
+ dexFile.setReadOnly()
+ add(dexFile)
+ }
+ }
+
+ return LocalSdkDexFiles(fileList)
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/SdkSandboxManagerCompat.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/SdkSandboxManagerCompat.kt
new file mode 100644
index 0000000..5d426e7
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/SdkSandboxManagerCompat.kt
@@ -0,0 +1,216 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client
+
+import android.annotation.SuppressLint
+import android.app.sdksandbox.LoadSdkException
+import android.app.sdksandbox.SandboxedSdk
+import android.app.sdksandbox.SdkSandboxManager
+import android.content.Context
+import android.os.Bundle
+import android.os.ext.SdkExtensions.AD_SERVICES
+import androidx.annotation.DoNotInline
+import androidx.annotation.RequiresExtension
+import androidx.core.os.asOutcomeReceiver
+import androidx.privacysandbox.sdkruntime.client.config.LocalSdkConfigsHolder
+import androidx.privacysandbox.sdkruntime.client.loader.LocalSdk
+import androidx.privacysandbox.sdkruntime.client.loader.SdkLoader
+import androidx.privacysandbox.sdkruntime.core.AdServicesInfo
+import androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException
+import androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException.Companion.LOAD_SDK_ALREADY_LOADED
+import androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException.Companion.LOAD_SDK_NOT_FOUND
+import androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException.Companion.toLoadCompatSdkException
+import androidx.privacysandbox.sdkruntime.core.SandboxedSdkCompat
+import java.util.WeakHashMap
+import kotlinx.coroutines.suspendCancellableCoroutine
+
+/**
+ * Compat version of [SdkSandboxManager].
+ *
+ * Provides APIs to load [androidx.privacysandbox.sdkruntime.core.SandboxedSdkProviderCompat]
+ * into SDK sandbox process or locally, and then interact with them.
+ *
+ * SdkSandbox process is a java process running in a separate uid range. Each app has its own
+ * SDK sandbox process.
+ *
+ * First app needs to declare SDKs it depends on in it's AndroidManifest.xml
+ * using <uses-sdk-library> tag. App can only load SDKs it depends on into the
+ * SDK sandbox process.
+ *
+ * For loading SDKs locally App need to bundle and declare local SDKs in
+ * assets/RuntimeEnabledSdkTable.xml with following format:
+ *
+ * <runtime-enabled-sdk-table>
+ * <runtime-enabled-sdk>
+ * <package-name>com.sdk1</package-name>
+ * <compat-config-path>assets/RuntimeEnabledSdk-com.sdk1/CompatSdkConfig.xml</compat-config-path>
+ * </runtime-enabled-sdk>
+ * <runtime-enabled-sdk>
+ * <package-name>com.sdk2</package-name>
+ * <compat-config-path>assets/RuntimeEnabledSdk-com.sdk2/CompatSdkConfig.xml</compat-config-path>
+ * </runtime-enabled-sdk>
+ * </runtime-enabled-sdk-table>
+ *
+ * Each local SDK should have config with following format:
+ *
+ * <compat-config>
+ * <dex-path>RuntimeEnabledSdk-sdk.package.name/dex/classes.dex</dex-path>
+ * <dex-path>RuntimeEnabledSdk-sdk.package.name/dex/classes2.dex</dex-path>
+ * <java-resources-root-path>RuntimeEnabledSdk-sdk.package.name/res</java-resources-root-path>
+ * <compat-entrypoint>com.sdk.EntryPointClass</compat-entrypoint>
+ * <resource-id-remapping>
+ * <r-package-class>com.test.sdk.RPackage</r-package-class>
+ * <resources-package-id>123</resources-package-id>
+ * </resource-id-remapping>
+ * </compat-config>
+ *
+ * @see [SdkSandboxManager]
+ */
+class SdkSandboxManagerCompat private constructor(
+ private val platformApi: PlatformApi,
+ private val configHolder: LocalSdkConfigsHolder,
+ private val sdkLoader: SdkLoader
+) {
+
+ private val localLoadedSdks = HashMap<String, LocalSdk>()
+
+ /**
+ * Load SDK in a SDK sandbox java process or locally.
+ *
+ * App should already declare SDKs it depends on in its AndroidManifest using
+ * <use-sdk-library> tag. App can only load SDKs it depends on into the SDK Sandbox process.
+ *
+ * When client application loads the first SDK, a new SdkSandbox process will be
+ * created, otherwise other SDKs will be loaded into the same sandbox which already created for
+ * the client application.
+ *
+ * Alternatively App could bundle and declare local SDKs dependencies in
+ * assets/RuntimeEnabledSdkTable.xml to load SDKs locally.
+ *
+ * This API may only be called while the caller is running in the foreground. Calls from the
+ * background will result in a [LoadSdkCompatException] being thrown.
+ *
+ * @param sdkName name of the SDK to be loaded.
+ * @param params additional parameters to be passed to the SDK in the form of a [Bundle]
+ * as agreed between the client and the SDK.
+ * @return [SandboxedSdkCompat] from SDK on a successful run.
+ * @throws [LoadSdkCompatException] on fail.
+ *
+ * @see [SdkSandboxManager.loadSdk]
+ */
+ @Throws(LoadSdkCompatException::class)
+ suspend fun loadSdk(
+ sdkName: String,
+ params: Bundle
+ ): SandboxedSdkCompat {
+ if (localLoadedSdks.containsKey(sdkName)) {
+ throw LoadSdkCompatException(LOAD_SDK_ALREADY_LOADED, "$sdkName already loaded")
+ }
+
+ val sdkConfig = configHolder.getSdkConfig(sdkName)
+ if (sdkConfig != null) {
+ val sdkHolder = sdkLoader.loadSdk(sdkConfig)
+ val sandboxedSdkCompat = sdkHolder.onLoadSdk(params)
+ localLoadedSdks.put(sdkName, sdkHolder)
+ return sandboxedSdkCompat
+ }
+
+ return platformApi.loadSdk(sdkName, params)
+ }
+
+ private interface PlatformApi {
+ @DoNotInline
+ suspend fun loadSdk(sdkName: String, params: Bundle): SandboxedSdkCompat
+ }
+
+ // TODO(b/249981547) Remove suppress after updating to new lint version (b/262251309)
+ @SuppressLint("NewApi", "ClassVerificationFailure")
+ @RequiresExtension(extension = AD_SERVICES, version = 4)
+ private class ApiAdServicesV4Impl(context: Context) : PlatformApi {
+ private val sdkSandboxManager = context.getSystemService(
+ SdkSandboxManager::class.java
+ )
+
+ @DoNotInline
+ override suspend fun loadSdk(
+ sdkName: String,
+ params: Bundle
+ ): SandboxedSdkCompat {
+ try {
+ val sandboxedSdk = loadSdkInternal(sdkName, params)
+ return SandboxedSdkCompat(sandboxedSdk)
+ } catch (ex: LoadSdkException) {
+ throw toLoadCompatSdkException(ex)
+ }
+ }
+
+ private suspend fun loadSdkInternal(
+ sdkName: String,
+ params: Bundle
+ ): SandboxedSdk {
+ return suspendCancellableCoroutine { continuation ->
+ sdkSandboxManager.loadSdk(
+ sdkName,
+ params,
+ Runnable::run,
+ continuation.asOutcomeReceiver()
+ )
+ }
+ }
+ }
+
+ private class FailImpl : PlatformApi {
+ @DoNotInline
+ override suspend fun loadSdk(
+ sdkName: String,
+ params: Bundle
+ ): SandboxedSdkCompat {
+ throw LoadSdkCompatException(LOAD_SDK_NOT_FOUND, "$sdkName not bundled with app")
+ }
+ }
+
+ companion object {
+
+ private val sInstances = WeakHashMap<Context, SdkSandboxManagerCompat>()
+
+ /**
+ * Creates [SdkSandboxManagerCompat].
+ *
+ * @param context Application context
+ *
+ * @return SdkSandboxManagerCompat object.
+ */
+ @JvmStatic
+ fun from(context: Context): SdkSandboxManagerCompat {
+ synchronized(sInstances) {
+ var instance = sInstances[context]
+ if (instance == null) {
+ val configHolder = LocalSdkConfigsHolder.load(context)
+ val sdkLoader = SdkLoader.create(context)
+ val platformApi =
+ if (AdServicesInfo.version() >= 4) {
+ ApiAdServicesV4Impl(context)
+ } else {
+ FailImpl()
+ }
+ instance = SdkSandboxManagerCompat(platformApi, configHolder, sdkLoader)
+ sInstances[context] = instance
+ }
+ return instance
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/main/androidx/privacysandbox/sdkruntime/androidx-privacysandbox-sdkruntime-sdkruntime-client-documentation.md b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/androidx-privacysandbox-sdkruntime-sdkruntime-client-documentation.md
similarity index 100%
rename from privacysandbox/sdkruntime/sdkruntime-client/src/main/androidx/privacysandbox/sdkruntime/androidx-privacysandbox-sdkruntime-sdkruntime-client-documentation.md
rename to privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/androidx-privacysandbox-sdkruntime-sdkruntime-client-documentation.md
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/config/LocalSdkConfig.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/config/LocalSdkConfig.kt
new file mode 100644
index 0000000..081acf5
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/config/LocalSdkConfig.kt
@@ -0,0 +1,33 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.config
+
+/**
+ * Information required for loading SDK bundled with App.
+ *
+ */
+internal data class LocalSdkConfig(
+ val packageName: String,
+ val dexPaths: List<String>,
+ val entryPoint: String,
+ val javaResourcesRoot: String? = null,
+ val resourceRemapping: ResourceRemappingConfig? = null
+)
+
+internal data class ResourceRemappingConfig(
+ val rPackageClassName: String,
+ val packageId: Int
+)
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/config/LocalSdkConfigParser.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/config/LocalSdkConfigParser.kt
new file mode 100644
index 0000000..b9f10c2
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/config/LocalSdkConfigParser.kt
@@ -0,0 +1,180 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.config
+
+import android.util.Xml
+import java.io.InputStream
+import org.xmlpull.v1.XmlPullParser
+import org.xmlpull.v1.XmlPullParser.END_TAG
+import org.xmlpull.v1.XmlPullParser.START_TAG
+import org.xmlpull.v1.XmlPullParserException
+
+/**
+ * Parser for SDK config.
+ *
+ * The expected XML structure is:
+ * <compat-config>
+ * <dex-path>RuntimeEnabledSdk-sdk.package.name/dex/classes.dex</dex-path>
+ * <dex-path>RuntimeEnabledSdk-sdk.package.name/dex/classes2.dex</dex-path>
+ * <java-resources-root-path>RuntimeEnabledSdk-sdk.package.name/res</java-resources-root-path>
+ * <compat-entrypoint>com.sdk.EntryPointClass</compat-entrypoint>
+ * <resource-id-remapping>
+ * <r-package-class>com.test.sdk.RPackage</r-package-class>
+ * <resources-package-id>123</resources-package-id>
+ * </resource-id-remapping>
+ * </compat-config>
+ */
+internal class LocalSdkConfigParser private constructor(
+ private val xmlParser: XmlPullParser
+) {
+
+ private fun readConfig(packageName: String): LocalSdkConfig {
+ xmlParser.require(XmlPullParser.START_DOCUMENT, NAMESPACE, null)
+ xmlParser.nextTag()
+
+ val dexPaths = mutableListOf<String>()
+ var javaResourcesRoot: String? = null
+ var entryPoint: String? = null
+ var resourceRemapping: ResourceRemappingConfig? = null
+
+ xmlParser.require(START_TAG, NAMESPACE, CONFIG_ELEMENT_NAME)
+ while (xmlParser.next() != END_TAG) {
+ if (xmlParser.eventType != START_TAG) {
+ continue
+ }
+ when (xmlParser.name) {
+ DEX_PATH_ELEMENT_NAME -> {
+ val dexPath = xmlParser.nextText()
+ dexPaths.add(dexPath)
+ }
+
+ RESOURCE_ROOT_ELEMENT_NAME -> {
+ if (javaResourcesRoot != null) {
+ throw XmlPullParserException(
+ "Duplicate $RESOURCE_ROOT_ELEMENT_NAME tag found"
+ )
+ }
+ javaResourcesRoot = xmlParser.nextText()
+ }
+
+ ENTRYPOINT_ELEMENT_NAME -> {
+ if (entryPoint != null) {
+ throw XmlPullParserException(
+ "Duplicate $ENTRYPOINT_ELEMENT_NAME tag found"
+ )
+ }
+ entryPoint = xmlParser.nextText()
+ }
+
+ RESOURCE_REMAPPING_ENTRY_ELEMENT_NAME -> {
+ if (resourceRemapping != null) {
+ throw XmlPullParserException(
+ "Duplicate $RESOURCE_REMAPPING_ENTRY_ELEMENT_NAME tag found"
+ )
+ }
+ resourceRemapping = readResourceRemappingConfig()
+ }
+
+ else -> xmlParser.skipCurrentTag()
+ }
+ }
+ xmlParser.require(END_TAG, NAMESPACE, CONFIG_ELEMENT_NAME)
+
+ if (entryPoint == null) {
+ throw XmlPullParserException("No $ENTRYPOINT_ELEMENT_NAME tag found")
+ }
+ if (dexPaths.isEmpty()) {
+ throw XmlPullParserException("No $DEX_PATH_ELEMENT_NAME tags found")
+ }
+
+ return LocalSdkConfig(
+ packageName,
+ dexPaths,
+ entryPoint,
+ javaResourcesRoot,
+ resourceRemapping
+ )
+ }
+
+ private fun readResourceRemappingConfig(): ResourceRemappingConfig {
+ var rPackageClassName: String? = null
+ var packageId: Int? = null
+
+ xmlParser.require(START_TAG, NAMESPACE, RESOURCE_REMAPPING_ENTRY_ELEMENT_NAME)
+ while (xmlParser.next() != END_TAG) {
+ if (xmlParser.eventType != START_TAG) {
+ continue
+ }
+ when (xmlParser.name) {
+ RESOURCE_REMAPPING_CLASS_ELEMENT_NAME -> {
+ if (rPackageClassName != null) {
+ throw XmlPullParserException(
+ "Duplicate $RESOURCE_REMAPPING_CLASS_ELEMENT_NAME tag found"
+ )
+ }
+ rPackageClassName = xmlParser.nextText()
+ }
+
+ RESOURCE_REMAPPING_ID_ELEMENT_NAME -> {
+ if (packageId != null) {
+ throw XmlPullParserException(
+ "Duplicate $RESOURCE_REMAPPING_ID_ELEMENT_NAME tag found"
+ )
+ }
+ packageId = xmlParser.nextText().toInt()
+ }
+
+ else -> xmlParser.skipCurrentTag()
+ }
+ }
+ xmlParser.require(END_TAG, NAMESPACE, RESOURCE_REMAPPING_ENTRY_ELEMENT_NAME)
+
+ if (rPackageClassName == null) {
+ throw XmlPullParserException(
+ "No $RESOURCE_REMAPPING_CLASS_ELEMENT_NAME tag found"
+ )
+ }
+ if (packageId == null) {
+ throw XmlPullParserException(
+ "No $RESOURCE_REMAPPING_ID_ELEMENT_NAME tag found"
+ )
+ }
+
+ return ResourceRemappingConfig(rPackageClassName, packageId)
+ }
+
+ companion object {
+ private val NAMESPACE: String? = null // We don't use namespaces
+ private const val CONFIG_ELEMENT_NAME = "compat-config"
+ private const val DEX_PATH_ELEMENT_NAME = "dex-path"
+ private const val RESOURCE_ROOT_ELEMENT_NAME = "java-resources-root-path"
+ private const val ENTRYPOINT_ELEMENT_NAME = "compat-entrypoint"
+ private const val RESOURCE_REMAPPING_ENTRY_ELEMENT_NAME = "resource-id-remapping"
+ private const val RESOURCE_REMAPPING_CLASS_ELEMENT_NAME = "r-package-class"
+ private const val RESOURCE_REMAPPING_ID_ELEMENT_NAME = "resources-package-id"
+
+ fun parse(inputStream: InputStream, packageName: String): LocalSdkConfig {
+ val parser = Xml.newPullParser()
+ try {
+ parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)
+ parser.setInput(inputStream, null)
+ return LocalSdkConfigParser(parser).readConfig(packageName)
+ } finally {
+ parser.setInput(null)
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/config/LocalSdkConfigsHolder.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/config/LocalSdkConfigsHolder.kt
new file mode 100644
index 0000000..4232878
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/config/LocalSdkConfigsHolder.kt
@@ -0,0 +1,70 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.config
+
+import android.content.Context
+import androidx.annotation.RestrictTo
+import java.io.FileNotFoundException
+
+/**
+ * Holds information about all SDKs bundled with App.
+ *
+ * @suppress
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY)
+internal class LocalSdkConfigsHolder private constructor(
+ private val configs: Map<String, LocalSdkConfig>
+) {
+
+ fun getSdkConfig(sdkName: String): LocalSdkConfig? {
+ return configs[sdkName]
+ }
+
+ companion object {
+ private const val SDK_TABLE_ASSET_NAME = "RuntimeEnabledSdkTable.xml"
+
+ fun load(
+ context: Context,
+ sdkTableAssetName: String = SDK_TABLE_ASSET_NAME
+ ): LocalSdkConfigsHolder {
+ val sdkTable = loadSdkTable(context, sdkTableAssetName)
+
+ val data = buildMap {
+ for ((packageName, configPath) in sdkTable) {
+ context.assets.open(configPath).use { sdkConfigAsset ->
+ val sdkInfo = LocalSdkConfigParser.parse(sdkConfigAsset, packageName)
+ put(packageName, sdkInfo)
+ }
+ }
+ }
+
+ return LocalSdkConfigsHolder(data)
+ }
+
+ private fun loadSdkTable(
+ context: Context,
+ sdkTableAssetName: String
+ ): Set<SdkTableConfigParser.SdkTableEntry> {
+ try {
+ context.assets.open(sdkTableAssetName).use { sdkTableAsset ->
+ return SdkTableConfigParser.parse(sdkTableAsset)
+ }
+ } catch (ignored: FileNotFoundException) {
+ return emptySet()
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/config/SdkTableConfigParser.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/config/SdkTableConfigParser.kt
new file mode 100644
index 0000000..eea19cc
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/config/SdkTableConfigParser.kt
@@ -0,0 +1,146 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.config
+
+import android.util.Xml
+import androidx.annotation.RestrictTo
+import java.io.InputStream
+import org.xmlpull.v1.XmlPullParser
+import org.xmlpull.v1.XmlPullParser.END_TAG
+import org.xmlpull.v1.XmlPullParser.START_TAG
+import org.xmlpull.v1.XmlPullParserException
+
+/**
+ * Parser for config with paths to compat SDK configs for each SDK that bundled with app.
+ *
+ * The expected XML structure is:
+ * <runtime-enabled-sdk-table>
+ * <runtime-enabled-sdk>
+ * <package-name>com.sdk1</package-name>
+ * <compat-config-path>assets/RuntimeEnabledSdk-com.sdk1/CompatSdkConfig.xml</compat-config-path>
+ * </runtime-enabled-sdk>
+ * <runtime-enabled-sdk>
+ * <package-name>com.sdk2</package-name>
+ * <compat-config-path>assets/RuntimeEnabledSdk-com.sdk2/CompatSdkConfig.xml</compat-config-path>
+ * </runtime-enabled-sdk>
+ * </runtime-enabled-sdk-table>
+ *
+ * @suppress
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY)
+internal class SdkTableConfigParser private constructor(
+ private val xmlParser: XmlPullParser
+) {
+
+ private fun readSdkTable(): Set<SdkTableEntry> {
+ xmlParser.require(XmlPullParser.START_DOCUMENT, NAMESPACE, null)
+ xmlParser.nextTag()
+
+ val packages = mutableSetOf<String>()
+
+ return buildSet {
+ xmlParser.require(START_TAG, NAMESPACE, SDK_TABLE_ELEMENT_NAME)
+ while (xmlParser.next() != END_TAG) {
+ if (xmlParser.eventType != START_TAG) {
+ continue
+ }
+ if (xmlParser.name == SDK_ENTRY_ELEMENT_NAME) {
+ val entry = readSdkEntry()
+ if (!packages.add(entry.packageName)) {
+ throw XmlPullParserException(
+ "Duplicate entry for ${entry.packageName} found"
+ )
+ }
+ add(entry)
+ } else {
+ xmlParser.skipCurrentTag()
+ }
+ }
+ xmlParser.require(END_TAG, NAMESPACE, SDK_TABLE_ELEMENT_NAME)
+ }
+ }
+
+ private fun readSdkEntry(): SdkTableEntry {
+ var packageName: String? = null
+ var configPath: String? = null
+
+ xmlParser.require(START_TAG, NAMESPACE, SDK_ENTRY_ELEMENT_NAME)
+ while (xmlParser.next() != END_TAG) {
+ if (xmlParser.eventType != START_TAG) {
+ continue
+ }
+ when (xmlParser.name) {
+ SDK_PACKAGE_NAME_ELEMENT_NAME -> {
+ if (packageName != null) {
+ throw XmlPullParserException(
+ "Duplicate $SDK_PACKAGE_NAME_ELEMENT_NAME tag found"
+ )
+ }
+ packageName = xmlParser.nextText()
+ }
+
+ COMPAT_CONFIG_PATH_ELEMENT_NAME -> {
+ if (configPath != null) {
+ throw XmlPullParserException(
+ "Duplicate $COMPAT_CONFIG_PATH_ELEMENT_NAME tag found"
+ )
+ }
+ configPath = xmlParser.nextText()
+ }
+
+ else -> xmlParser.skipCurrentTag()
+ }
+ }
+ xmlParser.require(END_TAG, NAMESPACE, SDK_ENTRY_ELEMENT_NAME)
+
+ if (packageName == null) {
+ throw XmlPullParserException(
+ "No $SDK_PACKAGE_NAME_ELEMENT_NAME tag found"
+ )
+ }
+ if (configPath == null) {
+ throw XmlPullParserException(
+ "No $COMPAT_CONFIG_PATH_ELEMENT_NAME tag found"
+ )
+ }
+
+ return SdkTableEntry(packageName, configPath)
+ }
+
+ internal data class SdkTableEntry(
+ val packageName: String,
+ val compatConfigPath: String,
+ )
+
+ companion object {
+ private val NAMESPACE: String? = null // We don't use namespaces
+ private const val SDK_TABLE_ELEMENT_NAME = "runtime-enabled-sdk-table"
+ private const val SDK_ENTRY_ELEMENT_NAME = "runtime-enabled-sdk"
+ private const val SDK_PACKAGE_NAME_ELEMENT_NAME = "package-name"
+ private const val COMPAT_CONFIG_PATH_ELEMENT_NAME = "compat-config-path"
+
+ fun parse(inputStream: InputStream): Set<SdkTableEntry> {
+ val parser = Xml.newPullParser()
+ try {
+ parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)
+ parser.setInput(inputStream, null)
+ return SdkTableConfigParser(parser).readSdkTable()
+ } finally {
+ parser.setInput(null)
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/config/XmlUtils.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/config/XmlUtils.kt
new file mode 100644
index 0000000..6a91815
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/config/XmlUtils.kt
@@ -0,0 +1,40 @@
+/*
+ * 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.
+ */
+
+@file:RestrictTo(RestrictTo.Scope.LIBRARY)
+
+package androidx.privacysandbox.sdkruntime.client.config
+
+import androidx.annotation.RestrictTo
+import org.xmlpull.v1.XmlPullParser
+import org.xmlpull.v1.XmlPullParser.END_TAG
+import org.xmlpull.v1.XmlPullParser.START_TAG
+
+/**
+ * Skip current tag (including inner tags)
+ *
+ * @suppress
+ */
+internal fun XmlPullParser.skipCurrentTag() {
+ require(START_TAG, null, null)
+ var depth = 1
+ while (depth != 0) {
+ when (next()) {
+ END_TAG -> depth--
+ START_TAG -> depth++
+ }
+ }
+}
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/FileClassLoaderFactory.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/FileClassLoaderFactory.kt
new file mode 100644
index 0000000..e6d8eb6
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/FileClassLoaderFactory.kt
@@ -0,0 +1,86 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.loader
+
+import android.util.Log
+import androidx.privacysandbox.sdkruntime.client.config.LocalSdkConfig
+import androidx.privacysandbox.sdkruntime.client.loader.storage.LocalSdkStorage
+import androidx.privacysandbox.sdkruntime.client.loader.storage.toClassPathString
+import dalvik.system.BaseDexClassLoader
+import java.io.File
+
+/**
+ * Loading SDK using BaseDexClassLoader.
+ * Using [LocalSdkStorage] to get SDK DEX files,
+ * if no files available - delegating to fallback.
+ */
+internal class FileClassLoaderFactory(
+ private val localSdkStorage: LocalSdkStorage,
+ private val fallback: SdkLoader.ClassLoaderFactory,
+) : SdkLoader.ClassLoaderFactory {
+
+ override fun createClassLoaderFor(
+ sdkConfig: LocalSdkConfig,
+ parent: ClassLoader
+ ): ClassLoader {
+ return tryCreateBaseDexClassLoaderFor(sdkConfig, parent)
+ ?: fallback.createClassLoaderFor(
+ sdkConfig,
+ parent
+ )
+ }
+
+ private fun tryCreateBaseDexClassLoaderFor(
+ sdkConfig: LocalSdkConfig,
+ parent: ClassLoader
+ ): ClassLoader? {
+ try {
+ val dexFiles = localSdkStorage.dexFilesFor(sdkConfig)
+ if (dexFiles == null) {
+ Log.w(
+ LOG_TAG,
+ "Can't use BaseDexClassLoader for ${sdkConfig.packageName} - no dexFiles"
+ )
+ return null
+ }
+
+ val optimizedDirectory = File(dexFiles.files[0].parentFile, "DexOpt")
+ if (!optimizedDirectory.exists()) {
+ optimizedDirectory.mkdirs()
+ }
+
+ return BaseDexClassLoader(
+ dexFiles.toClassPathString(),
+ optimizedDirectory,
+ /* librarySearchPath = */ null,
+ parent
+ )
+ } catch (ex: Exception) {
+ Log.e(
+ LOG_TAG,
+ "Failed to use BaseDexClassLoader for ${sdkConfig.packageName} - exception",
+ ex
+ )
+ return null
+ }
+ }
+
+ companion object {
+ const val LOG_TAG =
+ "FileClassLoaderFactory"
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/InMemorySdkClassLoaderFactory.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/InMemorySdkClassLoaderFactory.kt
new file mode 100644
index 0000000..2fa4a55
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/InMemorySdkClassLoaderFactory.kt
@@ -0,0 +1,87 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.loader
+
+import android.content.Context
+import android.content.res.AssetManager
+import android.os.Build
+import androidx.annotation.DoNotInline
+import androidx.annotation.RequiresApi
+import androidx.privacysandbox.sdkruntime.client.config.LocalSdkConfig
+import androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException
+import dalvik.system.InMemoryDexClassLoader
+import java.nio.ByteBuffer
+import java.nio.channels.Channels
+
+/**
+ * Loading SDK in memory on API 27+
+ */
+internal abstract class InMemorySdkClassLoaderFactory : SdkLoader.ClassLoaderFactory {
+
+ @RequiresApi(Build.VERSION_CODES.O_MR1)
+ internal class InMemoryImpl(
+ private val assetManager: AssetManager
+ ) : InMemorySdkClassLoaderFactory() {
+
+ @DoNotInline
+ override fun createClassLoaderFor(
+ sdkConfig: LocalSdkConfig,
+ parent: ClassLoader
+ ): ClassLoader {
+ try {
+ val buffers = arrayOfNulls<ByteBuffer>(sdkConfig.dexPaths.size)
+ for (i in sdkConfig.dexPaths.indices) {
+ assetManager.open(sdkConfig.dexPaths[i]).use { inputStream ->
+ val byteBuffer = ByteBuffer.allocate(inputStream.available())
+ Channels.newChannel(inputStream).read(byteBuffer)
+ byteBuffer.flip()
+ buffers[i] = byteBuffer
+ }
+ }
+ return InMemoryDexClassLoader(buffers, parent)
+ } catch (ex: Exception) {
+ throw LoadSdkCompatException(
+ LoadSdkCompatException.LOAD_SDK_INTERNAL_ERROR,
+ "Failed to instantiate classloader",
+ ex
+ )
+ }
+ }
+ }
+
+ internal class FailImpl : InMemorySdkClassLoaderFactory() {
+ @DoNotInline
+ override fun createClassLoaderFor(
+ sdkConfig: LocalSdkConfig,
+ parent: ClassLoader
+ ): ClassLoader {
+ throw LoadSdkCompatException(
+ LoadSdkCompatException.LOAD_SDK_SDK_SANDBOX_DISABLED,
+ "Can't use InMemoryDexClassLoader"
+ )
+ }
+ }
+
+ companion object {
+ fun create(context: Context): InMemorySdkClassLoaderFactory {
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
+ InMemoryImpl(context.assets)
+ } else {
+ FailImpl()
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/JavaResourcesLoadingClassLoaderFactory.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/JavaResourcesLoadingClassLoaderFactory.kt
new file mode 100644
index 0000000..b669af8
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/JavaResourcesLoadingClassLoaderFactory.kt
@@ -0,0 +1,85 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.loader
+
+import androidx.privacysandbox.sdkruntime.client.config.LocalSdkConfig
+import java.io.File
+import java.io.IOException
+import java.net.URL
+import java.util.Enumeration
+
+/**
+ * Delegate java resources related calls to app classloader.
+ *
+ * Classloaders normally delegate calls to parent classloader first, that's why this factory
+ * creates classloader that will work with java resources and pass it as parent to
+ * [codeClassLoaderFactory] thus overrides java resources for all classes loaded down the line.
+ *
+ * Add [LocalSdkConfig.javaResourcesRoot] as prefix to resource names before delegating calls,
+ * thus allowing isolating java resources for different local sdks.
+ */
+internal class JavaResourcesLoadingClassLoaderFactory(
+ private val appClassloader: ClassLoader,
+ private val codeClassLoaderFactory: SdkLoader.ClassLoaderFactory
+) : SdkLoader.ClassLoaderFactory {
+ override fun createClassLoaderFor(
+ sdkConfig: LocalSdkConfig,
+ parent: ClassLoader
+ ): ClassLoader {
+ val javaResourcesLoadingClassLoader = createJavaResourcesLoadingClassLoader(
+ sdkConfig,
+ parent
+ )
+ return codeClassLoaderFactory.createClassLoaderFor(
+ sdkConfig,
+ parent = javaResourcesLoadingClassLoader
+ )
+ }
+
+ private fun createJavaResourcesLoadingClassLoader(
+ sdkConfig: LocalSdkConfig,
+ parent: ClassLoader
+ ): ClassLoader {
+ return if (sdkConfig.javaResourcesRoot == null) {
+ parent
+ } else {
+ JavaResourcesLoadingClassLoader(
+ parent,
+ appClassloader,
+ File(ASSETS_DIR, sdkConfig.javaResourcesRoot)
+ )
+ }
+ }
+
+ private class JavaResourcesLoadingClassLoader constructor(
+ parent: ClassLoader,
+ private val appClassloader: ClassLoader,
+ private val javaResourcePrefix: File
+ ) : ClassLoader(parent) {
+ override fun findResource(name: String): URL? {
+ return appClassloader.getResource(File(javaResourcePrefix, name).path)
+ }
+
+ @Throws(IOException::class)
+ override fun findResources(name: String): Enumeration<URL> {
+ return appClassloader.getResources(File(javaResourcePrefix, name).path)
+ }
+ }
+
+ companion object {
+ const val ASSETS_DIR = "assets/"
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/LocalSdk.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/LocalSdk.kt
new file mode 100644
index 0000000..0867e6e
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/LocalSdk.kt
@@ -0,0 +1,37 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.loader
+
+import android.os.Bundle
+import androidx.annotation.RestrictTo
+import androidx.privacysandbox.sdkruntime.core.SandboxedSdkCompat
+import org.jetbrains.annotations.TestOnly
+
+/**
+ * Provides interface for interaction with locally loaded SDK.
+ * Handle different protocol versions inside.
+ *
+ * @suppress
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY)
+internal abstract class LocalSdk protected constructor(
+ @get:TestOnly val sdkProvider: Any
+) {
+
+ abstract fun onLoadSdk(params: Bundle): SandboxedSdkCompat
+
+ abstract fun beforeUnloadSdk()
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/ResourceRemapping.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/ResourceRemapping.kt
new file mode 100644
index 0000000..711d7b1
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/ResourceRemapping.kt
@@ -0,0 +1,48 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.loader
+
+import androidx.privacysandbox.sdkruntime.client.config.ResourceRemappingConfig
+
+/**
+ * Update RPackage.packageId for supporting Android Resource remapping for SDK.
+ * Each resource has id calculated as id = RPackage.packageId + index.
+ * Updating packageId effectively shifting all SDK resource ids in resource table.
+ * IMPORTANT: ResourceRemapping should happen before ANY interactions with R.class
+ */
+internal object ResourceRemapping {
+
+ private const val PACKAGE_ID_FIELD_NAME = "packageId"
+
+ fun apply(
+ sdkClassLoader: ClassLoader,
+ remappingConfig: ResourceRemappingConfig?
+ ) {
+ if (remappingConfig == null)
+ return
+
+ val rPackageClass = Class.forName(
+ remappingConfig.rPackageClassName,
+ /* initialize = */ false,
+ sdkClassLoader
+ )
+
+ val field = rPackageClass.getDeclaredField(PACKAGE_ID_FIELD_NAME)
+
+ field.setInt(null, remappingConfig.packageId)
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/SdkLoader.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/SdkLoader.kt
new file mode 100644
index 0000000..89e3457
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/SdkLoader.kt
@@ -0,0 +1,115 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.loader
+
+import android.content.Context
+import androidx.privacysandbox.sdkruntime.client.config.LocalSdkConfig
+import androidx.privacysandbox.sdkruntime.client.loader.impl.SdkV1
+import androidx.privacysandbox.sdkruntime.client.loader.storage.CachedLocalSdkStorage
+import androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException
+
+/**
+ * Load SDK bundled with App.
+ */
+internal class SdkLoader internal constructor(
+ private val classLoaderFactory: ClassLoaderFactory,
+ private val appContext: Context
+) {
+
+ internal interface ClassLoaderFactory {
+ fun createClassLoaderFor(sdkConfig: LocalSdkConfig, parent: ClassLoader): ClassLoader
+ }
+
+ /**
+ * Loading SDK in separate classloader:
+ * 1. Create classloader for sdk;
+ * 2. Performing handshake to determine api version;
+ * 3. (optional) Update RPackage.packageId to support Android Resource remapping for SDK
+ * 4. Select [LocalSdk] implementation that could work with that api version.
+ *
+ * @param sdkConfig sdk to load
+ * @return LocalSdk implementation for loaded SDK
+ */
+ fun loadSdk(sdkConfig: LocalSdkConfig): LocalSdk {
+ val classLoader = classLoaderFactory.createClassLoaderFor(
+ sdkConfig,
+ getParentClassLoader()
+ )
+ return createLocalSdk(classLoader, sdkConfig)
+ }
+
+ private fun getParentClassLoader(): ClassLoader = appContext.classLoader.parent!!
+
+ private fun createLocalSdk(classLoader: ClassLoader, sdkConfig: LocalSdkConfig): LocalSdk {
+ try {
+ val apiVersion = VersionHandshake.perform(classLoader)
+ ResourceRemapping.apply(classLoader, sdkConfig.resourceRemapping)
+ if (apiVersion >= 1) {
+ return SdkV1.create(classLoader, sdkConfig.entryPoint, appContext)
+ }
+ } catch (ex: Exception) {
+ throw LoadSdkCompatException(
+ LoadSdkCompatException.LOAD_SDK_INTERNAL_ERROR,
+ "Failed to instantiate local SDK",
+ ex
+ )
+ }
+
+ throw LoadSdkCompatException(
+ LoadSdkCompatException.LOAD_SDK_NOT_FOUND,
+ "Incorrect Api version"
+ )
+ }
+
+ companion object {
+ /**
+ * Build chain of [ClassLoaderFactory] that could load SDKs with their resources.
+ * Order is important because classloaders normally delegate calls to parent classloader
+ * first:
+ * 1. [JavaResourcesLoadingClassLoaderFactory] - to provide java resources to classes
+ * loaded by child classloaders;
+ * 2a. [FileClassLoaderFactory] - first trying to use factory that extracting SDK Dex
+ * to storage and load it using [dalvik.system.BaseDexClassLoader].
+ * Supports all platform versions (Api14+, minSdkVersion for library).
+ * 2b. [InMemorySdkClassLoaderFactory] - fallback for low available space. Trying to load
+ * SDK in-memory using [dalvik.system.InMemoryDexClassLoader].
+ * Supports Api27+ only, fails SDK loading on non-supported platform versions.
+ *
+ * @param context App context
+ * @param lowSpaceThreshold Minimal available space in bytes required to proceed with
+ * extracting SDK Dex files.
+ *
+ * @return SdkLoader that could load SDKs with their resources.
+ */
+ fun create(
+ context: Context,
+ lowSpaceThreshold: Long = 100 * 1024 * 1024
+ ): SdkLoader {
+ val cachedLocalSdkStorage = CachedLocalSdkStorage.create(
+ context,
+ lowSpaceThreshold
+ )
+ val classLoaderFactory = JavaResourcesLoadingClassLoaderFactory(
+ context.classLoader,
+ codeClassLoaderFactory = FileClassLoaderFactory(
+ cachedLocalSdkStorage,
+ fallback = InMemorySdkClassLoaderFactory.create(context)
+ )
+ )
+ return SdkLoader(classLoaderFactory, context)
+ }
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/VersionHandshake.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/VersionHandshake.kt
new file mode 100644
index 0000000..21a6a17
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/VersionHandshake.kt
@@ -0,0 +1,39 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.loader
+
+import android.annotation.SuppressLint
+import androidx.annotation.RestrictTo
+import androidx.privacysandbox.sdkruntime.core.Versions
+
+/**
+ * Performing version handshake.
+ *
+ * @suppress
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY)
+internal object VersionHandshake {
+ @SuppressLint("BanUncheckedReflection") // calling method on Versions class
+ fun perform(classLoader: ClassLoader?): Int {
+ val versionsClass = Class.forName(
+ Versions::class.java.name,
+ false,
+ classLoader
+ )
+ val handShakeMethod = versionsClass.getMethod("handShake", Int::class.javaPrimitiveType)
+ return handShakeMethod.invoke(null, Versions.API_VERSION) as Int
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/impl/SandboxedSdkContextCompat.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/impl/SandboxedSdkContextCompat.kt
new file mode 100644
index 0000000..4a9fd3b
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/impl/SandboxedSdkContextCompat.kt
@@ -0,0 +1,35 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.loader.impl
+
+import android.content.Context
+import android.content.ContextWrapper
+import androidx.annotation.RestrictTo
+
+/**
+ * Refers to the context of the SDK loaded locally.
+ *
+ * @suppress
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY)
+internal class SandboxedSdkContextCompat(
+ base: Context,
+ private val classLoader: ClassLoader?
+) : ContextWrapper(base) {
+ override fun getClassLoader(): ClassLoader? {
+ return classLoader
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/impl/SdkV1.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/impl/SdkV1.kt
new file mode 100644
index 0000000..9602b3cd
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/impl/SdkV1.kt
@@ -0,0 +1,174 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.loader.impl
+
+import android.annotation.SuppressLint
+import android.content.Context
+import android.os.Bundle
+import android.os.IBinder
+import androidx.annotation.RestrictTo
+import androidx.privacysandbox.sdkruntime.client.loader.LocalSdk
+import androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException
+import androidx.privacysandbox.sdkruntime.core.SandboxedSdkCompat
+import java.lang.reflect.InvocationTargetException
+import java.lang.reflect.Method
+
+/**
+ * Provides interface for interaction with locally loaded SDK with ApiVersion 1.
+ *
+ * @suppress
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY)
+internal class SdkV1 private constructor(
+ sdkProvider: Any,
+
+ private val onLoadSdkMethod: Method,
+ private val beforeUnloadSdkMethod: Method,
+
+ private val sandboxedSdkCompatBuilder: SandboxedSdkCompatBuilderV1,
+ private val loadSdkCompatExceptionBuilder: LoadSdkCompatExceptionBuilderV1
+) : LocalSdk(sdkProvider) {
+
+ @SuppressLint("BanUncheckedReflection") // using reflection on library classes
+ override fun onLoadSdk(params: Bundle): SandboxedSdkCompat {
+ try {
+ val rawResult = onLoadSdkMethod.invoke(sdkProvider, params)
+ return sandboxedSdkCompatBuilder.build(rawResult!!)
+ } catch (e: InvocationTargetException) {
+ throw loadSdkCompatExceptionBuilder.tryRebuildCompatException(e.targetException)
+ } catch (ex: Exception) {
+ throw LoadSdkCompatException(
+ LoadSdkCompatException.LOAD_SDK_INTERNAL_ERROR,
+ "Failed during onLoadSdk call",
+ ex
+ )
+ }
+ }
+
+ @SuppressLint("BanUncheckedReflection") // using reflection on library classes
+ override fun beforeUnloadSdk() {
+ beforeUnloadSdkMethod.invoke(sdkProvider)
+ }
+
+ internal class SandboxedSdkCompatBuilderV1 private constructor(
+ private val getInterfaceMethod: Method
+ ) {
+
+ @SuppressLint("BanUncheckedReflection") // calling method on SandboxedSdkCompat class
+ fun build(rawObject: Any): SandboxedSdkCompat {
+ val binder = getInterfaceMethod.invoke(rawObject) as IBinder
+ return SandboxedSdkCompat(binder)
+ }
+
+ companion object {
+
+ fun create(classLoader: ClassLoader?): SandboxedSdkCompatBuilderV1 {
+ val sandboxedSdkCompatClass = Class.forName(
+ SandboxedSdkCompat::class.java.name,
+ /* initialize = */ false,
+ classLoader
+ )
+ val getInterfaceMethod = sandboxedSdkCompatClass.getMethod("getInterface")
+ return SandboxedSdkCompatBuilderV1(getInterfaceMethod)
+ }
+ }
+ }
+
+ internal class LoadSdkCompatExceptionBuilderV1 private constructor(
+ private val getLoadSdkErrorCodeMethod: Method,
+ private val getExtraInformationMethod: Method
+ ) {
+ @SuppressLint("BanUncheckedReflection") // calling method on LoadSdkCompatException class
+ fun tryRebuildCompatException(rawException: Throwable): Throwable {
+ if (rawException.javaClass.name != LoadSdkCompatException::class.java.name) {
+ return rawException
+ }
+
+ return try {
+ val loadSdkErrorCode = getLoadSdkErrorCodeMethod.invoke(rawException) as Int
+ val extraInformation = getExtraInformationMethod.invoke(rawException) as Bundle
+ LoadSdkCompatException(
+ loadSdkErrorCode,
+ rawException.message,
+ rawException.cause,
+ extraInformation
+ )
+ } catch (ex: Throwable) {
+ // failed to rebuild, just wrap original
+ LoadSdkCompatException(
+ LoadSdkCompatException.LOAD_SDK_INTERNAL_ERROR,
+ "Failed to rebuild exception with error ${ex.message}",
+ rawException
+ )
+ }
+ }
+
+ companion object {
+ fun create(classLoader: ClassLoader?): LoadSdkCompatExceptionBuilderV1 {
+ val loadSdkCompatExceptionClass = Class.forName(
+ LoadSdkCompatException::class.java.name,
+ /* initialize = */ false,
+ classLoader
+ )
+ val getLoadSdkErrorCodeMethod = loadSdkCompatExceptionClass.getMethod(
+ "getLoadSdkErrorCode"
+ )
+ val getExtraInformationMethod = loadSdkCompatExceptionClass.getMethod(
+ "getExtraInformation"
+ )
+ return LoadSdkCompatExceptionBuilderV1(
+ getLoadSdkErrorCodeMethod,
+ getExtraInformationMethod
+ )
+ }
+ }
+ }
+
+ companion object {
+
+ @SuppressLint("BanUncheckedReflection") // calling method of SandboxedSdkProviderCompat
+ fun create(
+ classLoader: ClassLoader?,
+ sdkProviderClassName: String,
+ appContext: Context
+ ): SdkV1 {
+ val sdkProviderClass = Class.forName(
+ sdkProviderClassName,
+ /* initialize = */ false,
+ classLoader
+ )
+ val attachContextMethod =
+ sdkProviderClass.getMethod("attachContext", Context::class.java)
+ val onLoadSdkMethod = sdkProviderClass.getMethod("onLoadSdk", Bundle::class.java)
+ val beforeUnloadSdkMethod = sdkProviderClass.getMethod("beforeUnloadSdk")
+ val sandboxedSdkCompatBuilder = SandboxedSdkCompatBuilderV1.create(classLoader)
+ val loadSdkCompatExceptionBuilder =
+ LoadSdkCompatExceptionBuilderV1.create(classLoader)
+
+ val sdkProvider = sdkProviderClass.getConstructor().newInstance()
+ val sandboxedSdkContextCompat = SandboxedSdkContextCompat(appContext, classLoader)
+ attachContextMethod.invoke(sdkProvider, sandboxedSdkContextCompat)
+
+ return SdkV1(
+ sdkProvider,
+ onLoadSdkMethod,
+ beforeUnloadSdkMethod,
+ sandboxedSdkCompatBuilder,
+ loadSdkCompatExceptionBuilder
+ )
+ }
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/storage/CachedLocalSdkStorage.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/storage/CachedLocalSdkStorage.kt
new file mode 100644
index 0000000..82251fc
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/storage/CachedLocalSdkStorage.kt
@@ -0,0 +1,148 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.loader.storage
+
+import android.content.Context
+import android.os.Build
+import android.os.Build.VERSION_CODES.JELLY_BEAN_MR2
+import android.os.Environment
+import android.os.StatFs
+import android.util.Log
+import androidx.annotation.DoNotInline
+import androidx.annotation.RequiresApi
+import androidx.privacysandbox.sdkruntime.client.config.LocalSdkConfig
+import java.io.File
+
+/**
+ * Caching implementation of [LocalSdkStorage].
+ *
+ * Extract SDK DEX files into folder provided by [LocalSdkFolderProvider].
+ * Not extracting new files if available space lower than lowSpaceThreshold.
+ * Return result only if all files successfully extracted.
+ */
+internal class CachedLocalSdkStorage private constructor(
+ private val context: Context,
+ private val rootFolderProvider: LocalSdkFolderProvider,
+ private val lowSpaceThreshold: Long
+) : LocalSdkStorage {
+
+ /**
+ * Return SDK DEX files from folder provided by [LocalSdkFolderProvider].
+ * Extract missing files from assets if available space bigger than lowSpaceThreshold.
+ *
+ * @param sdkConfig sdk config
+ * @return [LocalSdkDexFiles] if all SDK DEX files available in SDK folder
+ * or null if something missing and couldn't be extracted because of
+ * available space lower than lowSpaceThreshold
+ */
+ override fun dexFilesFor(sdkConfig: LocalSdkConfig): LocalSdkDexFiles? {
+ val disableExtracting = availableBytes() < lowSpaceThreshold
+ val targetFolder = rootFolderProvider.dexFolderFor(sdkConfig)
+
+ try {
+ val files = buildList {
+ for (index in sdkConfig.dexPaths.indices) {
+ val assetName = sdkConfig.dexPaths[index]
+ val outputFileName = "$index.dex"
+ val outputDexFile = File(targetFolder, outputFileName)
+
+ if (!outputDexFile.exists()) {
+ if (disableExtracting) {
+ Log.i(LOG_TAG, "Can't extract $assetName because of low space")
+ return null
+ }
+ extractAssetToFile(assetName, outputDexFile)
+ }
+
+ add(outputDexFile)
+ }
+ }
+ return LocalSdkDexFiles(files)
+ } catch (ex: Exception) {
+ Log.e(
+ LOG_TAG,
+ "Failed to extract ${sdkConfig.packageName}, deleting $targetFolder.",
+ ex
+ )
+
+ if (!targetFolder.deleteRecursively()) {
+ Log.e(
+ LOG_TAG,
+ "Failed to delete $targetFolder during cleanup.",
+ ex
+ )
+ }
+
+ throw ex
+ }
+ }
+
+ private fun extractAssetToFile(
+ assetName: String,
+ outputFile: File,
+ ) {
+ outputFile.createNewFile()
+ context.assets.open(assetName).use { fromStream ->
+ outputFile.outputStream().use { toStream ->
+ fromStream.copyTo(toStream)
+ }
+ }
+ outputFile.setReadOnly()
+ }
+
+ private fun availableBytes(): Long {
+ val dataDirectory = Environment.getDataDirectory()
+ val statFs = StatFs(dataDirectory.path)
+ if (Build.VERSION.SDK_INT >= JELLY_BEAN_MR2) {
+ return Api18Impl.availableBytes(statFs)
+ }
+
+ @Suppress("DEPRECATION")
+ val blockSize = statFs.blockSize.toLong()
+
+ @Suppress("DEPRECATION")
+ val availableBlocks = statFs.availableBlocks.toLong()
+
+ return availableBlocks * blockSize
+ }
+
+ @RequiresApi(JELLY_BEAN_MR2)
+ private object Api18Impl {
+ @DoNotInline
+ fun availableBytes(statFs: StatFs) = statFs.availableBytes
+ }
+
+ companion object {
+
+ const val LOG_TAG = "CachedLocalSdkStorage"
+
+ /**
+ * Create CachedLocalSdkStorage.
+ *
+ * @param context Application context
+ * @param lowSpaceThreshold Minimal available space in bytes required to proceed with
+ * extracting new SDK Dex files.
+ */
+ fun create(
+ context: Context,
+ lowSpaceThreshold: Long
+ ): CachedLocalSdkStorage {
+ val localSdkFolderProvider = LocalSdkFolderProvider.create(context)
+ return CachedLocalSdkStorage(context, localSdkFolderProvider, lowSpaceThreshold)
+ }
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/storage/LocalSdkDexFiles.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/storage/LocalSdkDexFiles.kt
new file mode 100644
index 0000000..6cf8035
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/storage/LocalSdkDexFiles.kt
@@ -0,0 +1,35 @@
+/*
+ * 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.
+ */
+
+@file:RestrictTo(RestrictTo.Scope.LIBRARY)
+
+package androidx.privacysandbox.sdkruntime.client.loader.storage
+
+import androidx.annotation.RestrictTo
+import java.io.File
+
+/**
+ * Represent SDK Dex files extracted to device storage.
+ */
+internal data class LocalSdkDexFiles(
+ val files: List<File>
+)
+
+/**
+ * Convert [LocalSdkDexFiles] to ClassPath string.
+ */
+internal fun LocalSdkDexFiles.toClassPathString() =
+ files.joinToString(separator = File.pathSeparator, transform = File::getPath)
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/storage/LocalSdkFolderProvider.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/storage/LocalSdkFolderProvider.kt
new file mode 100644
index 0000000..72aaffb
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/storage/LocalSdkFolderProvider.kt
@@ -0,0 +1,128 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.loader.storage
+
+import android.content.Context
+import android.content.pm.PackageManager
+import android.os.Build
+import android.os.Build.VERSION_CODES.TIRAMISU
+import androidx.annotation.DoNotInline
+import androidx.annotation.RequiresApi
+import androidx.privacysandbox.sdkruntime.client.config.LocalSdkConfig
+import java.io.DataInputStream
+import java.io.DataOutputStream
+import java.io.File
+
+/**
+ * Create folders for Local SDKs in ([Context.getCacheDir] / RuntimeEnabledSdk / <packageName>)
+ *
+ * Store Application update time ([android.content.pm.PackageInfo.lastUpdateTime]) in
+ * ([Context.getCacheDir] / RuntimeEnabledSdk / Folder.version) file.
+ * Remove SDK Folders if Application was updated after folders were created.
+ */
+internal class LocalSdkFolderProvider private constructor(
+ private val sdkRootFolder: File
+) {
+
+ /**
+ * Return folder on storage that should be used for storing SDK DEX files.
+ */
+ fun dexFolderFor(sdkConfig: LocalSdkConfig): File {
+ val sdkDexFolder = File(sdkRootFolder, sdkConfig.packageName)
+ if (!sdkDexFolder.exists()) {
+ sdkDexFolder.mkdirs()
+ }
+ return sdkDexFolder
+ }
+
+ companion object {
+
+ private const val SDK_ROOT_FOLDER = "RuntimeEnabledSdk"
+ private const val VERSION_FILE_NAME = "Folder.version"
+
+ /**
+ * Create LocalSdkFolderProvider.
+ *
+ * Check if current root folder created in same app installation
+ * and remove folder content if not.
+ */
+ fun create(context: Context): LocalSdkFolderProvider {
+ val sdkRootFolder = createSdkRootFolder(context)
+ return LocalSdkFolderProvider(sdkRootFolder)
+ }
+
+ private fun createSdkRootFolder(context: Context): File {
+ val rootFolder = File(context.cacheDir, SDK_ROOT_FOLDER)
+ val versionFile = File(rootFolder, VERSION_FILE_NAME)
+
+ val sdkRootFolderVersion = readVersion(versionFile)
+ val lastUpdateTime = appLastUpdateTime(context)
+
+ if (lastUpdateTime != sdkRootFolderVersion) {
+ if (rootFolder.exists()) {
+ rootFolder.deleteRecursively()
+ }
+ rootFolder.mkdirs()
+ versionFile.createNewFile()
+
+ versionFile.outputStream().use { outputStream ->
+ DataOutputStream(outputStream).use { dataStream ->
+ dataStream.writeLong(lastUpdateTime)
+ }
+ }
+ }
+
+ return rootFolder
+ }
+
+ private fun appLastUpdateTime(context: Context): Long {
+ if (Build.VERSION.SDK_INT >= TIRAMISU) {
+ return Api33Impl.getLastUpdateTime(context)
+ }
+
+ @Suppress("DEPRECATION")
+ val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
+ return packageInfo.lastUpdateTime
+ }
+
+ private fun readVersion(versionFile: File): Long? {
+ if (!versionFile.exists()) {
+ return null
+ }
+ try {
+ versionFile.inputStream().use { inputStream ->
+ DataInputStream(inputStream).use { dataStream ->
+ return dataStream.readLong()
+ }
+ }
+ } catch (e: Exception) {
+ // Failed to parse or IOException, treat as no version file exists.
+ return null
+ }
+ }
+ }
+
+ @RequiresApi(TIRAMISU)
+ private object Api33Impl {
+ @DoNotInline
+ fun getLastUpdateTime(context: Context): Long =
+ context.packageManager.getPackageInfo(
+ context.packageName,
+ PackageManager.PackageInfoFlags.of(0)
+ ).lastUpdateTime
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/storage/LocalSdkStorage.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/storage/LocalSdkStorage.kt
new file mode 100644
index 0000000..66fdab7
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/main/java/androidx/privacysandbox/sdkruntime/client/loader/storage/LocalSdkStorage.kt
@@ -0,0 +1,32 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.loader.storage
+
+import androidx.privacysandbox.sdkruntime.client.config.LocalSdkConfig
+
+/**
+ * Provides interface for getting SDK related files.
+ */
+internal interface LocalSdkStorage {
+ /**
+ * Get [LocalSdkDexFiles] for bundled SDK.
+ *
+ * @param sdkConfig sdk config
+ * @return [LocalSdkDexFiles] if DEX files available or null if not.
+ */
+ fun dexFilesFor(sdkConfig: LocalSdkConfig): LocalSdkDexFiles?
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-client/src/test/java/androidx/privacysandbox/sdkruntime/client/loader/ResourceRemappingTest.kt b/privacysandbox/sdkruntime/sdkruntime-client/src/test/java/androidx/privacysandbox/sdkruntime/client/loader/ResourceRemappingTest.kt
new file mode 100644
index 0000000..cb17a81
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-client/src/test/java/androidx/privacysandbox/sdkruntime/client/loader/ResourceRemappingTest.kt
@@ -0,0 +1,149 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.client.loader
+
+import androidx.privacysandbox.sdkruntime.client.config.ResourceRemappingConfig
+import androidx.room.compiler.processing.util.Source
+import androidx.room.compiler.processing.util.compiler.TestCompilationArguments
+import androidx.room.compiler.processing.util.compiler.compile
+import com.google.common.truth.Truth.assertThat
+import java.net.URLClassLoader
+import kotlin.reflect.KClass
+import org.junit.Assert.assertThrows
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TemporaryFolder
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+
+@RunWith(JUnit4::class)
+class ResourceRemappingTest {
+
+ @field:Rule
+ @JvmField
+ val temporaryFolder = TemporaryFolder()
+
+ @Test
+ fun apply_whenNonNullConfig_updatePackageId() {
+ val classLoader = compileAndLoad(
+ Source.java(
+ "RPackage", """
+ public class RPackage {
+ public static int packageId = 0;
+ }
+ """
+ )
+ )
+
+ ResourceRemapping.apply(
+ classLoader,
+ ResourceRemappingConfig(
+ rPackageClassName = "RPackage",
+ packageId = 42
+ )
+ )
+
+ val rPackageClass = classLoader.loadClass("RPackage")
+ val packageIdField = rPackageClass.getDeclaredField("packageId")
+ val value = packageIdField.getInt(null)
+
+ assertThat(value).isEqualTo(42)
+ }
+
+ @Test
+ fun apply_whenNullConfig_doesntThrow() {
+ val classLoader = compileAndLoad(
+ Source.java(
+ "AnotherClass", """
+ public class AnotherClass {
+ }
+ """
+ )
+ )
+
+ ResourceRemapping.apply(
+ classLoader,
+ remappingConfig = null
+ )
+ }
+
+ @Test
+ fun apply_whenNoRPackageClass_throwsClassNotFoundException() {
+ val source = Source.java(
+ "AnotherClass", """
+ public class AnotherClass {
+ }
+ """
+ )
+
+ val config = ResourceRemappingConfig(
+ rPackageClassName = "RPackage",
+ packageId = 42
+ )
+
+ assertThrows(ClassNotFoundException::class, source, config)
+ }
+
+ @Test
+ fun apply_whenNoPackageIdField_throwsNoSuchFieldException() {
+ val source = Source.java(
+ "RPackage", """
+ public class RPackage {
+ }
+ """
+ )
+
+ val config = ResourceRemappingConfig(
+ rPackageClassName = "RPackage",
+ packageId = 42
+ )
+
+ assertThrows(NoSuchFieldException::class, source, config)
+ }
+
+ private fun assertThrows(
+ expectedThrowable: KClass<out Exception>,
+ source: Source,
+ config: ResourceRemappingConfig
+ ) {
+ val classLoader = compileAndLoad(source)
+ assertThrows(expectedThrowable.java) {
+ ResourceRemapping.apply(
+ classLoader,
+ config
+ )
+ }
+ }
+
+ private fun compileAndLoad(source: Source): ClassLoader {
+ val compilationResult = compile(
+ temporaryFolder.root,
+ TestCompilationArguments(
+ sources = listOf(source),
+ )
+ )
+
+ assertThat(compilationResult.success).isTrue()
+
+ return URLClassLoader.newInstance(
+ compilationResult.outputClasspath.map {
+ it.toURI().toURL()
+ }.toTypedArray(),
+ /* parent = */ null
+ )
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-core/api/current.txt b/privacysandbox/sdkruntime/sdkruntime-core/api/current.txt
index e6f50d0..cc05185 100644
--- a/privacysandbox/sdkruntime/sdkruntime-core/api/current.txt
+++ b/privacysandbox/sdkruntime/sdkruntime-core/api/current.txt
@@ -1 +1,50 @@
// Signature format: 4.0
+package androidx.privacysandbox.sdkruntime.core {
+
+ public final class LoadSdkCompatException extends java.lang.Exception {
+ ctor public LoadSdkCompatException(Throwable cause, android.os.Bundle extraInfo);
+ method public android.os.Bundle getExtraInformation();
+ method public int getLoadSdkErrorCode();
+ property public final android.os.Bundle extraInformation;
+ property public final int loadSdkErrorCode;
+ field public static final androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException.Companion Companion;
+ field public static final int LOAD_SDK_ALREADY_LOADED = 101; // 0x65
+ field public static final int LOAD_SDK_INTERNAL_ERROR = 500; // 0x1f4
+ field public static final int LOAD_SDK_NOT_FOUND = 100; // 0x64
+ field public static final int LOAD_SDK_SDK_DEFINED_ERROR = 102; // 0x66
+ field public static final int LOAD_SDK_SDK_SANDBOX_DISABLED = 103; // 0x67
+ field public static final int SDK_SANDBOX_PROCESS_NOT_AVAILABLE = 503; // 0x1f7
+ }
+
+ public static final class LoadSdkCompatException.Companion {
+ }
+
+ public final class SandboxedSdkCompat {
+ ctor public SandboxedSdkCompat(android.os.IBinder sdkInterface);
+ method public static androidx.privacysandbox.sdkruntime.core.SandboxedSdkCompat create(android.os.IBinder binder);
+ method public android.os.IBinder? getInterface();
+ field public static final androidx.privacysandbox.sdkruntime.core.SandboxedSdkCompat.Companion Companion;
+ }
+
+ public static final class SandboxedSdkCompat.Companion {
+ method public androidx.privacysandbox.sdkruntime.core.SandboxedSdkCompat create(android.os.IBinder binder);
+ }
+
+ @RequiresExtension(extension=android.os.ext.SdkExtensions.AD_SERVICES, version=4) public final class SandboxedSdkProviderAdapter extends android.app.sdksandbox.SandboxedSdkProvider {
+ ctor public SandboxedSdkProviderAdapter();
+ method public android.view.View getView(android.content.Context windowContext, android.os.Bundle params, int width, int height);
+ method @kotlin.jvm.Throws(exceptionClasses=LoadSdkException::class) public android.app.sdksandbox.SandboxedSdk onLoadSdk(android.os.Bundle params) throws android.app.sdksandbox.LoadSdkException;
+ }
+
+ public abstract class SandboxedSdkProviderCompat {
+ ctor public SandboxedSdkProviderCompat();
+ method public final void attachContext(android.content.Context context);
+ method public void beforeUnloadSdk();
+ method public final android.content.Context? getContext();
+ method public abstract android.view.View getView(android.content.Context windowContext, android.os.Bundle params, int width, int height);
+ method @kotlin.jvm.Throws(exceptionClasses=LoadSdkCompatException::class) public abstract androidx.privacysandbox.sdkruntime.core.SandboxedSdkCompat onLoadSdk(android.os.Bundle params) throws androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException;
+ property public final android.content.Context? context;
+ }
+
+}
+
diff --git a/privacysandbox/sdkruntime/sdkruntime-core/api/public_plus_experimental_current.txt b/privacysandbox/sdkruntime/sdkruntime-core/api/public_plus_experimental_current.txt
index e6f50d0..cc05185 100644
--- a/privacysandbox/sdkruntime/sdkruntime-core/api/public_plus_experimental_current.txt
+++ b/privacysandbox/sdkruntime/sdkruntime-core/api/public_plus_experimental_current.txt
@@ -1 +1,50 @@
// Signature format: 4.0
+package androidx.privacysandbox.sdkruntime.core {
+
+ public final class LoadSdkCompatException extends java.lang.Exception {
+ ctor public LoadSdkCompatException(Throwable cause, android.os.Bundle extraInfo);
+ method public android.os.Bundle getExtraInformation();
+ method public int getLoadSdkErrorCode();
+ property public final android.os.Bundle extraInformation;
+ property public final int loadSdkErrorCode;
+ field public static final androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException.Companion Companion;
+ field public static final int LOAD_SDK_ALREADY_LOADED = 101; // 0x65
+ field public static final int LOAD_SDK_INTERNAL_ERROR = 500; // 0x1f4
+ field public static final int LOAD_SDK_NOT_FOUND = 100; // 0x64
+ field public static final int LOAD_SDK_SDK_DEFINED_ERROR = 102; // 0x66
+ field public static final int LOAD_SDK_SDK_SANDBOX_DISABLED = 103; // 0x67
+ field public static final int SDK_SANDBOX_PROCESS_NOT_AVAILABLE = 503; // 0x1f7
+ }
+
+ public static final class LoadSdkCompatException.Companion {
+ }
+
+ public final class SandboxedSdkCompat {
+ ctor public SandboxedSdkCompat(android.os.IBinder sdkInterface);
+ method public static androidx.privacysandbox.sdkruntime.core.SandboxedSdkCompat create(android.os.IBinder binder);
+ method public android.os.IBinder? getInterface();
+ field public static final androidx.privacysandbox.sdkruntime.core.SandboxedSdkCompat.Companion Companion;
+ }
+
+ public static final class SandboxedSdkCompat.Companion {
+ method public androidx.privacysandbox.sdkruntime.core.SandboxedSdkCompat create(android.os.IBinder binder);
+ }
+
+ @RequiresExtension(extension=android.os.ext.SdkExtensions.AD_SERVICES, version=4) public final class SandboxedSdkProviderAdapter extends android.app.sdksandbox.SandboxedSdkProvider {
+ ctor public SandboxedSdkProviderAdapter();
+ method public android.view.View getView(android.content.Context windowContext, android.os.Bundle params, int width, int height);
+ method @kotlin.jvm.Throws(exceptionClasses=LoadSdkException::class) public android.app.sdksandbox.SandboxedSdk onLoadSdk(android.os.Bundle params) throws android.app.sdksandbox.LoadSdkException;
+ }
+
+ public abstract class SandboxedSdkProviderCompat {
+ ctor public SandboxedSdkProviderCompat();
+ method public final void attachContext(android.content.Context context);
+ method public void beforeUnloadSdk();
+ method public final android.content.Context? getContext();
+ method public abstract android.view.View getView(android.content.Context windowContext, android.os.Bundle params, int width, int height);
+ method @kotlin.jvm.Throws(exceptionClasses=LoadSdkCompatException::class) public abstract androidx.privacysandbox.sdkruntime.core.SandboxedSdkCompat onLoadSdk(android.os.Bundle params) throws androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException;
+ property public final android.content.Context? context;
+ }
+
+}
+
diff --git a/privacysandbox/sdkruntime/sdkruntime-core/api/restricted_current.txt b/privacysandbox/sdkruntime/sdkruntime-core/api/restricted_current.txt
index e6f50d0..cc05185 100644
--- a/privacysandbox/sdkruntime/sdkruntime-core/api/restricted_current.txt
+++ b/privacysandbox/sdkruntime/sdkruntime-core/api/restricted_current.txt
@@ -1 +1,50 @@
// Signature format: 4.0
+package androidx.privacysandbox.sdkruntime.core {
+
+ public final class LoadSdkCompatException extends java.lang.Exception {
+ ctor public LoadSdkCompatException(Throwable cause, android.os.Bundle extraInfo);
+ method public android.os.Bundle getExtraInformation();
+ method public int getLoadSdkErrorCode();
+ property public final android.os.Bundle extraInformation;
+ property public final int loadSdkErrorCode;
+ field public static final androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException.Companion Companion;
+ field public static final int LOAD_SDK_ALREADY_LOADED = 101; // 0x65
+ field public static final int LOAD_SDK_INTERNAL_ERROR = 500; // 0x1f4
+ field public static final int LOAD_SDK_NOT_FOUND = 100; // 0x64
+ field public static final int LOAD_SDK_SDK_DEFINED_ERROR = 102; // 0x66
+ field public static final int LOAD_SDK_SDK_SANDBOX_DISABLED = 103; // 0x67
+ field public static final int SDK_SANDBOX_PROCESS_NOT_AVAILABLE = 503; // 0x1f7
+ }
+
+ public static final class LoadSdkCompatException.Companion {
+ }
+
+ public final class SandboxedSdkCompat {
+ ctor public SandboxedSdkCompat(android.os.IBinder sdkInterface);
+ method public static androidx.privacysandbox.sdkruntime.core.SandboxedSdkCompat create(android.os.IBinder binder);
+ method public android.os.IBinder? getInterface();
+ field public static final androidx.privacysandbox.sdkruntime.core.SandboxedSdkCompat.Companion Companion;
+ }
+
+ public static final class SandboxedSdkCompat.Companion {
+ method public androidx.privacysandbox.sdkruntime.core.SandboxedSdkCompat create(android.os.IBinder binder);
+ }
+
+ @RequiresExtension(extension=android.os.ext.SdkExtensions.AD_SERVICES, version=4) public final class SandboxedSdkProviderAdapter extends android.app.sdksandbox.SandboxedSdkProvider {
+ ctor public SandboxedSdkProviderAdapter();
+ method public android.view.View getView(android.content.Context windowContext, android.os.Bundle params, int width, int height);
+ method @kotlin.jvm.Throws(exceptionClasses=LoadSdkException::class) public android.app.sdksandbox.SandboxedSdk onLoadSdk(android.os.Bundle params) throws android.app.sdksandbox.LoadSdkException;
+ }
+
+ public abstract class SandboxedSdkProviderCompat {
+ ctor public SandboxedSdkProviderCompat();
+ method public final void attachContext(android.content.Context context);
+ method public void beforeUnloadSdk();
+ method public final android.content.Context? getContext();
+ method public abstract android.view.View getView(android.content.Context windowContext, android.os.Bundle params, int width, int height);
+ method @kotlin.jvm.Throws(exceptionClasses=LoadSdkCompatException::class) public abstract androidx.privacysandbox.sdkruntime.core.SandboxedSdkCompat onLoadSdk(android.os.Bundle params) throws androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException;
+ property public final android.content.Context? context;
+ }
+
+}
+
diff --git a/privacysandbox/sdkruntime/sdkruntime-core/build.gradle b/privacysandbox/sdkruntime/sdkruntime-core/build.gradle
index bbd8542..f976dc3 100644
--- a/privacysandbox/sdkruntime/sdkruntime-core/build.gradle
+++ b/privacysandbox/sdkruntime/sdkruntime-core/build.gradle
@@ -24,9 +24,30 @@
dependencies {
api(libs.kotlinStdlib)
+ api(projectOrArtifact(":annotation:annotation"))
+
+ implementation("androidx.core:core:1.8.0")
+
+ // TODO(b/249982004): cleanup dependencies
+ androidTestImplementation(libs.testCore)
+ androidTestImplementation(libs.testExtJunit)
+ androidTestImplementation(libs.testRunner)
+ androidTestImplementation(libs.testRules)
+ androidTestImplementation(libs.truth)
+ androidTestImplementation(libs.junit)
+
+ androidTestImplementation(libs.mockitoCore, excludes.bytebuddy) // DexMaker has it"s own MockMaker
+ androidTestImplementation(libs.dexmakerMockitoInline, excludes.bytebuddy) // DexMaker has it"s own MockMaker
}
android {
+ lintOptions {
+ // All components could be loaded from another app via client library
+ disable("BanKeepAnnotation")
+ }
+
+ compileSdk = 33
+ compileSdkExtension = 4
namespace "androidx.privacysandbox.sdkruntime.core"
}
diff --git a/privacysandbox/sdkruntime/sdkruntime-core/src/androidTest/AndroidManifest.xml b/privacysandbox/sdkruntime/sdkruntime-core/src/androidTest/AndroidManifest.xml
new file mode 100644
index 0000000..3f2e804
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-core/src/androidTest/AndroidManifest.xml
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ 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.
+ -->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+</manifest>
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-core/src/androidTest/assets/SandboxedSdkProviderCompatClassName.txt b/privacysandbox/sdkruntime/sdkruntime-core/src/androidTest/assets/SandboxedSdkProviderCompatClassName.txt
new file mode 100644
index 0000000..3d062e4
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-core/src/androidTest/assets/SandboxedSdkProviderCompatClassName.txt
@@ -0,0 +1 @@
+androidx.privacysandbox.sdkruntime.core.SandboxedSdkProviderAdapterTest$TestOnLoadReturnResultSdkProvider
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-core/src/androidTest/java/androidx/privacysandbox/sdkruntime/core/LoadSdkCompatExceptionTest.kt b/privacysandbox/sdkruntime/sdkruntime-core/src/androidTest/java/androidx/privacysandbox/sdkruntime/core/LoadSdkCompatExceptionTest.kt
new file mode 100644
index 0000000..9235febc
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-core/src/androidTest/java/androidx/privacysandbox/sdkruntime/core/LoadSdkCompatExceptionTest.kt
@@ -0,0 +1,81 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.core
+
+import android.annotation.SuppressLint
+import android.app.sdksandbox.LoadSdkException
+import android.os.Build.VERSION_CODES.TIRAMISU
+import android.os.Bundle
+import android.os.ext.SdkExtensions.AD_SERVICES
+import androidx.annotation.RequiresExtension
+import androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException.Companion.toLoadCompatSdkException
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SdkSuppress
+import androidx.test.filters.SmallTest
+import com.google.common.truth.Truth.assertThat
+import org.junit.Assume.assumeTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+// TODO(b/249981547) Remove suppress after updating to new lint version (b/262251309)
+@SuppressLint("NewApi")
+// TODO(b/262577044) Remove RequiresExtension after extensions support in @SdkSuppress
+@RequiresExtension(extension = AD_SERVICES, version = 4)
+@SdkSuppress(minSdkVersion = TIRAMISU)
+class LoadSdkCompatExceptionTest {
+
+ @Before
+ fun setUp() {
+ assumeTrue("Requires Sandbox API available", isSandboxApiAvailable())
+ }
+
+ @Test
+ fun toLoadSdkException_returnLoadSdkException() {
+ val loadSdkCompatException = LoadSdkCompatException(RuntimeException(), Bundle())
+
+ val loadSdkException = loadSdkCompatException.toLoadSdkException()
+
+ assertThat(loadSdkException.cause)
+ .isSameInstanceAs(loadSdkCompatException.cause)
+ assertThat(loadSdkException.extraInformation)
+ .isSameInstanceAs(loadSdkCompatException.extraInformation)
+ assertThat(loadSdkException.loadSdkErrorCode)
+ .isEqualTo(loadSdkCompatException.loadSdkErrorCode)
+ }
+
+ @Test
+ fun toLoadCompatSdkException_returnLoadCompatSdkException() {
+ val loadSdkException = LoadSdkException(
+ RuntimeException(),
+ Bundle()
+ )
+
+ val loadCompatSdkException = toLoadCompatSdkException(loadSdkException)
+
+ assertThat(loadCompatSdkException.cause)
+ .isSameInstanceAs(loadSdkException.cause)
+ assertThat(loadCompatSdkException.extraInformation)
+ .isSameInstanceAs(loadSdkException.extraInformation)
+ assertThat(loadCompatSdkException.loadSdkErrorCode)
+ .isEqualTo(loadSdkException.loadSdkErrorCode)
+ }
+
+ private fun isSandboxApiAvailable() =
+ AdServicesInfo.version() >= 4
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-core/src/androidTest/java/androidx/privacysandbox/sdkruntime/core/SandboxedSdkCompatTest.kt b/privacysandbox/sdkruntime/sdkruntime-core/src/androidTest/java/androidx/privacysandbox/sdkruntime/core/SandboxedSdkCompatTest.kt
new file mode 100644
index 0000000..195b68a
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-core/src/androidTest/java/androidx/privacysandbox/sdkruntime/core/SandboxedSdkCompatTest.kt
@@ -0,0 +1,83 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.core
+
+import android.annotation.SuppressLint
+import android.app.sdksandbox.SandboxedSdk
+import android.os.Binder
+import android.os.Build.VERSION_CODES.TIRAMISU
+import android.os.ext.SdkExtensions
+import androidx.annotation.RequiresExtension
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SdkSuppress
+import androidx.test.filters.SmallTest
+import com.google.common.truth.Truth.assertThat
+import org.junit.Assume.assumeTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class SandboxedSdkCompatTest {
+
+ @Test
+ fun getInterface_returnsBinderPassedToCreate() {
+ val binder = Binder()
+
+ val sandboxedSdkCompat = SandboxedSdkCompat(binder)
+
+ assertThat(sandboxedSdkCompat.getInterface())
+ .isSameInstanceAs(binder)
+ }
+
+ @Test
+ // TODO(b/249981547) Remove suppress after updating to new lint version (b/262251309)
+ @SuppressLint("NewApi")
+ // TODO(b/262577044) Remove RequiresExtension after extensions support in @SdkSuppress
+ @RequiresExtension(extension = SdkExtensions.AD_SERVICES, version = 4)
+ @SdkSuppress(minSdkVersion = TIRAMISU)
+ fun toSandboxedSdk_whenCreatedFromBinder_returnsSandboxedSdkWithSameBinder() {
+ assumeTrue("Requires Sandbox API available", isSandboxApiAvailable())
+
+ val binder = Binder()
+
+ val toSandboxedSdkResult = SandboxedSdkCompat(binder).toSandboxedSdk()
+
+ assertThat(toSandboxedSdkResult.getInterface())
+ .isSameInstanceAs(binder)
+ }
+
+ @Test
+ // TODO(b/249981547) Remove suppress after updating to new lint version (b/262251309)
+ @SuppressLint("NewApi")
+ // TODO(b/262577044) Remove RequiresExtension after extensions support in @SdkSuppress
+ @RequiresExtension(extension = SdkExtensions.AD_SERVICES, version = 4)
+ @SdkSuppress(minSdkVersion = TIRAMISU)
+ fun toSandboxedSdk_whenCreatedFromSandboxedSdk_returnsSameSandboxedSdk() {
+ assumeTrue("Requires Sandbox API available", isSandboxApiAvailable())
+
+ val binder = Binder()
+ val sandboxedSdk = SandboxedSdk(binder)
+
+ val toSandboxedSdkResult = SandboxedSdkCompat(sandboxedSdk).toSandboxedSdk()
+
+ assertThat(toSandboxedSdkResult)
+ .isSameInstanceAs(sandboxedSdk)
+ }
+
+ private fun isSandboxApiAvailable() =
+ AdServicesInfo.version() >= 4
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-core/src/androidTest/java/androidx/privacysandbox/sdkruntime/core/SandboxedSdkProviderAdapterTest.kt b/privacysandbox/sdkruntime/sdkruntime-core/src/androidTest/java/androidx/privacysandbox/sdkruntime/core/SandboxedSdkProviderAdapterTest.kt
new file mode 100644
index 0000000..db9b56b
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-core/src/androidTest/java/androidx/privacysandbox/sdkruntime/core/SandboxedSdkProviderAdapterTest.kt
@@ -0,0 +1,263 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.core
+
+import android.annotation.SuppressLint
+import android.app.sdksandbox.LoadSdkException
+import android.content.Context
+import android.os.Binder
+import android.os.Build.VERSION_CODES.TIRAMISU
+import android.os.Bundle
+import android.os.ext.SdkExtensions.AD_SERVICES
+import android.view.View
+import androidx.annotation.RequiresExtension
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SdkSuppress
+import androidx.test.filters.SmallTest
+import com.google.common.truth.Truth.assertThat
+import kotlin.reflect.KClass
+import org.junit.Assert.assertThrows
+import org.junit.Assume.assumeTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.Mockito.mock
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+// TODO(b/249981547) Remove suppress after updating to new lint version (b/262251309)
+@SuppressLint("NewApi")
+// TODO(b/262577044) Remove RequiresExtension after extensions support in @SdkSuppress
+@RequiresExtension(extension = AD_SERVICES, version = 4)
+@SdkSuppress(minSdkVersion = TIRAMISU)
+class SandboxedSdkProviderAdapterTest {
+
+ private lateinit var context: Context
+
+ @Before
+ fun setUp() {
+ assumeTrue("Requires Sandbox API available", isSandboxApiAvailable())
+ context = ApplicationProvider.getApplicationContext()
+ }
+
+ @Test
+ fun testAdapterGetCompatClassNameFromAsset() {
+ val expectedClassName = context.assets
+ .open("SandboxedSdkProviderCompatClassName.txt")
+ .use { inputStream ->
+ inputStream.bufferedReader().readLine()
+ }
+
+ val adapter = SandboxedSdkProviderAdapter()
+ adapter.attachContext(context)
+
+ adapter.onLoadSdk(Bundle())
+
+ val delegate = adapter.extractDelegate<SandboxedSdkProviderCompat>()
+ assertThat(delegate.javaClass.name)
+ .isEqualTo(expectedClassName)
+ }
+
+ @Test
+ fun onLoadSdk_shouldInstantiateDelegateAndAttachContext() {
+ val adapter = createAdapterFor(TestOnLoadReturnResultSdkProvider::class)
+
+ adapter.onLoadSdk(Bundle())
+
+ val delegate = adapter.extractDelegate<TestOnLoadReturnResultSdkProvider>()
+ assertThat(delegate.context)
+ .isSameInstanceAs(context)
+ }
+
+ @Test
+ fun onLoadSdk_shouldDelegateToCompatClassAndReturnResult() {
+ val adapter = createAdapterFor(TestOnLoadReturnResultSdkProvider::class)
+ val params = Bundle()
+
+ val result = adapter.onLoadSdk(params)
+
+ val delegate = adapter.extractDelegate<TestOnLoadReturnResultSdkProvider>()
+ assertThat(delegate.mLastOnLoadSdkBundle)
+ .isSameInstanceAs(params)
+ assertThat(result.getInterface())
+ .isEqualTo(delegate.mResult.getInterface())
+ }
+
+ @Test
+ fun loadSdk_shouldRethrowExceptionFromCompatClass() {
+ val adapter = createAdapterFor(TestOnLoadThrowSdkProvider::class)
+
+ val ex = assertThrows(LoadSdkException::class.java) {
+ adapter.onLoadSdk(Bundle())
+ }
+
+ val delegate = adapter.extractDelegate<TestOnLoadThrowSdkProvider>()
+ assertThat(ex.cause)
+ .isSameInstanceAs(delegate.mError.cause)
+ assertThat(ex.extraInformation)
+ .isSameInstanceAs(delegate.mError.extraInformation)
+ }
+
+ @Test
+ fun loadSdk_shouldThrowIfCompatClassNotExists() {
+ val adapter = createAdapterFor("NOTEXISTS")
+
+ assertThrows(ClassNotFoundException::class.java) {
+ adapter.onLoadSdk(Bundle())
+ }
+ }
+
+ @Test
+ fun beforeUnloadSdk_shouldDelegateToCompatProvider() {
+ val adapter = createAdapterFor(TestOnBeforeUnloadDelegateSdkProvider::class)
+
+ adapter.beforeUnloadSdk()
+
+ val delegate = adapter.extractDelegate<TestOnBeforeUnloadDelegateSdkProvider>()
+ assertThat(delegate.mBeforeUnloadSdkCalled)
+ .isTrue()
+ }
+
+ @Test
+ fun getView_shouldDelegateToCompatProviderAndReturnResult() {
+ val adapter = createAdapterFor(TestGetViewSdkProvider::class)
+ val windowContext = mock(Context::class.java)
+ val params = Bundle()
+ val width = 1
+ val height = 2
+
+ val result = adapter.getView(windowContext, params, width, height)
+
+ val delegate = adapter.extractDelegate<TestGetViewSdkProvider>()
+ assertThat(result)
+ .isSameInstanceAs(delegate.mView)
+ assertThat(delegate.mLastWindowContext)
+ .isSameInstanceAs(windowContext)
+ assertThat(delegate.mLastParams)
+ .isSameInstanceAs(params)
+ assertThat(delegate.mLastWidth)
+ .isSameInstanceAs(width)
+ assertThat(delegate.mLastHeigh)
+ .isSameInstanceAs(height)
+ }
+
+ private fun createAdapterFor(
+ clazz: KClass<out SandboxedSdkProviderCompat>
+ ): SandboxedSdkProviderAdapter = createAdapterFor(clazz.java.name)
+
+ private fun createAdapterFor(delegateClassName: String): SandboxedSdkProviderAdapter {
+ val adapter = SandboxedSdkProviderAdapter(
+ object : SandboxedSdkProviderAdapter.CompatClassNameProvider {
+ override fun getCompatProviderClassName(context: Context): String {
+ return delegateClassName
+ }
+ })
+ adapter.attachContext(context)
+ return adapter
+ }
+
+ private inline fun <reified T : SandboxedSdkProviderCompat>
+ SandboxedSdkProviderAdapter.extractDelegate(): T = delegate as T
+
+ class TestOnLoadReturnResultSdkProvider : SandboxedSdkProviderCompat() {
+ var mResult = SandboxedSdkCompat(Binder())
+ var mLastOnLoadSdkBundle: Bundle? = null
+
+ override fun onLoadSdk(params: Bundle): SandboxedSdkCompat {
+ mLastOnLoadSdkBundle = params
+ return mResult
+ }
+
+ override fun getView(
+ windowContext: Context,
+ params: Bundle,
+ width: Int,
+ height: Int
+ ): View {
+ throw RuntimeException("Not implemented")
+ }
+ }
+
+ class TestOnLoadThrowSdkProvider : SandboxedSdkProviderCompat() {
+ var mError = LoadSdkCompatException(RuntimeException(), Bundle())
+
+ @Throws(LoadSdkCompatException::class)
+ override fun onLoadSdk(params: Bundle): SandboxedSdkCompat {
+ throw mError
+ }
+
+ override fun getView(
+ windowContext: Context,
+ params: Bundle,
+ width: Int,
+ height: Int
+ ): View {
+ throw RuntimeException("Stub!")
+ }
+ }
+
+ class TestOnBeforeUnloadDelegateSdkProvider : SandboxedSdkProviderCompat() {
+ var mBeforeUnloadSdkCalled = false
+
+ override fun onLoadSdk(params: Bundle): SandboxedSdkCompat {
+ throw RuntimeException("Not implemented")
+ }
+
+ override fun beforeUnloadSdk() {
+ mBeforeUnloadSdkCalled = true
+ }
+
+ override fun getView(
+ windowContext: Context,
+ params: Bundle,
+ width: Int,
+ height: Int
+ ): View {
+ throw RuntimeException("Not implemented")
+ }
+ }
+
+ class TestGetViewSdkProvider : SandboxedSdkProviderCompat() {
+ val mView: View = mock(View::class.java)
+
+ var mLastWindowContext: Context? = null
+ var mLastParams: Bundle? = null
+ var mLastWidth = 0
+ var mLastHeigh = 0
+
+ override fun onLoadSdk(params: Bundle): SandboxedSdkCompat {
+ throw RuntimeException("Not implemented")
+ }
+
+ override fun getView(
+ windowContext: Context,
+ params: Bundle,
+ width: Int,
+ height: Int
+ ): View {
+ mLastWindowContext = windowContext
+ mLastParams = params
+ mLastWidth = width
+ mLastHeigh = height
+
+ return mView
+ }
+ }
+
+ private fun isSandboxApiAvailable() =
+ AdServicesInfo.version() >= 4
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-core/src/main/java/androidx/privacysandbox/sdkruntime/core/AdServicesInfo.kt b/privacysandbox/sdkruntime/sdkruntime-core/src/main/java/androidx/privacysandbox/sdkruntime/core/AdServicesInfo.kt
new file mode 100644
index 0000000..c43ea33
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-core/src/main/java/androidx/privacysandbox/sdkruntime/core/AdServicesInfo.kt
@@ -0,0 +1,48 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.core
+
+import android.os.Build
+import android.os.ext.SdkExtensions
+import androidx.annotation.DoNotInline
+import androidx.annotation.RequiresApi
+import androidx.annotation.RestrictTo
+
+/**
+ * Temporary replacement for BuildCompat.AD_SERVICES_EXTENSION_INT.
+ * TODO(b/249981547) Replace with AD_SERVICES_EXTENSION_INT after new core library release
+ *
+ * @suppress
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+object AdServicesInfo {
+
+ fun version(): Int {
+ return if (Build.VERSION.SDK_INT >= 30) {
+ Extensions30Impl.getAdServicesVersion()
+ } else {
+ 0
+ }
+ }
+
+ @RequiresApi(30)
+ private object Extensions30Impl {
+ @DoNotInline
+ fun getAdServicesVersion() =
+ SdkExtensions.getExtensionVersion(SdkExtensions.AD_SERVICES)
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-core/src/main/java/androidx/privacysandbox/sdkruntime/core/LoadSdkCompatException.kt b/privacysandbox/sdkruntime/sdkruntime-core/src/main/java/androidx/privacysandbox/sdkruntime/core/LoadSdkCompatException.kt
new file mode 100644
index 0000000..b1851c4
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-core/src/main/java/androidx/privacysandbox/sdkruntime/core/LoadSdkCompatException.kt
@@ -0,0 +1,227 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.core
+
+import android.annotation.SuppressLint
+import android.app.sdksandbox.LoadSdkException
+import android.os.Bundle
+import android.os.ext.SdkExtensions.AD_SERVICES
+import androidx.annotation.DoNotInline
+import androidx.annotation.IntDef
+import androidx.annotation.RequiresExtension
+import androidx.annotation.RestrictTo
+import androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP
+
+/**
+ * Compat alternative for [LoadSdkException].
+ * Thrown from [SandboxedSdkProviderCompat.onLoadSdk].
+ *
+ * @see [LoadSdkException]
+ */
+class LoadSdkCompatException : Exception {
+
+ /**
+ * Result code this exception was constructed with.
+ *
+ * @see [LoadSdkException.getLoadSdkErrorCode]
+ */
+ @field:LoadSdkErrorCode
+ @get:LoadSdkErrorCode
+ val loadSdkErrorCode: Int
+
+ /**
+ * Extra error information this exception was constructed with.
+ *
+ * @see [LoadSdkException.getExtraInformation]
+ */
+ val extraInformation: Bundle
+
+ /**
+ * Initializes a LoadSdkCompatException with a result code, a message, a cause and extra
+ * information.
+ *
+ * @param loadSdkErrorCode The result code.
+ * @param message The detailed message.
+ * @param cause The cause of the exception. A null value is permitted, and indicates that the
+ * cause is nonexistent or unknown.
+ * @param extraInformation Extra error information. This is empty if there is no such information.
+ * @suppress
+ */
+ @RestrictTo(LIBRARY_GROUP)
+ @JvmOverloads
+ constructor(
+ @LoadSdkErrorCode loadSdkErrorCode: Int,
+ message: String?,
+ cause: Throwable?,
+ extraInformation: Bundle = Bundle()
+ ) : super(message, cause) {
+ this.loadSdkErrorCode = loadSdkErrorCode
+ this.extraInformation = extraInformation
+ }
+
+ /**
+ * Initializes a LoadSdkCompatException with a result code and a message
+ *
+ * @param loadSdkErrorCode The result code.
+ * @param message The detailed message.
+ * @suppress
+ */
+ @RestrictTo(LIBRARY_GROUP)
+ constructor(
+ @LoadSdkErrorCode loadSdkErrorCode: Int,
+ message: String?
+ ) : this(loadSdkErrorCode, message, cause = null)
+
+ /**
+ * Initializes a LoadSdkCompatException with a Throwable and a Bundle.
+ *
+ * @param cause The cause of the exception.
+ * @param extraInfo Extra error information. This is empty if there is no such information.
+ */
+ constructor(
+ cause: Throwable,
+ extraInfo: Bundle
+ ) : this(LOAD_SDK_SDK_DEFINED_ERROR, "", cause, extraInfo)
+
+ /** @suppress */
+ @IntDef(
+ SDK_SANDBOX_PROCESS_NOT_AVAILABLE,
+ LOAD_SDK_NOT_FOUND,
+ LOAD_SDK_ALREADY_LOADED,
+ LOAD_SDK_SDK_DEFINED_ERROR,
+ LOAD_SDK_SDK_SANDBOX_DISABLED,
+ LOAD_SDK_INTERNAL_ERROR,
+ )
+ @RestrictTo(RestrictTo.Scope.LIBRARY)
+ @Retention(AnnotationRetention.SOURCE)
+ annotation class LoadSdkErrorCode
+
+ /**
+ * Create platform [LoadSdkException] from compat exception.
+ *
+ * @return Platform exception.
+ */
+ @RequiresExtension(extension = AD_SERVICES, version = 4)
+ internal fun toLoadSdkException(): LoadSdkException {
+ return ApiAdServicesV4Impl.toLoadSdkException(this)
+ }
+
+ // TODO(b/249981547) Remove suppress after updating to new lint version (b/262251309)
+ @SuppressLint("NewApi", "ClassVerificationFailure")
+ @RequiresExtension(extension = AD_SERVICES, version = 4)
+ private object ApiAdServicesV4Impl {
+
+ @DoNotInline
+ fun toLoadSdkException(ex: LoadSdkCompatException): LoadSdkException {
+ return LoadSdkException(
+ ex.cause!!,
+ ex.extraInformation
+ )
+ }
+
+ @DoNotInline
+ fun toLoadCompatSdkException(ex: LoadSdkException): LoadSdkCompatException {
+ return LoadSdkCompatException(
+ toLoadSdkErrorCodeCompat(ex.loadSdkErrorCode),
+ ex.message,
+ ex.cause,
+ ex.extraInformation
+ )
+ }
+
+ @LoadSdkErrorCode
+ private fun toLoadSdkErrorCodeCompat(
+ value: Int
+ ): Int {
+ return value // TODO(b/249982002): Validate and convert
+ }
+ }
+
+ companion object {
+
+ /**
+ * Sdk sandbox process is not available.
+ *
+ * This indicates that the sdk sandbox process is not available, either because it has died,
+ * disconnected or was not created in the first place.
+ *
+ * @see [android.app.sdksandbox.SdkSandboxManager.SDK_SANDBOX_PROCESS_NOT_AVAILABLE]
+ */
+ const val SDK_SANDBOX_PROCESS_NOT_AVAILABLE = 503
+
+ /**
+ * SDK not found.
+ *
+ * This indicates that client application tried to load a non-existing SDK.
+ *
+ * @see [android.app.sdksandbox.SdkSandboxManager.LOAD_SDK_NOT_FOUND]
+ */
+ const val LOAD_SDK_NOT_FOUND = 100
+
+ /**
+ * SDK is already loaded.
+ *
+ * This indicates that client application tried to reload the same SDK after being
+ * successfully loaded.
+ *
+ * @see [android.app.sdksandbox.SdkSandboxManager.LOAD_SDK_ALREADY_LOADED]
+ */
+ const val LOAD_SDK_ALREADY_LOADED = 101
+
+ /**
+ * SDK error after being loaded.
+ *
+ * This indicates that the SDK encountered an error during post-load initialization. The
+ * details of this can be obtained from the Bundle returned in [LoadSdkCompatException].
+ *
+ * @see [android.app.sdksandbox.SdkSandboxManager.LOAD_SDK_SDK_DEFINED_ERROR]
+ */
+ const val LOAD_SDK_SDK_DEFINED_ERROR = 102
+
+ /**
+ * SDK sandbox is disabled.
+ *
+ * This indicates that the SDK sandbox is disabled. Any subsequent attempts to load SDKs in
+ * this boot will also fail.
+ *
+ * @see [android.app.sdksandbox.SdkSandboxManager.LOAD_SDK_SDK_SANDBOX_DISABLED]
+ */
+ const val LOAD_SDK_SDK_SANDBOX_DISABLED = 103
+
+ /**
+ * Internal error while loading SDK.
+ *
+ * This indicates a generic internal error happened while applying the call from
+ * client application.
+ *
+ * @see [android.app.sdksandbox.SdkSandboxManager.LOAD_SDK_INTERNAL_ERROR]
+ */
+ const val LOAD_SDK_INTERNAL_ERROR = 500
+
+ /**
+ * Create compat exception from platform [LoadSdkException].
+ *
+ * @param ex Platform exception
+ * @return Compat exception.
+ * @suppress
+ */
+ @RequiresExtension(extension = AD_SERVICES, version = 4)
+ @RestrictTo(LIBRARY_GROUP)
+ fun toLoadCompatSdkException(ex: LoadSdkException): LoadSdkCompatException {
+ return ApiAdServicesV4Impl.toLoadCompatSdkException(ex)
+ }
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-core/src/main/java/androidx/privacysandbox/sdkruntime/core/SandboxedSdkCompat.kt b/privacysandbox/sdkruntime/sdkruntime-core/src/main/java/androidx/privacysandbox/sdkruntime/core/SandboxedSdkCompat.kt
new file mode 100644
index 0000000..54bce19
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-core/src/main/java/androidx/privacysandbox/sdkruntime/core/SandboxedSdkCompat.kt
@@ -0,0 +1,141 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.core
+
+import android.annotation.SuppressLint
+import android.app.sdksandbox.SandboxedSdk
+import android.os.IBinder
+import android.os.ext.SdkExtensions.AD_SERVICES
+import androidx.annotation.DoNotInline
+import androidx.annotation.RequiresExtension
+import androidx.annotation.RestrictTo
+import androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP
+
+/**
+ * Compat wrapper for [SandboxedSdk].
+ * Represents an SDK loaded in the sandbox process or locally.
+ * An application should use this object to obtain an interface to the SDK through [getInterface].
+ *
+ * The SDK should create it when [SandboxedSdkProviderCompat.onLoadSdk] is called, and drop all
+ * references to it when [SandboxedSdkProviderCompat.beforeUnloadSdk] is called. Additionally, the
+ * SDK should fail calls made to the [IBinder] returned from [getInterface] after
+ * [SandboxedSdkProviderCompat.beforeUnloadSdk] has been called.
+ *
+ * @see [SandboxedSdk]
+ *
+ */
+class SandboxedSdkCompat private constructor(
+ private val sdkImpl: SandboxedSdkImpl
+) {
+
+ /**
+ * Creates SandboxedSdkCompat from SDK Binder object.
+ *
+ * @param sdkInterface The SDK's interface. This will be the entrypoint into the sandboxed SDK
+ * for the application. The SDK should keep this valid until it's loaded in the sandbox, and
+ * start failing calls to this interface once it has been unloaded
+ *
+ * This interface can later be retrieved using [getInterface].
+ *
+ * @see [SandboxedSdk]
+ */
+ constructor(sdkInterface: IBinder) : this(CompatImpl(sdkInterface))
+
+ /**
+ * Creates SandboxedSdkCompat wrapper around existing [SandboxedSdk] object.
+ *
+ * @param sandboxedSdk SandboxedSdk object. All calls will be delegated to that object.
+ * @suppress
+ */
+ @RequiresExtension(extension = AD_SERVICES, version = 4)
+ @RestrictTo(LIBRARY_GROUP)
+ constructor(sandboxedSdk: SandboxedSdk) : this(ApiAdServicesV4Impl(sandboxedSdk))
+
+ /**
+ * Returns the interface to the loaded SDK.
+ * A null interface is returned if the Binder has since
+ * become unavailable, in response to the SDK being unloaded.
+ *
+ * @return [IBinder] object for loaded SDK.
+ *
+ * @see [SandboxedSdk.getInterface]
+ */
+ fun getInterface() = sdkImpl.getInterface()
+
+ /**
+ * Create [SandboxedSdk] from compat object.
+ *
+ * @return Platform SandboxedSdk
+ */
+ @RequiresExtension(extension = AD_SERVICES, version = 4)
+ internal fun toSandboxedSdk() = sdkImpl.toSandboxedSdk()
+
+ internal interface SandboxedSdkImpl {
+ fun getInterface(): IBinder?
+
+ @RequiresExtension(extension = AD_SERVICES, version = 4)
+ @DoNotInline
+ fun toSandboxedSdk(): SandboxedSdk
+ }
+
+ // TODO(b/249981547) Remove suppress after updating to new lint version (b/262251309)
+ @SuppressLint("NewApi", "ClassVerificationFailure")
+ @RequiresExtension(extension = AD_SERVICES, version = 4)
+ private class ApiAdServicesV4Impl(private val mSandboxedSdk: SandboxedSdk) : SandboxedSdkImpl {
+
+ @DoNotInline
+ override fun getInterface(): IBinder? {
+ return mSandboxedSdk.getInterface()
+ }
+
+ @DoNotInline
+ override fun toSandboxedSdk(): SandboxedSdk {
+ return mSandboxedSdk
+ }
+
+ companion object {
+ @DoNotInline
+ fun createSandboxedSdk(sdkInterface: IBinder): SandboxedSdk {
+ return SandboxedSdk(sdkInterface)
+ }
+ }
+ }
+
+ private class CompatImpl(private val sdkInterface: IBinder) : SandboxedSdkImpl {
+
+ override fun getInterface(): IBinder {
+ // This will be null if the SDK has been unloaded and the IBinder originally provided
+ // is now a dead object.
+ return sdkInterface
+ }
+
+ @RequiresExtension(extension = AD_SERVICES, version = 4)
+ override fun toSandboxedSdk(): SandboxedSdk {
+ // avoid class verifications errors
+ return ApiAdServicesV4Impl.createSandboxedSdk(sdkInterface)
+ }
+ }
+
+ companion object {
+ /**
+ * Deprecated and will be removed in next release.
+ * Use [SandboxedSdkCompat] constructor instead.
+ * TODO(b/261013990) Remove method after Shim generator migration and release
+ */
+ @JvmStatic
+ fun create(binder: IBinder): SandboxedSdkCompat = SandboxedSdkCompat(binder)
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-core/src/main/java/androidx/privacysandbox/sdkruntime/core/SandboxedSdkProviderAdapter.kt b/privacysandbox/sdkruntime/sdkruntime-core/src/main/java/androidx/privacysandbox/sdkruntime/core/SandboxedSdkProviderAdapter.kt
new file mode 100644
index 0000000..d0af98f
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-core/src/main/java/androidx/privacysandbox/sdkruntime/core/SandboxedSdkProviderAdapter.kt
@@ -0,0 +1,95 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.core
+
+import android.annotation.SuppressLint
+import android.app.sdksandbox.LoadSdkException
+import android.app.sdksandbox.SandboxedSdk
+import android.app.sdksandbox.SandboxedSdkProvider
+import android.content.Context
+import android.os.Bundle
+import android.os.ext.SdkExtensions.AD_SERVICES
+import android.view.View
+import androidx.annotation.RequiresExtension
+
+/**
+ * Implementation of platform [SandboxedSdkProvider] that delegate to [SandboxedSdkProviderCompat]
+ * Gets compat class name from asset "SandboxedSdkProviderCompatClassName.txt"
+ *
+ */
+// TODO(b/249981547) Remove suppress after updating to new lint version (b/262251309)
+@SuppressLint("NewApi", "ClassVerificationFailure", "Override")
+@RequiresExtension(extension = AD_SERVICES, version = 4)
+class SandboxedSdkProviderAdapter internal constructor(
+ private val classNameProvider: CompatClassNameProvider
+) : SandboxedSdkProvider() {
+
+ /**
+ * Provides classname of [SandboxedSdkProviderCompat] implementation.
+ */
+ internal interface CompatClassNameProvider {
+ fun getCompatProviderClassName(context: Context): String
+ }
+
+ constructor () : this(DefaultClassNameProvider())
+
+ internal val delegate: SandboxedSdkProviderCompat by lazy {
+ val currentContext = context!!
+ val compatSdkProviderClassName =
+ classNameProvider.getCompatProviderClassName(currentContext)
+ val clz = Class.forName(compatSdkProviderClassName)
+ val newDelegate = clz.getConstructor().newInstance() as SandboxedSdkProviderCompat
+ newDelegate.attachContext(currentContext)
+ newDelegate
+ }
+
+ @Throws(LoadSdkException::class)
+ override fun onLoadSdk(params: Bundle): SandboxedSdk {
+ return try {
+ delegate.onLoadSdk(params).toSandboxedSdk()
+ } catch (e: LoadSdkCompatException) {
+ throw e.toLoadSdkException()
+ }
+ }
+
+ override fun beforeUnloadSdk() {
+ delegate.beforeUnloadSdk()
+ }
+
+ override fun getView(
+ windowContext: Context,
+ params: Bundle,
+ width: Int,
+ height: Int
+ ): View {
+ return delegate.getView(windowContext, params, width, height)
+ }
+
+ private class DefaultClassNameProvider : CompatClassNameProvider {
+ override fun getCompatProviderClassName(context: Context): String {
+ // TODO(b/257966930) Read classname from SDK manifest property
+ return context.assets.open(COMPAT_SDK_PROVIDER_CLASS_ASSET_NAME)
+ .use { inputStream ->
+ inputStream.bufferedReader().readLine()
+ }
+ }
+ }
+
+ private companion object {
+ private const val COMPAT_SDK_PROVIDER_CLASS_ASSET_NAME =
+ "SandboxedSdkProviderCompatClassName.txt"
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-core/src/main/java/androidx/privacysandbox/sdkruntime/core/SandboxedSdkProviderCompat.kt b/privacysandbox/sdkruntime/sdkruntime-core/src/main/java/androidx/privacysandbox/sdkruntime/core/SandboxedSdkProviderCompat.kt
new file mode 100644
index 0000000..8882d6f
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-core/src/main/java/androidx/privacysandbox/sdkruntime/core/SandboxedSdkProviderCompat.kt
@@ -0,0 +1,106 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.core
+
+import android.content.Context
+import android.os.Bundle
+import android.view.View
+
+/**
+ * Compat version of [android.app.sdksandbox.SandboxedSdkProvider].
+ *
+ * Encapsulates API which SDK sandbox can use to interact with SDKs loaded into it.
+ *
+ * SDK has to implement this abstract class to generate an entry point for SDK sandbox to be able
+ * to call it through.
+ *
+ * @see [android.app.sdksandbox.SandboxedSdkProvider]
+ */
+abstract class SandboxedSdkProviderCompat {
+ /**
+ * Context previously set through [SandboxedSdkProviderCompat.attachContext].
+ * This will return null if no context has been previously set.
+ */
+ var context: Context? = null
+ private set
+
+ /**
+ * Sets the SDK [Context] which can then be received using [SandboxedSdkProviderCompat.context]
+ *
+ * This is called before [SandboxedSdkProviderCompat.onLoadSdk] is invoked.
+ * No operations requiring a [Context] should be performed before then, as
+ * [SandboxedSdkProviderCompat.context] will return null until this method has been called.
+ *
+ * @throws IllegalStateException if a base context has already been set.
+ *
+ * @param context The new base context.
+ *
+ * @see [android.app.sdksandbox.SandboxedSdkProvider.attachContext]
+ */
+ fun attachContext(context: Context) {
+ check(this.context == null) { "Context already set" }
+ this.context = context
+ }
+
+ /**
+ * Does the work needed for the SDK to start handling requests.
+ *
+ * This function is called by the SDK sandbox after it loads the SDK.
+ *
+ * SDK should do any work to be ready to handle upcoming requests. It should not do any
+ * long-running tasks here, like I/O and network calls. Doing so can prevent the SDK from
+ * receiving requests from the client. Additionally, it should not do initialization that
+ * depends on other SDKs being loaded into the SDK sandbox.
+ *
+ * The SDK should not do any operations requiring a [Context] object before this method
+ * has been called.
+ *
+ * @param params list of params passed from the client when it loads the SDK. This can be empty.
+ * @return Returns a [SandboxedSdkCompat], passed back to the client. The IBinder used to create
+ * the [SandboxedSdkCompat] object will be used by the client to call into the SDK.
+ *
+ * @throws LoadSdkCompatException if initialization failed.
+ *
+ * @see [android.app.sdksandbox.SandboxedSdkProvider.onLoadSdk]
+ */
+ @Throws(LoadSdkCompatException::class)
+ abstract fun onLoadSdk(params: Bundle): SandboxedSdkCompat
+
+ /**
+ * Does the work needed for the SDK to free its resources before being unloaded.
+ *
+ * This function is called by the SDK sandbox manager before it unloads the SDK. The SDK
+ * should fail any invocations on the Binder previously returned to the client through
+ * [SandboxedSdkCompat.getInterface]
+ *
+ * The SDK should not do any long-running tasks here, like I/O and network calls.
+ *
+ * @see [android.app.sdksandbox.SandboxedSdkProvider.beforeUnloadSdk]
+ */
+ open fun beforeUnloadSdk() {}
+
+ /**
+ * Requests a view to be remotely rendered to the client app process.
+ *
+ * @see [android.app.sdksandbox.SandboxedSdkProvider.getView]
+ */
+ abstract fun getView(
+ windowContext: Context,
+ params: Bundle,
+ width: Int,
+ height: Int
+ ): View
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-core/src/main/java/androidx/privacysandbox/sdkruntime/core/Versions.kt b/privacysandbox/sdkruntime/sdkruntime-core/src/main/java/androidx/privacysandbox/sdkruntime/core/Versions.kt
new file mode 100644
index 0000000..d683bdf
--- /dev/null
+++ b/privacysandbox/sdkruntime/sdkruntime-core/src/main/java/androidx/privacysandbox/sdkruntime/core/Versions.kt
@@ -0,0 +1,43 @@
+/*
+ * 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 androidx.privacysandbox.sdkruntime.core
+
+import androidx.annotation.Keep
+import androidx.annotation.RestrictTo
+
+/**
+ * Store internal API version (for Client-Core communication).
+ * Methods invoked via reflection.
+ *
+ * @suppress
+ */
+@Suppress("unused")
+@Keep
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+object Versions {
+
+ const val API_VERSION = 1
+
+ @JvmField
+ var CLIENT_VERSION: Int? = null
+
+ @JvmStatic
+ fun handShake(clientVersion: Int): Int {
+ CLIENT_VERSION = clientVersion
+ return API_VERSION
+ }
+}
\ No newline at end of file
diff --git a/privacysandbox/sdkruntime/sdkruntime-core/src/main/androidx/privacysandbox/sdkruntime/androidx-privacysandbox-sdkruntime-sdkruntime-core-documentation.md b/privacysandbox/sdkruntime/sdkruntime-core/src/main/java/androidx/privacysandbox/sdkruntime/core/androidx-privacysandbox-sdkruntime-sdkruntime-core-documentation.md
similarity index 100%
rename from privacysandbox/sdkruntime/sdkruntime-core/src/main/androidx/privacysandbox/sdkruntime/androidx-privacysandbox-sdkruntime-sdkruntime-core-documentation.md
rename to privacysandbox/sdkruntime/sdkruntime-core/src/main/java/androidx/privacysandbox/sdkruntime/core/androidx-privacysandbox-sdkruntime-sdkruntime-core-documentation.md
diff --git a/recyclerview/recyclerview/api/api_lint.ignore b/recyclerview/recyclerview/api/api_lint.ignore
index ee7fa16..463599f 100644
--- a/recyclerview/recyclerview/api/api_lint.ignore
+++ b/recyclerview/recyclerview/api/api_lint.ignore
@@ -161,12 +161,6 @@
Internal field mLayoutManager must not be exposed
-InvalidNullabilityOverride: androidx.recyclerview.widget.RecyclerView#draw(android.graphics.Canvas) parameter #0:
- Invalid nullability on parameter `c` in method `draw`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
-InvalidNullabilityOverride: androidx.recyclerview.widget.RecyclerView#drawChild(android.graphics.Canvas, android.view.View, long) parameter #0:
- Invalid nullability on parameter `canvas` in method `drawChild`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
-InvalidNullabilityOverride: androidx.recyclerview.widget.RecyclerView#onDraw(android.graphics.Canvas) parameter #0:
- Invalid nullability on parameter `c` in method `onDraw`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
InvalidNullabilityOverride: androidx.recyclerview.widget.RecyclerViewAccessibilityDelegate.ItemDelegate#dispatchPopulateAccessibilityEvent(android.view.View, android.view.accessibility.AccessibilityEvent) parameter #0:
Invalid nullability on parameter `host` in method `dispatchPopulateAccessibilityEvent`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
InvalidNullabilityOverride: androidx.recyclerview.widget.RecyclerViewAccessibilityDelegate.ItemDelegate#dispatchPopulateAccessibilityEvent(android.view.View, android.view.accessibility.AccessibilityEvent) parameter #1:
@@ -551,6 +545,10 @@
Missing nullability on parameter `container` in method `dispatchRestoreInstanceState`
MissingNullability: androidx.recyclerview.widget.RecyclerView#dispatchSaveInstanceState(android.util.SparseArray<android.os.Parcelable>) parameter #0:
Missing nullability on parameter `container` in method `dispatchSaveInstanceState`
+MissingNullability: androidx.recyclerview.widget.RecyclerView#draw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `c` in method `draw`
+MissingNullability: androidx.recyclerview.widget.RecyclerView#drawChild(android.graphics.Canvas, android.view.View, long) parameter #0:
+ Missing nullability on parameter `canvas` in method `drawChild`
MissingNullability: androidx.recyclerview.widget.RecyclerView#drawChild(android.graphics.Canvas, android.view.View, long) parameter #1:
Missing nullability on parameter `child` in method `drawChild`
MissingNullability: androidx.recyclerview.widget.RecyclerView#findViewHolderForItemId(long):
@@ -573,6 +571,8 @@
Missing nullability on method `getAccessibilityClassName` return
MissingNullability: androidx.recyclerview.widget.RecyclerView#getChildViewHolder(android.view.View):
Missing nullability on method `getChildViewHolder` return
+MissingNullability: androidx.recyclerview.widget.RecyclerView#onDraw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `c` in method `onDraw`
MissingNullability: androidx.recyclerview.widget.RecyclerView#onGenericMotionEvent(android.view.MotionEvent) parameter #0:
Missing nullability on parameter `event` in method `onGenericMotionEvent`
MissingNullability: androidx.recyclerview.widget.RecyclerView#onInterceptTouchEvent(android.view.MotionEvent) parameter #0:
diff --git a/security/security-identity-credential/src/main/java/androidx/security/identity/HardwareIdentityCredential.java b/security/security-identity-credential/src/main/java/androidx/security/identity/HardwareIdentityCredential.java
index 855f060..096366c 100644
--- a/security/security-identity-credential/src/main/java/androidx/security/identity/HardwareIdentityCredential.java
+++ b/security/security-identity-credential/src/main/java/androidx/security/identity/HardwareIdentityCredential.java
@@ -249,6 +249,7 @@
return builder.build();
}
+ @SuppressWarnings("deprecation")
@Override
public void setAvailableAuthenticationKeys(int keyCount, int maxUsesPerKey) {
mCredential.setAvailableAuthenticationKeys(keyCount, maxUsesPerKey);
@@ -271,6 +272,7 @@
}
}
+ @SuppressWarnings("deprecation")
@Override
public @NonNull
int[] getAuthenticationDataUsageCount() {
diff --git a/settings.gradle b/settings.gradle
index 2471fc2d..a929cff 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -92,9 +92,9 @@
value("androidx.projects", getRequestedProjectSubsetName() ?: "Unset")
value("androidx.useMaxDepVersions", providers.gradleProperty("androidx.useMaxDepVersions").isPresent().toString())
- // Publish scan for androidx-main
- publishAlways()
- publishIfAuthenticated()
+ // Do not publish scan for androidx-platform-dev
+ // publishAlways()
+ // publishIfAuthenticated()
}
}
@@ -692,8 +692,9 @@
includeProject(":glance:glance-wear-tiles-preview", [BuildType.GLANCE])
includeProject(":graphics:filters:filters", [BuildType.MAIN])
includeProject(":graphics:graphics-core", [BuildType.MAIN])
-includeProject(":graphics:integration-tests:testapp", [BuildType.MAIN])
+includeProject(":graphics:graphics-path", [BuildType.MAIN])
includeProject(":graphics:graphics-shapes", [BuildType.MAIN])
+includeProject(":graphics:integration-tests:testapp", [BuildType.MAIN])
includeProject(":gridlayout:gridlayout", [BuildType.MAIN])
includeProject(":health:connect:connect-client", [BuildType.MAIN])
includeProject(":health:connect:connect-client-proto", [BuildType.MAIN])
@@ -983,6 +984,7 @@
includeProject(":webkit:integration-tests:testapp", [BuildType.MAIN])
includeProject(":webkit:webkit", [BuildType.MAIN])
includeProject(":window:window", [BuildType.MAIN, BuildType.COMPOSE, BuildType.FLAN, BuildType.CAMERA, BuildType.WINDOW])
+includeProject(":window:window-samples", "window/window/samples", [BuildType.MAIN, BuildType.COMPOSE, BuildType.FLAN, BuildType.CAMERA, BuildType.WINDOW])
includeProject(":window:extensions:extensions", [BuildType.MAIN, BuildType.COMPOSE, BuildType.FLAN, BuildType.CAMERA, BuildType.WINDOW])
includeProject(":window:extensions:core:core", [BuildType.MAIN, BuildType.COMPOSE, BuildType.FLAN, BuildType.CAMERA, BuildType.WINDOW])
includeProject(":window:integration-tests:configuration-change-tests", [BuildType.MAIN, BuildType.WINDOW])
@@ -991,7 +993,9 @@
includeProject(":window:window-core", [BuildType.MAIN, BuildType.COMPOSE, BuildType.FLAN, BuildType.CAMERA, BuildType.WINDOW])
includeProject(":window:window-rxjava2", [BuildType.MAIN, BuildType.WINDOW])
includeProject(":window:window-rxjava3", [BuildType.MAIN, BuildType.WINDOW])
-includeProject(":window:window-samples", [BuildType.MAIN, BuildType.COMPOSE, BuildType.FLAN, BuildType.CAMERA, BuildType.WINDOW])
+includeProject(":window:window-demos:demo", [BuildType.MAIN, BuildType.COMPOSE, BuildType.FLAN, BuildType.CAMERA, BuildType.WINDOW])
+includeProject(":window:window-demos:demo-common", [BuildType.MAIN, BuildType.COMPOSE, BuildType.FLAN, BuildType.CAMERA, BuildType.WINDOW])
+includeProject(":window:window-demos:demo-second-app", [BuildType.MAIN, BuildType.COMPOSE, BuildType.FLAN, BuildType.CAMERA, BuildType.WINDOW])
includeProject(":window:window-testing", [BuildType.MAIN, BuildType.COMPOSE, BuildType.FLAN, BuildType.CAMERA, BuildType.WINDOW])
includeProject(":work:integration-tests:testapp", [BuildType.MAIN])
includeProject(":work:work-benchmark", [BuildType.MAIN])
diff --git a/slidingpanelayout/slidingpanelayout/api/api_lint.ignore b/slidingpanelayout/slidingpanelayout/api/api_lint.ignore
index e495753..a288bd0 100644
--- a/slidingpanelayout/slidingpanelayout/api/api_lint.ignore
+++ b/slidingpanelayout/slidingpanelayout/api/api_lint.ignore
@@ -1,10 +1,6 @@
// Baseline format: 1.0
InvalidNullabilityOverride: androidx.slidingpanelayout.widget.SlidingPaneLayout#addView(android.view.View, int, android.view.ViewGroup.LayoutParams) parameter #0:
Invalid nullability on parameter `child` in method `addView`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
-InvalidNullabilityOverride: androidx.slidingpanelayout.widget.SlidingPaneLayout#draw(android.graphics.Canvas) parameter #0:
- Invalid nullability on parameter `c` in method `draw`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
-InvalidNullabilityOverride: androidx.slidingpanelayout.widget.SlidingPaneLayout#drawChild(android.graphics.Canvas, android.view.View, long) parameter #0:
- Invalid nullability on parameter `canvas` in method `drawChild`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
InvalidNullabilityOverride: androidx.slidingpanelayout.widget.SlidingPaneLayout#removeView(android.view.View) parameter #0:
Invalid nullability on parameter `view` in method `removeView`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
@@ -15,6 +11,10 @@
MissingNullability: androidx.slidingpanelayout.widget.SlidingPaneLayout#checkLayoutParams(android.view.ViewGroup.LayoutParams) parameter #0:
Missing nullability on parameter `p` in method `checkLayoutParams`
+MissingNullability: androidx.slidingpanelayout.widget.SlidingPaneLayout#draw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `c` in method `draw`
+MissingNullability: androidx.slidingpanelayout.widget.SlidingPaneLayout#drawChild(android.graphics.Canvas, android.view.View, long) parameter #0:
+ Missing nullability on parameter `canvas` in method `drawChild`
MissingNullability: androidx.slidingpanelayout.widget.SlidingPaneLayout#drawChild(android.graphics.Canvas, android.view.View, long) parameter #1:
Missing nullability on parameter `child` in method `drawChild`
MissingNullability: androidx.slidingpanelayout.widget.SlidingPaneLayout#generateDefaultLayoutParams():
diff --git a/swiperefreshlayout/swiperefreshlayout/api/api_lint.ignore b/swiperefreshlayout/swiperefreshlayout/api/api_lint.ignore
index 6038f08..25a9da5 100644
--- a/swiperefreshlayout/swiperefreshlayout/api/api_lint.ignore
+++ b/swiperefreshlayout/swiperefreshlayout/api/api_lint.ignore
@@ -13,6 +13,8 @@
Internal field mOriginalOffsetTop must not be exposed
+MissingNullability: androidx.swiperefreshlayout.widget.CircularProgressDrawable#draw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `canvas` in method `draw`
MissingNullability: androidx.swiperefreshlayout.widget.CircularProgressDrawable#setColorFilter(android.graphics.ColorFilter) parameter #0:
Missing nullability on parameter `colorFilter` in method `setColorFilter`
MissingNullability: androidx.swiperefreshlayout.widget.SwipeRefreshLayout#onInterceptTouchEvent(android.view.MotionEvent) parameter #0:
diff --git a/viewpager/viewpager/api/api_lint.ignore b/viewpager/viewpager/api/api_lint.ignore
index 1c07b48..908ecb2 100644
--- a/viewpager/viewpager/api/api_lint.ignore
+++ b/viewpager/viewpager/api/api_lint.ignore
@@ -9,18 +9,12 @@
Symmetric method for `setDrawFullUnderline` must be named `isDrawFullUnderline`; was `getDrawFullUnderline`
-InvalidNullabilityOverride: androidx.viewpager.widget.PagerTabStrip#onDraw(android.graphics.Canvas) parameter #0:
- Invalid nullability on parameter `canvas` in method `onDraw`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
-InvalidNullabilityOverride: androidx.viewpager.widget.ViewPager#draw(android.graphics.Canvas) parameter #0:
- Invalid nullability on parameter `canvas` in method `draw`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
-InvalidNullabilityOverride: androidx.viewpager.widget.ViewPager#onDraw(android.graphics.Canvas) parameter #0:
- Invalid nullability on parameter `canvas` in method `onDraw`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
-
-
ListenerInterface: androidx.viewpager.widget.ViewPager.SimpleOnPageChangeListener:
Listeners should be an interface, or otherwise renamed Callback: SimpleOnPageChangeListener
+MissingNullability: androidx.viewpager.widget.PagerTabStrip#onDraw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `canvas` in method `onDraw`
MissingNullability: androidx.viewpager.widget.PagerTabStrip#onTouchEvent(android.view.MotionEvent) parameter #0:
Missing nullability on parameter `ev` in method `onTouchEvent`
MissingNullability: androidx.viewpager.widget.PagerTabStrip#setBackgroundDrawable(android.graphics.drawable.Drawable) parameter #0:
@@ -39,6 +33,8 @@
Missing nullability on parameter `event` in method `dispatchKeyEvent`
MissingNullability: androidx.viewpager.widget.ViewPager#dispatchPopulateAccessibilityEvent(android.view.accessibility.AccessibilityEvent) parameter #0:
Missing nullability on parameter `event` in method `dispatchPopulateAccessibilityEvent`
+MissingNullability: androidx.viewpager.widget.ViewPager#draw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `canvas` in method `draw`
MissingNullability: androidx.viewpager.widget.ViewPager#generateDefaultLayoutParams():
Missing nullability on method `generateDefaultLayoutParams` return
MissingNullability: androidx.viewpager.widget.ViewPager#generateLayoutParams(android.util.AttributeSet):
@@ -49,6 +45,8 @@
Missing nullability on method `generateLayoutParams` return
MissingNullability: androidx.viewpager.widget.ViewPager#generateLayoutParams(android.view.ViewGroup.LayoutParams) parameter #0:
Missing nullability on parameter `p` in method `generateLayoutParams`
+MissingNullability: androidx.viewpager.widget.ViewPager#onDraw(android.graphics.Canvas) parameter #0:
+ Missing nullability on parameter `canvas` in method `onDraw`
MissingNullability: androidx.viewpager.widget.ViewPager#onInterceptTouchEvent(android.view.MotionEvent) parameter #0:
Missing nullability on parameter `ev` in method `onInterceptTouchEvent`
MissingNullability: androidx.viewpager.widget.ViewPager#onRequestFocusInDescendants(int, android.graphics.Rect) parameter #1:
diff --git a/webkit/webkit/api/1.6.0-beta02.txt b/webkit/webkit/api/1.6.0-beta02.txt
deleted file mode 100644
index faf13cb..0000000
--- a/webkit/webkit/api/1.6.0-beta02.txt
+++ /dev/null
@@ -1,300 +0,0 @@
-// Signature format: 4.0
-package androidx.webkit {
-
- public class CookieManagerCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.GET_COOKIE_INFO, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static java.util.List<java.lang.String!> getCookieInfo(android.webkit.CookieManager, String);
- }
-
- public abstract class JavaScriptReplyProxy {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_MESSAGE_LISTENER, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void postMessage(String);
- }
-
- public class ProcessGlobalConfig {
- ctor public ProcessGlobalConfig();
- method public static void apply(androidx.webkit.ProcessGlobalConfig);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.STARTUP_FEATURE_SET_DATA_DIRECTORY_SUFFIX, enforcement="androidx.webkit.WebViewFeature#isConfigFeatureSupported(String, Context)") public androidx.webkit.ProcessGlobalConfig setDataDirectorySuffix(android.content.Context, String);
- }
-
- public final class ProxyConfig {
- method public java.util.List<java.lang.String!> getBypassRules();
- method public java.util.List<androidx.webkit.ProxyConfig.ProxyRule!> getProxyRules();
- method public boolean isReverseBypassEnabled();
- field public static final String MATCH_ALL_SCHEMES = "*";
- field public static final String MATCH_HTTP = "http";
- field public static final String MATCH_HTTPS = "https";
- }
-
- public static final class ProxyConfig.Builder {
- ctor public ProxyConfig.Builder();
- ctor public ProxyConfig.Builder(androidx.webkit.ProxyConfig);
- method public androidx.webkit.ProxyConfig.Builder addBypassRule(String);
- method public androidx.webkit.ProxyConfig.Builder addDirect(String);
- method public androidx.webkit.ProxyConfig.Builder addDirect();
- method public androidx.webkit.ProxyConfig.Builder addProxyRule(String);
- method public androidx.webkit.ProxyConfig.Builder addProxyRule(String, String);
- method public androidx.webkit.ProxyConfig build();
- method public androidx.webkit.ProxyConfig.Builder bypassSimpleHostnames();
- method public androidx.webkit.ProxyConfig.Builder removeImplicitRules();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.PROXY_OVERRIDE_REVERSE_BYPASS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public androidx.webkit.ProxyConfig.Builder setReverseBypassEnabled(boolean);
- }
-
- public static final class ProxyConfig.ProxyRule {
- method public String getSchemeFilter();
- method public String getUrl();
- }
-
- public abstract class ProxyController {
- method public abstract void clearProxyOverride(java.util.concurrent.Executor, Runnable);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.PROXY_OVERRIDE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static androidx.webkit.ProxyController getInstance();
- method public abstract void setProxyOverride(androidx.webkit.ProxyConfig, java.util.concurrent.Executor, Runnable);
- }
-
- public abstract class SafeBrowsingResponseCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_RESPONSE_BACK_TO_SAFETY, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void backToSafety(boolean);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_RESPONSE_PROCEED, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void proceed(boolean);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_RESPONSE_SHOW_INTERSTITIAL, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void showInterstitial(boolean);
- }
-
- public abstract class ServiceWorkerClientCompat {
- ctor public ServiceWorkerClientCompat();
- method @WorkerThread public abstract android.webkit.WebResourceResponse? shouldInterceptRequest(android.webkit.WebResourceRequest);
- }
-
- public abstract class ServiceWorkerControllerCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_BASIC_USAGE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static androidx.webkit.ServiceWorkerControllerCompat getInstance();
- method public abstract androidx.webkit.ServiceWorkerWebSettingsCompat getServiceWorkerWebSettings();
- method public abstract void setServiceWorkerClient(androidx.webkit.ServiceWorkerClientCompat?);
- }
-
- public abstract class ServiceWorkerWebSettingsCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_CONTENT_ACCESS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract boolean getAllowContentAccess();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_FILE_ACCESS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract boolean getAllowFileAccess();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_BLOCK_NETWORK_LOADS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract boolean getBlockNetworkLoads();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_CACHE_MODE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract int getCacheMode();
- method @RequiresFeature(name="REQUESTED_WITH_HEADER_ALLOW_LIST", enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract java.util.Set<java.lang.String!> getRequestedWithHeaderOriginAllowList();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_CONTENT_ACCESS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void setAllowContentAccess(boolean);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_FILE_ACCESS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void setAllowFileAccess(boolean);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_BLOCK_NETWORK_LOADS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void setBlockNetworkLoads(boolean);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_CACHE_MODE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void setCacheMode(int);
- method @RequiresFeature(name="REQUESTED_WITH_HEADER_ALLOW_LIST", enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void setRequestedWithHeaderOriginAllowList(java.util.Set<java.lang.String!>);
- }
-
- public class TracingConfig {
- method public java.util.List<java.lang.String!> getCustomIncludedCategories();
- method public int getPredefinedCategories();
- method public int getTracingMode();
- field public static final int CATEGORIES_ALL = 1; // 0x1
- field public static final int CATEGORIES_ANDROID_WEBVIEW = 2; // 0x2
- field public static final int CATEGORIES_FRAME_VIEWER = 64; // 0x40
- field public static final int CATEGORIES_INPUT_LATENCY = 8; // 0x8
- field public static final int CATEGORIES_JAVASCRIPT_AND_RENDERING = 32; // 0x20
- field public static final int CATEGORIES_NONE = 0; // 0x0
- field public static final int CATEGORIES_RENDERING = 16; // 0x10
- field public static final int CATEGORIES_WEB_DEVELOPER = 4; // 0x4
- field public static final int RECORD_CONTINUOUSLY = 1; // 0x1
- field public static final int RECORD_UNTIL_FULL = 0; // 0x0
- }
-
- public static class TracingConfig.Builder {
- ctor public TracingConfig.Builder();
- method public androidx.webkit.TracingConfig.Builder addCategories(int...);
- method public androidx.webkit.TracingConfig.Builder addCategories(java.lang.String!...);
- method public androidx.webkit.TracingConfig.Builder addCategories(java.util.Collection<java.lang.String!>);
- method public androidx.webkit.TracingConfig build();
- method public androidx.webkit.TracingConfig.Builder setTracingMode(int);
- }
-
- public abstract class TracingController {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.TRACING_CONTROLLER_BASIC_USAGE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static androidx.webkit.TracingController getInstance();
- method public abstract boolean isTracing();
- method public abstract void start(androidx.webkit.TracingConfig);
- method public abstract boolean stop(java.io.OutputStream?, java.util.concurrent.Executor);
- }
-
- public class WebMessageCompat {
- ctor public WebMessageCompat(String?);
- ctor public WebMessageCompat(String?, androidx.webkit.WebMessagePortCompat![]?);
- method public String? getData();
- method public androidx.webkit.WebMessagePortCompat![]? getPorts();
- }
-
- public abstract class WebMessagePortCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_MESSAGE_PORT_CLOSE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void close();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_MESSAGE_PORT_POST_MESSAGE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void postMessage(androidx.webkit.WebMessageCompat);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_MESSAGE_PORT_SET_MESSAGE_CALLBACK, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void setWebMessageCallback(androidx.webkit.WebMessagePortCompat.WebMessageCallbackCompat);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_MESSAGE_PORT_SET_MESSAGE_CALLBACK, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void setWebMessageCallback(android.os.Handler?, androidx.webkit.WebMessagePortCompat.WebMessageCallbackCompat);
- }
-
- public abstract static class WebMessagePortCompat.WebMessageCallbackCompat {
- ctor public WebMessagePortCompat.WebMessageCallbackCompat();
- method public void onMessage(androidx.webkit.WebMessagePortCompat, androidx.webkit.WebMessageCompat?);
- }
-
- public abstract class WebResourceErrorCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_RESOURCE_ERROR_GET_DESCRIPTION, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract CharSequence getDescription();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_RESOURCE_ERROR_GET_CODE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract int getErrorCode();
- }
-
- public class WebResourceRequestCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_RESOURCE_REQUEST_IS_REDIRECT, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static boolean isRedirect(android.webkit.WebResourceRequest);
- }
-
- public class WebSettingsCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.DISABLED_ACTION_MODE_MENU_ITEMS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static int getDisabledActionModeMenuItems(android.webkit.WebSettings);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.ENTERPRISE_AUTHENTICATION_APP_LINK_POLICY, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static boolean getEnterpriseAuthenticationAppLinkPolicyEnabled(android.webkit.WebSettings);
- method @Deprecated @RequiresFeature(name=androidx.webkit.WebViewFeature.FORCE_DARK, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static int getForceDark(android.webkit.WebSettings);
- method @Deprecated @RequiresFeature(name=androidx.webkit.WebViewFeature.FORCE_DARK_STRATEGY, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static int getForceDarkStrategy(android.webkit.WebSettings);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.OFF_SCREEN_PRERASTER, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static boolean getOffscreenPreRaster(android.webkit.WebSettings);
- method @RequiresFeature(name="REQUESTED_WITH_HEADER_ALLOW_LIST", enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static java.util.Set<java.lang.String!> getRequestedWithHeaderOriginAllowList(android.webkit.WebSettings);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_ENABLE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static boolean getSafeBrowsingEnabled(android.webkit.WebSettings);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.ALGORITHMIC_DARKENING, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static boolean isAlgorithmicDarkeningAllowed(android.webkit.WebSettings);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.ALGORITHMIC_DARKENING, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setAlgorithmicDarkeningAllowed(android.webkit.WebSettings, boolean);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.DISABLED_ACTION_MODE_MENU_ITEMS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setDisabledActionModeMenuItems(android.webkit.WebSettings, int);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.ENTERPRISE_AUTHENTICATION_APP_LINK_POLICY, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setEnterpriseAuthenticationAppLinkPolicyEnabled(android.webkit.WebSettings, boolean);
- method @Deprecated @RequiresFeature(name=androidx.webkit.WebViewFeature.FORCE_DARK, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setForceDark(android.webkit.WebSettings, int);
- method @Deprecated @RequiresFeature(name=androidx.webkit.WebViewFeature.FORCE_DARK_STRATEGY, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setForceDarkStrategy(android.webkit.WebSettings, int);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.OFF_SCREEN_PRERASTER, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setOffscreenPreRaster(android.webkit.WebSettings, boolean);
- method @RequiresFeature(name="REQUESTED_WITH_HEADER_ALLOW_LIST", enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setRequestedWithHeaderOriginAllowList(android.webkit.WebSettings, java.util.Set<java.lang.String!>);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_ENABLE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setSafeBrowsingEnabled(android.webkit.WebSettings, boolean);
- field @Deprecated public static final int DARK_STRATEGY_PREFER_WEB_THEME_OVER_USER_AGENT_DARKENING = 2; // 0x2
- field @Deprecated public static final int DARK_STRATEGY_USER_AGENT_DARKENING_ONLY = 0; // 0x0
- field @Deprecated public static final int DARK_STRATEGY_WEB_THEME_DARKENING_ONLY = 1; // 0x1
- field @Deprecated public static final int FORCE_DARK_AUTO = 1; // 0x1
- field @Deprecated public static final int FORCE_DARK_OFF = 0; // 0x0
- field @Deprecated public static final int FORCE_DARK_ON = 2; // 0x2
- }
-
- public final class WebViewAssetLoader {
- method @WorkerThread public android.webkit.WebResourceResponse? shouldInterceptRequest(android.net.Uri);
- field public static final String DEFAULT_DOMAIN = "appassets.androidplatform.net";
- }
-
- public static final class WebViewAssetLoader.AssetsPathHandler implements androidx.webkit.WebViewAssetLoader.PathHandler {
- ctor public WebViewAssetLoader.AssetsPathHandler(android.content.Context);
- method @WorkerThread public android.webkit.WebResourceResponse? handle(String);
- }
-
- public static final class WebViewAssetLoader.Builder {
- ctor public WebViewAssetLoader.Builder();
- method public androidx.webkit.WebViewAssetLoader.Builder addPathHandler(String, androidx.webkit.WebViewAssetLoader.PathHandler);
- method public androidx.webkit.WebViewAssetLoader build();
- method public androidx.webkit.WebViewAssetLoader.Builder setDomain(String);
- method public androidx.webkit.WebViewAssetLoader.Builder setHttpAllowed(boolean);
- }
-
- public static final class WebViewAssetLoader.InternalStoragePathHandler implements androidx.webkit.WebViewAssetLoader.PathHandler {
- ctor public WebViewAssetLoader.InternalStoragePathHandler(android.content.Context, java.io.File);
- method @WorkerThread public android.webkit.WebResourceResponse handle(String);
- }
-
- public static interface WebViewAssetLoader.PathHandler {
- method @WorkerThread public android.webkit.WebResourceResponse? handle(String);
- }
-
- public static final class WebViewAssetLoader.ResourcesPathHandler implements androidx.webkit.WebViewAssetLoader.PathHandler {
- ctor public WebViewAssetLoader.ResourcesPathHandler(android.content.Context);
- method @WorkerThread public android.webkit.WebResourceResponse? handle(String);
- }
-
- public class WebViewClientCompat extends android.webkit.WebViewClient {
- ctor public WebViewClientCompat();
- method @RequiresApi(23) public final void onReceivedError(android.webkit.WebView, android.webkit.WebResourceRequest, android.webkit.WebResourceError);
- method @RequiresApi(21) @UiThread public void onReceivedError(android.webkit.WebView, android.webkit.WebResourceRequest, androidx.webkit.WebResourceErrorCompat);
- method @RequiresApi(27) public final void onSafeBrowsingHit(android.webkit.WebView, android.webkit.WebResourceRequest, int, android.webkit.SafeBrowsingResponse);
- method @UiThread public void onSafeBrowsingHit(android.webkit.WebView, android.webkit.WebResourceRequest, int, androidx.webkit.SafeBrowsingResponseCompat);
- }
-
- public class WebViewCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_MESSAGE_LISTENER, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void addWebMessageListener(android.webkit.WebView, String, java.util.Set<java.lang.String!>, androidx.webkit.WebViewCompat.WebMessageListener);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.CREATE_WEB_MESSAGE_CHANNEL, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static androidx.webkit.WebMessagePortCompat![] createWebMessageChannel(android.webkit.WebView);
- method public static android.content.pm.PackageInfo? getCurrentWebViewPackage(android.content.Context);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_PRIVACY_POLICY_URL, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static android.net.Uri getSafeBrowsingPrivacyPolicyUrl();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.GET_VARIATIONS_HEADER, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static String getVariationsHeader();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.GET_WEB_CHROME_CLIENT, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static android.webkit.WebChromeClient? getWebChromeClient(android.webkit.WebView);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.GET_WEB_VIEW_CLIENT, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static android.webkit.WebViewClient getWebViewClient(android.webkit.WebView);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.GET_WEB_VIEW_RENDERER, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static androidx.webkit.WebViewRenderProcess? getWebViewRenderProcess(android.webkit.WebView);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_VIEW_RENDERER_CLIENT_BASIC_USAGE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static androidx.webkit.WebViewRenderProcessClient? getWebViewRenderProcessClient(android.webkit.WebView);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.MULTI_PROCESS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static boolean isMultiProcessEnabled();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.VISUAL_STATE_CALLBACK, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void postVisualStateCallback(android.webkit.WebView, long, androidx.webkit.WebViewCompat.VisualStateCallback);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.POST_WEB_MESSAGE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void postWebMessage(android.webkit.WebView, androidx.webkit.WebMessageCompat, android.net.Uri);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_MESSAGE_LISTENER, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void removeWebMessageListener(android.webkit.WebView, String);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_ALLOWLIST, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setSafeBrowsingAllowlist(java.util.Set<java.lang.String!>, android.webkit.ValueCallback<java.lang.Boolean!>?);
- method @Deprecated @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_WHITELIST, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setSafeBrowsingWhitelist(java.util.List<java.lang.String!>, android.webkit.ValueCallback<java.lang.Boolean!>?);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_VIEW_RENDERER_CLIENT_BASIC_USAGE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setWebViewRenderProcessClient(android.webkit.WebView, java.util.concurrent.Executor, androidx.webkit.WebViewRenderProcessClient);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_VIEW_RENDERER_CLIENT_BASIC_USAGE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setWebViewRenderProcessClient(android.webkit.WebView, androidx.webkit.WebViewRenderProcessClient?);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.START_SAFE_BROWSING, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void startSafeBrowsing(android.content.Context, android.webkit.ValueCallback<java.lang.Boolean!>?);
- }
-
- public static interface WebViewCompat.VisualStateCallback {
- method @UiThread public void onComplete(long);
- }
-
- public static interface WebViewCompat.WebMessageListener {
- method @UiThread public void onPostMessage(android.webkit.WebView, androidx.webkit.WebMessageCompat, android.net.Uri, boolean, androidx.webkit.JavaScriptReplyProxy);
- }
-
- public class WebViewFeature {
- method public static boolean isFeatureSupported(String);
- method public static boolean isStartupFeatureSupported(android.content.Context, String);
- field public static final String ALGORITHMIC_DARKENING = "ALGORITHMIC_DARKENING";
- field public static final String CREATE_WEB_MESSAGE_CHANNEL = "CREATE_WEB_MESSAGE_CHANNEL";
- field public static final String DISABLED_ACTION_MODE_MENU_ITEMS = "DISABLED_ACTION_MODE_MENU_ITEMS";
- field public static final String ENTERPRISE_AUTHENTICATION_APP_LINK_POLICY = "ENTERPRISE_AUTHENTICATION_APP_LINK_POLICY";
- field public static final String FORCE_DARK = "FORCE_DARK";
- field public static final String FORCE_DARK_STRATEGY = "FORCE_DARK_STRATEGY";
- field public static final String GET_COOKIE_INFO = "GET_COOKIE_INFO";
- field public static final String GET_VARIATIONS_HEADER = "GET_VARIATIONS_HEADER";
- field public static final String GET_WEB_CHROME_CLIENT = "GET_WEB_CHROME_CLIENT";
- field public static final String GET_WEB_VIEW_CLIENT = "GET_WEB_VIEW_CLIENT";
- field public static final String GET_WEB_VIEW_RENDERER = "GET_WEB_VIEW_RENDERER";
- field public static final String MULTI_PROCESS = "MULTI_PROCESS";
- field public static final String OFF_SCREEN_PRERASTER = "OFF_SCREEN_PRERASTER";
- field public static final String POST_WEB_MESSAGE = "POST_WEB_MESSAGE";
- field public static final String PROXY_OVERRIDE = "PROXY_OVERRIDE";
- field public static final String PROXY_OVERRIDE_REVERSE_BYPASS = "PROXY_OVERRIDE_REVERSE_BYPASS";
- field public static final String RECEIVE_HTTP_ERROR = "RECEIVE_HTTP_ERROR";
- field public static final String RECEIVE_WEB_RESOURCE_ERROR = "RECEIVE_WEB_RESOURCE_ERROR";
- field public static final String SAFE_BROWSING_ALLOWLIST = "SAFE_BROWSING_ALLOWLIST";
- field public static final String SAFE_BROWSING_ENABLE = "SAFE_BROWSING_ENABLE";
- field public static final String SAFE_BROWSING_HIT = "SAFE_BROWSING_HIT";
- field public static final String SAFE_BROWSING_PRIVACY_POLICY_URL = "SAFE_BROWSING_PRIVACY_POLICY_URL";
- field public static final String SAFE_BROWSING_RESPONSE_BACK_TO_SAFETY = "SAFE_BROWSING_RESPONSE_BACK_TO_SAFETY";
- field public static final String SAFE_BROWSING_RESPONSE_PROCEED = "SAFE_BROWSING_RESPONSE_PROCEED";
- field public static final String SAFE_BROWSING_RESPONSE_SHOW_INTERSTITIAL = "SAFE_BROWSING_RESPONSE_SHOW_INTERSTITIAL";
- field @Deprecated public static final String SAFE_BROWSING_WHITELIST = "SAFE_BROWSING_WHITELIST";
- field public static final String SERVICE_WORKER_BASIC_USAGE = "SERVICE_WORKER_BASIC_USAGE";
- field public static final String SERVICE_WORKER_BLOCK_NETWORK_LOADS = "SERVICE_WORKER_BLOCK_NETWORK_LOADS";
- field public static final String SERVICE_WORKER_CACHE_MODE = "SERVICE_WORKER_CACHE_MODE";
- field public static final String SERVICE_WORKER_CONTENT_ACCESS = "SERVICE_WORKER_CONTENT_ACCESS";
- field public static final String SERVICE_WORKER_FILE_ACCESS = "SERVICE_WORKER_FILE_ACCESS";
- field public static final String SERVICE_WORKER_SHOULD_INTERCEPT_REQUEST = "SERVICE_WORKER_SHOULD_INTERCEPT_REQUEST";
- field public static final String SHOULD_OVERRIDE_WITH_REDIRECTS = "SHOULD_OVERRIDE_WITH_REDIRECTS";
- field public static final String STARTUP_FEATURE_SET_DATA_DIRECTORY_SUFFIX = "STARTUP_FEATURE_SET_DATA_DIRECTORY_SUFFIX";
- field public static final String START_SAFE_BROWSING = "START_SAFE_BROWSING";
- field public static final String TRACING_CONTROLLER_BASIC_USAGE = "TRACING_CONTROLLER_BASIC_USAGE";
- field public static final String VISUAL_STATE_CALLBACK = "VISUAL_STATE_CALLBACK";
- field public static final String WEB_MESSAGE_CALLBACK_ON_MESSAGE = "WEB_MESSAGE_CALLBACK_ON_MESSAGE";
- field public static final String WEB_MESSAGE_LISTENER = "WEB_MESSAGE_LISTENER";
- field public static final String WEB_MESSAGE_PORT_CLOSE = "WEB_MESSAGE_PORT_CLOSE";
- field public static final String WEB_MESSAGE_PORT_POST_MESSAGE = "WEB_MESSAGE_PORT_POST_MESSAGE";
- field public static final String WEB_MESSAGE_PORT_SET_MESSAGE_CALLBACK = "WEB_MESSAGE_PORT_SET_MESSAGE_CALLBACK";
- field public static final String WEB_RESOURCE_ERROR_GET_CODE = "WEB_RESOURCE_ERROR_GET_CODE";
- field public static final String WEB_RESOURCE_ERROR_GET_DESCRIPTION = "WEB_RESOURCE_ERROR_GET_DESCRIPTION";
- field public static final String WEB_RESOURCE_REQUEST_IS_REDIRECT = "WEB_RESOURCE_REQUEST_IS_REDIRECT";
- field public static final String WEB_VIEW_RENDERER_CLIENT_BASIC_USAGE = "WEB_VIEW_RENDERER_CLIENT_BASIC_USAGE";
- field public static final String WEB_VIEW_RENDERER_TERMINATE = "WEB_VIEW_RENDERER_TERMINATE";
- }
-
- public abstract class WebViewRenderProcess {
- ctor public WebViewRenderProcess();
- method public abstract boolean terminate();
- }
-
- public abstract class WebViewRenderProcessClient {
- ctor public WebViewRenderProcessClient();
- method public abstract void onRenderProcessResponsive(android.webkit.WebView, androidx.webkit.WebViewRenderProcess?);
- method public abstract void onRenderProcessUnresponsive(android.webkit.WebView, androidx.webkit.WebViewRenderProcess?);
- }
-
-}
-
diff --git a/webkit/webkit/api/public_plus_experimental_1.6.0-beta02.txt b/webkit/webkit/api/public_plus_experimental_1.6.0-beta02.txt
deleted file mode 100644
index faf13cb..0000000
--- a/webkit/webkit/api/public_plus_experimental_1.6.0-beta02.txt
+++ /dev/null
@@ -1,300 +0,0 @@
-// Signature format: 4.0
-package androidx.webkit {
-
- public class CookieManagerCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.GET_COOKIE_INFO, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static java.util.List<java.lang.String!> getCookieInfo(android.webkit.CookieManager, String);
- }
-
- public abstract class JavaScriptReplyProxy {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_MESSAGE_LISTENER, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void postMessage(String);
- }
-
- public class ProcessGlobalConfig {
- ctor public ProcessGlobalConfig();
- method public static void apply(androidx.webkit.ProcessGlobalConfig);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.STARTUP_FEATURE_SET_DATA_DIRECTORY_SUFFIX, enforcement="androidx.webkit.WebViewFeature#isConfigFeatureSupported(String, Context)") public androidx.webkit.ProcessGlobalConfig setDataDirectorySuffix(android.content.Context, String);
- }
-
- public final class ProxyConfig {
- method public java.util.List<java.lang.String!> getBypassRules();
- method public java.util.List<androidx.webkit.ProxyConfig.ProxyRule!> getProxyRules();
- method public boolean isReverseBypassEnabled();
- field public static final String MATCH_ALL_SCHEMES = "*";
- field public static final String MATCH_HTTP = "http";
- field public static final String MATCH_HTTPS = "https";
- }
-
- public static final class ProxyConfig.Builder {
- ctor public ProxyConfig.Builder();
- ctor public ProxyConfig.Builder(androidx.webkit.ProxyConfig);
- method public androidx.webkit.ProxyConfig.Builder addBypassRule(String);
- method public androidx.webkit.ProxyConfig.Builder addDirect(String);
- method public androidx.webkit.ProxyConfig.Builder addDirect();
- method public androidx.webkit.ProxyConfig.Builder addProxyRule(String);
- method public androidx.webkit.ProxyConfig.Builder addProxyRule(String, String);
- method public androidx.webkit.ProxyConfig build();
- method public androidx.webkit.ProxyConfig.Builder bypassSimpleHostnames();
- method public androidx.webkit.ProxyConfig.Builder removeImplicitRules();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.PROXY_OVERRIDE_REVERSE_BYPASS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public androidx.webkit.ProxyConfig.Builder setReverseBypassEnabled(boolean);
- }
-
- public static final class ProxyConfig.ProxyRule {
- method public String getSchemeFilter();
- method public String getUrl();
- }
-
- public abstract class ProxyController {
- method public abstract void clearProxyOverride(java.util.concurrent.Executor, Runnable);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.PROXY_OVERRIDE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static androidx.webkit.ProxyController getInstance();
- method public abstract void setProxyOverride(androidx.webkit.ProxyConfig, java.util.concurrent.Executor, Runnable);
- }
-
- public abstract class SafeBrowsingResponseCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_RESPONSE_BACK_TO_SAFETY, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void backToSafety(boolean);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_RESPONSE_PROCEED, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void proceed(boolean);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_RESPONSE_SHOW_INTERSTITIAL, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void showInterstitial(boolean);
- }
-
- public abstract class ServiceWorkerClientCompat {
- ctor public ServiceWorkerClientCompat();
- method @WorkerThread public abstract android.webkit.WebResourceResponse? shouldInterceptRequest(android.webkit.WebResourceRequest);
- }
-
- public abstract class ServiceWorkerControllerCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_BASIC_USAGE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static androidx.webkit.ServiceWorkerControllerCompat getInstance();
- method public abstract androidx.webkit.ServiceWorkerWebSettingsCompat getServiceWorkerWebSettings();
- method public abstract void setServiceWorkerClient(androidx.webkit.ServiceWorkerClientCompat?);
- }
-
- public abstract class ServiceWorkerWebSettingsCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_CONTENT_ACCESS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract boolean getAllowContentAccess();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_FILE_ACCESS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract boolean getAllowFileAccess();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_BLOCK_NETWORK_LOADS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract boolean getBlockNetworkLoads();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_CACHE_MODE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract int getCacheMode();
- method @RequiresFeature(name="REQUESTED_WITH_HEADER_ALLOW_LIST", enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract java.util.Set<java.lang.String!> getRequestedWithHeaderOriginAllowList();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_CONTENT_ACCESS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void setAllowContentAccess(boolean);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_FILE_ACCESS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void setAllowFileAccess(boolean);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_BLOCK_NETWORK_LOADS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void setBlockNetworkLoads(boolean);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_CACHE_MODE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void setCacheMode(int);
- method @RequiresFeature(name="REQUESTED_WITH_HEADER_ALLOW_LIST", enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void setRequestedWithHeaderOriginAllowList(java.util.Set<java.lang.String!>);
- }
-
- public class TracingConfig {
- method public java.util.List<java.lang.String!> getCustomIncludedCategories();
- method public int getPredefinedCategories();
- method public int getTracingMode();
- field public static final int CATEGORIES_ALL = 1; // 0x1
- field public static final int CATEGORIES_ANDROID_WEBVIEW = 2; // 0x2
- field public static final int CATEGORIES_FRAME_VIEWER = 64; // 0x40
- field public static final int CATEGORIES_INPUT_LATENCY = 8; // 0x8
- field public static final int CATEGORIES_JAVASCRIPT_AND_RENDERING = 32; // 0x20
- field public static final int CATEGORIES_NONE = 0; // 0x0
- field public static final int CATEGORIES_RENDERING = 16; // 0x10
- field public static final int CATEGORIES_WEB_DEVELOPER = 4; // 0x4
- field public static final int RECORD_CONTINUOUSLY = 1; // 0x1
- field public static final int RECORD_UNTIL_FULL = 0; // 0x0
- }
-
- public static class TracingConfig.Builder {
- ctor public TracingConfig.Builder();
- method public androidx.webkit.TracingConfig.Builder addCategories(int...);
- method public androidx.webkit.TracingConfig.Builder addCategories(java.lang.String!...);
- method public androidx.webkit.TracingConfig.Builder addCategories(java.util.Collection<java.lang.String!>);
- method public androidx.webkit.TracingConfig build();
- method public androidx.webkit.TracingConfig.Builder setTracingMode(int);
- }
-
- public abstract class TracingController {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.TRACING_CONTROLLER_BASIC_USAGE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static androidx.webkit.TracingController getInstance();
- method public abstract boolean isTracing();
- method public abstract void start(androidx.webkit.TracingConfig);
- method public abstract boolean stop(java.io.OutputStream?, java.util.concurrent.Executor);
- }
-
- public class WebMessageCompat {
- ctor public WebMessageCompat(String?);
- ctor public WebMessageCompat(String?, androidx.webkit.WebMessagePortCompat![]?);
- method public String? getData();
- method public androidx.webkit.WebMessagePortCompat![]? getPorts();
- }
-
- public abstract class WebMessagePortCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_MESSAGE_PORT_CLOSE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void close();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_MESSAGE_PORT_POST_MESSAGE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void postMessage(androidx.webkit.WebMessageCompat);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_MESSAGE_PORT_SET_MESSAGE_CALLBACK, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void setWebMessageCallback(androidx.webkit.WebMessagePortCompat.WebMessageCallbackCompat);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_MESSAGE_PORT_SET_MESSAGE_CALLBACK, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void setWebMessageCallback(android.os.Handler?, androidx.webkit.WebMessagePortCompat.WebMessageCallbackCompat);
- }
-
- public abstract static class WebMessagePortCompat.WebMessageCallbackCompat {
- ctor public WebMessagePortCompat.WebMessageCallbackCompat();
- method public void onMessage(androidx.webkit.WebMessagePortCompat, androidx.webkit.WebMessageCompat?);
- }
-
- public abstract class WebResourceErrorCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_RESOURCE_ERROR_GET_DESCRIPTION, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract CharSequence getDescription();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_RESOURCE_ERROR_GET_CODE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract int getErrorCode();
- }
-
- public class WebResourceRequestCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_RESOURCE_REQUEST_IS_REDIRECT, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static boolean isRedirect(android.webkit.WebResourceRequest);
- }
-
- public class WebSettingsCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.DISABLED_ACTION_MODE_MENU_ITEMS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static int getDisabledActionModeMenuItems(android.webkit.WebSettings);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.ENTERPRISE_AUTHENTICATION_APP_LINK_POLICY, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static boolean getEnterpriseAuthenticationAppLinkPolicyEnabled(android.webkit.WebSettings);
- method @Deprecated @RequiresFeature(name=androidx.webkit.WebViewFeature.FORCE_DARK, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static int getForceDark(android.webkit.WebSettings);
- method @Deprecated @RequiresFeature(name=androidx.webkit.WebViewFeature.FORCE_DARK_STRATEGY, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static int getForceDarkStrategy(android.webkit.WebSettings);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.OFF_SCREEN_PRERASTER, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static boolean getOffscreenPreRaster(android.webkit.WebSettings);
- method @RequiresFeature(name="REQUESTED_WITH_HEADER_ALLOW_LIST", enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static java.util.Set<java.lang.String!> getRequestedWithHeaderOriginAllowList(android.webkit.WebSettings);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_ENABLE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static boolean getSafeBrowsingEnabled(android.webkit.WebSettings);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.ALGORITHMIC_DARKENING, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static boolean isAlgorithmicDarkeningAllowed(android.webkit.WebSettings);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.ALGORITHMIC_DARKENING, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setAlgorithmicDarkeningAllowed(android.webkit.WebSettings, boolean);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.DISABLED_ACTION_MODE_MENU_ITEMS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setDisabledActionModeMenuItems(android.webkit.WebSettings, int);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.ENTERPRISE_AUTHENTICATION_APP_LINK_POLICY, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setEnterpriseAuthenticationAppLinkPolicyEnabled(android.webkit.WebSettings, boolean);
- method @Deprecated @RequiresFeature(name=androidx.webkit.WebViewFeature.FORCE_DARK, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setForceDark(android.webkit.WebSettings, int);
- method @Deprecated @RequiresFeature(name=androidx.webkit.WebViewFeature.FORCE_DARK_STRATEGY, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setForceDarkStrategy(android.webkit.WebSettings, int);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.OFF_SCREEN_PRERASTER, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setOffscreenPreRaster(android.webkit.WebSettings, boolean);
- method @RequiresFeature(name="REQUESTED_WITH_HEADER_ALLOW_LIST", enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setRequestedWithHeaderOriginAllowList(android.webkit.WebSettings, java.util.Set<java.lang.String!>);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_ENABLE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setSafeBrowsingEnabled(android.webkit.WebSettings, boolean);
- field @Deprecated public static final int DARK_STRATEGY_PREFER_WEB_THEME_OVER_USER_AGENT_DARKENING = 2; // 0x2
- field @Deprecated public static final int DARK_STRATEGY_USER_AGENT_DARKENING_ONLY = 0; // 0x0
- field @Deprecated public static final int DARK_STRATEGY_WEB_THEME_DARKENING_ONLY = 1; // 0x1
- field @Deprecated public static final int FORCE_DARK_AUTO = 1; // 0x1
- field @Deprecated public static final int FORCE_DARK_OFF = 0; // 0x0
- field @Deprecated public static final int FORCE_DARK_ON = 2; // 0x2
- }
-
- public final class WebViewAssetLoader {
- method @WorkerThread public android.webkit.WebResourceResponse? shouldInterceptRequest(android.net.Uri);
- field public static final String DEFAULT_DOMAIN = "appassets.androidplatform.net";
- }
-
- public static final class WebViewAssetLoader.AssetsPathHandler implements androidx.webkit.WebViewAssetLoader.PathHandler {
- ctor public WebViewAssetLoader.AssetsPathHandler(android.content.Context);
- method @WorkerThread public android.webkit.WebResourceResponse? handle(String);
- }
-
- public static final class WebViewAssetLoader.Builder {
- ctor public WebViewAssetLoader.Builder();
- method public androidx.webkit.WebViewAssetLoader.Builder addPathHandler(String, androidx.webkit.WebViewAssetLoader.PathHandler);
- method public androidx.webkit.WebViewAssetLoader build();
- method public androidx.webkit.WebViewAssetLoader.Builder setDomain(String);
- method public androidx.webkit.WebViewAssetLoader.Builder setHttpAllowed(boolean);
- }
-
- public static final class WebViewAssetLoader.InternalStoragePathHandler implements androidx.webkit.WebViewAssetLoader.PathHandler {
- ctor public WebViewAssetLoader.InternalStoragePathHandler(android.content.Context, java.io.File);
- method @WorkerThread public android.webkit.WebResourceResponse handle(String);
- }
-
- public static interface WebViewAssetLoader.PathHandler {
- method @WorkerThread public android.webkit.WebResourceResponse? handle(String);
- }
-
- public static final class WebViewAssetLoader.ResourcesPathHandler implements androidx.webkit.WebViewAssetLoader.PathHandler {
- ctor public WebViewAssetLoader.ResourcesPathHandler(android.content.Context);
- method @WorkerThread public android.webkit.WebResourceResponse? handle(String);
- }
-
- public class WebViewClientCompat extends android.webkit.WebViewClient {
- ctor public WebViewClientCompat();
- method @RequiresApi(23) public final void onReceivedError(android.webkit.WebView, android.webkit.WebResourceRequest, android.webkit.WebResourceError);
- method @RequiresApi(21) @UiThread public void onReceivedError(android.webkit.WebView, android.webkit.WebResourceRequest, androidx.webkit.WebResourceErrorCompat);
- method @RequiresApi(27) public final void onSafeBrowsingHit(android.webkit.WebView, android.webkit.WebResourceRequest, int, android.webkit.SafeBrowsingResponse);
- method @UiThread public void onSafeBrowsingHit(android.webkit.WebView, android.webkit.WebResourceRequest, int, androidx.webkit.SafeBrowsingResponseCompat);
- }
-
- public class WebViewCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_MESSAGE_LISTENER, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void addWebMessageListener(android.webkit.WebView, String, java.util.Set<java.lang.String!>, androidx.webkit.WebViewCompat.WebMessageListener);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.CREATE_WEB_MESSAGE_CHANNEL, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static androidx.webkit.WebMessagePortCompat![] createWebMessageChannel(android.webkit.WebView);
- method public static android.content.pm.PackageInfo? getCurrentWebViewPackage(android.content.Context);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_PRIVACY_POLICY_URL, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static android.net.Uri getSafeBrowsingPrivacyPolicyUrl();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.GET_VARIATIONS_HEADER, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static String getVariationsHeader();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.GET_WEB_CHROME_CLIENT, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static android.webkit.WebChromeClient? getWebChromeClient(android.webkit.WebView);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.GET_WEB_VIEW_CLIENT, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static android.webkit.WebViewClient getWebViewClient(android.webkit.WebView);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.GET_WEB_VIEW_RENDERER, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static androidx.webkit.WebViewRenderProcess? getWebViewRenderProcess(android.webkit.WebView);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_VIEW_RENDERER_CLIENT_BASIC_USAGE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static androidx.webkit.WebViewRenderProcessClient? getWebViewRenderProcessClient(android.webkit.WebView);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.MULTI_PROCESS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static boolean isMultiProcessEnabled();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.VISUAL_STATE_CALLBACK, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void postVisualStateCallback(android.webkit.WebView, long, androidx.webkit.WebViewCompat.VisualStateCallback);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.POST_WEB_MESSAGE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void postWebMessage(android.webkit.WebView, androidx.webkit.WebMessageCompat, android.net.Uri);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_MESSAGE_LISTENER, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void removeWebMessageListener(android.webkit.WebView, String);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_ALLOWLIST, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setSafeBrowsingAllowlist(java.util.Set<java.lang.String!>, android.webkit.ValueCallback<java.lang.Boolean!>?);
- method @Deprecated @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_WHITELIST, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setSafeBrowsingWhitelist(java.util.List<java.lang.String!>, android.webkit.ValueCallback<java.lang.Boolean!>?);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_VIEW_RENDERER_CLIENT_BASIC_USAGE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setWebViewRenderProcessClient(android.webkit.WebView, java.util.concurrent.Executor, androidx.webkit.WebViewRenderProcessClient);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_VIEW_RENDERER_CLIENT_BASIC_USAGE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setWebViewRenderProcessClient(android.webkit.WebView, androidx.webkit.WebViewRenderProcessClient?);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.START_SAFE_BROWSING, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void startSafeBrowsing(android.content.Context, android.webkit.ValueCallback<java.lang.Boolean!>?);
- }
-
- public static interface WebViewCompat.VisualStateCallback {
- method @UiThread public void onComplete(long);
- }
-
- public static interface WebViewCompat.WebMessageListener {
- method @UiThread public void onPostMessage(android.webkit.WebView, androidx.webkit.WebMessageCompat, android.net.Uri, boolean, androidx.webkit.JavaScriptReplyProxy);
- }
-
- public class WebViewFeature {
- method public static boolean isFeatureSupported(String);
- method public static boolean isStartupFeatureSupported(android.content.Context, String);
- field public static final String ALGORITHMIC_DARKENING = "ALGORITHMIC_DARKENING";
- field public static final String CREATE_WEB_MESSAGE_CHANNEL = "CREATE_WEB_MESSAGE_CHANNEL";
- field public static final String DISABLED_ACTION_MODE_MENU_ITEMS = "DISABLED_ACTION_MODE_MENU_ITEMS";
- field public static final String ENTERPRISE_AUTHENTICATION_APP_LINK_POLICY = "ENTERPRISE_AUTHENTICATION_APP_LINK_POLICY";
- field public static final String FORCE_DARK = "FORCE_DARK";
- field public static final String FORCE_DARK_STRATEGY = "FORCE_DARK_STRATEGY";
- field public static final String GET_COOKIE_INFO = "GET_COOKIE_INFO";
- field public static final String GET_VARIATIONS_HEADER = "GET_VARIATIONS_HEADER";
- field public static final String GET_WEB_CHROME_CLIENT = "GET_WEB_CHROME_CLIENT";
- field public static final String GET_WEB_VIEW_CLIENT = "GET_WEB_VIEW_CLIENT";
- field public static final String GET_WEB_VIEW_RENDERER = "GET_WEB_VIEW_RENDERER";
- field public static final String MULTI_PROCESS = "MULTI_PROCESS";
- field public static final String OFF_SCREEN_PRERASTER = "OFF_SCREEN_PRERASTER";
- field public static final String POST_WEB_MESSAGE = "POST_WEB_MESSAGE";
- field public static final String PROXY_OVERRIDE = "PROXY_OVERRIDE";
- field public static final String PROXY_OVERRIDE_REVERSE_BYPASS = "PROXY_OVERRIDE_REVERSE_BYPASS";
- field public static final String RECEIVE_HTTP_ERROR = "RECEIVE_HTTP_ERROR";
- field public static final String RECEIVE_WEB_RESOURCE_ERROR = "RECEIVE_WEB_RESOURCE_ERROR";
- field public static final String SAFE_BROWSING_ALLOWLIST = "SAFE_BROWSING_ALLOWLIST";
- field public static final String SAFE_BROWSING_ENABLE = "SAFE_BROWSING_ENABLE";
- field public static final String SAFE_BROWSING_HIT = "SAFE_BROWSING_HIT";
- field public static final String SAFE_BROWSING_PRIVACY_POLICY_URL = "SAFE_BROWSING_PRIVACY_POLICY_URL";
- field public static final String SAFE_BROWSING_RESPONSE_BACK_TO_SAFETY = "SAFE_BROWSING_RESPONSE_BACK_TO_SAFETY";
- field public static final String SAFE_BROWSING_RESPONSE_PROCEED = "SAFE_BROWSING_RESPONSE_PROCEED";
- field public static final String SAFE_BROWSING_RESPONSE_SHOW_INTERSTITIAL = "SAFE_BROWSING_RESPONSE_SHOW_INTERSTITIAL";
- field @Deprecated public static final String SAFE_BROWSING_WHITELIST = "SAFE_BROWSING_WHITELIST";
- field public static final String SERVICE_WORKER_BASIC_USAGE = "SERVICE_WORKER_BASIC_USAGE";
- field public static final String SERVICE_WORKER_BLOCK_NETWORK_LOADS = "SERVICE_WORKER_BLOCK_NETWORK_LOADS";
- field public static final String SERVICE_WORKER_CACHE_MODE = "SERVICE_WORKER_CACHE_MODE";
- field public static final String SERVICE_WORKER_CONTENT_ACCESS = "SERVICE_WORKER_CONTENT_ACCESS";
- field public static final String SERVICE_WORKER_FILE_ACCESS = "SERVICE_WORKER_FILE_ACCESS";
- field public static final String SERVICE_WORKER_SHOULD_INTERCEPT_REQUEST = "SERVICE_WORKER_SHOULD_INTERCEPT_REQUEST";
- field public static final String SHOULD_OVERRIDE_WITH_REDIRECTS = "SHOULD_OVERRIDE_WITH_REDIRECTS";
- field public static final String STARTUP_FEATURE_SET_DATA_DIRECTORY_SUFFIX = "STARTUP_FEATURE_SET_DATA_DIRECTORY_SUFFIX";
- field public static final String START_SAFE_BROWSING = "START_SAFE_BROWSING";
- field public static final String TRACING_CONTROLLER_BASIC_USAGE = "TRACING_CONTROLLER_BASIC_USAGE";
- field public static final String VISUAL_STATE_CALLBACK = "VISUAL_STATE_CALLBACK";
- field public static final String WEB_MESSAGE_CALLBACK_ON_MESSAGE = "WEB_MESSAGE_CALLBACK_ON_MESSAGE";
- field public static final String WEB_MESSAGE_LISTENER = "WEB_MESSAGE_LISTENER";
- field public static final String WEB_MESSAGE_PORT_CLOSE = "WEB_MESSAGE_PORT_CLOSE";
- field public static final String WEB_MESSAGE_PORT_POST_MESSAGE = "WEB_MESSAGE_PORT_POST_MESSAGE";
- field public static final String WEB_MESSAGE_PORT_SET_MESSAGE_CALLBACK = "WEB_MESSAGE_PORT_SET_MESSAGE_CALLBACK";
- field public static final String WEB_RESOURCE_ERROR_GET_CODE = "WEB_RESOURCE_ERROR_GET_CODE";
- field public static final String WEB_RESOURCE_ERROR_GET_DESCRIPTION = "WEB_RESOURCE_ERROR_GET_DESCRIPTION";
- field public static final String WEB_RESOURCE_REQUEST_IS_REDIRECT = "WEB_RESOURCE_REQUEST_IS_REDIRECT";
- field public static final String WEB_VIEW_RENDERER_CLIENT_BASIC_USAGE = "WEB_VIEW_RENDERER_CLIENT_BASIC_USAGE";
- field public static final String WEB_VIEW_RENDERER_TERMINATE = "WEB_VIEW_RENDERER_TERMINATE";
- }
-
- public abstract class WebViewRenderProcess {
- ctor public WebViewRenderProcess();
- method public abstract boolean terminate();
- }
-
- public abstract class WebViewRenderProcessClient {
- ctor public WebViewRenderProcessClient();
- method public abstract void onRenderProcessResponsive(android.webkit.WebView, androidx.webkit.WebViewRenderProcess?);
- method public abstract void onRenderProcessUnresponsive(android.webkit.WebView, androidx.webkit.WebViewRenderProcess?);
- }
-
-}
-
diff --git a/webkit/webkit/api/restricted_1.6.0-beta02.txt b/webkit/webkit/api/restricted_1.6.0-beta02.txt
deleted file mode 100644
index faf13cb..0000000
--- a/webkit/webkit/api/restricted_1.6.0-beta02.txt
+++ /dev/null
@@ -1,300 +0,0 @@
-// Signature format: 4.0
-package androidx.webkit {
-
- public class CookieManagerCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.GET_COOKIE_INFO, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static java.util.List<java.lang.String!> getCookieInfo(android.webkit.CookieManager, String);
- }
-
- public abstract class JavaScriptReplyProxy {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_MESSAGE_LISTENER, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void postMessage(String);
- }
-
- public class ProcessGlobalConfig {
- ctor public ProcessGlobalConfig();
- method public static void apply(androidx.webkit.ProcessGlobalConfig);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.STARTUP_FEATURE_SET_DATA_DIRECTORY_SUFFIX, enforcement="androidx.webkit.WebViewFeature#isConfigFeatureSupported(String, Context)") public androidx.webkit.ProcessGlobalConfig setDataDirectorySuffix(android.content.Context, String);
- }
-
- public final class ProxyConfig {
- method public java.util.List<java.lang.String!> getBypassRules();
- method public java.util.List<androidx.webkit.ProxyConfig.ProxyRule!> getProxyRules();
- method public boolean isReverseBypassEnabled();
- field public static final String MATCH_ALL_SCHEMES = "*";
- field public static final String MATCH_HTTP = "http";
- field public static final String MATCH_HTTPS = "https";
- }
-
- public static final class ProxyConfig.Builder {
- ctor public ProxyConfig.Builder();
- ctor public ProxyConfig.Builder(androidx.webkit.ProxyConfig);
- method public androidx.webkit.ProxyConfig.Builder addBypassRule(String);
- method public androidx.webkit.ProxyConfig.Builder addDirect(String);
- method public androidx.webkit.ProxyConfig.Builder addDirect();
- method public androidx.webkit.ProxyConfig.Builder addProxyRule(String);
- method public androidx.webkit.ProxyConfig.Builder addProxyRule(String, String);
- method public androidx.webkit.ProxyConfig build();
- method public androidx.webkit.ProxyConfig.Builder bypassSimpleHostnames();
- method public androidx.webkit.ProxyConfig.Builder removeImplicitRules();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.PROXY_OVERRIDE_REVERSE_BYPASS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public androidx.webkit.ProxyConfig.Builder setReverseBypassEnabled(boolean);
- }
-
- public static final class ProxyConfig.ProxyRule {
- method public String getSchemeFilter();
- method public String getUrl();
- }
-
- public abstract class ProxyController {
- method public abstract void clearProxyOverride(java.util.concurrent.Executor, Runnable);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.PROXY_OVERRIDE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static androidx.webkit.ProxyController getInstance();
- method public abstract void setProxyOverride(androidx.webkit.ProxyConfig, java.util.concurrent.Executor, Runnable);
- }
-
- public abstract class SafeBrowsingResponseCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_RESPONSE_BACK_TO_SAFETY, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void backToSafety(boolean);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_RESPONSE_PROCEED, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void proceed(boolean);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_RESPONSE_SHOW_INTERSTITIAL, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void showInterstitial(boolean);
- }
-
- public abstract class ServiceWorkerClientCompat {
- ctor public ServiceWorkerClientCompat();
- method @WorkerThread public abstract android.webkit.WebResourceResponse? shouldInterceptRequest(android.webkit.WebResourceRequest);
- }
-
- public abstract class ServiceWorkerControllerCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_BASIC_USAGE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static androidx.webkit.ServiceWorkerControllerCompat getInstance();
- method public abstract androidx.webkit.ServiceWorkerWebSettingsCompat getServiceWorkerWebSettings();
- method public abstract void setServiceWorkerClient(androidx.webkit.ServiceWorkerClientCompat?);
- }
-
- public abstract class ServiceWorkerWebSettingsCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_CONTENT_ACCESS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract boolean getAllowContentAccess();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_FILE_ACCESS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract boolean getAllowFileAccess();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_BLOCK_NETWORK_LOADS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract boolean getBlockNetworkLoads();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_CACHE_MODE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract int getCacheMode();
- method @RequiresFeature(name="REQUESTED_WITH_HEADER_ALLOW_LIST", enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract java.util.Set<java.lang.String!> getRequestedWithHeaderOriginAllowList();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_CONTENT_ACCESS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void setAllowContentAccess(boolean);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_FILE_ACCESS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void setAllowFileAccess(boolean);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_BLOCK_NETWORK_LOADS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void setBlockNetworkLoads(boolean);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SERVICE_WORKER_CACHE_MODE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void setCacheMode(int);
- method @RequiresFeature(name="REQUESTED_WITH_HEADER_ALLOW_LIST", enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void setRequestedWithHeaderOriginAllowList(java.util.Set<java.lang.String!>);
- }
-
- public class TracingConfig {
- method public java.util.List<java.lang.String!> getCustomIncludedCategories();
- method public int getPredefinedCategories();
- method public int getTracingMode();
- field public static final int CATEGORIES_ALL = 1; // 0x1
- field public static final int CATEGORIES_ANDROID_WEBVIEW = 2; // 0x2
- field public static final int CATEGORIES_FRAME_VIEWER = 64; // 0x40
- field public static final int CATEGORIES_INPUT_LATENCY = 8; // 0x8
- field public static final int CATEGORIES_JAVASCRIPT_AND_RENDERING = 32; // 0x20
- field public static final int CATEGORIES_NONE = 0; // 0x0
- field public static final int CATEGORIES_RENDERING = 16; // 0x10
- field public static final int CATEGORIES_WEB_DEVELOPER = 4; // 0x4
- field public static final int RECORD_CONTINUOUSLY = 1; // 0x1
- field public static final int RECORD_UNTIL_FULL = 0; // 0x0
- }
-
- public static class TracingConfig.Builder {
- ctor public TracingConfig.Builder();
- method public androidx.webkit.TracingConfig.Builder addCategories(int...);
- method public androidx.webkit.TracingConfig.Builder addCategories(java.lang.String!...);
- method public androidx.webkit.TracingConfig.Builder addCategories(java.util.Collection<java.lang.String!>);
- method public androidx.webkit.TracingConfig build();
- method public androidx.webkit.TracingConfig.Builder setTracingMode(int);
- }
-
- public abstract class TracingController {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.TRACING_CONTROLLER_BASIC_USAGE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static androidx.webkit.TracingController getInstance();
- method public abstract boolean isTracing();
- method public abstract void start(androidx.webkit.TracingConfig);
- method public abstract boolean stop(java.io.OutputStream?, java.util.concurrent.Executor);
- }
-
- public class WebMessageCompat {
- ctor public WebMessageCompat(String?);
- ctor public WebMessageCompat(String?, androidx.webkit.WebMessagePortCompat![]?);
- method public String? getData();
- method public androidx.webkit.WebMessagePortCompat![]? getPorts();
- }
-
- public abstract class WebMessagePortCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_MESSAGE_PORT_CLOSE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void close();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_MESSAGE_PORT_POST_MESSAGE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void postMessage(androidx.webkit.WebMessageCompat);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_MESSAGE_PORT_SET_MESSAGE_CALLBACK, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void setWebMessageCallback(androidx.webkit.WebMessagePortCompat.WebMessageCallbackCompat);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_MESSAGE_PORT_SET_MESSAGE_CALLBACK, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract void setWebMessageCallback(android.os.Handler?, androidx.webkit.WebMessagePortCompat.WebMessageCallbackCompat);
- }
-
- public abstract static class WebMessagePortCompat.WebMessageCallbackCompat {
- ctor public WebMessagePortCompat.WebMessageCallbackCompat();
- method public void onMessage(androidx.webkit.WebMessagePortCompat, androidx.webkit.WebMessageCompat?);
- }
-
- public abstract class WebResourceErrorCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_RESOURCE_ERROR_GET_DESCRIPTION, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract CharSequence getDescription();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_RESOURCE_ERROR_GET_CODE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public abstract int getErrorCode();
- }
-
- public class WebResourceRequestCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_RESOURCE_REQUEST_IS_REDIRECT, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static boolean isRedirect(android.webkit.WebResourceRequest);
- }
-
- public class WebSettingsCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.DISABLED_ACTION_MODE_MENU_ITEMS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static int getDisabledActionModeMenuItems(android.webkit.WebSettings);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.ENTERPRISE_AUTHENTICATION_APP_LINK_POLICY, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static boolean getEnterpriseAuthenticationAppLinkPolicyEnabled(android.webkit.WebSettings);
- method @Deprecated @RequiresFeature(name=androidx.webkit.WebViewFeature.FORCE_DARK, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static int getForceDark(android.webkit.WebSettings);
- method @Deprecated @RequiresFeature(name=androidx.webkit.WebViewFeature.FORCE_DARK_STRATEGY, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static int getForceDarkStrategy(android.webkit.WebSettings);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.OFF_SCREEN_PRERASTER, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static boolean getOffscreenPreRaster(android.webkit.WebSettings);
- method @RequiresFeature(name="REQUESTED_WITH_HEADER_ALLOW_LIST", enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static java.util.Set<java.lang.String!> getRequestedWithHeaderOriginAllowList(android.webkit.WebSettings);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_ENABLE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static boolean getSafeBrowsingEnabled(android.webkit.WebSettings);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.ALGORITHMIC_DARKENING, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static boolean isAlgorithmicDarkeningAllowed(android.webkit.WebSettings);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.ALGORITHMIC_DARKENING, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setAlgorithmicDarkeningAllowed(android.webkit.WebSettings, boolean);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.DISABLED_ACTION_MODE_MENU_ITEMS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setDisabledActionModeMenuItems(android.webkit.WebSettings, int);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.ENTERPRISE_AUTHENTICATION_APP_LINK_POLICY, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setEnterpriseAuthenticationAppLinkPolicyEnabled(android.webkit.WebSettings, boolean);
- method @Deprecated @RequiresFeature(name=androidx.webkit.WebViewFeature.FORCE_DARK, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setForceDark(android.webkit.WebSettings, int);
- method @Deprecated @RequiresFeature(name=androidx.webkit.WebViewFeature.FORCE_DARK_STRATEGY, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setForceDarkStrategy(android.webkit.WebSettings, int);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.OFF_SCREEN_PRERASTER, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setOffscreenPreRaster(android.webkit.WebSettings, boolean);
- method @RequiresFeature(name="REQUESTED_WITH_HEADER_ALLOW_LIST", enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setRequestedWithHeaderOriginAllowList(android.webkit.WebSettings, java.util.Set<java.lang.String!>);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_ENABLE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setSafeBrowsingEnabled(android.webkit.WebSettings, boolean);
- field @Deprecated public static final int DARK_STRATEGY_PREFER_WEB_THEME_OVER_USER_AGENT_DARKENING = 2; // 0x2
- field @Deprecated public static final int DARK_STRATEGY_USER_AGENT_DARKENING_ONLY = 0; // 0x0
- field @Deprecated public static final int DARK_STRATEGY_WEB_THEME_DARKENING_ONLY = 1; // 0x1
- field @Deprecated public static final int FORCE_DARK_AUTO = 1; // 0x1
- field @Deprecated public static final int FORCE_DARK_OFF = 0; // 0x0
- field @Deprecated public static final int FORCE_DARK_ON = 2; // 0x2
- }
-
- public final class WebViewAssetLoader {
- method @WorkerThread public android.webkit.WebResourceResponse? shouldInterceptRequest(android.net.Uri);
- field public static final String DEFAULT_DOMAIN = "appassets.androidplatform.net";
- }
-
- public static final class WebViewAssetLoader.AssetsPathHandler implements androidx.webkit.WebViewAssetLoader.PathHandler {
- ctor public WebViewAssetLoader.AssetsPathHandler(android.content.Context);
- method @WorkerThread public android.webkit.WebResourceResponse? handle(String);
- }
-
- public static final class WebViewAssetLoader.Builder {
- ctor public WebViewAssetLoader.Builder();
- method public androidx.webkit.WebViewAssetLoader.Builder addPathHandler(String, androidx.webkit.WebViewAssetLoader.PathHandler);
- method public androidx.webkit.WebViewAssetLoader build();
- method public androidx.webkit.WebViewAssetLoader.Builder setDomain(String);
- method public androidx.webkit.WebViewAssetLoader.Builder setHttpAllowed(boolean);
- }
-
- public static final class WebViewAssetLoader.InternalStoragePathHandler implements androidx.webkit.WebViewAssetLoader.PathHandler {
- ctor public WebViewAssetLoader.InternalStoragePathHandler(android.content.Context, java.io.File);
- method @WorkerThread public android.webkit.WebResourceResponse handle(String);
- }
-
- public static interface WebViewAssetLoader.PathHandler {
- method @WorkerThread public android.webkit.WebResourceResponse? handle(String);
- }
-
- public static final class WebViewAssetLoader.ResourcesPathHandler implements androidx.webkit.WebViewAssetLoader.PathHandler {
- ctor public WebViewAssetLoader.ResourcesPathHandler(android.content.Context);
- method @WorkerThread public android.webkit.WebResourceResponse? handle(String);
- }
-
- public class WebViewClientCompat extends android.webkit.WebViewClient {
- ctor public WebViewClientCompat();
- method @RequiresApi(23) public final void onReceivedError(android.webkit.WebView, android.webkit.WebResourceRequest, android.webkit.WebResourceError);
- method @RequiresApi(21) @UiThread public void onReceivedError(android.webkit.WebView, android.webkit.WebResourceRequest, androidx.webkit.WebResourceErrorCompat);
- method @RequiresApi(27) public final void onSafeBrowsingHit(android.webkit.WebView, android.webkit.WebResourceRequest, int, android.webkit.SafeBrowsingResponse);
- method @UiThread public void onSafeBrowsingHit(android.webkit.WebView, android.webkit.WebResourceRequest, int, androidx.webkit.SafeBrowsingResponseCompat);
- }
-
- public class WebViewCompat {
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_MESSAGE_LISTENER, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void addWebMessageListener(android.webkit.WebView, String, java.util.Set<java.lang.String!>, androidx.webkit.WebViewCompat.WebMessageListener);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.CREATE_WEB_MESSAGE_CHANNEL, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static androidx.webkit.WebMessagePortCompat![] createWebMessageChannel(android.webkit.WebView);
- method public static android.content.pm.PackageInfo? getCurrentWebViewPackage(android.content.Context);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_PRIVACY_POLICY_URL, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static android.net.Uri getSafeBrowsingPrivacyPolicyUrl();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.GET_VARIATIONS_HEADER, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static String getVariationsHeader();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.GET_WEB_CHROME_CLIENT, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static android.webkit.WebChromeClient? getWebChromeClient(android.webkit.WebView);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.GET_WEB_VIEW_CLIENT, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static android.webkit.WebViewClient getWebViewClient(android.webkit.WebView);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.GET_WEB_VIEW_RENDERER, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static androidx.webkit.WebViewRenderProcess? getWebViewRenderProcess(android.webkit.WebView);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_VIEW_RENDERER_CLIENT_BASIC_USAGE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static androidx.webkit.WebViewRenderProcessClient? getWebViewRenderProcessClient(android.webkit.WebView);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.MULTI_PROCESS, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static boolean isMultiProcessEnabled();
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.VISUAL_STATE_CALLBACK, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void postVisualStateCallback(android.webkit.WebView, long, androidx.webkit.WebViewCompat.VisualStateCallback);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.POST_WEB_MESSAGE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void postWebMessage(android.webkit.WebView, androidx.webkit.WebMessageCompat, android.net.Uri);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_MESSAGE_LISTENER, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void removeWebMessageListener(android.webkit.WebView, String);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_ALLOWLIST, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setSafeBrowsingAllowlist(java.util.Set<java.lang.String!>, android.webkit.ValueCallback<java.lang.Boolean!>?);
- method @Deprecated @RequiresFeature(name=androidx.webkit.WebViewFeature.SAFE_BROWSING_WHITELIST, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setSafeBrowsingWhitelist(java.util.List<java.lang.String!>, android.webkit.ValueCallback<java.lang.Boolean!>?);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_VIEW_RENDERER_CLIENT_BASIC_USAGE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setWebViewRenderProcessClient(android.webkit.WebView, java.util.concurrent.Executor, androidx.webkit.WebViewRenderProcessClient);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.WEB_VIEW_RENDERER_CLIENT_BASIC_USAGE, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void setWebViewRenderProcessClient(android.webkit.WebView, androidx.webkit.WebViewRenderProcessClient?);
- method @RequiresFeature(name=androidx.webkit.WebViewFeature.START_SAFE_BROWSING, enforcement="androidx.webkit.WebViewFeature#isFeatureSupported") public static void startSafeBrowsing(android.content.Context, android.webkit.ValueCallback<java.lang.Boolean!>?);
- }
-
- public static interface WebViewCompat.VisualStateCallback {
- method @UiThread public void onComplete(long);
- }
-
- public static interface WebViewCompat.WebMessageListener {
- method @UiThread public void onPostMessage(android.webkit.WebView, androidx.webkit.WebMessageCompat, android.net.Uri, boolean, androidx.webkit.JavaScriptReplyProxy);
- }
-
- public class WebViewFeature {
- method public static boolean isFeatureSupported(String);
- method public static boolean isStartupFeatureSupported(android.content.Context, String);
- field public static final String ALGORITHMIC_DARKENING = "ALGORITHMIC_DARKENING";
- field public static final String CREATE_WEB_MESSAGE_CHANNEL = "CREATE_WEB_MESSAGE_CHANNEL";
- field public static final String DISABLED_ACTION_MODE_MENU_ITEMS = "DISABLED_ACTION_MODE_MENU_ITEMS";
- field public static final String ENTERPRISE_AUTHENTICATION_APP_LINK_POLICY = "ENTERPRISE_AUTHENTICATION_APP_LINK_POLICY";
- field public static final String FORCE_DARK = "FORCE_DARK";
- field public static final String FORCE_DARK_STRATEGY = "FORCE_DARK_STRATEGY";
- field public static final String GET_COOKIE_INFO = "GET_COOKIE_INFO";
- field public static final String GET_VARIATIONS_HEADER = "GET_VARIATIONS_HEADER";
- field public static final String GET_WEB_CHROME_CLIENT = "GET_WEB_CHROME_CLIENT";
- field public static final String GET_WEB_VIEW_CLIENT = "GET_WEB_VIEW_CLIENT";
- field public static final String GET_WEB_VIEW_RENDERER = "GET_WEB_VIEW_RENDERER";
- field public static final String MULTI_PROCESS = "MULTI_PROCESS";
- field public static final String OFF_SCREEN_PRERASTER = "OFF_SCREEN_PRERASTER";
- field public static final String POST_WEB_MESSAGE = "POST_WEB_MESSAGE";
- field public static final String PROXY_OVERRIDE = "PROXY_OVERRIDE";
- field public static final String PROXY_OVERRIDE_REVERSE_BYPASS = "PROXY_OVERRIDE_REVERSE_BYPASS";
- field public static final String RECEIVE_HTTP_ERROR = "RECEIVE_HTTP_ERROR";
- field public static final String RECEIVE_WEB_RESOURCE_ERROR = "RECEIVE_WEB_RESOURCE_ERROR";
- field public static final String SAFE_BROWSING_ALLOWLIST = "SAFE_BROWSING_ALLOWLIST";
- field public static final String SAFE_BROWSING_ENABLE = "SAFE_BROWSING_ENABLE";
- field public static final String SAFE_BROWSING_HIT = "SAFE_BROWSING_HIT";
- field public static final String SAFE_BROWSING_PRIVACY_POLICY_URL = "SAFE_BROWSING_PRIVACY_POLICY_URL";
- field public static final String SAFE_BROWSING_RESPONSE_BACK_TO_SAFETY = "SAFE_BROWSING_RESPONSE_BACK_TO_SAFETY";
- field public static final String SAFE_BROWSING_RESPONSE_PROCEED = "SAFE_BROWSING_RESPONSE_PROCEED";
- field public static final String SAFE_BROWSING_RESPONSE_SHOW_INTERSTITIAL = "SAFE_BROWSING_RESPONSE_SHOW_INTERSTITIAL";
- field @Deprecated public static final String SAFE_BROWSING_WHITELIST = "SAFE_BROWSING_WHITELIST";
- field public static final String SERVICE_WORKER_BASIC_USAGE = "SERVICE_WORKER_BASIC_USAGE";
- field public static final String SERVICE_WORKER_BLOCK_NETWORK_LOADS = "SERVICE_WORKER_BLOCK_NETWORK_LOADS";
- field public static final String SERVICE_WORKER_CACHE_MODE = "SERVICE_WORKER_CACHE_MODE";
- field public static final String SERVICE_WORKER_CONTENT_ACCESS = "SERVICE_WORKER_CONTENT_ACCESS";
- field public static final String SERVICE_WORKER_FILE_ACCESS = "SERVICE_WORKER_FILE_ACCESS";
- field public static final String SERVICE_WORKER_SHOULD_INTERCEPT_REQUEST = "SERVICE_WORKER_SHOULD_INTERCEPT_REQUEST";
- field public static final String SHOULD_OVERRIDE_WITH_REDIRECTS = "SHOULD_OVERRIDE_WITH_REDIRECTS";
- field public static final String STARTUP_FEATURE_SET_DATA_DIRECTORY_SUFFIX = "STARTUP_FEATURE_SET_DATA_DIRECTORY_SUFFIX";
- field public static final String START_SAFE_BROWSING = "START_SAFE_BROWSING";
- field public static final String TRACING_CONTROLLER_BASIC_USAGE = "TRACING_CONTROLLER_BASIC_USAGE";
- field public static final String VISUAL_STATE_CALLBACK = "VISUAL_STATE_CALLBACK";
- field public static final String WEB_MESSAGE_CALLBACK_ON_MESSAGE = "WEB_MESSAGE_CALLBACK_ON_MESSAGE";
- field public static final String WEB_MESSAGE_LISTENER = "WEB_MESSAGE_LISTENER";
- field public static final String WEB_MESSAGE_PORT_CLOSE = "WEB_MESSAGE_PORT_CLOSE";
- field public static final String WEB_MESSAGE_PORT_POST_MESSAGE = "WEB_MESSAGE_PORT_POST_MESSAGE";
- field public static final String WEB_MESSAGE_PORT_SET_MESSAGE_CALLBACK = "WEB_MESSAGE_PORT_SET_MESSAGE_CALLBACK";
- field public static final String WEB_RESOURCE_ERROR_GET_CODE = "WEB_RESOURCE_ERROR_GET_CODE";
- field public static final String WEB_RESOURCE_ERROR_GET_DESCRIPTION = "WEB_RESOURCE_ERROR_GET_DESCRIPTION";
- field public static final String WEB_RESOURCE_REQUEST_IS_REDIRECT = "WEB_RESOURCE_REQUEST_IS_REDIRECT";
- field public static final String WEB_VIEW_RENDERER_CLIENT_BASIC_USAGE = "WEB_VIEW_RENDERER_CLIENT_BASIC_USAGE";
- field public static final String WEB_VIEW_RENDERER_TERMINATE = "WEB_VIEW_RENDERER_TERMINATE";
- }
-
- public abstract class WebViewRenderProcess {
- ctor public WebViewRenderProcess();
- method public abstract boolean terminate();
- }
-
- public abstract class WebViewRenderProcessClient {
- ctor public WebViewRenderProcessClient();
- method public abstract void onRenderProcessResponsive(android.webkit.WebView, androidx.webkit.WebViewRenderProcess?);
- method public abstract void onRenderProcessUnresponsive(android.webkit.WebView, androidx.webkit.WebViewRenderProcess?);
- }
-
-}
-
diff --git a/window/extensions/extensions/api/current.txt b/window/extensions/extensions/api/current.txt
index 8867f5f6c..ead684f 100644
--- a/window/extensions/extensions/api/current.txt
+++ b/window/extensions/extensions/api/current.txt
@@ -4,6 +4,7 @@
public interface WindowExtensions {
method public default androidx.window.extensions.embedding.ActivityEmbeddingComponent? getActivityEmbeddingComponent();
method public default int getVendorApiLevel();
+ method public default androidx.window.extensions.area.WindowAreaComponent? getWindowAreaComponent();
method public androidx.window.extensions.layout.WindowLayoutComponent? getWindowLayoutComponent();
}
@@ -13,13 +14,32 @@
}
+package androidx.window.extensions.area {
+
+ public interface WindowAreaComponent {
+ method public void addRearDisplayStatusListener(java.util.function.Consumer<java.lang.Integer!>);
+ method public void endRearDisplaySession();
+ method public void removeRearDisplayStatusListener(java.util.function.Consumer<java.lang.Integer!>);
+ method public void startRearDisplaySession(android.app.Activity, java.util.function.Consumer<java.lang.Integer!>);
+ field public static final int SESSION_STATE_ACTIVE = 1; // 0x1
+ field public static final int SESSION_STATE_INACTIVE = 0; // 0x0
+ field public static final int STATUS_AVAILABLE = 2; // 0x2
+ field public static final int STATUS_UNAVAILABLE = 1; // 0x1
+ field public static final int STATUS_UNSUPPORTED = 0; // 0x0
+ }
+
+}
+
package androidx.window.extensions.embedding {
public interface ActivityEmbeddingComponent {
+ method public void clearSplitAttributesCalculator();
method public void clearSplitInfoCallback();
method public boolean isActivityEmbedded(android.app.Activity);
method public void setEmbeddingRules(java.util.Set<androidx.window.extensions.embedding.EmbeddingRule!>);
- method public void setSplitInfoCallback(java.util.function.Consumer<java.util.List<androidx.window.extensions.embedding.SplitInfo!>!>);
+ method public void setSplitAttributesCalculator(androidx.window.extensions.core.util.function.Function<androidx.window.extensions.embedding.SplitAttributesCalculatorParams!,androidx.window.extensions.embedding.SplitAttributes!>);
+ method @Deprecated public void setSplitInfoCallback(java.util.function.Consumer<java.util.List<androidx.window.extensions.embedding.SplitInfo!>!>);
+ method public default void setSplitInfoCallback(androidx.window.extensions.core.util.function.Consumer<java.util.List<androidx.window.extensions.embedding.SplitInfo!>!>);
}
public class ActivityRule extends androidx.window.extensions.embedding.EmbeddingRule {
@@ -29,9 +49,11 @@
}
public static final class ActivityRule.Builder {
- ctor public ActivityRule.Builder(java.util.function.Predicate<android.app.Activity!>, java.util.function.Predicate<android.content.Intent!>);
+ ctor @Deprecated @RequiresApi(android.os.Build.VERSION_CODES.N) public ActivityRule.Builder(java.util.function.Predicate<android.app.Activity!>, java.util.function.Predicate<android.content.Intent!>);
+ ctor public ActivityRule.Builder(androidx.window.extensions.core.util.function.Predicate<android.app.Activity!>, androidx.window.extensions.core.util.function.Predicate<android.content.Intent!>);
method public androidx.window.extensions.embedding.ActivityRule build();
method public androidx.window.extensions.embedding.ActivityRule.Builder setShouldAlwaysExpand(boolean);
+ method public androidx.window.extensions.embedding.ActivityRule.Builder setTag(String);
}
public class ActivityStack {
@@ -41,13 +63,64 @@
}
public abstract class EmbeddingRule {
+ method public String? getTag();
+ }
+
+ public class SplitAttributes {
+ method @ColorInt public int getAnimationBackgroundColor();
+ method public int getLayoutDirection();
+ method public androidx.window.extensions.embedding.SplitAttributes.SplitType getSplitType();
+ }
+
+ public static final class SplitAttributes.Builder {
+ ctor public SplitAttributes.Builder();
+ method public androidx.window.extensions.embedding.SplitAttributes build();
+ method public androidx.window.extensions.embedding.SplitAttributes.Builder setAnimationBackgroundColor(@ColorInt int);
+ method public androidx.window.extensions.embedding.SplitAttributes.Builder setLayoutDirection(int);
+ method public androidx.window.extensions.embedding.SplitAttributes.Builder setSplitType(androidx.window.extensions.embedding.SplitAttributes.SplitType);
+ }
+
+ public static final class SplitAttributes.LayoutDirection {
+ field public static final int BOTTOM_TO_TOP = 5; // 0x5
+ field public static final int LEFT_TO_RIGHT = 0; // 0x0
+ field public static final int LOCALE = 3; // 0x3
+ field public static final int RIGHT_TO_LEFT = 1; // 0x1
+ field public static final int TOP_TO_BOTTOM = 4; // 0x4
+ }
+
+ public static class SplitAttributes.SplitType {
+ }
+
+ public static final class SplitAttributes.SplitType.ExpandContainersSplitType extends androidx.window.extensions.embedding.SplitAttributes.SplitType {
+ ctor public SplitAttributes.SplitType.ExpandContainersSplitType();
+ }
+
+ public static final class SplitAttributes.SplitType.HingeSplitType extends androidx.window.extensions.embedding.SplitAttributes.SplitType {
+ ctor public SplitAttributes.SplitType.HingeSplitType(androidx.window.extensions.embedding.SplitAttributes.SplitType);
+ method public androidx.window.extensions.embedding.SplitAttributes.SplitType getFallbackSplitType();
+ }
+
+ public static final class SplitAttributes.SplitType.RatioSplitType extends androidx.window.extensions.embedding.SplitAttributes.SplitType {
+ ctor public SplitAttributes.SplitType.RatioSplitType(@FloatRange(from=0.0, to=1.0, fromInclusive=false, toInclusive=false) float);
+ method @FloatRange(from=0.0, to=1.0, fromInclusive=false, toInclusive=false) public float getRatio();
+ method public static androidx.window.extensions.embedding.SplitAttributes.SplitType.RatioSplitType splitEqually();
+ }
+
+ public class SplitAttributesCalculatorParams {
+ method public boolean areDefaultConstraintsSatisfied();
+ method public androidx.window.extensions.embedding.SplitAttributes getDefaultSplitAttributes();
+ method public android.content.res.Configuration getParentConfiguration();
+ method public androidx.window.extensions.layout.WindowLayoutInfo getParentWindowLayoutInfo();
+ method public android.view.WindowMetrics getParentWindowMetrics();
+ method public String? getSplitRuleTag();
}
public class SplitInfo {
- ctor public SplitInfo(androidx.window.extensions.embedding.ActivityStack, androidx.window.extensions.embedding.ActivityStack, float);
+ ctor public SplitInfo(androidx.window.extensions.embedding.ActivityStack, androidx.window.extensions.embedding.ActivityStack, androidx.window.extensions.embedding.SplitAttributes);
method public androidx.window.extensions.embedding.ActivityStack getPrimaryActivityStack();
method public androidx.window.extensions.embedding.ActivityStack getSecondaryActivityStack();
- method public float getSplitRatio();
+ method public androidx.window.extensions.embedding.SplitAttributes getSplitAttributes();
+ method @Deprecated public float getSplitRatio();
}
public class SplitPairRule extends androidx.window.extensions.embedding.SplitRule {
@@ -59,15 +132,18 @@
}
public static final class SplitPairRule.Builder {
- ctor public SplitPairRule.Builder(java.util.function.Predicate<android.util.Pair<android.app.Activity!,android.app.Activity!>!>, java.util.function.Predicate<android.util.Pair<android.app.Activity!,android.content.Intent!>!>, java.util.function.Predicate<android.view.WindowMetrics!>);
+ ctor @Deprecated @RequiresApi(android.os.Build.VERSION_CODES.N) public SplitPairRule.Builder(java.util.function.Predicate<android.util.Pair<android.app.Activity!,android.app.Activity!>!>, java.util.function.Predicate<android.util.Pair<android.app.Activity!,android.content.Intent!>!>, java.util.function.Predicate<android.view.WindowMetrics!>);
+ ctor public SplitPairRule.Builder(androidx.window.extensions.core.util.function.Predicate<android.util.Pair<android.app.Activity!,android.app.Activity!>!>, androidx.window.extensions.core.util.function.Predicate<android.util.Pair<android.app.Activity!,android.content.Intent!>!>, androidx.window.extensions.core.util.function.Predicate<android.view.WindowMetrics!>);
method public androidx.window.extensions.embedding.SplitPairRule build();
+ method public androidx.window.extensions.embedding.SplitPairRule.Builder setDefaultSplitAttributes(androidx.window.extensions.embedding.SplitAttributes);
method public androidx.window.extensions.embedding.SplitPairRule.Builder setFinishPrimaryWithSecondary(int);
method public androidx.window.extensions.embedding.SplitPairRule.Builder setFinishSecondaryWithPrimary(int);
- method public androidx.window.extensions.embedding.SplitPairRule.Builder setLayoutDirection(int);
+ method @Deprecated public androidx.window.extensions.embedding.SplitPairRule.Builder setLayoutDirection(int);
method public androidx.window.extensions.embedding.SplitPairRule.Builder setShouldClearTop(boolean);
method @Deprecated public androidx.window.extensions.embedding.SplitPairRule.Builder setShouldFinishPrimaryWithSecondary(boolean);
method @Deprecated public androidx.window.extensions.embedding.SplitPairRule.Builder setShouldFinishSecondaryWithPrimary(boolean);
- method public androidx.window.extensions.embedding.SplitPairRule.Builder setSplitRatio(float);
+ method @Deprecated public androidx.window.extensions.embedding.SplitPairRule.Builder setSplitRatio(@FloatRange(from=0.0, to=1.0) float);
+ method public androidx.window.extensions.embedding.SplitPairRule.Builder setTag(String);
}
public class SplitPlaceholderRule extends androidx.window.extensions.embedding.SplitRule {
@@ -80,19 +156,23 @@
}
public static final class SplitPlaceholderRule.Builder {
- ctor public SplitPlaceholderRule.Builder(android.content.Intent, java.util.function.Predicate<android.app.Activity!>, java.util.function.Predicate<android.content.Intent!>, java.util.function.Predicate<android.view.WindowMetrics!>);
+ ctor @Deprecated @RequiresApi(android.os.Build.VERSION_CODES.N) public SplitPlaceholderRule.Builder(android.content.Intent, java.util.function.Predicate<android.app.Activity!>, java.util.function.Predicate<android.content.Intent!>, java.util.function.Predicate<android.view.WindowMetrics!>);
+ ctor public SplitPlaceholderRule.Builder(android.content.Intent, androidx.window.extensions.core.util.function.Predicate<android.app.Activity!>, androidx.window.extensions.core.util.function.Predicate<android.content.Intent!>, androidx.window.extensions.core.util.function.Predicate<android.view.WindowMetrics!>);
method public androidx.window.extensions.embedding.SplitPlaceholderRule build();
+ method public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setDefaultSplitAttributes(androidx.window.extensions.embedding.SplitAttributes);
method public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setFinishPrimaryWithPlaceholder(int);
method @Deprecated public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setFinishPrimaryWithSecondary(int);
- method public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setLayoutDirection(int);
- method public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setSplitRatio(float);
+ method @Deprecated public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setLayoutDirection(int);
+ method @Deprecated public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setSplitRatio(@FloatRange(from=0.0, to=1.0) float);
method public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setSticky(boolean);
+ method public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setTag(String);
}
public abstract class SplitRule extends androidx.window.extensions.embedding.EmbeddingRule {
method @RequiresApi(api=android.os.Build.VERSION_CODES.N) public boolean checkParentMetrics(android.view.WindowMetrics);
- method public int getLayoutDirection();
- method public float getSplitRatio();
+ method public androidx.window.extensions.embedding.SplitAttributes getDefaultSplitAttributes();
+ method @Deprecated public int getLayoutDirection();
+ method @Deprecated public float getSplitRatio();
field public static final int FINISH_ADJACENT = 2; // 0x2
field public static final int FINISH_ALWAYS = 1; // 0x1
field public static final int FINISH_NEVER = 0; // 0x0
@@ -118,8 +198,11 @@
}
public interface WindowLayoutComponent {
- method public void addWindowLayoutInfoListener(android.app.Activity, java.util.function.Consumer<androidx.window.extensions.layout.WindowLayoutInfo!>);
- method public void removeWindowLayoutInfoListener(java.util.function.Consumer<androidx.window.extensions.layout.WindowLayoutInfo!>);
+ method @Deprecated public void addWindowLayoutInfoListener(android.app.Activity, java.util.function.Consumer<androidx.window.extensions.layout.WindowLayoutInfo!>);
+ method @Deprecated public default void addWindowLayoutInfoListener(@UiContext android.content.Context, java.util.function.Consumer<androidx.window.extensions.layout.WindowLayoutInfo!>);
+ method public default void addWindowLayoutInfoListener(@UiContext android.content.Context, androidx.window.extensions.core.util.function.Consumer<androidx.window.extensions.layout.WindowLayoutInfo!>);
+ method @Deprecated public void removeWindowLayoutInfoListener(java.util.function.Consumer<androidx.window.extensions.layout.WindowLayoutInfo!>);
+ method public default void removeWindowLayoutInfoListener(androidx.window.extensions.core.util.function.Consumer<androidx.window.extensions.layout.WindowLayoutInfo!>);
}
public class WindowLayoutInfo {
diff --git a/window/extensions/extensions/api/public_plus_experimental_current.txt b/window/extensions/extensions/api/public_plus_experimental_current.txt
index 8867f5f6c..ead684f 100644
--- a/window/extensions/extensions/api/public_plus_experimental_current.txt
+++ b/window/extensions/extensions/api/public_plus_experimental_current.txt
@@ -4,6 +4,7 @@
public interface WindowExtensions {
method public default androidx.window.extensions.embedding.ActivityEmbeddingComponent? getActivityEmbeddingComponent();
method public default int getVendorApiLevel();
+ method public default androidx.window.extensions.area.WindowAreaComponent? getWindowAreaComponent();
method public androidx.window.extensions.layout.WindowLayoutComponent? getWindowLayoutComponent();
}
@@ -13,13 +14,32 @@
}
+package androidx.window.extensions.area {
+
+ public interface WindowAreaComponent {
+ method public void addRearDisplayStatusListener(java.util.function.Consumer<java.lang.Integer!>);
+ method public void endRearDisplaySession();
+ method public void removeRearDisplayStatusListener(java.util.function.Consumer<java.lang.Integer!>);
+ method public void startRearDisplaySession(android.app.Activity, java.util.function.Consumer<java.lang.Integer!>);
+ field public static final int SESSION_STATE_ACTIVE = 1; // 0x1
+ field public static final int SESSION_STATE_INACTIVE = 0; // 0x0
+ field public static final int STATUS_AVAILABLE = 2; // 0x2
+ field public static final int STATUS_UNAVAILABLE = 1; // 0x1
+ field public static final int STATUS_UNSUPPORTED = 0; // 0x0
+ }
+
+}
+
package androidx.window.extensions.embedding {
public interface ActivityEmbeddingComponent {
+ method public void clearSplitAttributesCalculator();
method public void clearSplitInfoCallback();
method public boolean isActivityEmbedded(android.app.Activity);
method public void setEmbeddingRules(java.util.Set<androidx.window.extensions.embedding.EmbeddingRule!>);
- method public void setSplitInfoCallback(java.util.function.Consumer<java.util.List<androidx.window.extensions.embedding.SplitInfo!>!>);
+ method public void setSplitAttributesCalculator(androidx.window.extensions.core.util.function.Function<androidx.window.extensions.embedding.SplitAttributesCalculatorParams!,androidx.window.extensions.embedding.SplitAttributes!>);
+ method @Deprecated public void setSplitInfoCallback(java.util.function.Consumer<java.util.List<androidx.window.extensions.embedding.SplitInfo!>!>);
+ method public default void setSplitInfoCallback(androidx.window.extensions.core.util.function.Consumer<java.util.List<androidx.window.extensions.embedding.SplitInfo!>!>);
}
public class ActivityRule extends androidx.window.extensions.embedding.EmbeddingRule {
@@ -29,9 +49,11 @@
}
public static final class ActivityRule.Builder {
- ctor public ActivityRule.Builder(java.util.function.Predicate<android.app.Activity!>, java.util.function.Predicate<android.content.Intent!>);
+ ctor @Deprecated @RequiresApi(android.os.Build.VERSION_CODES.N) public ActivityRule.Builder(java.util.function.Predicate<android.app.Activity!>, java.util.function.Predicate<android.content.Intent!>);
+ ctor public ActivityRule.Builder(androidx.window.extensions.core.util.function.Predicate<android.app.Activity!>, androidx.window.extensions.core.util.function.Predicate<android.content.Intent!>);
method public androidx.window.extensions.embedding.ActivityRule build();
method public androidx.window.extensions.embedding.ActivityRule.Builder setShouldAlwaysExpand(boolean);
+ method public androidx.window.extensions.embedding.ActivityRule.Builder setTag(String);
}
public class ActivityStack {
@@ -41,13 +63,64 @@
}
public abstract class EmbeddingRule {
+ method public String? getTag();
+ }
+
+ public class SplitAttributes {
+ method @ColorInt public int getAnimationBackgroundColor();
+ method public int getLayoutDirection();
+ method public androidx.window.extensions.embedding.SplitAttributes.SplitType getSplitType();
+ }
+
+ public static final class SplitAttributes.Builder {
+ ctor public SplitAttributes.Builder();
+ method public androidx.window.extensions.embedding.SplitAttributes build();
+ method public androidx.window.extensions.embedding.SplitAttributes.Builder setAnimationBackgroundColor(@ColorInt int);
+ method public androidx.window.extensions.embedding.SplitAttributes.Builder setLayoutDirection(int);
+ method public androidx.window.extensions.embedding.SplitAttributes.Builder setSplitType(androidx.window.extensions.embedding.SplitAttributes.SplitType);
+ }
+
+ public static final class SplitAttributes.LayoutDirection {
+ field public static final int BOTTOM_TO_TOP = 5; // 0x5
+ field public static final int LEFT_TO_RIGHT = 0; // 0x0
+ field public static final int LOCALE = 3; // 0x3
+ field public static final int RIGHT_TO_LEFT = 1; // 0x1
+ field public static final int TOP_TO_BOTTOM = 4; // 0x4
+ }
+
+ public static class SplitAttributes.SplitType {
+ }
+
+ public static final class SplitAttributes.SplitType.ExpandContainersSplitType extends androidx.window.extensions.embedding.SplitAttributes.SplitType {
+ ctor public SplitAttributes.SplitType.ExpandContainersSplitType();
+ }
+
+ public static final class SplitAttributes.SplitType.HingeSplitType extends androidx.window.extensions.embedding.SplitAttributes.SplitType {
+ ctor public SplitAttributes.SplitType.HingeSplitType(androidx.window.extensions.embedding.SplitAttributes.SplitType);
+ method public androidx.window.extensions.embedding.SplitAttributes.SplitType getFallbackSplitType();
+ }
+
+ public static final class SplitAttributes.SplitType.RatioSplitType extends androidx.window.extensions.embedding.SplitAttributes.SplitType {
+ ctor public SplitAttributes.SplitType.RatioSplitType(@FloatRange(from=0.0, to=1.0, fromInclusive=false, toInclusive=false) float);
+ method @FloatRange(from=0.0, to=1.0, fromInclusive=false, toInclusive=false) public float getRatio();
+ method public static androidx.window.extensions.embedding.SplitAttributes.SplitType.RatioSplitType splitEqually();
+ }
+
+ public class SplitAttributesCalculatorParams {
+ method public boolean areDefaultConstraintsSatisfied();
+ method public androidx.window.extensions.embedding.SplitAttributes getDefaultSplitAttributes();
+ method public android.content.res.Configuration getParentConfiguration();
+ method public androidx.window.extensions.layout.WindowLayoutInfo getParentWindowLayoutInfo();
+ method public android.view.WindowMetrics getParentWindowMetrics();
+ method public String? getSplitRuleTag();
}
public class SplitInfo {
- ctor public SplitInfo(androidx.window.extensions.embedding.ActivityStack, androidx.window.extensions.embedding.ActivityStack, float);
+ ctor public SplitInfo(androidx.window.extensions.embedding.ActivityStack, androidx.window.extensions.embedding.ActivityStack, androidx.window.extensions.embedding.SplitAttributes);
method public androidx.window.extensions.embedding.ActivityStack getPrimaryActivityStack();
method public androidx.window.extensions.embedding.ActivityStack getSecondaryActivityStack();
- method public float getSplitRatio();
+ method public androidx.window.extensions.embedding.SplitAttributes getSplitAttributes();
+ method @Deprecated public float getSplitRatio();
}
public class SplitPairRule extends androidx.window.extensions.embedding.SplitRule {
@@ -59,15 +132,18 @@
}
public static final class SplitPairRule.Builder {
- ctor public SplitPairRule.Builder(java.util.function.Predicate<android.util.Pair<android.app.Activity!,android.app.Activity!>!>, java.util.function.Predicate<android.util.Pair<android.app.Activity!,android.content.Intent!>!>, java.util.function.Predicate<android.view.WindowMetrics!>);
+ ctor @Deprecated @RequiresApi(android.os.Build.VERSION_CODES.N) public SplitPairRule.Builder(java.util.function.Predicate<android.util.Pair<android.app.Activity!,android.app.Activity!>!>, java.util.function.Predicate<android.util.Pair<android.app.Activity!,android.content.Intent!>!>, java.util.function.Predicate<android.view.WindowMetrics!>);
+ ctor public SplitPairRule.Builder(androidx.window.extensions.core.util.function.Predicate<android.util.Pair<android.app.Activity!,android.app.Activity!>!>, androidx.window.extensions.core.util.function.Predicate<android.util.Pair<android.app.Activity!,android.content.Intent!>!>, androidx.window.extensions.core.util.function.Predicate<android.view.WindowMetrics!>);
method public androidx.window.extensions.embedding.SplitPairRule build();
+ method public androidx.window.extensions.embedding.SplitPairRule.Builder setDefaultSplitAttributes(androidx.window.extensions.embedding.SplitAttributes);
method public androidx.window.extensions.embedding.SplitPairRule.Builder setFinishPrimaryWithSecondary(int);
method public androidx.window.extensions.embedding.SplitPairRule.Builder setFinishSecondaryWithPrimary(int);
- method public androidx.window.extensions.embedding.SplitPairRule.Builder setLayoutDirection(int);
+ method @Deprecated public androidx.window.extensions.embedding.SplitPairRule.Builder setLayoutDirection(int);
method public androidx.window.extensions.embedding.SplitPairRule.Builder setShouldClearTop(boolean);
method @Deprecated public androidx.window.extensions.embedding.SplitPairRule.Builder setShouldFinishPrimaryWithSecondary(boolean);
method @Deprecated public androidx.window.extensions.embedding.SplitPairRule.Builder setShouldFinishSecondaryWithPrimary(boolean);
- method public androidx.window.extensions.embedding.SplitPairRule.Builder setSplitRatio(float);
+ method @Deprecated public androidx.window.extensions.embedding.SplitPairRule.Builder setSplitRatio(@FloatRange(from=0.0, to=1.0) float);
+ method public androidx.window.extensions.embedding.SplitPairRule.Builder setTag(String);
}
public class SplitPlaceholderRule extends androidx.window.extensions.embedding.SplitRule {
@@ -80,19 +156,23 @@
}
public static final class SplitPlaceholderRule.Builder {
- ctor public SplitPlaceholderRule.Builder(android.content.Intent, java.util.function.Predicate<android.app.Activity!>, java.util.function.Predicate<android.content.Intent!>, java.util.function.Predicate<android.view.WindowMetrics!>);
+ ctor @Deprecated @RequiresApi(android.os.Build.VERSION_CODES.N) public SplitPlaceholderRule.Builder(android.content.Intent, java.util.function.Predicate<android.app.Activity!>, java.util.function.Predicate<android.content.Intent!>, java.util.function.Predicate<android.view.WindowMetrics!>);
+ ctor public SplitPlaceholderRule.Builder(android.content.Intent, androidx.window.extensions.core.util.function.Predicate<android.app.Activity!>, androidx.window.extensions.core.util.function.Predicate<android.content.Intent!>, androidx.window.extensions.core.util.function.Predicate<android.view.WindowMetrics!>);
method public androidx.window.extensions.embedding.SplitPlaceholderRule build();
+ method public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setDefaultSplitAttributes(androidx.window.extensions.embedding.SplitAttributes);
method public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setFinishPrimaryWithPlaceholder(int);
method @Deprecated public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setFinishPrimaryWithSecondary(int);
- method public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setLayoutDirection(int);
- method public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setSplitRatio(float);
+ method @Deprecated public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setLayoutDirection(int);
+ method @Deprecated public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setSplitRatio(@FloatRange(from=0.0, to=1.0) float);
method public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setSticky(boolean);
+ method public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setTag(String);
}
public abstract class SplitRule extends androidx.window.extensions.embedding.EmbeddingRule {
method @RequiresApi(api=android.os.Build.VERSION_CODES.N) public boolean checkParentMetrics(android.view.WindowMetrics);
- method public int getLayoutDirection();
- method public float getSplitRatio();
+ method public androidx.window.extensions.embedding.SplitAttributes getDefaultSplitAttributes();
+ method @Deprecated public int getLayoutDirection();
+ method @Deprecated public float getSplitRatio();
field public static final int FINISH_ADJACENT = 2; // 0x2
field public static final int FINISH_ALWAYS = 1; // 0x1
field public static final int FINISH_NEVER = 0; // 0x0
@@ -118,8 +198,11 @@
}
public interface WindowLayoutComponent {
- method public void addWindowLayoutInfoListener(android.app.Activity, java.util.function.Consumer<androidx.window.extensions.layout.WindowLayoutInfo!>);
- method public void removeWindowLayoutInfoListener(java.util.function.Consumer<androidx.window.extensions.layout.WindowLayoutInfo!>);
+ method @Deprecated public void addWindowLayoutInfoListener(android.app.Activity, java.util.function.Consumer<androidx.window.extensions.layout.WindowLayoutInfo!>);
+ method @Deprecated public default void addWindowLayoutInfoListener(@UiContext android.content.Context, java.util.function.Consumer<androidx.window.extensions.layout.WindowLayoutInfo!>);
+ method public default void addWindowLayoutInfoListener(@UiContext android.content.Context, androidx.window.extensions.core.util.function.Consumer<androidx.window.extensions.layout.WindowLayoutInfo!>);
+ method @Deprecated public void removeWindowLayoutInfoListener(java.util.function.Consumer<androidx.window.extensions.layout.WindowLayoutInfo!>);
+ method public default void removeWindowLayoutInfoListener(androidx.window.extensions.core.util.function.Consumer<androidx.window.extensions.layout.WindowLayoutInfo!>);
}
public class WindowLayoutInfo {
diff --git a/window/extensions/extensions/api/restricted_current.txt b/window/extensions/extensions/api/restricted_current.txt
index 8867f5f6c..ead684f 100644
--- a/window/extensions/extensions/api/restricted_current.txt
+++ b/window/extensions/extensions/api/restricted_current.txt
@@ -4,6 +4,7 @@
public interface WindowExtensions {
method public default androidx.window.extensions.embedding.ActivityEmbeddingComponent? getActivityEmbeddingComponent();
method public default int getVendorApiLevel();
+ method public default androidx.window.extensions.area.WindowAreaComponent? getWindowAreaComponent();
method public androidx.window.extensions.layout.WindowLayoutComponent? getWindowLayoutComponent();
}
@@ -13,13 +14,32 @@
}
+package androidx.window.extensions.area {
+
+ public interface WindowAreaComponent {
+ method public void addRearDisplayStatusListener(java.util.function.Consumer<java.lang.Integer!>);
+ method public void endRearDisplaySession();
+ method public void removeRearDisplayStatusListener(java.util.function.Consumer<java.lang.Integer!>);
+ method public void startRearDisplaySession(android.app.Activity, java.util.function.Consumer<java.lang.Integer!>);
+ field public static final int SESSION_STATE_ACTIVE = 1; // 0x1
+ field public static final int SESSION_STATE_INACTIVE = 0; // 0x0
+ field public static final int STATUS_AVAILABLE = 2; // 0x2
+ field public static final int STATUS_UNAVAILABLE = 1; // 0x1
+ field public static final int STATUS_UNSUPPORTED = 0; // 0x0
+ }
+
+}
+
package androidx.window.extensions.embedding {
public interface ActivityEmbeddingComponent {
+ method public void clearSplitAttributesCalculator();
method public void clearSplitInfoCallback();
method public boolean isActivityEmbedded(android.app.Activity);
method public void setEmbeddingRules(java.util.Set<androidx.window.extensions.embedding.EmbeddingRule!>);
- method public void setSplitInfoCallback(java.util.function.Consumer<java.util.List<androidx.window.extensions.embedding.SplitInfo!>!>);
+ method public void setSplitAttributesCalculator(androidx.window.extensions.core.util.function.Function<androidx.window.extensions.embedding.SplitAttributesCalculatorParams!,androidx.window.extensions.embedding.SplitAttributes!>);
+ method @Deprecated public void setSplitInfoCallback(java.util.function.Consumer<java.util.List<androidx.window.extensions.embedding.SplitInfo!>!>);
+ method public default void setSplitInfoCallback(androidx.window.extensions.core.util.function.Consumer<java.util.List<androidx.window.extensions.embedding.SplitInfo!>!>);
}
public class ActivityRule extends androidx.window.extensions.embedding.EmbeddingRule {
@@ -29,9 +49,11 @@
}
public static final class ActivityRule.Builder {
- ctor public ActivityRule.Builder(java.util.function.Predicate<android.app.Activity!>, java.util.function.Predicate<android.content.Intent!>);
+ ctor @Deprecated @RequiresApi(android.os.Build.VERSION_CODES.N) public ActivityRule.Builder(java.util.function.Predicate<android.app.Activity!>, java.util.function.Predicate<android.content.Intent!>);
+ ctor public ActivityRule.Builder(androidx.window.extensions.core.util.function.Predicate<android.app.Activity!>, androidx.window.extensions.core.util.function.Predicate<android.content.Intent!>);
method public androidx.window.extensions.embedding.ActivityRule build();
method public androidx.window.extensions.embedding.ActivityRule.Builder setShouldAlwaysExpand(boolean);
+ method public androidx.window.extensions.embedding.ActivityRule.Builder setTag(String);
}
public class ActivityStack {
@@ -41,13 +63,64 @@
}
public abstract class EmbeddingRule {
+ method public String? getTag();
+ }
+
+ public class SplitAttributes {
+ method @ColorInt public int getAnimationBackgroundColor();
+ method public int getLayoutDirection();
+ method public androidx.window.extensions.embedding.SplitAttributes.SplitType getSplitType();
+ }
+
+ public static final class SplitAttributes.Builder {
+ ctor public SplitAttributes.Builder();
+ method public androidx.window.extensions.embedding.SplitAttributes build();
+ method public androidx.window.extensions.embedding.SplitAttributes.Builder setAnimationBackgroundColor(@ColorInt int);
+ method public androidx.window.extensions.embedding.SplitAttributes.Builder setLayoutDirection(int);
+ method public androidx.window.extensions.embedding.SplitAttributes.Builder setSplitType(androidx.window.extensions.embedding.SplitAttributes.SplitType);
+ }
+
+ public static final class SplitAttributes.LayoutDirection {
+ field public static final int BOTTOM_TO_TOP = 5; // 0x5
+ field public static final int LEFT_TO_RIGHT = 0; // 0x0
+ field public static final int LOCALE = 3; // 0x3
+ field public static final int RIGHT_TO_LEFT = 1; // 0x1
+ field public static final int TOP_TO_BOTTOM = 4; // 0x4
+ }
+
+ public static class SplitAttributes.SplitType {
+ }
+
+ public static final class SplitAttributes.SplitType.ExpandContainersSplitType extends androidx.window.extensions.embedding.SplitAttributes.SplitType {
+ ctor public SplitAttributes.SplitType.ExpandContainersSplitType();
+ }
+
+ public static final class SplitAttributes.SplitType.HingeSplitType extends androidx.window.extensions.embedding.SplitAttributes.SplitType {
+ ctor public SplitAttributes.SplitType.HingeSplitType(androidx.window.extensions.embedding.SplitAttributes.SplitType);
+ method public androidx.window.extensions.embedding.SplitAttributes.SplitType getFallbackSplitType();
+ }
+
+ public static final class SplitAttributes.SplitType.RatioSplitType extends androidx.window.extensions.embedding.SplitAttributes.SplitType {
+ ctor public SplitAttributes.SplitType.RatioSplitType(@FloatRange(from=0.0, to=1.0, fromInclusive=false, toInclusive=false) float);
+ method @FloatRange(from=0.0, to=1.0, fromInclusive=false, toInclusive=false) public float getRatio();
+ method public static androidx.window.extensions.embedding.SplitAttributes.SplitType.RatioSplitType splitEqually();
+ }
+
+ public class SplitAttributesCalculatorParams {
+ method public boolean areDefaultConstraintsSatisfied();
+ method public androidx.window.extensions.embedding.SplitAttributes getDefaultSplitAttributes();
+ method public android.content.res.Configuration getParentConfiguration();
+ method public androidx.window.extensions.layout.WindowLayoutInfo getParentWindowLayoutInfo();
+ method public android.view.WindowMetrics getParentWindowMetrics();
+ method public String? getSplitRuleTag();
}
public class SplitInfo {
- ctor public SplitInfo(androidx.window.extensions.embedding.ActivityStack, androidx.window.extensions.embedding.ActivityStack, float);
+ ctor public SplitInfo(androidx.window.extensions.embedding.ActivityStack, androidx.window.extensions.embedding.ActivityStack, androidx.window.extensions.embedding.SplitAttributes);
method public androidx.window.extensions.embedding.ActivityStack getPrimaryActivityStack();
method public androidx.window.extensions.embedding.ActivityStack getSecondaryActivityStack();
- method public float getSplitRatio();
+ method public androidx.window.extensions.embedding.SplitAttributes getSplitAttributes();
+ method @Deprecated public float getSplitRatio();
}
public class SplitPairRule extends androidx.window.extensions.embedding.SplitRule {
@@ -59,15 +132,18 @@
}
public static final class SplitPairRule.Builder {
- ctor public SplitPairRule.Builder(java.util.function.Predicate<android.util.Pair<android.app.Activity!,android.app.Activity!>!>, java.util.function.Predicate<android.util.Pair<android.app.Activity!,android.content.Intent!>!>, java.util.function.Predicate<android.view.WindowMetrics!>);
+ ctor @Deprecated @RequiresApi(android.os.Build.VERSION_CODES.N) public SplitPairRule.Builder(java.util.function.Predicate<android.util.Pair<android.app.Activity!,android.app.Activity!>!>, java.util.function.Predicate<android.util.Pair<android.app.Activity!,android.content.Intent!>!>, java.util.function.Predicate<android.view.WindowMetrics!>);
+ ctor public SplitPairRule.Builder(androidx.window.extensions.core.util.function.Predicate<android.util.Pair<android.app.Activity!,android.app.Activity!>!>, androidx.window.extensions.core.util.function.Predicate<android.util.Pair<android.app.Activity!,android.content.Intent!>!>, androidx.window.extensions.core.util.function.Predicate<android.view.WindowMetrics!>);
method public androidx.window.extensions.embedding.SplitPairRule build();
+ method public androidx.window.extensions.embedding.SplitPairRule.Builder setDefaultSplitAttributes(androidx.window.extensions.embedding.SplitAttributes);
method public androidx.window.extensions.embedding.SplitPairRule.Builder setFinishPrimaryWithSecondary(int);
method public androidx.window.extensions.embedding.SplitPairRule.Builder setFinishSecondaryWithPrimary(int);
- method public androidx.window.extensions.embedding.SplitPairRule.Builder setLayoutDirection(int);
+ method @Deprecated public androidx.window.extensions.embedding.SplitPairRule.Builder setLayoutDirection(int);
method public androidx.window.extensions.embedding.SplitPairRule.Builder setShouldClearTop(boolean);
method @Deprecated public androidx.window.extensions.embedding.SplitPairRule.Builder setShouldFinishPrimaryWithSecondary(boolean);
method @Deprecated public androidx.window.extensions.embedding.SplitPairRule.Builder setShouldFinishSecondaryWithPrimary(boolean);
- method public androidx.window.extensions.embedding.SplitPairRule.Builder setSplitRatio(float);
+ method @Deprecated public androidx.window.extensions.embedding.SplitPairRule.Builder setSplitRatio(@FloatRange(from=0.0, to=1.0) float);
+ method public androidx.window.extensions.embedding.SplitPairRule.Builder setTag(String);
}
public class SplitPlaceholderRule extends androidx.window.extensions.embedding.SplitRule {
@@ -80,19 +156,23 @@
}
public static final class SplitPlaceholderRule.Builder {
- ctor public SplitPlaceholderRule.Builder(android.content.Intent, java.util.function.Predicate<android.app.Activity!>, java.util.function.Predicate<android.content.Intent!>, java.util.function.Predicate<android.view.WindowMetrics!>);
+ ctor @Deprecated @RequiresApi(android.os.Build.VERSION_CODES.N) public SplitPlaceholderRule.Builder(android.content.Intent, java.util.function.Predicate<android.app.Activity!>, java.util.function.Predicate<android.content.Intent!>, java.util.function.Predicate<android.view.WindowMetrics!>);
+ ctor public SplitPlaceholderRule.Builder(android.content.Intent, androidx.window.extensions.core.util.function.Predicate<android.app.Activity!>, androidx.window.extensions.core.util.function.Predicate<android.content.Intent!>, androidx.window.extensions.core.util.function.Predicate<android.view.WindowMetrics!>);
method public androidx.window.extensions.embedding.SplitPlaceholderRule build();
+ method public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setDefaultSplitAttributes(androidx.window.extensions.embedding.SplitAttributes);
method public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setFinishPrimaryWithPlaceholder(int);
method @Deprecated public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setFinishPrimaryWithSecondary(int);
- method public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setLayoutDirection(int);
- method public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setSplitRatio(float);
+ method @Deprecated public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setLayoutDirection(int);
+ method @Deprecated public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setSplitRatio(@FloatRange(from=0.0, to=1.0) float);
method public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setSticky(boolean);
+ method public androidx.window.extensions.embedding.SplitPlaceholderRule.Builder setTag(String);
}
public abstract class SplitRule extends androidx.window.extensions.embedding.EmbeddingRule {
method @RequiresApi(api=android.os.Build.VERSION_CODES.N) public boolean checkParentMetrics(android.view.WindowMetrics);
- method public int getLayoutDirection();
- method public float getSplitRatio();
+ method public androidx.window.extensions.embedding.SplitAttributes getDefaultSplitAttributes();
+ method @Deprecated public int getLayoutDirection();
+ method @Deprecated public float getSplitRatio();
field public static final int FINISH_ADJACENT = 2; // 0x2
field public static final int FINISH_ALWAYS = 1; // 0x1
field public static final int FINISH_NEVER = 0; // 0x0
@@ -118,8 +198,11 @@
}
public interface WindowLayoutComponent {
- method public void addWindowLayoutInfoListener(android.app.Activity, java.util.function.Consumer<androidx.window.extensions.layout.WindowLayoutInfo!>);
- method public void removeWindowLayoutInfoListener(java.util.function.Consumer<androidx.window.extensions.layout.WindowLayoutInfo!>);
+ method @Deprecated public void addWindowLayoutInfoListener(android.app.Activity, java.util.function.Consumer<androidx.window.extensions.layout.WindowLayoutInfo!>);
+ method @Deprecated public default void addWindowLayoutInfoListener(@UiContext android.content.Context, java.util.function.Consumer<androidx.window.extensions.layout.WindowLayoutInfo!>);
+ method public default void addWindowLayoutInfoListener(@UiContext android.content.Context, androidx.window.extensions.core.util.function.Consumer<androidx.window.extensions.layout.WindowLayoutInfo!>);
+ method @Deprecated public void removeWindowLayoutInfoListener(java.util.function.Consumer<androidx.window.extensions.layout.WindowLayoutInfo!>);
+ method public default void removeWindowLayoutInfoListener(androidx.window.extensions.core.util.function.Consumer<androidx.window.extensions.layout.WindowLayoutInfo!>);
}
public class WindowLayoutInfo {
diff --git a/window/extensions/extensions/build.gradle b/window/extensions/extensions/build.gradle
index f9deca6..9db659b 100644
--- a/window/extensions/extensions/build.gradle
+++ b/window/extensions/extensions/build.gradle
@@ -24,8 +24,13 @@
dependencies {
api(libs.kotlinStdlib)
- implementation("androidx.annotation:annotation:1.1.0")
+ implementation("androidx.annotation:annotation:1.3.0")
implementation("androidx.annotation:annotation-experimental:1.1.0")
+ implementation("androidx.window.extensions.core:core:1.0.0-alpha01")
+
+ testImplementation(libs.testExtJunit)
+ testImplementation(libs.testRunner)
+ testImplementation(libs.testRules)
androidTestImplementation(libs.testExtJunit)
androidTestImplementation(libs.testRunner)
diff --git a/window/extensions/extensions/src/main/java/androidx/window/extensions/WindowExtensions.java b/window/extensions/extensions/src/main/java/androidx/window/extensions/WindowExtensions.java
index c1a9bd8..df1fa32 100644
--- a/window/extensions/extensions/src/main/java/androidx/window/extensions/WindowExtensions.java
+++ b/window/extensions/extensions/src/main/java/androidx/window/extensions/WindowExtensions.java
@@ -16,8 +16,13 @@
package androidx.window.extensions;
+import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP;
+
import androidx.annotation.Nullable;
+import androidx.annotation.RestrictTo;
+import androidx.window.extensions.area.WindowAreaComponent;
import androidx.window.extensions.embedding.ActivityEmbeddingComponent;
+import androidx.window.extensions.embedding.SplitPlaceholderRule;
import androidx.window.extensions.layout.WindowLayoutComponent;
/**
@@ -29,6 +34,54 @@
* {@link WindowExtensions#getVendorApiLevel()}.
*/
public interface WindowExtensions {
+ // TODO(b/241323716) Removed after we have annotation to check API level
+ /**
+ * An invalid {@link #getVendorApiLevel vendor API level}
+ * @hide
+ */
+ @RestrictTo(LIBRARY_GROUP)
+ int INVALID_VENDOR_API_LEVEL = -1;
+
+ // TODO(b/241323716) Removed after we have annotation to check API level
+ /**
+ * A vendor API level constant. It helps to unify the format of documenting {@code @since}
+ * block.
+ * <p>
+ * The added APIs for Vendor API level 1 are:
+ * <ul>
+ * <li>{@link androidx.window.extensions.embedding.ActivityRule} APIs</li>
+ * <li>{@link androidx.window.extensions.embedding.SplitPairRule} APIs</li>
+ * <li>{@link androidx.window.extensions.embedding.SplitPlaceholderRule} APIs</li>
+ * <li>{@link androidx.window.extensions.embedding.SplitInfo} APIs</li>
+ * <li>{@link androidx.window.extensions.layout.DisplayFeature} APIs</li>
+ * <li>{@link androidx.window.extensions.layout.FoldingFeature} APIs</li>
+ * <li>{@link androidx.window.extensions.layout.WindowLayoutInfo} APIs</li>
+ * <li>{@link androidx.window.extensions.layout.WindowLayoutComponent} APIs</li>
+ * <li>{@link androidx.window.extensions.area.WindowAreaComponent} APIs</li>
+ * </ul>
+ * </p>
+ * @hide
+ */
+ @RestrictTo(LIBRARY_GROUP)
+ int VENDOR_API_LEVEL_1 = 1;
+ // TODO(b/241323716) Removed after we have annotation to check API level
+ /**
+ * A vendor API level constant. It helps to unify the format of documenting {@code @since}
+ * block.
+ * <p>
+ * The added APIs for Vendor API level 2 are:
+ * <ul>
+ * <li>{@link SplitPlaceholderRule.Builder#setFinishPrimaryWithPlaceholder(int)}</li>
+ * <li>{@link androidx.window.extensions.embedding.SplitAttributes} APIs</li>
+ * <li>{@link ActivityEmbeddingComponent#setSplitAttributesCalculator(
+ * androidx.window.extensions.core.util.function.Function)}</li>
+ * </ul>
+ * </p>
+ * @hide
+ */
+ @RestrictTo(LIBRARY_GROUP)
+ int VENDOR_API_LEVEL_2 = 2;
+
/**
* Returns the API level of the vendor library on the device. If the returned version is not
* supported by the WindowManager library, then some functions may not be available or replaced
@@ -39,7 +92,7 @@
* @return the API level supported by the library.
*/
default int getVendorApiLevel() {
- return 1;
+ throw new RuntimeException("Not implemented. Must override in a subclass.");
}
/**
@@ -61,4 +114,15 @@
default ActivityEmbeddingComponent getActivityEmbeddingComponent() {
return null;
}
+
+ /**
+ * Returns the OEM implementation of {@link WindowAreaComponent} if it is supported on
+ * the device, {@code null} otherwise. The implementation must match the API level reported in
+ * {@link WindowExtensions}.
+ * @return the OEM implementation of {@link WindowAreaComponent}
+ */
+ @Nullable
+ default WindowAreaComponent getWindowAreaComponent() {
+ return null;
+ }
}
diff --git a/window/extensions/extensions/src/main/java/androidx/window/extensions/area/WindowAreaComponent.java b/window/extensions/extensions/src/main/java/androidx/window/extensions/area/WindowAreaComponent.java
new file mode 100644
index 0000000..afd3e36
--- /dev/null
+++ b/window/extensions/extensions/src/main/java/androidx/window/extensions/area/WindowAreaComponent.java
@@ -0,0 +1,149 @@
+/*
+ * Copyright 2021 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 androidx.window.extensions.area;
+
+import android.app.Activity;
+
+import androidx.annotation.IntDef;
+import androidx.annotation.NonNull;
+import androidx.annotation.RestrictTo;
+import androidx.window.extensions.WindowExtensions;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.util.function.Consumer;
+
+/**
+ * The interface definition that will be used by the WindowManager library to get custom
+ * OEM-provided behavior around moving windows between displays or display areas on a device.
+ *
+ * Currently the only behavior supported is RearDisplay Mode, where the window
+ * is moved to the display that faces the same direction as the rear camera.
+ *
+ * <p>This interface should be implemented by OEM and deployed to the target devices.
+ * @see WindowExtensions#getWindowLayoutComponent()
+ */
+public interface WindowAreaComponent {
+
+ /**
+ * WindowArea status constant to signify that the feature is
+ * unsupported on this device. Could be due to the device not supporting that
+ * specific feature.
+ */
+ int STATUS_UNSUPPORTED = 0;
+
+ /**
+ * WindowArea status constant to signify that the feature is
+ * currently unavailable but is supported on this device. This value could signify
+ * that the current device state does not support the specific feature or another
+ * process is currently enabled in that feature.
+ */
+ int STATUS_UNAVAILABLE = 1;
+
+ /**
+ * WindowArea status constant to signify that the feature is
+ * available to be entered or enabled.
+ */
+ int STATUS_AVAILABLE = 2;
+
+ /** @hide */
+ @RestrictTo(RestrictTo.Scope.LIBRARY)
+ @Retention(RetentionPolicy.SOURCE)
+ @Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE})
+ @IntDef({
+ STATUS_UNSUPPORTED,
+ STATUS_UNAVAILABLE,
+ STATUS_AVAILABLE
+ })
+ @interface WindowAreaStatus {}
+
+ /**
+ * Session state constant to represent there being no active session
+ * currently in progress. Used by the library to call the correct callbacks if
+ * a session is ended.
+ */
+ int SESSION_STATE_INACTIVE = 0;
+
+ /**
+ * Session state constant to represent that there is an
+ * active session currently in progress. Used by the library to
+ * know when to return the session object to the developer when the
+ * session is created and active.
+ */
+ int SESSION_STATE_ACTIVE = 1;
+
+ /** @hide */
+ @RestrictTo(RestrictTo.Scope.LIBRARY)
+ @Retention(RetentionPolicy.SOURCE)
+ @Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE})
+ @IntDef({
+ SESSION_STATE_ACTIVE,
+ SESSION_STATE_INACTIVE
+ })
+ @interface WindowAreaSessionState {}
+
+ /**
+ * Adds a listener interested in receiving updates on the RearDisplayStatus
+ * of the device. Because this is being called from the OEM provided
+ * extensions, the library will post the result of the listener on the executor
+ * provided by the developer.
+ *
+ * The listener provided will receive values that
+ * correspond to the [WindowAreaStatus] value that aligns with the current status
+ * of the rear display.
+ * @param consumer interested in receiving updates to WindowAreaStatus.
+ */
+ void addRearDisplayStatusListener(@NonNull Consumer<Integer> consumer);
+
+ /**
+ * Removes a listener no longer interested in receiving updates.
+ * @param consumer no longer interested in receiving updates to WindowAreaStatus
+ */
+ void removeRearDisplayStatusListener(@NonNull Consumer<Integer> consumer);
+
+
+ /**
+ * Creates and starts a rear display session and sends state updates to the
+ * consumer provided. This consumer will receive a constant represented by
+ * [WindowAreaSessionState] to represent the state of the current rear display
+ * session. We will translate to a more friendly interface in the library.
+ *
+ * Because this is being called from the OEM provided extensions, the library
+ * will post the result of the listener on the executor provided by the developer.
+ *
+ * @param activity to allow that the OEM implementation will use as a base
+ * context and to identify the source display area of the request.
+ * The reference to the activity instance must not be stored in the OEM
+ * implementation to prevent memory leaks.
+ * @param consumer to provide updates to the client on the status of the session
+ * @throws UnsupportedOperationException if this method is called when RearDisplay
+ * mode is not available. This could be to an incompatible device state or when
+ * another process is currently in this mode.
+ */
+ @SuppressWarnings("ExecutorRegistration") // Jetpack will post it on the app-provided executor.
+ void startRearDisplaySession(@NonNull Activity activity,
+ @NonNull Consumer<Integer> consumer);
+
+ /**
+ * Ends a RearDisplaySession and sends [STATE_INACTIVE] to the consumer
+ * provided in the {@code startRearDisplaySession} method. This method is only
+ * called through the {@code RearDisplaySession} provided to the developer.
+ */
+ void endRearDisplaySession();
+}
diff --git a/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/ActivityEmbeddingComponent.java b/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/ActivityEmbeddingComponent.java
index 16caa61..9e5ef39 100644
--- a/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/ActivityEmbeddingComponent.java
+++ b/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/ActivityEmbeddingComponent.java
@@ -17,13 +17,15 @@
package androidx.window.extensions.embedding;
import android.app.Activity;
+import android.view.WindowMetrics;
import androidx.annotation.NonNull;
import androidx.window.extensions.WindowExtensions;
+import androidx.window.extensions.core.util.function.Consumer;
+import androidx.window.extensions.core.util.function.Function;
import java.util.List;
import java.util.Set;
-import java.util.function.Consumer;
/**
* Extension component definition that is used by the WindowManager library to trigger custom
@@ -40,13 +42,29 @@
void setEmbeddingRules(@NonNull Set<EmbeddingRule> splitRules);
/**
+ * @deprecated Use {@link #setSplitInfoCallback(Consumer)} starting with
+ * {@link WindowExtensions#VENDOR_API_LEVEL_2}. Only used if
+ * {@link #setSplitInfoCallback(Consumer)} can't be called on
+ * {@link WindowExtensions#VENDOR_API_LEVEL_1}.
+ */
+ @Deprecated
+ @SuppressWarnings("ExecutorRegistration") // Jetpack will post it on the app-provided executor.
+ void setSplitInfoCallback(@NonNull java.util.function.Consumer<List<SplitInfo>> consumer);
+
+ /**
* Sets the callback that notifies WM Jetpack about changes in split states from the Extensions
* Sidecar implementation. The listener should be registered for the lifetime of the process.
* There are no threading guarantees where the events are dispatched from. All messages are
* re-posted to the executors provided by developers.
+ *
+ * @param consumer the callback to notify {@link SplitInfo} list changes
+ * @since {@link WindowExtensions#VENDOR_API_LEVEL_2}
*/
@SuppressWarnings("ExecutorRegistration") // Jetpack will post it on the app-provided executor.
- void setSplitInfoCallback(@NonNull Consumer<List<SplitInfo>> consumer);
+ default void setSplitInfoCallback(@NonNull Consumer<List<SplitInfo>> consumer) {
+ throw new UnsupportedOperationException("This method must not be called unless there is a"
+ + " corresponding override implementation on the device.");
+ }
/**
* Clears the callback that was set in
@@ -62,4 +80,27 @@
* occupies a portion of Task bounds.
*/
boolean isActivityEmbedded(@NonNull Activity activity);
+
+ /**
+ * Sets a callback to compute the {@link SplitAttributes} for the {@link SplitRule} and current
+ * window state provided in {@link SplitAttributesCalculatorParams}. This method can be used
+ * to dynamically configure the split layout properties when new activities are launched or
+ * window properties change. If set, {@link SplitRule#getDefaultSplitAttributes() the default
+ * split properties} and {@link SplitRule#checkParentMetrics(WindowMetrics) restrictions}
+ * will be ignored, and the callback will be invoked for every change.
+ *
+ * @param calculator the callback to set. It will replace the previously set callback if it
+ * exists.
+ * @since {@link androidx.window.extensions.WindowExtensions#VENDOR_API_LEVEL_2}
+ */
+ void setSplitAttributesCalculator(
+ @NonNull Function<SplitAttributesCalculatorParams, SplitAttributes> calculator);
+
+ /**
+ * Clears the previously callback set in {@link #setSplitAttributesCalculator(Function)}.
+ *
+ * @see #setSplitAttributesCalculator(Function)
+ * @since {@link androidx.window.extensions.WindowExtensions#VENDOR_API_LEVEL_2}
+ */
+ void clearSplitAttributesCalculator();
}
diff --git a/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/ActivityRule.java b/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/ActivityRule.java
index 2d1fc33..0ac32f7 100644
--- a/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/ActivityRule.java
+++ b/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/ActivityRule.java
@@ -22,9 +22,12 @@
import android.os.Build;
import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
+import androidx.window.extensions.WindowExtensions;
+import androidx.window.extensions.core.util.function.Predicate;
-import java.util.function.Predicate;
+import java.util.Objects;
/**
* Split configuration rule for individual activities.
@@ -37,7 +40,9 @@
private final boolean mShouldAlwaysExpand;
ActivityRule(@NonNull Predicate<Activity> activityPredicate,
- @NonNull Predicate<Intent> intentPredicate, boolean shouldAlwaysExpand) {
+ @NonNull Predicate<Intent> intentPredicate, boolean shouldAlwaysExpand,
+ @Nullable String tag) {
+ super(tag);
mActivityPredicate = activityPredicate;
mIntentPredicate = intentPredicate;
mShouldAlwaysExpand = shouldAlwaysExpand;
@@ -78,7 +83,32 @@
@NonNull
private final Predicate<Intent> mIntentPredicate;
private boolean mAlwaysExpand;
+ @Nullable
+ private String mTag;
+ /**
+ * @deprecated Use {@link #Builder(Predicate, Predicate)} starting with
+ * {@link WindowExtensions#VENDOR_API_LEVEL_2}. Only used if
+ * {@link #Builder(Predicate, Predicate)} can't be called on
+ * {@link WindowExtensions#VENDOR_API_LEVEL_1}.
+ */
+ @Deprecated
+ @RequiresApi(Build.VERSION_CODES.N)
+ public Builder(@NonNull java.util.function.Predicate<Activity> activityPredicate,
+ @NonNull java.util.function.Predicate<Intent> intentPredicate) {
+ mActivityPredicate = activityPredicate::test;
+ mIntentPredicate = intentPredicate::test;
+ }
+
+ /**
+ * The {@link ActivityRule} Builder constructor
+ *
+ * @param activityPredicate the {@link Predicate} to verify if a given {@link Activity}
+ * matches the rule
+ * @param intentPredicate the {@link Predicate} to verify if a given {@link Intent}
+ * matches the rule
+ * @since {@link WindowExtensions#VENDOR_API_LEVEL_2}
+ */
public Builder(@NonNull Predicate<Activity> activityPredicate,
@NonNull Predicate<Intent> intentPredicate) {
mActivityPredicate = activityPredicate;
@@ -92,10 +122,20 @@
return this;
}
+ /**
+ * @see ActivityRule#getTag()
+ * @since {@link androidx.window.extensions.WindowExtensions#VENDOR_API_LEVEL_2}
+ */
+ @NonNull
+ public Builder setTag(@NonNull String tag) {
+ mTag = Objects.requireNonNull(tag);
+ return this;
+ }
+
/** Builds a new instance of {@link ActivityRule}. */
@NonNull
public ActivityRule build() {
- return new ActivityRule(mActivityPredicate, mIntentPredicate, mAlwaysExpand);
+ return new ActivityRule(mActivityPredicate, mIntentPredicate, mAlwaysExpand, mTag);
}
}
@@ -104,14 +144,16 @@
if (this == o) return true;
if (!(o instanceof ActivityRule)) return false;
ActivityRule that = (ActivityRule) o;
- return mShouldAlwaysExpand == that.mShouldAlwaysExpand
+ return super.equals(o)
+ && mShouldAlwaysExpand == that.mShouldAlwaysExpand
&& mActivityPredicate.equals(that.mActivityPredicate)
&& mIntentPredicate.equals(that.mIntentPredicate);
}
@Override
public int hashCode() {
- int result = mActivityPredicate.hashCode();
+ int result = super.hashCode();
+ result = 31 * result + mActivityPredicate.hashCode();
result = 31 * result + mIntentPredicate.hashCode();
result = 31 * result + (mShouldAlwaysExpand ? 1 : 0);
return result;
@@ -120,6 +162,7 @@
@NonNull
@Override
public String toString() {
- return "ActivityRule{" + "mShouldAlwaysExpand=" + mShouldAlwaysExpand + '}';
+ return "ActivityRule{mTag=" + getTag()
+ + "mShouldAlwaysExpand=" + mShouldAlwaysExpand + '}';
}
}
diff --git a/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/EmbeddingRule.java b/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/EmbeddingRule.java
index 571eda0..6c9577d 100644
--- a/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/EmbeddingRule.java
+++ b/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/EmbeddingRule.java
@@ -16,10 +16,48 @@
package androidx.window.extensions.embedding;
+import androidx.annotation.Nullable;
+import androidx.window.extensions.core.util.function.Function;
+
+import java.util.Objects;
+
/**
* Base interface for activity embedding rules. Used to group different types of rules together when
* updating from the core library.
*/
public abstract class EmbeddingRule {
- EmbeddingRule() {}
+ @Nullable
+ private final String mTag;
+
+ EmbeddingRule(@Nullable String tag) {
+ mTag = tag;
+ }
+
+ /**
+ * A unique string to identify this {@link EmbeddingRule}.
+ * The suggested usage is to set the tag in the corresponding rule builder to be able to
+ * differentiate between different rules in {@link SplitAttributes} calculator function. For
+ * example, it can be used to compute the {@link SplitAttributes} for the specific
+ * {@link SplitRule} in the {@link Function} set with
+ * {@link ActivityEmbeddingComponent#setSplitAttributesCalculator(Function)}.
+ *
+ * @since {@link androidx.window.extensions.WindowExtensions#VENDOR_API_LEVEL_2}
+ */
+ @Nullable
+ public String getTag() {
+ return mTag;
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (this == other) return true;
+ if (!(other instanceof EmbeddingRule)) return false;
+ final EmbeddingRule otherRule = (EmbeddingRule) other;
+ return Objects.equals(mTag, otherRule.mTag);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hashCode(mTag);
+ }
}
diff --git a/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/SplitAttributes.java b/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/SplitAttributes.java
new file mode 100644
index 0000000..d724e1b
--- /dev/null
+++ b/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/SplitAttributes.java
@@ -0,0 +1,559 @@
+/*
+ * 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 androidx.window.extensions.embedding;
+
+import static androidx.window.extensions.embedding.SplitAttributes.LayoutDirection.BOTTOM_TO_TOP;
+import static androidx.window.extensions.embedding.SplitAttributes.LayoutDirection.LEFT_TO_RIGHT;
+import static androidx.window.extensions.embedding.SplitAttributes.LayoutDirection.LOCALE;
+import static androidx.window.extensions.embedding.SplitAttributes.LayoutDirection.RIGHT_TO_LEFT;
+import static androidx.window.extensions.embedding.SplitAttributes.LayoutDirection.TOP_TO_BOTTOM;
+
+import android.annotation.SuppressLint;
+
+import androidx.annotation.ColorInt;
+import androidx.annotation.FloatRange;
+import androidx.annotation.IntDef;
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+import androidx.window.extensions.core.util.function.Function;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * Attributes that describe how the parent window (typically the activity task
+ * window) is split between the primary and secondary activity containers,
+ * including:
+ * <ul>
+ * <li>Split type -- Categorizes the split and specifies the sizes of the
+ * primary and secondary activity containers relative to the parent
+ * bounds</li>
+ * <li>Layout direction -- Specifies whether the parent window is split
+ * vertically or horizontally and in which direction the primary and
+ * secondary containers are respectively positioned (left to right,
+ * right to left, top to bottom, and so forth)</li>
+ * <li>Animation background color -- The color of the background during
+ * animation of the split involving this {@code SplitAttributes} object
+ * if the animation requires a background</li>
+ * </ul>
+ *
+ * <p>Attributes can be configured by:
+ * <ul>
+ * <li>Setting the default {@code SplitAttributes} using
+ * {@link SplitPairRule.Builder#setDefaultSplitAttributes} or
+ * {@link SplitPlaceholderRule.Builder#setDefaultSplitAttributes}.</li>
+ * <li>Using {@link ActivityEmbeddingComponent#setSplitAttributesCalculator(Function)} to set
+ * the callback to customize the {@code SplitAttributes} for a given device and window
+ * state.</li>
+ * </ul>
+ *
+ * @see SplitAttributes.SplitType
+ * @see SplitAttributes.LayoutDirection
+ * @since {@link androidx.window.extensions.WindowExtensions#VENDOR_API_LEVEL_2}
+ */
+public class SplitAttributes {
+ /**
+ * The type of window split, which defines the proportion of the parent
+ * window occupied by the primary and secondary activity containers.
+ */
+ public static class SplitType {
+ @NonNull
+ private final String mDescription;
+
+ SplitType(@NonNull String description) {
+ mDescription = description;
+ }
+
+ @Override
+ public int hashCode() {
+ return mDescription.hashCode();
+ }
+
+ @Override
+ public boolean equals(@Nullable Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (!(obj instanceof SplitType)) {
+ return false;
+ }
+ final SplitType that = (SplitType) obj;
+ return mDescription.equals(that.mDescription);
+ }
+
+ @NonNull
+ @Override
+ public String toString() {
+ return mDescription;
+ }
+
+ @SuppressLint("Range") // The range is covered.
+ @NonNull
+ static SplitType createSplitTypeFromLegacySplitRatio(
+ @FloatRange(from = 0.0, to = 1.0) float splitRatio) {
+ // Treat 0.0 and 1.0 as ExpandContainerSplitType because it means the parent container
+ // is filled with secondary or primary container.
+ if (splitRatio == 0.0 || splitRatio == 1.0) {
+ return new ExpandContainersSplitType();
+ }
+ return new RatioSplitType(splitRatio);
+ }
+
+ /**
+ * A window split that's based on the ratio of the size of the primary
+ * container to the size of the parent window.
+ *
+ * <p>Values in the non-inclusive range (0.0, 1.0) define the size of
+ * the primary container relative to the size of the parent window:
+ * <ul>
+ * <li>0.5 -- Primary container occupies half of the parent
+ * window; secondary container, the other half</li>
+ * <li>Greater than 0.5 -- Primary container occupies a larger
+ * proportion of the parent window than the secondary
+ * container</li>
+ * <li>Less than 0.5 -- Primary container occupies a smaller
+ * proportion of the parent window than the secondary
+ * container</li>
+ * </ul>
+ */
+ public static final class RatioSplitType extends SplitType {
+ @FloatRange(from = 0.0, to = 1.0, fromInclusive = false, toInclusive = false)
+ private final float mRatio;
+
+ /**
+ * Creates an instance of this {@code RatioSplitType}.
+ *
+ * @param ratio The proportion of the parent window occupied by the
+ * primary container of the split. Can be a value in the
+ * non-inclusive range (0.0, 1.0). Use
+ * {@link SplitType.ExpandContainersSplitType} to create a split
+ * type that occupies the entire parent window.
+ */
+ public RatioSplitType(
+ @FloatRange(from = 0.0, to = 1.0, fromInclusive = false, toInclusive = false)
+ float ratio) {
+ super("ratio:" + ratio);
+ if (ratio <= 0.0f || ratio >= 1.0f) {
+ throw new IllegalArgumentException("Ratio must be in range (0.0, 1.0). "
+ + " Use SplitType.ExpandContainersSplitType() instead of 0 or 1.");
+ }
+ mRatio = ratio;
+ }
+
+ /**
+ * Gets the proportion of the parent window occupied by the primary
+ * activity container of the split.
+ *
+ * @return The proportion of the split occupied by the primary
+ * container.
+ */
+ @FloatRange(from = 0.0, to = 1.0, fromInclusive = false, toInclusive = false)
+ public float getRatio() {
+ return mRatio;
+ }
+
+ /**
+ * Creates a split type in which the primary and secondary
+ * containers occupy equal portions of the parent window.
+ *
+ * Serves as the default {@link SplitType} if
+ * {@link SplitAttributes.Builder#setSplitType(SplitType)} is not
+ * specified.
+ *
+ * @return A {@code RatioSplitType} in which the activity containers
+ * occupy equal portions of the parent window.
+ */
+ @NonNull
+ public static RatioSplitType splitEqually() {
+ return new RatioSplitType(0.5f);
+ }
+ }
+
+ /**
+ * A parent window split in which the split ratio conforms to the
+ * position of a hinge or separating fold in the device display.
+ *
+ * The split type is created only if:
+ * <ul>
+ * <li>The host task is not in multi-window mode (e.g.,
+ * split-screen mode or picture-in-picture mode)</li>
+ * <li>The device has a hinge or separating fold reported by
+ * [androidx.window.layout.FoldingFeature.isSeparating]</li>
+ * <li>The hinge or separating fold orientation matches how the
+ * parent bounds are split:
+ * <ul>
+ * <li>The hinge or fold orientation is vertical, and
+ * the task bounds are also split vertically
+ * (containers are side by side)</li>
+ * <li>The hinge or fold orientation is horizontal, and
+ * the task bounds are also split horizontally
+ * (containers are top and bottom)</li>
+ * </ul>
+ * </li>
+ * </ul>
+ *
+ * Otherwise, the type falls back to the {@code SplitType} returned by
+ * {@link #getFallbackSplitType()}.
+ */
+ public static final class HingeSplitType extends SplitType {
+ @NonNull
+ private final SplitType mFallbackSplitType;
+
+ /**
+ * Creates an instance of this {@code HingeSplitType}.
+ *
+ * @param fallbackSplitType The split type to use if a split based
+ * on the device hinge or separating fold cannot be determined.
+ * Can be a {@link RatioSplitType} or
+ * {@link ExpandContainersSplitType}.
+ */
+ public HingeSplitType(@NonNull SplitType fallbackSplitType) {
+ super("hinge, fallbackType=" + fallbackSplitType);
+ mFallbackSplitType = fallbackSplitType;
+ }
+
+ /**
+ * Returns the fallback {@link SplitType} if a split based on the
+ * device hinge or separating fold cannot be determined.
+ */
+ @NonNull
+ public SplitType getFallbackSplitType() {
+ return mFallbackSplitType;
+ }
+ }
+
+ /**
+ * A window split in which the primary and secondary activity containers
+ * each occupy the entire parent window.
+ *
+ * The secondary container overlays the primary container.
+ */
+ public static final class ExpandContainersSplitType extends SplitType {
+
+ /**
+ * Creates an instance of this {@code ExpandContainersSplitType}.
+ */
+ public ExpandContainersSplitType() {
+ super("expandContainers");
+ }
+ }
+ }
+
+ /**
+ * The layout direction of the primary and secondary activity containers.
+ */
+ public static final class LayoutDirection {
+
+ /**
+ * Specifies that the parent bounds are split vertically (side to side).
+ *
+ * Places the primary container in the left portion of the parent
+ * window, and the secondary container in the right portion.
+ *
+ * A possible return value of {@link SplitType#getLayoutDirection()}.
+ */
+ //
+ // -------------------------
+ // | | |
+ // | Primary | Secondary |
+ // | | |
+ // -------------------------
+ //
+ // Must match {@link LayoutDirection#LTR} for backwards compatibility
+ // with prior versions of Extensions.
+ public static final int LEFT_TO_RIGHT = 0;
+
+ /**
+ * Specifies that the parent bounds are split vertically (side to
+ * side).
+ *
+ * Places the primary container in the right portion of the parent
+ * window, and the secondary container in the left portion.
+ *
+ * A possible return value of {@link SplitType#getLayoutDirection()}.
+ */
+ // -------------------------
+ // | | |
+ // | Secondary | Primary |
+ // | | |
+ // -------------------------
+ //
+ // Must match {@link LayoutDirection#RTL} for backwards compatibility
+ // with prior versions of Extensions.
+ public static final int RIGHT_TO_LEFT = 1;
+
+ /**
+ * Specifies that the parent bounds are split vertically (side to side).
+ *
+ * The direction of the primary and secondary containers is deduced from
+ * the locale as either {@link #LEFT_TO_RIGHT} or
+ * {@link #RIGHT_TO_LEFT}.
+ *
+ * A possible return value of {@link SplitType#getLayoutDirection()}.
+ */
+ // Must match {@link LayoutDirection#LOCALE} for backwards
+ // compatibility with prior versions of Extensions.
+ public static final int LOCALE = 3;
+
+ /**
+ * Specifies that the parent bounds are split horizontally (top and
+ * bottom).
+ *
+ * Places the primary container in the top portion of the parent window,
+ * and the secondary container in the bottom portion.
+ *
+ * If the horizontal layout direction is not supported on the device,
+ * layout direction falls back to {@link #LOCALE}.
+ *
+ * A possible return value of {@link SplitType#getLayoutDirection()}.
+ */
+ // -------------
+ // | |
+ // | Primary |
+ // | |
+ // -------------
+ // | |
+ // | Secondary |
+ // | |
+ // -------------
+ public static final int TOP_TO_BOTTOM = 4;
+
+ /**
+ * Specifies that the parent bounds are split horizontally (top and
+ * bottom).
+ *
+ * Places the primary container in the bottom portion of the parent
+ * window, and the secondary container in the top portion.
+ *
+ * If the horizontal layout direction is not supported on the device,
+ * layout direction falls back to {@link #LOCALE}.
+ *
+ * A possible return value of {@link SplitType#getLayoutDirection()}.
+ */
+ // -------------
+ // | |
+ // | Secondary |
+ // | |
+ // -------------
+ // | |
+ // | Primary |
+ // | |
+ // -------------
+ public static final int BOTTOM_TO_TOP = 5;
+
+ private LayoutDirection() {}
+ }
+
+ @IntDef({LEFT_TO_RIGHT, RIGHT_TO_LEFT, LOCALE, TOP_TO_BOTTOM, BOTTOM_TO_TOP})
+ @Retention(RetentionPolicy.SOURCE)
+ @interface ExtLayoutDirection {}
+
+ @ExtLayoutDirection
+ private final int mLayoutDirection;
+
+ private final SplitType mSplitType;
+
+ @ColorInt
+ private final int mAnimationBackgroundColor;
+
+ /**
+ * Creates an instance of this {@code SplitAttributes}.
+ *
+ * @param splitType The type of split. See
+ * {@link SplitAttributes.SplitType}.
+ * @param layoutDirection The layout direction of the split, such as left to
+ * right or top to bottom. See {@link SplitAttributes.LayoutDirection}.
+ * @param animationBackgroundColor The {@link ColorInt} to use for the
+ * background color during animation of the split involving this
+ * {@code SplitAttributes} object if the animation requires a
+ * background.
+ */
+ SplitAttributes(@NonNull SplitType splitType, @ExtLayoutDirection int layoutDirection,
+ @ColorInt int animationBackgroundColor) {
+ mSplitType = splitType;
+ mLayoutDirection = layoutDirection;
+ mAnimationBackgroundColor = animationBackgroundColor;
+ }
+
+ /**
+ * Gets the layout direction of the split.
+ *
+ * @return The layout direction of the split.
+ */
+ @ExtLayoutDirection
+ public int getLayoutDirection() {
+ return mLayoutDirection;
+ }
+
+ /**
+ * Gets the split type.
+ *
+ * @return The split type.
+ */
+ @NonNull
+ public SplitType getSplitType() {
+ return mSplitType;
+ }
+
+ /**
+ * Gets the {@link ColorInt} to use for the background color during the
+ * animation of the split involving this {@code SplitAttributes} object.
+ *
+ * @return The animation background {@code ColorInt}.
+ */
+ @ColorInt
+ public int getAnimationBackgroundColor() {
+ return mAnimationBackgroundColor;
+ }
+
+ /**
+ * Builder for creating an instance of {@link SplitAttributes}.
+ *
+ * The default split type is an equal split between primary and secondary
+ * containers. The default layout direction is based on locale. The default
+ * animation background color is 0, which specifies the theme window
+ * background color.
+ */
+ public static final class Builder {
+ @NonNull
+ private SplitType mSplitType = new SplitType.RatioSplitType(0.5f);
+ @ExtLayoutDirection
+ private int mLayoutDirection = LOCALE;
+
+ @ColorInt
+ private int mAnimationBackgroundColor = 0;
+
+ /**
+ * Sets the split type attribute.
+ *
+ * The default is an equal split between primary and secondary
+ * containers (see {@link SplitType.RatioSplitType#splitEqually()}).
+ *
+ * @param splitType The split type attribute.
+ * @return This {@code Builder}.
+ */
+ @NonNull
+ public Builder setSplitType(@NonNull SplitType splitType) {
+ mSplitType = splitType;
+ return this;
+ }
+
+ /**
+ * Sets the split layout direction attribute.
+ *
+ * The default is based on locale.
+ *
+ * Must be one of:
+ * <ul>
+ * <li>{@link LayoutDirection#LOCALE}</li>
+ * <li>{@link LayoutDirection#LEFT_TO_RIGHT}</li>
+ * <li>{@link LayoutDirection#RIGHT_TO_LEFT}</li>
+ * <li>{@link LayoutDirection#TOP_TO_BOTTOM}</li>
+ * <li>{@link LayoutDirection#BOTTOM_TO_TOP}</li>
+ * </ul>
+ *
+ * @param layoutDirection The layout direction attribute.
+ * @return This {@code Builder}.
+ */
+ @SuppressLint("WrongConstant") // To be compat with android.util.LayoutDirection APIs
+ @NonNull
+ public Builder setLayoutDirection(@ExtLayoutDirection int layoutDirection) {
+ mLayoutDirection = layoutDirection;
+ return this;
+ }
+
+ /**
+ * Sets the {@link ColorInt} to use for the background during the
+ * animation of the split involving this {@code SplitAttributes} object
+ * if the animation requires a background.
+ *
+ * The default value is 0, which specifies the theme window background
+ * color.
+ *
+ * @param color A packed color int of the form {@code AARRGGBB} for the
+ * animation background color.
+ * @return This {@code Builder}.
+ */
+ @NonNull
+ public Builder setAnimationBackgroundColor(@ColorInt int color) {
+ mAnimationBackgroundColor = color;
+ return this;
+ }
+
+ /**
+ * Builds a {@link SplitAttributes} instance with the attributes
+ * specified by {@link #setSplitType}, {@link #setLayoutDirection}, and
+ * {@link #setAnimationBackgroundColor}.
+ *
+ * @return The new {@code SplitAttributes} instance.
+ */
+ @NonNull
+ public SplitAttributes build() {
+ return new SplitAttributes(mSplitType, mLayoutDirection, mAnimationBackgroundColor);
+ }
+ }
+
+ @Override
+ public int hashCode() {
+ int result = mSplitType.hashCode();
+ result = result * 31 + mLayoutDirection;
+ result = result * 31 + mAnimationBackgroundColor;
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (other == this) {
+ return true;
+ }
+ if (!(other instanceof SplitAttributes)) {
+ return false;
+ }
+ final SplitAttributes otherAttributes = (SplitAttributes) other;
+ return mLayoutDirection == otherAttributes.mLayoutDirection
+ && mSplitType.equals(otherAttributes.mSplitType)
+ && mAnimationBackgroundColor == otherAttributes.mAnimationBackgroundColor;
+ }
+
+ @NonNull
+ @Override
+ public String toString() {
+ return SplitAttributes.class.getSimpleName() + "{"
+ + "layoutDir=" + layoutDirectionToString()
+ + ", ratio=" + mSplitType
+ + ", animationBgColor=" + Integer.toHexString(mAnimationBackgroundColor)
+ + "}";
+ }
+
+ @NonNull
+ private String layoutDirectionToString() {
+ switch(mLayoutDirection) {
+ case LEFT_TO_RIGHT:
+ return "LEFT_TO_RIGHT";
+ case RIGHT_TO_LEFT:
+ return "RIGHT_TO_LEFT";
+ case LOCALE:
+ return "LOCALE";
+ case TOP_TO_BOTTOM:
+ return "TOP_TO_BOTTOM";
+ case BOTTOM_TO_TOP:
+ return "BOTTOM_TO_TOP";
+ default:
+ throw new IllegalArgumentException("Invalid layout direction:" + mLayoutDirection);
+ }
+ }
+}
diff --git a/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/SplitAttributesCalculatorParams.java b/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/SplitAttributesCalculatorParams.java
new file mode 100644
index 0000000..e26e496
--- /dev/null
+++ b/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/SplitAttributesCalculatorParams.java
@@ -0,0 +1,149 @@
+/*
+ * 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 androidx.window.extensions.embedding;
+
+import android.content.res.Configuration;
+import android.os.Build;
+import android.view.WindowMetrics;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+import androidx.annotation.RequiresApi;
+import androidx.window.extensions.layout.WindowLayoutInfo;
+
+/**
+ * The parameter container used to report the current device and window state in
+ * {@link ActivityEmbeddingComponent#setSplitAttributesCalculator(
+ * androidx.window.extensions.core.util.function.Function)} and references the corresponding
+ * {@link SplitRule} by {@link #getSplitRuleTag()} if {@link SplitRule#getTag()} is specified.
+ *
+ * @see ActivityEmbeddingComponent#clearSplitAttributesCalculator()
+ * @since {@link androidx.window.extensions.WindowExtensions#VENDOR_API_LEVEL_2}
+ */
+public class SplitAttributesCalculatorParams {
+ @NonNull
+ private final WindowMetrics mParentWindowMetrics;
+ @NonNull
+ private final Configuration mParentConfiguration;
+ @NonNull
+ private final WindowLayoutInfo mParentWindowLayoutInfo;
+ @NonNull
+ private final SplitAttributes mDefaultSplitAttributes;
+ private final boolean mAreDefaultConstraintsSatisfied;
+ @Nullable
+ private final String mSplitRuleTag;
+
+ /** Returns the parent container's {@link WindowMetrics} */
+ @NonNull
+ public WindowMetrics getParentWindowMetrics() {
+ return mParentWindowMetrics;
+ }
+
+ /** Returns the parent container's {@link Configuration} */
+ @NonNull
+ public Configuration getParentConfiguration() {
+ return new Configuration(mParentConfiguration);
+ }
+
+ /**
+ * Returns the {@link SplitRule#getDefaultSplitAttributes()}. It could be from
+ * {@link SplitRule} Builder APIs
+ * ({@link SplitPairRule.Builder#setDefaultSplitAttributes(SplitAttributes)} or
+ * {@link SplitPlaceholderRule.Builder#setDefaultSplitAttributes(SplitAttributes)}) or from
+ * the {@code splitRatio} and {@code splitLayoutDirection} attributes from static rule
+ * definitions.
+ */
+ @NonNull
+ public SplitAttributes getDefaultSplitAttributes() {
+ return mDefaultSplitAttributes;
+ }
+
+ /**
+ * Returns whether the {@link #getParentWindowMetrics()} satisfies the dimensions and aspect
+ * ratios requirements specified in the {@link androidx.window.embedding.SplitRule}, which
+ * are:
+ * - {@link androidx.window.embedding.SplitRule#minWidthDp}
+ * - {@link androidx.window.embedding.SplitRule#minHeightDp}
+ * - {@link androidx.window.embedding.SplitRule#minSmallestWidthDp}
+ * - {@link androidx.window.embedding.SplitRule#maxAspectRatioInPortrait}
+ * - {@link androidx.window.embedding.SplitRule#maxAspectRatioInLandscape}
+ */
+ public boolean areDefaultConstraintsSatisfied() {
+ return mAreDefaultConstraintsSatisfied;
+ }
+
+ /** Returns the parent container's {@link WindowLayoutInfo} */
+ @NonNull
+ public WindowLayoutInfo getParentWindowLayoutInfo() {
+ return mParentWindowLayoutInfo;
+ }
+
+ /**
+ * Returns {@link SplitRule#getTag()} to apply the {@link SplitAttributes} result if it was
+ * set.
+ */
+ @Nullable
+ public String getSplitRuleTag() {
+ return mSplitRuleTag;
+ }
+
+ SplitAttributesCalculatorParams(
+ @NonNull WindowMetrics parentWindowMetrics,
+ @NonNull Configuration parentConfiguration,
+ @NonNull WindowLayoutInfo parentWindowLayoutInfo,
+ @NonNull SplitAttributes defaultSplitAttributes,
+ boolean areDefaultConstraintsSatisfied,
+ @Nullable String splitRuleTag
+ ) {
+ mParentWindowMetrics = parentWindowMetrics;
+ mParentConfiguration = parentConfiguration;
+ mParentWindowLayoutInfo = parentWindowLayoutInfo;
+ mDefaultSplitAttributes = defaultSplitAttributes;
+ mAreDefaultConstraintsSatisfied = areDefaultConstraintsSatisfied;
+ mSplitRuleTag = splitRuleTag;
+ }
+
+ @NonNull
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + ":{"
+ + "windowMetrics=" + windowMetricsToString(mParentWindowMetrics)
+ + ", configuration=" + mParentConfiguration
+ + ", windowLayoutInfo=" + mParentWindowLayoutInfo
+ + ", defaultSplitAttributes=" + mDefaultSplitAttributes
+ + ", areDefaultConstraintsSatisfied=" + mAreDefaultConstraintsSatisfied
+ + ", tag=" + mSplitRuleTag + "}";
+ }
+
+ private static String windowMetricsToString(@NonNull WindowMetrics windowMetrics) {
+ // TODO(b/187712731): Use WindowMetrics#toString after it's implemented in U.
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ return Api30Impl.windowMetricsToString(windowMetrics);
+ }
+ throw new UnsupportedOperationException("WindowMetrics didn't exist in R.");
+ }
+
+ @RequiresApi(30)
+ private static final class Api30Impl {
+ static String windowMetricsToString(@NonNull WindowMetrics windowMetrics) {
+ return WindowMetrics.class.getSimpleName() + ":{"
+ + "bounds=" + windowMetrics.getBounds()
+ + ", windowInsets=" + windowMetrics.getWindowInsets()
+ + "}";
+ }
+ }
+}
diff --git a/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/SplitInfo.java b/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/SplitInfo.java
index cfd8b1a..4f28788 100644
--- a/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/SplitInfo.java
+++ b/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/SplitInfo.java
@@ -17,6 +17,8 @@
package androidx.window.extensions.embedding;
import androidx.annotation.NonNull;
+import androidx.window.extensions.WindowExtensions;
+import androidx.window.extensions.embedding.SplitAttributes.SplitType;
/** Describes a split of two containers with activities. */
public class SplitInfo {
@@ -24,13 +26,16 @@
private final ActivityStack mPrimaryActivityStack;
@NonNull
private final ActivityStack mSecondaryActivityStack;
- private final float mSplitRatio;
+ @NonNull
+ private final SplitAttributes mSplitAttributes;
+ /** @since {@link androidx.window.extensions.WindowExtensions#VENDOR_API_LEVEL_2} */
public SplitInfo(@NonNull ActivityStack primaryActivityStack,
- @NonNull ActivityStack secondaryActivityStack, float splitRatio) {
+ @NonNull ActivityStack secondaryActivityStack,
+ @NonNull SplitAttributes splitAttributes) {
mPrimaryActivityStack = primaryActivityStack;
mSecondaryActivityStack = secondaryActivityStack;
- mSplitRatio = splitRatio;
+ mSplitAttributes = splitAttributes;
}
@NonNull
@@ -43,8 +48,28 @@
return mSecondaryActivityStack;
}
+ /**
+ * @deprecated Use {@link #getSplitAttributes()} starting with
+ * {@link WindowExtensions#VENDOR_API_LEVEL_2}. Only used if {@link #getSplitAttributes()}
+ * can't be called on {@link WindowExtensions#VENDOR_API_LEVEL_1}.
+ */
+ @Deprecated
public float getSplitRatio() {
- return mSplitRatio;
+ final SplitType splitType = mSplitAttributes.getSplitType();
+ if (splitType instanceof SplitType.RatioSplitType) {
+ return ((SplitType.RatioSplitType) splitType).getRatio();
+ } else { // Fallback to use 0.0 because the WM Jetpack may not support HingeSplitType.
+ return 0.0f;
+ }
+ }
+
+ /**
+ * Returns the {@link SplitAttributes} of this split.
+ * @since {@link androidx.window.extensions.WindowExtensions#VENDOR_API_LEVEL_2}
+ */
+ @NonNull
+ public SplitAttributes getSplitAttributes() {
+ return mSplitAttributes;
}
@Override
@@ -52,7 +77,7 @@
if (this == o) return true;
if (!(o instanceof SplitInfo)) return false;
SplitInfo that = (SplitInfo) o;
- return Float.compare(that.mSplitRatio, mSplitRatio) == 0 && mPrimaryActivityStack.equals(
+ return mSplitAttributes.equals(that.mSplitAttributes) && mPrimaryActivityStack.equals(
that.mPrimaryActivityStack) && mSecondaryActivityStack.equals(
that.mSecondaryActivityStack);
}
@@ -61,7 +86,7 @@
public int hashCode() {
int result = mPrimaryActivityStack.hashCode();
result = result * 31 + mSecondaryActivityStack.hashCode();
- result = result * 31 + (int) (mSplitRatio * 17);
+ result = result * 31 + mSplitAttributes.hashCode();
return result;
}
@@ -71,7 +96,7 @@
return "SplitInfo{"
+ "mPrimaryActivityStack=" + mPrimaryActivityStack
+ ", mSecondaryActivityStack=" + mSecondaryActivityStack
- + ", mSplitRatio=" + mSplitRatio
+ + ", mSplitAttributes=" + mSplitAttributes
+ '}';
}
}
diff --git a/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/SplitPairRule.java b/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/SplitPairRule.java
index d2e5209..10dac95 100644
--- a/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/SplitPairRule.java
+++ b/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/SplitPairRule.java
@@ -16,6 +16,8 @@
package androidx.window.extensions.embedding;
+import static androidx.window.extensions.embedding.SplitAttributes.SplitType.createSplitTypeFromLegacySplitRatio;
+
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
@@ -23,10 +25,14 @@
import android.util.Pair;
import android.view.WindowMetrics;
+import androidx.annotation.FloatRange;
import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
+import androidx.window.extensions.WindowExtensions;
+import androidx.window.extensions.core.util.function.Predicate;
-import java.util.function.Predicate;
+import java.util.Objects;
/**
* Split configuration rules for activity pairs.
@@ -42,13 +48,14 @@
private final int mFinishSecondaryWithPrimary;
private final boolean mClearTop;
- SplitPairRule(float splitRatio, @LayoutDirection int layoutDirection,
+ SplitPairRule(@NonNull SplitAttributes defaultSplitAttributes,
@SplitFinishBehavior int finishPrimaryWithSecondary,
@SplitFinishBehavior int finishSecondaryWithPrimary, boolean clearTop,
@NonNull Predicate<Pair<Activity, Activity>> activityPairPredicate,
@NonNull Predicate<Pair<Activity, Intent>> activityIntentPredicate,
- @NonNull Predicate<WindowMetrics> parentWindowMetricsPredicate) {
- super(parentWindowMetricsPredicate, splitRatio, layoutDirection);
+ @NonNull Predicate<WindowMetrics> parentWindowMetricsPredicate,
+ @Nullable String tag) {
+ super(parentWindowMetricsPredicate, defaultSplitAttributes, tag);
mActivityPairPredicate = activityPairPredicate;
mActivityIntentPredicate = activityIntentPredicate;
mFinishPrimaryWithSecondary = finishPrimaryWithSecondary;
@@ -114,15 +121,52 @@
private final Predicate<Pair<Activity, Intent>> mActivityIntentPredicate;
@NonNull
private final Predicate<WindowMetrics> mParentWindowMetricsPredicate;
+ // Keep for backward compatibility
+ @FloatRange(from = 0.0, to = 1.0)
private float mSplitRatio;
- @LayoutDirection
+ // Keep for backward compatibility
+ @SplitAttributes.ExtLayoutDirection
private int mLayoutDirection;
+ private SplitAttributes mDefaultSplitAttributes;
private boolean mClearTop;
@SplitFinishBehavior
private int mFinishPrimaryWithSecondary;
@SplitFinishBehavior
private int mFinishSecondaryWithPrimary;
+ @Nullable
+ private String mTag;
+ /**
+ * @deprecated Use {@link #Builder(Predicate, Predicate, Predicate)} starting with
+ * {@link WindowExtensions#VENDOR_API_LEVEL_2}. Only used if
+ * {@link #Builder(Predicate, Predicate, Predicate)} can't be called on
+ * {@link WindowExtensions#VENDOR_API_LEVEL_1}.
+ */
+ @Deprecated
+ @RequiresApi(Build.VERSION_CODES.N)
+ public Builder(@NonNull java.util.function.Predicate<Pair<Activity, Activity>>
+ activityPairPredicate,
+ @NonNull java.util.function.Predicate<Pair<Activity, Intent>>
+ activityIntentPredicate,
+ @NonNull java.util.function.Predicate<WindowMetrics>
+ parentWindowMetricsPredicate) {
+ mActivityPairPredicate = activityPairPredicate::test;
+ mActivityIntentPredicate = activityIntentPredicate::test;
+ mParentWindowMetricsPredicate = parentWindowMetricsPredicate::test;
+ }
+
+ /**
+ * The {@link SplitPairRule} builder constructor
+ *
+ * @param activityPairPredicate the {@link Predicate} to verify if an {@link Activity} pair
+ * matches this rule
+ * @param activityIntentPredicate the {@link Predicate} to verify if an ({@link Activity},
+ * {@link Intent}) pair matches this rule
+ * @param parentWindowMetricsPredicate the {@link Predicate} to verify if the matched split
+ * pair is allowed to show adjacent to each other with the
+ * given parent {@link WindowMetrics}
+ * @since {@link WindowExtensions#VENDOR_API_LEVEL_2}
+ */
public Builder(@NonNull Predicate<Pair<Activity, Activity>> activityPairPredicate,
@NonNull Predicate<Pair<Activity, Intent>> activityIntentPredicate,
@NonNull Predicate<WindowMetrics> parentWindowMetricsPredicate) {
@@ -131,20 +175,48 @@
mParentWindowMetricsPredicate = parentWindowMetricsPredicate;
}
- /** @see SplitRule#getSplitRatio() */
+ /**
+ * @deprecated Use {@link #setDefaultSplitAttributes(SplitAttributes)} starting with
+ * {@link WindowExtensions#VENDOR_API_LEVEL_2}. Only used if
+ * {@link #setDefaultSplitAttributes(SplitAttributes)} can't be called on
+ * {@link WindowExtensions#VENDOR_API_LEVEL_1}. {@code splitRatio} will be translated to
+ * {@link SplitAttributes.SplitType.ExpandContainersSplitType} for value {@code 0.0} and
+ * {@code 1.0}, and {@link SplitAttributes.SplitType.RatioSplitType} for value with range
+ * (0.0, 1.0).
+ */
+ @Deprecated
@NonNull
- public Builder setSplitRatio(float splitRatio) {
+ public Builder setSplitRatio(@FloatRange(from = 0.0, to = 1.0) float splitRatio) {
mSplitRatio = splitRatio;
return this;
}
- /** @see SplitRule#getLayoutDirection() */
+ /**
+ * @deprecated Use {@link #setDefaultSplitAttributes(SplitAttributes)} starting with
+ * {@link WindowExtensions#VENDOR_API_LEVEL_2}. Only used if
+ * {@link #setDefaultSplitAttributes(SplitAttributes)} can't be called on
+ * {@link WindowExtensions#VENDOR_API_LEVEL_1}.
+ */
+ @Deprecated
@NonNull
- public Builder setLayoutDirection(@LayoutDirection int layoutDirection) {
+ public Builder setLayoutDirection(@SplitAttributes.ExtLayoutDirection int layoutDirection) {
mLayoutDirection = layoutDirection;
return this;
}
+ /**
+ * See {@link SplitPairRule#getDefaultSplitAttributes()} for reference.
+ * Overrides values if set in {@link #setSplitRatio(float)} and
+ * {@link #setLayoutDirection(int)}
+ *
+ * @since {@link WindowExtensions#VENDOR_API_LEVEL_2}
+ */
+ @NonNull
+ public Builder setDefaultSplitAttributes(@NonNull SplitAttributes attrs) {
+ mDefaultSplitAttributes = attrs;
+ return this;
+ }
+
/** @deprecated To be removed with next developer preview. */
@Deprecated
@NonNull
@@ -181,13 +253,31 @@
return this;
}
+ /**
+ * @see SplitPairRule#getTag()
+ * @since {@link WindowExtensions#VENDOR_API_LEVEL_2}
+ */
+ @NonNull
+ public Builder setTag(@NonNull String tag) {
+ mTag = Objects.requireNonNull(tag);
+ return this;
+ }
+
/** Builds a new instance of {@link SplitPairRule}. */
@NonNull
public SplitPairRule build() {
- return new SplitPairRule(mSplitRatio, mLayoutDirection,
+ // To provide compatibility with prior version of WM Jetpack library, where
+ // #setDefaultAttributes hasn't yet been supported and thus would not be set.
+ mDefaultSplitAttributes = (mDefaultSplitAttributes != null)
+ ? mDefaultSplitAttributes
+ : new SplitAttributes.Builder()
+ .setSplitType(createSplitTypeFromLegacySplitRatio(mSplitRatio))
+ .setLayoutDirection(mLayoutDirection)
+ .build();
+ return new SplitPairRule(mDefaultSplitAttributes,
mFinishPrimaryWithSecondary, mFinishSecondaryWithPrimary,
mClearTop, mActivityPairPredicate, mActivityIntentPredicate,
- mParentWindowMetricsPredicate);
+ mParentWindowMetricsPredicate, mTag);
}
}
@@ -219,7 +309,9 @@
@Override
public String toString() {
return "SplitPairRule{"
- + "mFinishPrimaryWithSecondary=" + mFinishPrimaryWithSecondary
+ + "mTag=" + getTag()
+ + ", mDefaultSplitAttributes=" + getDefaultSplitAttributes()
+ + ", mFinishPrimaryWithSecondary=" + mFinishPrimaryWithSecondary
+ ", mFinishSecondaryWithPrimary=" + mFinishSecondaryWithPrimary
+ ", mClearTop=" + mClearTop
+ '}';
diff --git a/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/SplitPlaceholderRule.java b/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/SplitPlaceholderRule.java
index 7b30849..a928941 100644
--- a/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/SplitPlaceholderRule.java
+++ b/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/SplitPlaceholderRule.java
@@ -16,19 +16,25 @@
package androidx.window.extensions.embedding;
+import static androidx.window.extensions.embedding.SplitAttributes.SplitType.createSplitTypeFromLegacySplitRatio;
+
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.view.WindowMetrics;
+import androidx.annotation.FloatRange;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
+import androidx.window.extensions.WindowExtensions;
+import androidx.window.extensions.core.util.function.Predicate;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
-import java.util.function.Predicate;
+import java.util.Objects;
/**
* Split configuration rules for split placeholders - activities used to occupy additional
@@ -58,12 +64,14 @@
private final int mFinishPrimaryWithPlaceholder;
SplitPlaceholderRule(@NonNull Intent placeholderIntent,
- float splitRatio, @LayoutDirection int layoutDirection, boolean isSticky,
+ @NonNull SplitAttributes defaultSplitAttributes,
+ boolean isSticky,
@SplitPlaceholderFinishBehavior int finishPrimaryWithPlaceholder,
@NonNull Predicate<Activity> activityPredicate,
@NonNull Predicate<Intent> intentPredicate,
- @NonNull Predicate<WindowMetrics> parentWindowMetricsPredicate) {
- super(parentWindowMetricsPredicate, splitRatio, layoutDirection);
+ @NonNull Predicate<WindowMetrics> parentWindowMetricsPredicate,
+ @Nullable String tag) {
+ super(parentWindowMetricsPredicate, defaultSplitAttributes, tag);
mIsSticky = isSticky;
mFinishPrimaryWithPlaceholder = finishPrimaryWithPlaceholder;
mActivityPredicate = activityPredicate;
@@ -106,7 +114,10 @@
}
/**
- * @deprecated Use {@link #getFinishPrimaryWithPlaceholder()} instead.
+ * @deprecated Use {@link #getFinishPrimaryWithPlaceholder()} instead starting with
+ * {@link WindowExtensions#VENDOR_API_LEVEL_2}. Only used if
+ * {@link #getFinishPrimaryWithPlaceholder()} can't be called on
+ * {@link WindowExtensions#VENDOR_API_LEVEL_1}.
*/
@Deprecated
@SplitPlaceholderFinishBehavior
@@ -117,8 +128,10 @@
/**
* Determines what happens with the primary container when all activities are finished in the
* associated secondary/placeholder container.
- * TODO(b/238905747): Add api guard for extensions.
+ *
+ * @since {@link WindowExtensions#VENDOR_API_LEVEL_2}
*/
+ // TODO(b/238905747): Add api guard for extensions.
@SplitPlaceholderFinishBehavior
public int getFinishPrimaryWithPlaceholder() {
return mFinishPrimaryWithPlaceholder;
@@ -136,13 +149,51 @@
private final Predicate<WindowMetrics> mParentWindowMetricsPredicate;
@NonNull
private final Intent mPlaceholderIntent;
+ // Keep for backward compatibility
+ @FloatRange(from = 0.0, to = 1.0)
private float mSplitRatio;
- @LayoutDirection
+ // Keep for backward compatibility
+ @SplitAttributes.ExtLayoutDirection
private int mLayoutDirection;
+ private SplitAttributes mDefaultSplitAttributes;
private boolean mIsSticky = false;
@SplitPlaceholderFinishBehavior
private int mFinishPrimaryWithPlaceholder = FINISH_ALWAYS;
+ @Nullable
+ private String mTag;
+ /**
+ * @deprecated Use {@link #Builder(Intent, Predicate, Predicate, Predicate)} starting with
+ * {@link WindowExtensions#VENDOR_API_LEVEL_2}. Only used if
+ * {@link #Builder(Intent, Predicate, Predicate, Predicate)} can't be called on
+ * {@link WindowExtensions#VENDOR_API_LEVEL_1}.
+ */
+ @Deprecated
+ @RequiresApi(Build.VERSION_CODES.N)
+ public Builder(@NonNull Intent placeholderIntent,
+ @NonNull java.util.function.Predicate<Activity> activityPredicate,
+ @NonNull java.util.function.Predicate<Intent> intentPredicate,
+ @NonNull java.util.function.Predicate<WindowMetrics> parentWindowMetricsPredicate) {
+ mActivityPredicate = activityPredicate::test;
+ mIntentPredicate = intentPredicate::test;
+ mPlaceholderIntent = placeholderIntent;
+ mParentWindowMetricsPredicate = parentWindowMetricsPredicate::test;
+ }
+
+ /**
+ * The {@link SplitPlaceholderRule} Builder constructor
+ * @param placeholderIntent the placeholder activity to launch if
+ * {@link SplitPlaceholderRule#checkParentMetrics(WindowMetrics)}
+ * is satisfied
+ * @param activityPredicate the {@link Predicate} to verify if a given {@link Activity}
+ * matches the rule
+ * @param intentPredicate the {@link Predicate} to verify if a given {@link Intent}
+ * matches the rule
+ * @param parentWindowMetricsPredicate the {@link Predicate} to verify if the placeholder
+ * {@link Activity} should be launched with the given
+ * {@link WindowMetrics}
+ * @since {@link WindowExtensions#VENDOR_API_LEVEL_2}
+ */
public Builder(@NonNull Intent placeholderIntent,
@NonNull Predicate<Activity> activityPredicate,
@NonNull Predicate<Intent> intentPredicate,
@@ -153,20 +204,48 @@
mParentWindowMetricsPredicate = parentWindowMetricsPredicate;
}
- /** @see SplitRule#getSplitRatio() */
+ /**
+ * @deprecated Use {@link #setDefaultSplitAttributes(SplitAttributes)} starting with
+ * {@link WindowExtensions#VENDOR_API_LEVEL_2}. Only used if
+ * {@link #setDefaultSplitAttributes(SplitAttributes)} can't be called on
+ * {@link WindowExtensions#VENDOR_API_LEVEL_1}. {@code splitRatio} will be translated to
+ * @link SplitAttributes.SplitType.ExpandContainersSplitType} for value
+ * {@code 0.0} and {@code 1.0}, and {@link SplitAttributes.SplitType.RatioSplitType} for
+ * value with range (0.0, 1.0).
+ */
+ @Deprecated
@NonNull
- public Builder setSplitRatio(float splitRatio) {
+ public Builder setSplitRatio(@FloatRange(from = 0.0, to = 1.0) float splitRatio) {
mSplitRatio = splitRatio;
return this;
}
- /** @see SplitRule#getLayoutDirection() */
+ /**
+ * @deprecated Use {@link #setDefaultSplitAttributes(SplitAttributes)} starting with
+ * {@link WindowExtensions#VENDOR_API_LEVEL_2}. Only used if
+ * {@link #setDefaultSplitAttributes(SplitAttributes)} can't be called on
+ * {@link WindowExtensions#VENDOR_API_LEVEL_1}.
+ */
+ @Deprecated
@NonNull
- public Builder setLayoutDirection(@LayoutDirection int layoutDirection) {
+ public Builder setLayoutDirection(@SplitAttributes.ExtLayoutDirection int layoutDirection) {
mLayoutDirection = layoutDirection;
return this;
}
+ /**
+ * See {@link SplitPlaceholderRule#getDefaultSplitAttributes()} for reference.
+ * Overrides values if set in {@link #setSplitRatio(float)} and
+ * {@link #setLayoutDirection(int)}
+ *
+ * @since {@link WindowExtensions#VENDOR_API_LEVEL_2}
+ */
+ @NonNull
+ public Builder setDefaultSplitAttributes(@NonNull SplitAttributes attrs) {
+ mDefaultSplitAttributes = attrs;
+ return this;
+ }
+
/** @see SplitPlaceholderRule#isSticky() */
@NonNull
public Builder setSticky(boolean sticky) {
@@ -175,7 +254,8 @@
}
/**
- * @deprecated Use SplitPlaceholderRule#setFinishPrimaryWithPlaceholder(int)} instead.
+ * @deprecated Use SplitPlaceholderRule#setFinishPrimaryWithPlaceholder(int)} starting with
+ * {@link WindowExtensions#VENDOR_API_LEVEL_2}.
*/
@Deprecated
@NonNull
@@ -189,8 +269,9 @@
/**
* @see SplitPlaceholderRule#getFinishPrimaryWithPlaceholder()
- * TODO(b/238905747): Add api guard for extensions.
+ * @since {@link WindowExtensions#VENDOR_API_LEVEL_2}
*/
+ // TODO(b/238905747): Add api guard for extensions.
@NonNull
public Builder setFinishPrimaryWithPlaceholder(
@SplitPlaceholderFinishBehavior int finishBehavior) {
@@ -198,12 +279,30 @@
return this;
}
+ /**
+ * @see SplitPlaceholderRule#getTag()
+ * @since {@link WindowExtensions#VENDOR_API_LEVEL_2}
+ */
+ @NonNull
+ public Builder setTag(@NonNull String tag) {
+ mTag = Objects.requireNonNull(tag);
+ return this;
+ }
+
/** Builds a new instance of {@link SplitPlaceholderRule}. */
@NonNull
public SplitPlaceholderRule build() {
- return new SplitPlaceholderRule(mPlaceholderIntent, mSplitRatio,
- mLayoutDirection, mIsSticky, mFinishPrimaryWithPlaceholder, mActivityPredicate,
- mIntentPredicate, mParentWindowMetricsPredicate);
+ // To provide compatibility with prior version of WM Jetpack library, where
+ // #setDefaultAttributes hasn't yet been supported and thus would not be set.
+ mDefaultSplitAttributes = (mDefaultSplitAttributes != null)
+ ? mDefaultSplitAttributes
+ : new SplitAttributes.Builder()
+ .setSplitType(createSplitTypeFromLegacySplitRatio(mSplitRatio))
+ .setLayoutDirection(mLayoutDirection)
+ .build();
+ return new SplitPlaceholderRule(mPlaceholderIntent, mDefaultSplitAttributes, mIsSticky,
+ mFinishPrimaryWithPlaceholder, mActivityPredicate,
+ mIntentPredicate, mParentWindowMetricsPredicate, mTag);
}
}
@@ -237,7 +336,9 @@
@Override
public String toString() {
return "SplitPlaceholderRule{"
- + "mActivityPredicate=" + mActivityPredicate
+ + "mTag=" + getTag()
+ + ", mDefaultSplitAttributes=" + getDefaultSplitAttributes()
+ + ", mActivityPredicate=" + mActivityPredicate
+ ", mIsSticky=" + mIsSticky
+ ", mFinishPrimaryWithPlaceholder=" + mFinishPrimaryWithPlaceholder
+ '}';
diff --git a/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/SplitRule.java b/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/SplitRule.java
index bb24318..a1be65d 100644
--- a/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/SplitRule.java
+++ b/window/extensions/extensions/src/main/java/androidx/window/extensions/embedding/SplitRule.java
@@ -16,39 +16,36 @@
package androidx.window.extensions.embedding;
-import static android.util.LayoutDirection.LOCALE;
-import static android.util.LayoutDirection.LTR;
-import static android.util.LayoutDirection.RTL;
-
import android.annotation.SuppressLint;
import android.os.Build;
import android.view.WindowMetrics;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
+import androidx.window.extensions.WindowExtensions;
+import androidx.window.extensions.core.util.function.Predicate;
+import androidx.window.extensions.embedding.SplitAttributes.SplitType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
-import java.util.function.Predicate;
+import java.util.Objects;
/**
* Split configuration rules for activities that are launched to side in a split. Define when an
* activity that was launched in a side container from another activity should be shown
- * side-by-side or on top of it, as well as the visual properties of the split. Can be applied to
+ * adjacent or on top of it, as well as the visual properties of the split. Can be applied to
* new activities started from the same process automatically by the embedding implementation on
* the device.
*/
public abstract class SplitRule extends EmbeddingRule {
@NonNull
private final Predicate<WindowMetrics> mParentWindowMetricsPredicate;
- private final float mSplitRatio;
- @LayoutDirection
- private final int mLayoutDirection;
- @IntDef({LTR, RTL, LOCALE})
- @Retention(RetentionPolicy.SOURCE)
- @interface LayoutDirection {}
+ @NonNull
+ private final SplitAttributes mDefaultSplitAttributes;
+
/**
* Never finish the associated container.
* @see SplitFinishBehavior
@@ -60,9 +57,8 @@
*/
public static final int FINISH_ALWAYS = 1;
/**
- * Only finish the associated container when displayed side-by-side/adjacent to the one
- * being finished. Does not finish the associated one when containers are stacked on top of
- * each other.
+ * Only finish the associated container when displayed adjacent to the one being finished. Does
+ * not finish the associated one when containers are stacked on top of each other.
* @see SplitFinishBehavior
*/
public static final int FINISH_ADJACENT = 2;
@@ -73,7 +69,7 @@
* <p>
* For example, given that {@link SplitPairRule#getFinishPrimaryWithSecondary()} is
* {@link #FINISH_ADJACENT} and secondary container finishes. The primary associated
- * container is finished if it's side-by-side with secondary container. The primary
+ * container is finished if it's shown adjacent to the secondary container. The primary
* associated container is not finished if it occupies entire task bounds.</p>
*
* @see SplitPairRule#getFinishPrimaryWithSecondary()
@@ -88,15 +84,24 @@
@Retention(RetentionPolicy.SOURCE)
@interface SplitFinishBehavior {}
- SplitRule(@NonNull Predicate<WindowMetrics> parentWindowMetricsPredicate, float splitRatio,
- @LayoutDirection int layoutDirection) {
+ SplitRule(@NonNull Predicate<WindowMetrics> parentWindowMetricsPredicate,
+ @NonNull SplitAttributes defaultSplitAttributes, @Nullable String tag) {
+ super(tag);
mParentWindowMetricsPredicate = parentWindowMetricsPredicate;
- mSplitRatio = splitRatio;
- mLayoutDirection = layoutDirection;
+ mDefaultSplitAttributes = defaultSplitAttributes;
}
/**
- * Verifies if the provided parent bounds allow to show the split containers side by side.
+ * Checks whether the parent window satisfied the dimensions and aspect ratios requirements
+ * specified in the {@link androidx.window.embedding.SplitRule}, which are
+ * {@link androidx.window.embedding.SplitRule#minWidthDp},
+ * {@link androidx.window.embedding.SplitRule#minHeightDp},
+ * {@link androidx.window.embedding.SplitRule#minSmallestWidthDp},
+ * {@link androidx.window.embedding.SplitRule#maxAspectRatioInPortrait} and
+ * {@link androidx.window.embedding.SplitRule#maxAspectRatioInLandscape}.
+ *
+ * @param parentMetrics the {@link WindowMetrics} of the parent window.
+ * @return whether the parent window satisfied the {@link SplitRule} requirements.
*/
@SuppressLint("ClassVerificationFailure") // Only called by Extensions implementation on device.
@RequiresApi(api = Build.VERSION_CODES.N)
@@ -104,13 +109,43 @@
return mParentWindowMetricsPredicate.test(parentMetrics);
}
+ /**
+ * @deprecated Use {@link #getDefaultSplitAttributes()} instead starting with
+ * {@link WindowExtensions#VENDOR_API_LEVEL_2}. Only used if
+ * {@link #getDefaultSplitAttributes()} can't be called on
+ * {@link WindowExtensions#VENDOR_API_LEVEL_1}.
+ */
+ @Deprecated
public float getSplitRatio() {
- return mSplitRatio;
+ final SplitType splitType = mDefaultSplitAttributes.getSplitType();
+ if (splitType instanceof SplitType.RatioSplitType) {
+ return ((SplitType.RatioSplitType) splitType).getRatio();
+ } else { // Fallback to use 0.0 because the WM Jetpack may not support HingeSplitType.
+ return 0.0f;
+ }
}
- @LayoutDirection
+ /**
+ * @deprecated Use {@link #getDefaultSplitAttributes()} instead starting with
+ * {@link WindowExtensions#VENDOR_API_LEVEL_2}. Only used if
+ * {@link #getDefaultSplitAttributes()} can't be called on
+ * {@link WindowExtensions#VENDOR_API_LEVEL_1}.
+ */
+ @Deprecated
+ @SplitAttributes.ExtLayoutDirection
public int getLayoutDirection() {
- return mLayoutDirection;
+ return mDefaultSplitAttributes.getLayoutDirection();
+ }
+
+ /**
+ * Returns the default {@link SplitAttributes} which is applied if
+ * {@link #checkParentMetrics(WindowMetrics)} is {@code true}.
+ *
+ * @since {@link WindowExtensions#VENDOR_API_LEVEL_2}
+ */
+ @NonNull
+ public SplitAttributes getDefaultSplitAttributes() {
+ return mDefaultSplitAttributes;
}
@Override
@@ -118,16 +153,16 @@
if (this == o) return true;
if (!(o instanceof SplitRule)) return false;
SplitRule that = (SplitRule) o;
- return Float.compare(that.mSplitRatio, mSplitRatio) == 0
- && mParentWindowMetricsPredicate.equals(that.mParentWindowMetricsPredicate)
- && mLayoutDirection == that.mLayoutDirection;
+ return super.equals(that)
+ && mDefaultSplitAttributes.equals(that.mDefaultSplitAttributes)
+ && mParentWindowMetricsPredicate.equals(that.mParentWindowMetricsPredicate);
}
@Override
public int hashCode() {
- int result = (int) (mSplitRatio * 17);
+ int result = super.hashCode();
result = 31 * result + mParentWindowMetricsPredicate.hashCode();
- result = 31 * result + mLayoutDirection;
+ result = 31 * result + Objects.hashCode(mDefaultSplitAttributes);
return result;
}
@@ -135,8 +170,8 @@
@Override
public String toString() {
return "SplitRule{"
- + "mSplitRatio=" + mSplitRatio
- + ", mLayoutDirection=" + mLayoutDirection
+ + "mTag=" + getTag()
+ + ", mDefaultSplitAttributes=" + mDefaultSplitAttributes
+ '}';
}
}
diff --git a/window/extensions/extensions/src/main/java/androidx/window/extensions/layout/WindowLayoutComponent.java b/window/extensions/extensions/src/main/java/androidx/window/extensions/layout/WindowLayoutComponent.java
index 3b6dd1a..10c7831 100644
--- a/window/extensions/extensions/src/main/java/androidx/window/extensions/layout/WindowLayoutComponent.java
+++ b/window/extensions/extensions/src/main/java/androidx/window/extensions/layout/WindowLayoutComponent.java
@@ -17,18 +17,19 @@
package androidx.window.extensions.layout;
import android.app.Activity;
+import android.content.Context;
import androidx.annotation.NonNull;
+import androidx.annotation.UiContext;
import androidx.window.extensions.WindowExtensions;
-
-import java.util.function.Consumer;
+import androidx.window.extensions.core.util.function.Consumer;
/**
* The interface definition that will be used by the WindowManager library to get custom
* OEM-provided information about the window that isn't covered by platform APIs. Exposes methods
* to listen to changes in the {@link WindowLayoutInfo}. A {@link WindowLayoutInfo} contains a list
* of {@link DisplayFeature}s.
- *
+ * <p>
* Currently {@link FoldingFeature} is the only {@link DisplayFeature}. A {@link FoldingFeature}
* exposes the state of a hinge and the relative bounds within the window. Developers can
* optimize their UI to support a {@link FoldingFeature} by avoiding it and placing content in
@@ -38,19 +39,70 @@
* @see WindowExtensions#getWindowLayoutComponent()
*/
public interface WindowLayoutComponent {
+ /**
+ * @deprecated Use {@link #addWindowLayoutInfoListener(Context,Consumer)}
+ * starting with {@link WindowExtensions#VENDOR_API_LEVEL_2}. Only used if
+ * {@link #addWindowLayoutInfoListener(Context, Consumer)} can't be
+ * called on {@link WindowExtensions#VENDOR_API_LEVEL_1}.
+ */
+ @Deprecated
+ void addWindowLayoutInfoListener(@NonNull Activity activity,
+ @NonNull java.util.function.Consumer<WindowLayoutInfo> consumer);
/**
- * Adds a listener interested in receiving updates to {@link WindowLayoutInfo}
- * @param activity hosting a {@link android.view.Window}
- * @param consumer interested in receiving updates to {@link WindowLayoutInfo}
+ * @deprecated Use {@link #removeWindowLayoutInfoListener(Consumer)} starting with
+ * {@link WindowExtensions#VENDOR_API_LEVEL_2}. Only used if
+ * {@link #removeWindowLayoutInfoListener(Consumer)} can't be called on
+ * {@link WindowExtensions#VENDOR_API_LEVEL_1}.
*/
- void addWindowLayoutInfoListener(@NonNull Activity activity,
- @NonNull Consumer<WindowLayoutInfo> consumer);
+ @Deprecated
+ void removeWindowLayoutInfoListener(
+ @NonNull java.util.function.Consumer<WindowLayoutInfo> consumer);
+
+ // TODO(b/264546746): Remove addWindowLayoutInfoListener(Context, java.util.function.Consumer)
+ // after apps update to the latest WM Jetpack library.
+ /** @deprecated Use {@link #addWindowLayoutInfoListener(Context, Consumer)} instead */
+ @SuppressWarnings("PairedRegistration")
+ // The paired method for unregistering is also removeWindowLayoutInfoListener.
+ @Deprecated
+ default void addWindowLayoutInfoListener(@NonNull @UiContext Context context,
+ @NonNull java.util.function.Consumer<WindowLayoutInfo> consumer) {
+ throw new UnsupportedOperationException("This method must not be called unless there is a"
+ + " corresponding override implementation on the device.");
+ }
+
+ /**
+ * Adds a listener interested in receiving updates to {@link WindowLayoutInfo}.
+ * Use {@link WindowLayoutComponent#removeWindowLayoutInfoListener} to remove listener.
+ * <p>
+ * A {@link Context} or a Consumer instance can only be registered once.
+ * Registering the same {@link Context} or Consumer more than once will result in
+ * a noop.
+ *
+ * @param context a {@link UiContext} that corresponds to a window or an area on the
+ * screen - an {@link Activity}, a {@link Context} created with
+ * {@link Context#createWindowContext(Display, int , Bundle)}, or
+ * {@link android.inputmethodservice.InputMethodService}.
+ * @param consumer interested in receiving updates to {@link WindowLayoutInfo}
+ * @since {@link WindowExtensions#VENDOR_API_LEVEL_2}
+ */
+ // TODO(b/238905747): Add api guard for extensions.
+ @SuppressWarnings("PairedRegistration")
+ // The paired method for unregistering is also removeWindowLayoutInfoListener.
+ default void addWindowLayoutInfoListener(@NonNull @UiContext Context context,
+ @NonNull Consumer<WindowLayoutInfo> consumer) {
+ throw new UnsupportedOperationException("This method must not be called unless there is a"
+ + " corresponding override implementation on the device.");
+ }
/**
* Removes a listener no longer interested in receiving updates.
+ *
* @param consumer no longer interested in receiving updates to {@link WindowLayoutInfo}
+ * @since {@link WindowExtensions#VENDOR_API_LEVEL_2}
*/
- void removeWindowLayoutInfoListener(
- @NonNull Consumer<WindowLayoutInfo> consumer);
+ default void removeWindowLayoutInfoListener(@NonNull Consumer<WindowLayoutInfo> consumer) {
+ throw new UnsupportedOperationException("This method must not be called unless there is a"
+ + " corresponding override implementation on the device.");
+ }
}
diff --git a/window/extensions/extensions/src/test/java/androidx/window/extensions/embedding/SplitAttributesTest.java b/window/extensions/extensions/src/test/java/androidx/window/extensions/embedding/SplitAttributesTest.java
new file mode 100644
index 0000000..76a1107
--- /dev/null
+++ b/window/extensions/extensions/src/test/java/androidx/window/extensions/embedding/SplitAttributesTest.java
@@ -0,0 +1,104 @@
+/*
+ * 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 androidx.window.extensions.embedding;
+
+import static androidx.window.extensions.embedding.SplitAttributes.SplitType.RatioSplitType.splitEqually;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+
+import android.graphics.Color;
+
+import androidx.test.filters.SmallTest;
+import androidx.window.extensions.embedding.SplitAttributes.LayoutDirection;
+
+import org.junit.Test;
+
+/** Test for {@link SplitAttributes} */
+@SmallTest
+public class SplitAttributesTest {
+ @Test
+ public void testSplitAttributesEquals() {
+ final SplitAttributes layout1 = new SplitAttributes.Builder()
+ .setSplitType(splitEqually())
+ .setLayoutDirection(LayoutDirection.LOCALE)
+ .setAnimationBackgroundColor(0)
+ .build();
+ final SplitAttributes layout2 = new SplitAttributes.Builder()
+ .setSplitType(new SplitAttributes.SplitType.HingeSplitType(splitEqually()))
+ .setLayoutDirection(LayoutDirection.LOCALE)
+ .setAnimationBackgroundColor(0)
+ .build();
+ final SplitAttributes layout3 = new SplitAttributes.Builder()
+ .setSplitType(new SplitAttributes.SplitType.HingeSplitType(splitEqually()))
+ .setLayoutDirection(LayoutDirection.TOP_TO_BOTTOM)
+ .setAnimationBackgroundColor(0)
+ .build();
+ final SplitAttributes layout4 = new SplitAttributes.Builder()
+ .setSplitType(new SplitAttributes.SplitType.HingeSplitType(splitEqually()))
+ .setLayoutDirection(LayoutDirection.TOP_TO_BOTTOM)
+ .setAnimationBackgroundColor(Color.BLUE)
+ .build();
+ final SplitAttributes layout5 = new SplitAttributes.Builder()
+ .setSplitType(new SplitAttributes.SplitType.HingeSplitType(splitEqually()))
+ .setLayoutDirection(LayoutDirection.TOP_TO_BOTTOM)
+ .setAnimationBackgroundColor(Color.BLUE)
+ .build();
+
+ assertNotEquals(layout1, layout2);
+ assertNotEquals(layout1.hashCode(), layout2.hashCode());
+
+ assertNotEquals(layout2, layout3);
+ assertNotEquals(layout2.hashCode(), layout3.hashCode());
+
+ assertNotEquals(layout3, layout1);
+ assertNotEquals(layout3.hashCode(), layout1.hashCode());
+
+ assertNotEquals(layout4, layout3);
+ assertNotEquals(layout4.hashCode(), layout3.hashCode());
+
+ assertEquals(layout4, layout5);
+ assertEquals(layout4.hashCode(), layout5.hashCode());
+ }
+
+ @Test
+ public void testSplitTypeEquals() {
+ final SplitAttributes.SplitType[] splitTypes = new SplitAttributes.SplitType[]{
+ new SplitAttributes.SplitType.ExpandContainersSplitType(),
+ new SplitAttributes.SplitType.RatioSplitType(0.3f),
+ splitEqually(),
+ new SplitAttributes.SplitType.HingeSplitType(splitEqually()),
+ new SplitAttributes.SplitType.HingeSplitType(
+ new SplitAttributes.SplitType.ExpandContainersSplitType()
+ ),
+ };
+
+ for (int i = 0; i < splitTypes.length; i++) {
+ for (int j = 0; j < splitTypes.length; j++) {
+ final SplitAttributes.SplitType splitType0 = splitTypes[i];
+ final SplitAttributes.SplitType splitType1 = splitTypes[j];
+ if (i == j) {
+ assertEquals(splitType0, splitType1);
+ assertEquals(splitType0.hashCode(), splitType1.hashCode());
+ } else {
+ assertNotEquals(splitType0, splitType1);
+ assertNotEquals(splitType0.hashCode(), splitType1.hashCode());
+ }
+ }
+ }
+ }
+}
diff --git a/window/window-samples/build.gradle b/window/window-demos/demo-common/build.gradle
similarity index 61%
copy from window/window-samples/build.gradle
copy to window/window-demos/demo-common/build.gradle
index 99cf856..fd30ac1 100644
--- a/window/window-samples/build.gradle
+++ b/window/window-demos/demo-common/build.gradle
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 The Android Open Source Project
+ * 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.
@@ -14,28 +14,24 @@
* limitations under the License.
*/
-import androidx.build.Publish
-import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
-
plugins {
id("AndroidXPlugin")
- id("com.android.application")
- id("org.jetbrains.kotlin.android")
+ id("com.android.library")
+ id("kotlin-android")
}
android {
defaultConfig {
- applicationId "androidx.window.sample"
minSdkVersion 23
}
buildFeatures {
viewBinding true
}
- namespace "androidx.window.sample"
+ namespace "androidx.window.demo.common"
}
dependencies {
- implementation("androidx.appcompat:appcompat:1.5.1")
+ implementation("androidx.appcompat:appcompat:1.2.0")
implementation("androidx.core:core-ktx:1.3.2")
implementation("androidx.activity:activity:1.2.0")
implementation "androidx.recyclerview:recyclerview:1.2.1"
@@ -48,18 +44,4 @@
implementation(project(":window:window-java"))
debugImplementation(libs.leakcanary)
-
- androidTestImplementation(libs.testCore)
- androidTestImplementation(libs.testExtJunit)
- androidTestImplementation(libs.testRunner)
- androidTestImplementation(libs.testRules)
- androidTestImplementation(libs.espressoCore, excludes.espresso)
- androidTestImplementation(project(":window:window-testing"))
-}
-
-androidx {
- name = "Jetpack WindowManager library samples"
- publish = Publish.NONE
- inceptionYear = "2020"
- description = "Demo of Jetpack WindowManager library APIs"
}
diff --git a/window/window-demos/demo-common/src/main/AndroidManifest.xml b/window/window-demos/demo-common/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..134b96c
--- /dev/null
+++ b/window/window-demos/demo-common/src/main/AndroidManifest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ 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.
+ -->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <application
+ android:supportsRtl="true"
+ android:theme="@style/AppTheme">
+ <activity
+ android:name=".DisplayFeaturesActivity"
+ android:exported="true"
+ android:supportsPictureInPicture="true"
+ android:configChanges=
+ "orientation|screenSize|screenLayout|screenSize|layoutDirection|smallestScreenSize"
+ android:allowUntrustedActivityEmbedding="true"
+ android:label="@string/display_features_config_change" />
+ </application>
+</manifest>
diff --git a/window/window-samples/src/main/java/androidx/window/sample/DisplayFeaturesNoConfigChangeActivity.kt b/window/window-demos/demo-common/src/main/java/androidx/window/demo/common/DisplayFeaturesActivity.kt
similarity index 85%
rename from window/window-samples/src/main/java/androidx/window/sample/DisplayFeaturesNoConfigChangeActivity.kt
rename to window/window-demos/demo-common/src/main/java/androidx/window/demo/common/DisplayFeaturesActivity.kt
index 729ceb3..1126232 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/DisplayFeaturesNoConfigChangeActivity.kt
+++ b/window/window-demos/demo-common/src/main/java/androidx/window/demo/common/DisplayFeaturesActivity.kt
@@ -1,5 +1,5 @@
/*
- * Copyright 2021 The Android Open Source Project
+ * 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.
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package androidx.window.sample
+package androidx.window.demo.common
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
@@ -25,31 +25,33 @@
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
+import androidx.recyclerview.widget.RecyclerView
+import androidx.window.demo.common.databinding.ActivityDisplayFeaturesConfigChangeBinding
+import androidx.window.demo.common.infolog.InfoLogAdapter
+import androidx.window.demo.common.util.PictureInPictureUtil.appendPictureInPictureMenu
+import androidx.window.demo.common.util.PictureInPictureUtil.handlePictureInPictureMenuItem
import androidx.window.layout.FoldingFeature
import androidx.window.layout.WindowInfoTracker
import androidx.window.layout.WindowLayoutInfo
-import androidx.window.sample.databinding.ActivityDisplayFeaturesNoConfigChangeBinding
-import androidx.window.sample.infolog.InfoLogAdapter
-import androidx.window.sample.util.PictureInPictureUtil.appendPictureInPictureMenu
-import androidx.window.sample.util.PictureInPictureUtil.handlePictureInPictureMenuItem
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.launch
-class DisplayFeaturesNoConfigChangeActivity : AppCompatActivity() {
+/** Demo activity that shows all display features and current device state on the screen. */
+open class DisplayFeaturesActivity : AppCompatActivity() {
private val infoLogAdapter = InfoLogAdapter()
private val displayFeatureViews = ArrayList<View>()
- private lateinit var binding: ActivityDisplayFeaturesNoConfigChangeBinding
+ private lateinit var binding: ActivityDisplayFeaturesConfigChangeBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
- binding = ActivityDisplayFeaturesNoConfigChangeBinding.inflate(layoutInflater)
+ binding = ActivityDisplayFeaturesConfigChangeBinding.inflate(layoutInflater)
setContentView(binding.root)
- val recyclerView = binding.infoLogRecyclerView
+ val recyclerView = findViewById<RecyclerView>(R.id.infoLogRecyclerView)
recyclerView.adapter = infoLogAdapter
lifecycleScope.launch(Dispatchers.Main) {
@@ -59,8 +61,8 @@
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
// Safely collect from windowInfoRepo when the lifecycle is STARTED
// and stops collection when the lifecycle is STOPPED
- WindowInfoTracker.getOrCreate(this@DisplayFeaturesNoConfigChangeActivity)
- .windowLayoutInfo(this@DisplayFeaturesNoConfigChangeActivity)
+ WindowInfoTracker.getOrCreate(this@DisplayFeaturesActivity)
+ .windowLayoutInfo(this@DisplayFeaturesActivity)
.collect { newLayoutInfo ->
// New posture information
updateStateLog(newLayoutInfo)
diff --git a/window/window-samples/src/main/java/androidx/window/sample/SampleTools.kt b/window/window-demos/demo-common/src/main/java/androidx/window/demo/common/SampleTools.kt
similarity index 95%
rename from window/window-samples/src/main/java/androidx/window/sample/SampleTools.kt
rename to window/window-demos/demo-common/src/main/java/androidx/window/demo/common/SampleTools.kt
index b7c3a4d..ff88b99 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/SampleTools.kt
+++ b/window/window-demos/demo-common/src/main/java/androidx/window/demo/common/SampleTools.kt
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 The Android Open Source Project
+ * 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.
@@ -13,7 +13,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package androidx.window.sample
+package androidx.window.demo.common
+
import android.graphics.Rect
import android.view.View
import android.widget.FrameLayout
diff --git a/window/window-samples/src/main/java/androidx/window/sample/infolog/InfoLog.kt b/window/window-demos/demo-common/src/main/java/androidx/window/demo/common/infolog/InfoLog.kt
similarity index 89%
rename from window/window-samples/src/main/java/androidx/window/sample/infolog/InfoLog.kt
rename to window/window-demos/demo-common/src/main/java/androidx/window/demo/common/infolog/InfoLog.kt
index e69a77b..3ab4096 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/infolog/InfoLog.kt
+++ b/window/window-demos/demo-common/src/main/java/androidx/window/demo/common/infolog/InfoLog.kt
@@ -1,5 +1,5 @@
/*
- * Copyright 2021 The Android Open Source Project
+ * 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.
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package androidx.window.sample.infolog
+package androidx.window.demo.common.infolog
/**
* A data class to hold a title and a detail or subtitle that can be shown using [InfoLogAdapter]
diff --git a/window/window-samples/src/main/java/androidx/window/sample/infolog/InfoLogAdapter.kt b/window/window-demos/demo-common/src/main/java/androidx/window/demo/common/infolog/InfoLogAdapter.kt
similarity index 82%
rename from window/window-samples/src/main/java/androidx/window/sample/infolog/InfoLogAdapter.kt
rename to window/window-demos/demo-common/src/main/java/androidx/window/demo/common/infolog/InfoLogAdapter.kt
index 29fefd6..81df057 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/infolog/InfoLogAdapter.kt
+++ b/window/window-demos/demo-common/src/main/java/androidx/window/demo/common/infolog/InfoLogAdapter.kt
@@ -1,5 +1,5 @@
/*
- * Copyright 2021 The Android Open Source Project
+ * 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.
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-package androidx.window.sample.infolog
+package androidx.window.demo.common.infolog
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
-import androidx.window.sample.R
+import androidx.window.demo.common.R
class InfoLogAdapter : RecyclerView.Adapter<InfoLogVH>() {
@@ -34,14 +34,19 @@
override fun onBindViewHolder(holder: InfoLogVH, position: Int) {
val item = items[position]
- holder.titleView.text = "ID: ${item.id} Title: ${item.title}"
- holder.detailView.text = "Detail: ${item.detail}"
+ holder.titleView.text = "[ID${item.id}] ${item.title}"
+ holder.detailView.text = item.detail
}
override fun getItemCount(): Int {
return items.size
}
+ fun clear() {
+ items.clear()
+ id = 0
+ }
+
fun append(title: String, message: String) {
append(InfoLog(title, message, id))
++id
diff --git a/window/window-samples/src/main/java/androidx/window/sample/infolog/InfoLogVH.kt b/window/window-demos/demo-common/src/main/java/androidx/window/demo/common/infolog/InfoLogVH.kt
similarity index 86%
rename from window/window-samples/src/main/java/androidx/window/sample/infolog/InfoLogVH.kt
rename to window/window-demos/demo-common/src/main/java/androidx/window/demo/common/infolog/InfoLogVH.kt
index 4760be2..1bf7dfe 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/infolog/InfoLogVH.kt
+++ b/window/window-demos/demo-common/src/main/java/androidx/window/demo/common/infolog/InfoLogVH.kt
@@ -1,5 +1,5 @@
/*
- * Copyright 2021 The Android Open Source Project
+ * 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.
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-package androidx.window.sample.infolog
+package androidx.window.demo.common.infolog
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
-import androidx.window.sample.R
+import androidx.window.demo.common.R
class InfoLogVH(view: View) : RecyclerView.ViewHolder(view) {
val titleView: TextView = view.findViewById(R.id.title_view)
diff --git a/window/window-samples/src/main/java/androidx/window/sample/util/PictureInPictureUtil.kt b/window/window-demos/demo-common/src/main/java/androidx/window/demo/common/util/PictureInPictureUtil.kt
similarity index 96%
rename from window/window-samples/src/main/java/androidx/window/sample/util/PictureInPictureUtil.kt
rename to window/window-demos/demo-common/src/main/java/androidx/window/demo/common/util/PictureInPictureUtil.kt
index 4f50715..70eedab 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/util/PictureInPictureUtil.kt
+++ b/window/window-demos/demo-common/src/main/java/androidx/window/demo/common/util/PictureInPictureUtil.kt
@@ -1,5 +1,5 @@
/*
- * Copyright 2021 The Android Open Source Project
+ * 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.
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package androidx.window.sample.util
+package androidx.window.demo.common.util
import android.app.Activity
import android.app.PictureInPictureParams
@@ -24,7 +24,7 @@
import android.view.MenuItem
import android.widget.Toast
import androidx.annotation.RequiresApi
-import androidx.window.sample.R
+import androidx.window.demo.common.R
@RequiresApi(Build.VERSION_CODES.O)
private object PictureInPictureLauncherO {
diff --git a/window/window-samples/src/main/res/layout/activity_display_features_no_config_change.xml b/window/window-demos/demo-common/src/main/res/layout/activity_display_features_config_change.xml
similarity index 92%
rename from window/window-samples/src/main/res/layout/activity_display_features_no_config_change.xml
rename to window/window-demos/demo-common/src/main/res/layout/activity_display_features_config_change.xml
index 46ade36..419ab11 100644
--- a/window/window-samples/src/main/res/layout/activity_display_features_no_config_change.xml
+++ b/window/window-demos/demo-common/src/main/res/layout/activity_display_features_config_change.xml
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
- Copyright 2021 The Android Open Source Project
+ 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.
@@ -22,7 +22,7 @@
android:id="@+id/rootLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
- tools:context="androidx.window.sample.DisplayFeaturesNoConfigChangeActivity">
+ tools:context="androidx.window.demo.common.DisplayFeaturesActivity">
<FrameLayout
android:id="@+id/feature_container_layout"
@@ -38,7 +38,7 @@
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@string/current_state"
- android:textAppearance="@style/TextAppearance.AppCompat.Large"
+ android:textAppearance="@style/TextAppearance.AppCompat"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
@@ -87,7 +87,7 @@
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toBottomOf="@+id/current_state"
+ app:layout_constraintTop_toBottomOf="@id/current_state"
app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
\ No newline at end of file
diff --git a/window/window-samples/src/main/res/layout/view_holder_info_log.xml b/window/window-demos/demo-common/src/main/res/layout/view_holder_info_log.xml
similarity index 93%
rename from window/window-samples/src/main/res/layout/view_holder_info_log.xml
rename to window/window-demos/demo-common/src/main/res/layout/view_holder_info_log.xml
index 7487737..e7e20c1 100644
--- a/window/window-samples/src/main/res/layout/view_holder_info_log.xml
+++ b/window/window-demos/demo-common/src/main/res/layout/view_holder_info_log.xml
@@ -24,7 +24,8 @@
<TextView
android:id="@+id/title_view"
android:layout_width="wrap_content"
- android:layout_height="wrap_content"/>
+ android:layout_height="wrap_content"
+ android:textStyle="bold"/>
<TextView
android:id="@+id/detail_view"
diff --git a/window/window-samples/src/main/res/menu/picture_in_picture_menu.xml b/window/window-demos/demo-common/src/main/res/menu/picture_in_picture_menu.xml
similarity index 100%
copy from window/window-samples/src/main/res/menu/picture_in_picture_menu.xml
copy to window/window-demos/demo-common/src/main/res/menu/picture_in_picture_menu.xml
diff --git a/window/window-samples/src/main/res/values/colors.xml b/window/window-demos/demo-common/src/main/res/values/colors.xml
similarity index 85%
copy from window/window-samples/src/main/res/values/colors.xml
copy to window/window-demos/demo-common/src/main/res/values/colors.xml
index 41a72b2..be90b3af 100644
--- a/window/window-samples/src/main/res/values/colors.xml
+++ b/window/window-demos/demo-common/src/main/res/values/colors.xml
@@ -16,9 +16,9 @@
-->
<resources>
- <color name="colorPrimary">#6200EE</color>
- <color name="colorPrimaryDark">#3700B3</color>
- <color name="colorAccent">#03DAC5</color>
+ <color name="colorPrimary">#03A9F4</color>
+ <color name="colorPrimaryDark">#354395</color>
+ <color name="colorAccent">#009688</color>
<color name="colorFeatureFold">#7700FF00</color>
diff --git a/window/window-demos/demo-common/src/main/res/values/strings.xml b/window/window-demos/demo-common/src/main/res/values/strings.xml
new file mode 100644
index 0000000..aeb9f83
--- /dev/null
+++ b/window/window-demos/demo-common/src/main/res/values/strings.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ 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.
+ -->
+
+<resources>
+ <string name="trusted_embedding_activity">Trusted Embedding Activity</string>
+ <string name="trusted_embedding_activity_detail">Activity allows embedding in trusted mode via a
+ known certificate.</string>
+ <string name="untrusted_embedding_activity">Untrusted Embedding Activity</string>
+ <string name="untrusted_embedding_activity_detail">Activity allows embedding in untrusted mode
+ via opt-in.</string>
+ <string name="display_features_config_change">Display features handle config change</string>
+ <string name="fold">Fold</string>
+ <string name="legend">Legend:</string>
+ <string name="current_state">Current state</string>
+ <string name="window_layout">Window layout</string>
+ <string name="screens_are_separated">"Screens are separated"</string>
+ <string name="screens_are_not_separated">"Screen is not separated"</string>
+ <string name="screen_is_horizontal">"Hinge is horizontal"</string>
+ <string name="screen_is_vertical">"Hinge is vertical"</string>
+ <string name="occlusion_is_full">Full occlusion</string>
+ <string name="occlusion_is_none">No occlusion</string>
+</resources>
\ No newline at end of file
diff --git a/window/window-samples/src/main/res/values/styles.xml b/window/window-demos/demo-common/src/main/res/values/styles.xml
similarity index 94%
rename from window/window-samples/src/main/res/values/styles.xml
rename to window/window-demos/demo-common/src/main/res/values/styles.xml
index eaa9ab2..6f9733b 100644
--- a/window/window-samples/src/main/res/values/styles.xml
+++ b/window/window-demos/demo-common/src/main/res/values/styles.xml
@@ -1,5 +1,5 @@
<!--
- Copyright 2020 The Android Open Source Project
+ 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.
diff --git a/window/window-demos/demo-second-app/build.gradle b/window/window-demos/demo-second-app/build.gradle
new file mode 100644
index 0000000..6af138b
--- /dev/null
+++ b/window/window-demos/demo-second-app/build.gradle
@@ -0,0 +1,45 @@
+/*
+ * 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.
+ */
+
+plugins {
+ id("AndroidXPlugin")
+ id("com.android.application")
+ id("org.jetbrains.kotlin.android")
+}
+
+android {
+ defaultConfig {
+ applicationId "androidx.window.demo2"
+ minSdkVersion 23
+ }
+ buildFeatures {
+ viewBinding true
+ }
+ namespace "androidx.window.demo2"
+}
+
+dependencies {
+ implementation("androidx.activity:activity:1.2.0")
+ implementation("androidx.appcompat:appcompat:1.2.0")
+ api(libs.constraintLayout)
+ implementation("androidx.core:core-ktx:1.8.0")
+ // TODO(b/152245564) Conflicting dependencies cause IDE errors.
+ implementation("androidx.lifecycle:lifecycle-viewmodel:2.4.0-alpha02")
+ implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.4.0-alpha02")
+ implementation("androidx.recyclerview:recyclerview:1.2.1")
+ implementation(project(":window:window-java"))
+ implementation(project(":window:window-demos:demo-common"))
+}
diff --git a/window/window-demos/demo-second-app/src/main/AndroidManifest.xml b/window/window-demos/demo-second-app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..4d9f6c1
--- /dev/null
+++ b/window/window-demos/demo-second-app/src/main/AndroidManifest.xml
@@ -0,0 +1,53 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ 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.
+ -->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <application
+ android:label="Activity Embedding Sample"
+ android:supportsRtl="true">
+ <activity
+ android:name=".embedding.TrustedEmbeddingActivity"
+ android:exported="true"
+ android:label="@string/trusted_embedding_activity"
+ android:configChanges=
+ "orientation|screenSize|screenLayout|screenSize|layoutDirection|smallestScreenSize"
+ android:knownActivityEmbeddingCerts=
+ "6a8b96e278e58f62cfe3584022cec1d0527fcb85a9e5d2e1694eb0405be5b599">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+ <activity
+ android:name=".embedding.UntrustedEmbeddingActivity"
+ android:exported="true"
+ android:label="@string/untrusted_embedding_activity"
+ android:configChanges=
+ "orientation|screenSize|screenLayout|screenSize|layoutDirection|smallestScreenSize"
+ android:allowUntrustedActivityEmbedding="true">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+ <activity-alias
+ android:name="androidx.window.demo2.DisplayFeaturesActivity"
+ android:targetActivity="androidx.window.demo.common.DisplayFeaturesActivity"
+ android:exported="true">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity-alias>
+ </application>
+</manifest>
diff --git a/window/window-demos/demo-second-app/src/main/java/androidx/window/demo2/embedding/TrustedEmbeddingActivity.kt b/window/window-demos/demo-second-app/src/main/java/androidx/window/demo2/embedding/TrustedEmbeddingActivity.kt
new file mode 100644
index 0000000..bc2e7cd
--- /dev/null
+++ b/window/window-demos/demo-second-app/src/main/java/androidx/window/demo2/embedding/TrustedEmbeddingActivity.kt
@@ -0,0 +1,37 @@
+/*
+ * 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 androidx.window.demo2.embedding
+
+import android.app.Activity
+import android.os.Bundle
+import android.widget.TextView
+import androidx.window.demo2.R
+
+/**
+ * Activity that can be embedded by a process with a known certificate. See
+ * `android:allowUntrustedActivityEmbedding` in AndroidManifest. Activity can be launched from the
+ * split demos in window-samples/demos.
+ */
+class TrustedEmbeddingActivity : Activity() {
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_embedded)
+ findViewById<TextView>(R.id.detail_text_view).text =
+ getString(R.string.trusted_embedding_activity_detail)
+ }
+}
\ No newline at end of file
diff --git a/window/window-demos/demo-second-app/src/main/java/androidx/window/demo2/embedding/UntrustedEmbeddingActivity.kt b/window/window-demos/demo-second-app/src/main/java/androidx/window/demo2/embedding/UntrustedEmbeddingActivity.kt
new file mode 100644
index 0000000..f26aeee
--- /dev/null
+++ b/window/window-demos/demo-second-app/src/main/java/androidx/window/demo2/embedding/UntrustedEmbeddingActivity.kt
@@ -0,0 +1,37 @@
+/*
+ * 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 androidx.window.demo2.embedding
+
+import android.app.Activity
+import android.os.Bundle
+import android.widget.TextView
+import androidx.window.demo2.R
+
+/**
+ * Activity that can be embedded in untrusted mode. See
+ * `android:allowUntrustedActivityEmbedding` in AndroidManifest. Activity can be launched from
+ * the split demos in window-samples/demos.
+ */
+class UntrustedEmbeddingActivity : Activity() {
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_embedded)
+ findViewById<TextView>(R.id.detail_text_view).text =
+ getString(R.string.untrusted_embedding_activity_detail)
+ }
+}
\ No newline at end of file
diff --git a/window/window-samples/src/main/res/layout/test_ime.xml b/window/window-demos/demo-second-app/src/main/res/layout/activity_embedded.xml
similarity index 61%
rename from window/window-samples/src/main/res/layout/test_ime.xml
rename to window/window-demos/demo-second-app/src/main/res/layout/activity_embedded.xml
index feda1d7..fbd572c 100644
--- a/window/window-samples/src/main/res/layout/test_ime.xml
+++ b/window/window-demos/demo-second-app/src/main/res/layout/activity_embedded.xml
@@ -1,4 +1,5 @@
-<?xml version="1.0" encoding="utf-8"?><!--
+<?xml version="1.0" encoding="utf-8"?>
+<!--
Copyright 2022 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,15 +15,14 @@
limitations under the License.
-->
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
- android:layout_height="wrap_content">
+ android:layout_height="match_parent">
- <Button
- android:id="@+id/button_close"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="@string/test_ime_button_close"/>
+ <TextView
+ android:layout_gravity="center"
+ android:id="@+id/detail_text_view"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"/>
-</LinearLayout>
\ No newline at end of file
+</FrameLayout>
\ No newline at end of file
diff --git a/window/window-demos/demo-second-app/src/main/res/values/strings.xml b/window/window-demos/demo-second-app/src/main/res/values/strings.xml
new file mode 100644
index 0000000..de4172b
--- /dev/null
+++ b/window/window-demos/demo-second-app/src/main/res/values/strings.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ 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.
+ -->
+
+<resources>
+ <string name="trusted_embedding_activity">Trusted Embedding Activity</string>
+ <string name="trusted_embedding_activity_detail">Activity allows embedding in trusted mode via a
+ known certificate.</string>
+ <string name="untrusted_embedding_activity">Untrusted Embedding Activity</string>
+ <string name="untrusted_embedding_activity_detail">Activity allows embedding in untrusted mode
+ via opt-in.</string>
+</resources>
\ No newline at end of file
diff --git a/window/window-demos/demo/README.md b/window/window-demos/demo/README.md
new file mode 100644
index 0000000..f5f7378
--- /dev/null
+++ b/window/window-demos/demo/README.md
@@ -0,0 +1,6 @@
+# WindowManager Jetpack Demos
+
+The `keystore.jks` was generated using sample keys and certificates from Android AOSP. It is used to
+sign the demo app with a known key and showcase the usage of ActivityEmbedding APIs across apps
+for known certificates. See `build.gradle` for signing and
+`window-samples/demo-second-app` for the usage of the known certificate digest.
diff --git a/window/window-samples/build.gradle b/window/window-demos/demo/build.gradle
similarity index 71%
rename from window/window-samples/build.gradle
rename to window/window-demos/demo/build.gradle
index 99cf856..57c30e5 100644
--- a/window/window-samples/build.gradle
+++ b/window/window-demos/demo/build.gradle
@@ -14,7 +14,6 @@
* limitations under the License.
*/
-import androidx.build.Publish
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
@@ -25,13 +24,29 @@
android {
defaultConfig {
- applicationId "androidx.window.sample"
+ applicationId "androidx.window.demo"
minSdkVersion 23
}
buildFeatures {
viewBinding true
}
- namespace "androidx.window.sample"
+ namespace "androidx.window.demo"
+ signingConfigs {
+ config {
+ keyAlias 'alias'
+ keyPassword 'password'
+ storeFile file('keystore.jks')
+ storePassword 'password'
+ }
+ }
+ buildTypes {
+ release {
+ signingConfig signingConfigs.config
+ }
+ debug {
+ signingConfig signingConfigs.config
+ }
+ }
}
dependencies {
@@ -47,6 +62,7 @@
implementation("androidx.startup:startup-runtime:1.1.0")
implementation(project(":window:window-java"))
+ implementation(project(":window:window-demos:demo-common"))
debugImplementation(libs.leakcanary)
androidTestImplementation(libs.testCore)
@@ -55,11 +71,12 @@
androidTestImplementation(libs.testRules)
androidTestImplementation(libs.espressoCore, excludes.espresso)
androidTestImplementation(project(":window:window-testing"))
+ androidTestImplementation(project(":window:window-demos:demo-common"))
}
-androidx {
- name = "Jetpack WindowManager library samples"
- publish = Publish.NONE
- inceptionYear = "2020"
- description = "Demo of Jetpack WindowManager library APIs"
+// Allow usage of Kotlin's @OptIn.
+tasks.withType(KotlinCompile).configureEach {
+ kotlinOptions {
+ freeCompilerArgs += ["-opt-in=kotlin.RequiresOptIn"]
+ }
}
diff --git a/window/window-demos/demo/keystore.jks b/window/window-demos/demo/keystore.jks
new file mode 100644
index 0000000..35e18c9
--- /dev/null
+++ b/window/window-demos/demo/keystore.jks
Binary files differ
diff --git a/window/window-samples/src/androidTest/java/androidx/window/sample/DisplayFeaturesNoConfigChangeActivityTest.kt b/window/window-demos/demo/src/androidTest/java/androidx/window/demo/DisplayFeaturesNoConfigChangeActivityTest.kt
similarity index 98%
rename from window/window-samples/src/androidTest/java/androidx/window/sample/DisplayFeaturesNoConfigChangeActivityTest.kt
rename to window/window-demos/demo/src/androidTest/java/androidx/window/demo/DisplayFeaturesNoConfigChangeActivityTest.kt
index d0ff11b..53f1c78 100644
--- a/window/window-samples/src/androidTest/java/androidx/window/sample/DisplayFeaturesNoConfigChangeActivityTest.kt
+++ b/window/window-demos/demo/src/androidTest/java/androidx/window/demo/DisplayFeaturesNoConfigChangeActivityTest.kt
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package androidx.window.sample
+package androidx.window.demo
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.assertion.ViewAssertions.matches
diff --git a/window/window-samples/src/androidTest/java/androidx/window/sample/SplitLayoutActivityTest.kt b/window/window-demos/demo/src/androidTest/java/androidx/window/demo/SplitLayoutActivityTest.kt
similarity index 98%
rename from window/window-samples/src/androidTest/java/androidx/window/sample/SplitLayoutActivityTest.kt
rename to window/window-demos/demo/src/androidTest/java/androidx/window/demo/SplitLayoutActivityTest.kt
index f15e2ed..d3aa678d 100644
--- a/window/window-samples/src/androidTest/java/androidx/window/sample/SplitLayoutActivityTest.kt
+++ b/window/window-demos/demo/src/androidTest/java/androidx/window/demo/SplitLayoutActivityTest.kt
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package androidx.window.sample
+package androidx.window.demo
import android.graphics.Rect
import android.view.View
@@ -32,6 +32,7 @@
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
+import androidx.window.demo.common.adjustFeaturePositionOffset
import androidx.window.layout.FoldingFeature
import androidx.window.layout.FoldingFeature.Orientation.Companion.HORIZONTAL
import androidx.window.layout.FoldingFeature.Orientation.Companion.VERTICAL
diff --git a/window/window-samples/src/main/AndroidManifest.xml b/window/window-demos/demo/src/main/AndroidManifest.xml
similarity index 72%
rename from window/window-samples/src/main/AndroidManifest.xml
rename to window/window-demos/demo/src/main/AndroidManifest.xml
index 17431f8..e78433e 100644
--- a/window/window-samples/src/main/AndroidManifest.xml
+++ b/window/window-demos/demo/src/main/AndroidManifest.xml
@@ -19,7 +19,11 @@
android:supportsRtl="true"
android:theme="@style/AppTheme">
- <service android:name="androidx.window.sample.TestIme"
+ <property
+ android:name="android.window.PROPERTY_ACTIVITY_EMBEDDING_SPLITS_ENABLED"
+ android:value="true" />
+
+ <service android:name=".TestIme"
android:label="@string/test_ime"
android:permission="android.permission.BIND_INPUT_METHOD"
android:exported="true">
@@ -42,13 +46,6 @@
android:exported="false"
android:label="@string/presentation" />
<activity
- android:name=".DisplayFeaturesConfigChangeActivity"
- android:exported="false"
- android:supportsPictureInPicture="true"
- android:configChanges=
- "orientation|screenSize|screenLayout|screenSize|layoutDirection|smallestScreenSize"
- android:label="@string/display_features_config_change" />
- <activity
android:name=".DisplayFeaturesNoConfigChangeActivity"
android:exported="false"
android:supportsPictureInPicture="true"
@@ -61,12 +58,22 @@
android:exported="false"
android:configChanges="orientation|screenSize|screenLayout|screenSize"
android:label="@string/window_metrics"/>
+ <activity android:name=".RearDisplayActivityConfigChanges"
+ android:exported="true"
+ android:configChanges=
+ "orientation|screenLayout|screenSize|layoutDirection|smallestScreenSize"
+ android:label="@string/rear_display">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
<activity
android:name=".embedding.SplitActivityA"
android:exported="true"
android:label="Split Main"
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|colorMode|density|touchscreen"
- android:taskAffinity="androidx.window.sample.manual_split_affinity">
+ android:taskAffinity="androidx.window.demo.manual_split_affinity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
@@ -77,43 +84,50 @@
android:exported="false"
android:label="B"
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|colorMode|density|touchscreen"
- android:taskAffinity="androidx.window.sample.manual_split_affinity"/>
+ android:taskAffinity="androidx.window.demo.manual_split_affinity"/>
<activity
android:name=".embedding.SplitActivityC"
android:exported="false"
android:label="C"
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|colorMode|density|touchscreen"
- android:taskAffinity="androidx.window.sample.manual_split_affinity"/>
+ android:taskAffinity="androidx.window.demo.manual_split_affinity"/>
<activity
android:name=".embedding.SplitActivityD"
android:exported="false"
android:label="D"
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|colorMode|density|touchscreen"
- android:taskAffinity="androidx.window.sample.manual_split_affinity"/>
+ android:taskAffinity="androidx.window.demo.manual_split_affinity"/>
<activity
android:name=".embedding.SplitActivityE"
android:exported="false"
android:label="E"
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|colorMode|density|touchscreen"
- android:taskAffinity="androidx.window.sample.manual_split_affinity"/>
+ android:taskAffinity="androidx.window.demo.manual_split_affinity"/>
<activity
android:name=".embedding.SplitActivityF"
android:exported="false"
android:label="F"
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|colorMode|density|touchscreen"
- android:taskAffinity="androidx.window.sample.manual_split_affinity"/>
+ android:taskAffinity="androidx.window.demo.manual_split_affinity"/>
<activity
android:name=".embedding.SplitActivityPlaceholder"
android:exported="false"
android:label="Placeholder"
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|colorMode|density|touchscreen"
- android:taskAffinity="androidx.window.sample.manual_split_affinity"/>
+ android:taskAffinity="androidx.window.demo.manual_split_affinity"/>
+ <activity
+ android:name=".embedding.ExpandedDialogActivity"
+ android:theme="@style/ExpandedDialogTheme"
+ android:exported="false"
+ android:label="Dialog Activity"
+ android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|colorMode|density|touchscreen"
+ android:taskAffinity="androidx.window.demo.manual_split_affinity"/>
<activity
android:name=".embedding.SplitActivityTrampoline"
android:exported="true"
android:label="Split Trampoline"
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|colorMode|density|touchscreen"
- android:taskAffinity="androidx.window.sample.trampoline_affinity">
+ android:taskAffinity="androidx.window.demo.trampoline_affinity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
@@ -127,7 +141,7 @@
android:exported="true"
android:label="Split List"
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|colorMode|density|touchscreen"
- android:taskAffinity="androidx.window.sample.list_detail_split_affinity">
+ android:taskAffinity="androidx.window.demo.list_detail_split_affinity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
@@ -139,13 +153,13 @@
android:label="Item detail"
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|colorMode|density|touchscreen"
android:launchMode="singleTop"
- android:taskAffinity="androidx.window.sample.list_detail_split_affinity"/>
+ android:taskAffinity="androidx.window.demo.list_detail_split_affinity"/>
<activity
android:name=".embedding.SplitActivityListPlaceholder"
android:exported="false"
android:label="Placeholder"
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|colorMode|density|touchscreen"
- android:taskAffinity="androidx.window.sample.list_detail_split_affinity" />
+ android:taskAffinity="androidx.window.demo.list_detail_split_affinity" />
<!-- Split PiP App -->
@@ -155,7 +169,7 @@
android:label="Split and PiP"
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|colorMode|density|touchscreen"
android:supportsPictureInPicture="true"
- android:taskAffinity="androidx.window.sample.split_pip">
+ android:taskAffinity="androidx.window.demo.split_pip">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
@@ -167,21 +181,43 @@
android:label="PiP B"
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|colorMode|density|touchscreen"
android:supportsPictureInPicture="true"
- android:taskAffinity="androidx.window.sample.split_pip">
+ android:taskAffinity="androidx.window.demo.split_pip">
</activity>
<activity
android:name=".embedding.SplitPipActivityNoPip"
android:exported="false"
android:label="No PiP support"
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|colorMode|density|touchscreen"
- android:taskAffinity="androidx.window.sample.split_pip">
+ android:taskAffinity="androidx.window.demo.split_pip">
</activity>
<activity
android:name=".embedding.SplitPipActivityPlaceholder"
android:exported="false"
android:label="PiP Placeholder"
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|colorMode|density|touchscreen"
- android:taskAffinity="androidx.window.sample.split_pip">
+ android:taskAffinity="androidx.window.demo.split_pip">
+ </activity>
+
+ <!-- The demo App to show how to change the current split layout with the current device and
+ window states -->
+
+ <activity
+ android:name=".embedding.SplitDeviceStateActivityA"
+ android:exported="true"
+ android:label="Split on Device State"
+ android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|colorMode|density|touchscreen"
+ android:taskAffinity="androidx.window.demo.split_device_state_activity_affinity">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+ <activity
+ android:name=".embedding.SplitDeviceStateActivityB"
+ android:exported="true"
+ android:label="Split on Device State B"
+ android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|colorMode|density|touchscreen"
+ android:taskAffinity="androidx.window.demo.split_device_state_activity_affinity">
</activity>
<!-- The demo app that shows various IME-related use cases -->
@@ -198,7 +234,7 @@
android:exported="false"
tools:node="merge">
<!-- This entry makes ExampleWindowInitializer discoverable. -->
- <meta-data android:name="androidx.window.sample.embedding.ExampleWindowInitializer"
+ <meta-data android:name="androidx.window.demo.embedding.ExampleWindowInitializer"
android:value="androidx.startup" />
</provider>
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityListPlaceholder.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/DisplayFeaturesNoConfigChangeActivity.kt
similarity index 78%
copy from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityListPlaceholder.kt
copy to window/window-demos/demo/src/main/java/androidx/window/demo/DisplayFeaturesNoConfigChangeActivity.kt
index 754e11d8..bd77218 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityListPlaceholder.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/DisplayFeaturesNoConfigChangeActivity.kt
@@ -14,6 +14,8 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+package androidx.window.demo
-open class SplitActivityListPlaceholder : SplitActivityPlaceholder()
\ No newline at end of file
+import androidx.window.demo.common.DisplayFeaturesActivity
+
+class DisplayFeaturesNoConfigChangeActivity : DisplayFeaturesActivity()
\ No newline at end of file
diff --git a/window/window-samples/src/main/java/androidx/window/sample/ImeActivity.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/ImeActivity.kt
similarity index 97%
rename from window/window-samples/src/main/java/androidx/window/sample/ImeActivity.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/ImeActivity.kt
index 5ee6536..a31144d 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/ImeActivity.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/ImeActivity.kt
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package androidx.window.sample
+package androidx.window.demo
import android.content.Intent
import android.os.Bundle
diff --git a/window/window-samples/src/main/java/androidx/window/sample/PresentationActivity.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/PresentationActivity.kt
similarity index 99%
rename from window/window-samples/src/main/java/androidx/window/sample/PresentationActivity.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/PresentationActivity.kt
index d9001c8..5b4cb9c 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/PresentationActivity.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/PresentationActivity.kt
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package androidx.window.sample
+package androidx.window.demo
import android.app.Presentation
import android.content.Context
diff --git a/window/window-demos/demo/src/main/java/androidx/window/demo/RearDisplayActivityConfigChanges.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/RearDisplayActivityConfigChanges.kt
new file mode 100644
index 0000000..41c62be
--- /dev/null
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/RearDisplayActivityConfigChanges.kt
@@ -0,0 +1,136 @@
+/*
+ * Copyright 2021 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 androidx.window.demo
+
+import android.os.Bundle
+import androidx.appcompat.app.AppCompatActivity
+import androidx.core.content.ContextCompat
+import androidx.core.util.Consumer
+import androidx.window.area.WindowAreaController
+import androidx.window.area.WindowAreaSessionCallback
+import androidx.window.area.WindowAreaSession
+import androidx.window.area.WindowAreaStatus
+import androidx.window.core.ExperimentalWindowApi
+import androidx.window.java.area.WindowAreaControllerJavaAdapter
+import androidx.window.demo.databinding.ActivityRearDisplayBinding
+import androidx.window.demo.common.infolog.InfoLogAdapter
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+import java.util.concurrent.Executor
+
+/**
+ * Demo Activity that showcases listening for RearDisplay Status
+ * as well as enabling/disabling RearDisplay mode. This Activity
+ * implements [WindowAreaSessionCallback] for simplicity.
+ *
+ * This Activity overrides configuration changes for simplicity.
+ */
+@OptIn(ExperimentalWindowApi::class)
+class RearDisplayActivityConfigChanges : AppCompatActivity(), WindowAreaSessionCallback {
+
+ private lateinit var windowAreaController: WindowAreaControllerJavaAdapter
+ private var rearDisplaySession: WindowAreaSession? = null
+ private val infoLogAdapter = InfoLogAdapter()
+ private lateinit var binding: ActivityRearDisplayBinding
+ private lateinit var executor: Executor
+
+ private val rearDisplayStatusListener = Consumer<WindowAreaStatus> { status ->
+ infoLogAdapter.append(getCurrentTimeString(), status.toString())
+ infoLogAdapter.notifyDataSetChanged()
+ updateRearDisplayButton(status)
+ }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ binding = ActivityRearDisplayBinding.inflate(layoutInflater)
+ setContentView(binding.root)
+
+ executor = ContextCompat.getMainExecutor(this)
+ windowAreaController = WindowAreaControllerJavaAdapter(WindowAreaController.getOrCreate())
+
+ binding.rearStatusRecyclerView.adapter = infoLogAdapter
+
+ binding.rearDisplayButton.setOnClickListener {
+ if (rearDisplaySession != null) {
+ rearDisplaySession?.close()
+ } else {
+ windowAreaController.startRearDisplayModeSession(
+ this,
+ executor,
+ this)
+ }
+ }
+ }
+
+ override fun onStart() {
+ super.onStart()
+ windowAreaController.addRearDisplayStatusListener(
+ executor,
+ rearDisplayStatusListener
+ )
+ }
+
+ override fun onStop() {
+ super.onStop()
+ windowAreaController.removeRearDisplayStatusListener(rearDisplayStatusListener)
+ }
+
+ override fun onSessionStarted(session: WindowAreaSession) {
+ rearDisplaySession = session
+ infoLogAdapter.append(getCurrentTimeString(), "RearDisplay Session has been started")
+ infoLogAdapter.notifyDataSetChanged()
+ }
+
+ override fun onSessionEnded() {
+ rearDisplaySession = null
+ infoLogAdapter.append(getCurrentTimeString(), "RearDisplay Session has ended")
+ infoLogAdapter.notifyDataSetChanged()
+ }
+
+ private fun updateRearDisplayButton(status: WindowAreaStatus) {
+ if (rearDisplaySession != null) {
+ binding.rearDisplayButton.isEnabled = true
+ binding.rearDisplayButton.text = "Disable RearDisplay Mode"
+ return
+ }
+ when (status) {
+ WindowAreaStatus.UNSUPPORTED -> {
+ binding.rearDisplayButton.isEnabled = false
+ binding.rearDisplayButton.text = "RearDisplay is not supported on this device"
+ }
+ WindowAreaStatus.UNAVAILABLE -> {
+ binding.rearDisplayButton.isEnabled = false
+ binding.rearDisplayButton.text = "RearDisplay is not currently available"
+ }
+ WindowAreaStatus.AVAILABLE -> {
+ binding.rearDisplayButton.isEnabled = true
+ binding.rearDisplayButton.text = "Enable RearDisplay Mode"
+ }
+ }
+ }
+
+ private fun getCurrentTimeString(): String {
+ val sdf = SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault())
+ val currentDate = sdf.format(Date())
+ return currentDate.toString()
+ }
+
+ private companion object {
+ private val TAG = RearDisplayActivityConfigChanges::class.java.simpleName
+ }
+}
\ No newline at end of file
diff --git a/window/window-samples/src/main/java/androidx/window/sample/SplitLayout.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/SplitLayout.kt
similarity index 98%
rename from window/window-samples/src/main/java/androidx/window/sample/SplitLayout.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/SplitLayout.kt
index ca17b23..06ba0be 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/SplitLayout.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/SplitLayout.kt
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package androidx.window.sample
+package androidx.window.demo
import android.content.Context
import android.graphics.Rect
@@ -23,6 +23,7 @@
import android.view.View.MeasureSpec.AT_MOST
import android.view.View.MeasureSpec.EXACTLY
import android.widget.FrameLayout
+import androidx.window.demo.common.adjustFeaturePositionOffset
import androidx.window.layout.DisplayFeature
import androidx.window.layout.FoldingFeature
import androidx.window.layout.WindowLayoutInfo
diff --git a/window/window-samples/src/main/java/androidx/window/sample/SplitLayoutActivity.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/SplitLayoutActivity.kt
similarity index 98%
rename from window/window-samples/src/main/java/androidx/window/sample/SplitLayoutActivity.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/SplitLayoutActivity.kt
index 0bcdc5d..89290a9e 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/SplitLayoutActivity.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/SplitLayoutActivity.kt
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package androidx.window.sample
+package androidx.window.demo
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
diff --git a/window/window-demos/demo/src/main/java/androidx/window/demo/TestIme.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/TestIme.kt
new file mode 100644
index 0000000..a63b171
--- /dev/null
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/TestIme.kt
@@ -0,0 +1,93 @@
+/*
+ * 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 androidx.window.demo
+
+import android.inputmethodservice.InputMethodService
+import android.os.Build
+import android.view.View
+import android.view.inputmethod.InputMethodManager
+import android.widget.Button
+import androidx.core.view.WindowInsetsCompat.Type
+import androidx.recyclerview.widget.RecyclerView
+import androidx.window.core.ExperimentalWindowApi
+import androidx.window.demo.common.infolog.InfoLogAdapter
+import androidx.window.layout.WindowMetrics
+import androidx.window.layout.WindowMetricsCalculator
+
+/**
+ * A test IME that currently provides a minimal UI containing a "Close" button. To use this, go to
+ * "Settings > System > Languages & Input > On-screen keyboard" and enable "Test IME". Remember you
+ * may still need to switch to this IME after the default on-screen keyboard pops up.
+ */
+internal class TestIme : InputMethodService() {
+
+ private val adapter = InfoLogAdapter()
+
+ override fun onCreateInputView(): View {
+ return layoutInflater.inflate(R.layout.test_ime, null).apply {
+ findViewById<RecyclerView>(R.id.recycler_view).adapter = adapter
+
+ findViewById<Button>(R.id.button_clear).setOnClickListener {
+ adapter.clear()
+ adapter.notifyDataSetChanged()
+ }
+
+ findViewById<Button>(R.id.button_close).setOnClickListener {
+ requestHideSelf(InputMethodManager.HIDE_NOT_ALWAYS)
+ }
+
+ displayCurrentWindowMetrics()
+ displayMaximumWindowMetrics()
+ }
+ }
+
+ private fun displayCurrentWindowMetrics() {
+ val windowMetrics = WindowMetricsCalculator.getOrCreate()
+ .computeCurrentWindowMetrics(this@TestIme)
+ displayWindowMetrics("CurrentWindowMetrics update", windowMetrics)
+ }
+
+ private fun displayMaximumWindowMetrics() {
+ val windowMetrics = WindowMetricsCalculator.getOrCreate()
+ .computeMaximumWindowMetrics(this@TestIme)
+ displayWindowMetrics("MaximumWindowMetrics update", windowMetrics)
+ }
+
+ @OptIn(ExperimentalWindowApi::class)
+ private fun displayWindowMetrics(title: String, windowMetrics: WindowMetrics) {
+
+ val width = windowMetrics.bounds.width()
+ val height = windowMetrics.bounds.height()
+
+ val logBuilder = StringBuilder().append("Width: $width, Height: $height\n" +
+ "Top: ${windowMetrics.bounds.top}, Bottom: ${windowMetrics.bounds.bottom}, " +
+ "Left: ${windowMetrics.bounds.left}, Right: ${windowMetrics.bounds.right}")
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ val windowInsets = windowMetrics.getWindowInsets()
+ logBuilder.append("\nimeInset: ${windowInsets.getInsets(Type.ime())}")
+ logBuilder.append("\nnavInset: ${windowInsets.getInsets(Type.navigationBars())}")
+ logBuilder.append("\nstatusBarInset: ${windowInsets.getInsets(Type.statusBars())}")
+ }
+ adapter.append(title, logBuilder.toString())
+ adapter.notifyDataSetChanged()
+ }
+
+ override fun onEvaluateFullscreenMode(): Boolean {
+ return false
+ }
+}
\ No newline at end of file
diff --git a/window/window-samples/src/main/java/androidx/window/sample/WindowMetricsActivity.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/WindowMetricsActivity.kt
similarity index 94%
rename from window/window-samples/src/main/java/androidx/window/sample/WindowMetricsActivity.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/WindowMetricsActivity.kt
index 525648b..4b0faa7 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/WindowMetricsActivity.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/WindowMetricsActivity.kt
@@ -14,14 +14,14 @@
* limitations under the License.
*/
-package androidx.window.sample
+package androidx.window.demo
import android.content.res.Configuration
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import androidx.window.layout.WindowMetricsCalculator
-import androidx.window.sample.infolog.InfoLogAdapter
+import androidx.window.demo.common.infolog.InfoLogAdapter
class WindowMetricsActivity : AppCompatActivity() {
diff --git a/window/window-samples/src/main/java/androidx/window/sample/demos/DemoAdapter.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/demos/DemoAdapter.kt
similarity index 94%
rename from window/window-samples/src/main/java/androidx/window/sample/demos/DemoAdapter.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/demos/DemoAdapter.kt
index 8cb8aca..5bc46ae 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/demos/DemoAdapter.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/demos/DemoAdapter.kt
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-package androidx.window.sample.demos
+package androidx.window.demo.demos
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
-import androidx.window.sample.R
+import androidx.window.demo.R
class DemoAdapter(private val demoItems: List<DemoItem>) : RecyclerView.Adapter<DemoVH>() {
diff --git a/window/window-samples/src/main/java/androidx/window/sample/demos/DemoItem.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/demos/DemoItem.kt
similarity index 94%
rename from window/window-samples/src/main/java/androidx/window/sample/demos/DemoItem.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/demos/DemoItem.kt
index fb08562..88f3c65 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/demos/DemoItem.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/demos/DemoItem.kt
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package androidx.window.sample.demos
+package androidx.window.demo.demos
import android.app.Activity
diff --git a/window/window-samples/src/main/java/androidx/window/sample/demos/DemoVH.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/demos/DemoVH.kt
similarity index 94%
rename from window/window-samples/src/main/java/androidx/window/sample/demos/DemoVH.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/demos/DemoVH.kt
index 5c08cc1..d986288 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/demos/DemoVH.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/demos/DemoVH.kt
@@ -14,14 +14,14 @@
* limitations under the License.
*/
-package androidx.window.sample.demos
+package androidx.window.demo.demos
import android.content.Intent
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
-import androidx.window.sample.R
+import androidx.window.demo.R
class DemoVH(view: View) : RecyclerView.ViewHolder(view) {
private val description = view.findViewById<TextView>(R.id.demo_description)
diff --git a/window/window-samples/src/main/java/androidx/window/sample/demos/WindowDemosActivity.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/demos/WindowDemosActivity.kt
similarity index 76%
rename from window/window-samples/src/main/java/androidx/window/sample/demos/WindowDemosActivity.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/demos/WindowDemosActivity.kt
index dd2f206..19c0156 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/demos/WindowDemosActivity.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/demos/WindowDemosActivity.kt
@@ -14,22 +14,22 @@
* limitations under the License.
*/
-package androidx.window.sample.demos
+package androidx.window.demo.demos
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
-import androidx.window.sample.DisplayFeaturesConfigChangeActivity
-import androidx.window.sample.DisplayFeaturesNoConfigChangeActivity
-import androidx.window.sample.ImeActivity
-import androidx.window.sample.PresentationActivity
-import androidx.window.sample.R
-import androidx.window.sample.R.string.display_features_config_change
-import androidx.window.sample.R.string.display_features_no_config_change
-import androidx.window.sample.R.string.show_all_display_features_config_change_description
-import androidx.window.sample.R.string.show_all_display_features_no_config_change_description
-import androidx.window.sample.SplitLayoutActivity
-import androidx.window.sample.WindowMetricsActivity
+import androidx.window.demo.DisplayFeaturesNoConfigChangeActivity
+import androidx.window.demo.ImeActivity
+import androidx.window.demo.PresentationActivity
+import androidx.window.demo.R
+import androidx.window.demo.R.string.display_features_config_change
+import androidx.window.demo.R.string.display_features_no_config_change
+import androidx.window.demo.R.string.show_all_display_features_config_change_description
+import androidx.window.demo.R.string.show_all_display_features_no_config_change_description
+import androidx.window.demo.SplitLayoutActivity
+import androidx.window.demo.WindowMetricsActivity
+import androidx.window.demo.common.DisplayFeaturesActivity
/**
* Main activity that launches WindowManager demos.
@@ -43,7 +43,7 @@
DemoItem(
buttonTitle = getString(display_features_config_change),
description = getString(show_all_display_features_config_change_description),
- clazz = DisplayFeaturesConfigChangeActivity::class.java
+ clazz = DisplayFeaturesActivity::class.java
),
DemoItem(
buttonTitle = getString(display_features_no_config_change),
diff --git a/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/DemoActivityEmbeddingController.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/DemoActivityEmbeddingController.kt
new file mode 100644
index 0000000..0d3771e
--- /dev/null
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/DemoActivityEmbeddingController.kt
@@ -0,0 +1,63 @@
+/*
+ * 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 androidx.window.demo.embedding
+
+import androidx.annotation.ColorInt
+import androidx.annotation.GuardedBy
+import java.util.concurrent.locks.ReentrantLock
+import kotlin.concurrent.withLock
+
+/** A singleton controller to manage the global config. */
+class DemoActivityEmbeddingController private constructor() {
+
+ private val lock = Object()
+
+ @GuardedBy("lock")
+ @ColorInt
+ private var _animationBackgroundColor = 0
+
+ /** Animation background color to use when the animation requires a background. */
+ var animationBackgroundColor: Int
+ @ColorInt
+ get() = synchronized(lock) {
+ _animationBackgroundColor
+ }
+ set(@ColorInt value) = synchronized(lock) {
+ _animationBackgroundColor = value
+ }
+
+ companion object {
+ @Volatile
+ private var globalInstance: DemoActivityEmbeddingController? = null
+ private val globalLock = ReentrantLock()
+
+ /**
+ * Obtains the singleton instance of [DemoActivityEmbeddingController].
+ */
+ @JvmStatic
+ fun getInstance(): DemoActivityEmbeddingController {
+ if (globalInstance == null) {
+ globalLock.withLock {
+ if (globalInstance == null) {
+ globalInstance = DemoActivityEmbeddingController()
+ }
+ }
+ }
+ return globalInstance!!
+ }
+ }
+}
\ No newline at end of file
diff --git a/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/ExampleWindowInitializer.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/ExampleWindowInitializer.kt
new file mode 100644
index 0000000..8665740
--- /dev/null
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/ExampleWindowInitializer.kt
@@ -0,0 +1,228 @@
+/*
+ * Copyright 2021 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 androidx.window.demo.embedding
+
+import android.content.Context
+import androidx.startup.Initializer
+import androidx.window.demo.R
+import androidx.window.demo.embedding.SplitDeviceStateActivityBase.Companion.SUFFIX_AND_FULLSCREEN_IN_BOOK_MODE
+import androidx.window.demo.embedding.SplitDeviceStateActivityBase.Companion.SUFFIX_AND_HORIZONTAL_LAYOUT_IN_TABLETOP
+import androidx.window.demo.embedding.SplitDeviceStateActivityBase.Companion.SUFFIX_REVERSED
+import androidx.window.demo.embedding.SplitDeviceStateActivityBase.Companion.TAG_SHOW_DIFFERENT_LAYOUT_WITH_SIZE
+import androidx.window.demo.embedding.SplitDeviceStateActivityBase.Companion.TAG_SHOW_FULLSCREEN_IN_PORTRAIT
+import androidx.window.demo.embedding.SplitDeviceStateActivityBase.Companion.TAG_SHOW_HORIZONTAL_LAYOUT_IN_TABLETOP
+import androidx.window.demo.embedding.SplitDeviceStateActivityBase.Companion.TAG_SHOW_LAYOUT_FOLLOWING_HINGE_WHEN_SEPARATING
+import androidx.window.demo.embedding.SplitDeviceStateActivityBase.Companion.TAG_USE_DEFAULT_SPLIT_ATTRIBUTES
+import androidx.window.embedding.RuleController
+import androidx.window.embedding.SplitAttributes
+import androidx.window.embedding.SplitAttributes.LayoutDirection.Companion.BOTTOM_TO_TOP
+import androidx.window.embedding.SplitAttributes.LayoutDirection.Companion.LEFT_TO_RIGHT
+import androidx.window.embedding.SplitAttributes.LayoutDirection.Companion.RIGHT_TO_LEFT
+import androidx.window.embedding.SplitAttributes.LayoutDirection.Companion.TOP_TO_BOTTOM
+import androidx.window.embedding.SplitAttributesCalculatorParams
+import androidx.window.embedding.SplitController
+import androidx.window.layout.FoldingFeature
+import androidx.window.layout.WindowLayoutInfo
+import androidx.window.layout.WindowMetrics
+
+/**
+ * Initializes SplitController with a set of statically defined rules.
+ */
+class ExampleWindowInitializer : Initializer<RuleController> {
+ private val mDemoActivityEmbeddingController = DemoActivityEmbeddingController.getInstance()
+
+ override fun create(context: Context): RuleController {
+ SplitController.getInstance(context).apply {
+ if (isSplitAttributesCalculatorSupported()) {
+ setSplitAttributesCalculator(::sampleSplitAttributesCalculator)
+ }
+ }
+ return RuleController.getInstance(context).apply {
+ if (SplitController.getInstance(context).isSplitSupported()) {
+ setRules(RuleController.parseRules(context, R.xml.main_split_config))
+ }
+ }
+ }
+
+ /**
+ * A sample callback set in [SplitController.setSplitAttributesCalculator] to demonstrate how to
+ * change the [SplitAttributes] with the current device and window state and
+ * [SplitAttributesCalculatorParams.splitRuleTag].
+ */
+ private fun sampleSplitAttributesCalculator(
+ params: SplitAttributesCalculatorParams
+ ): SplitAttributes {
+ val isPortrait = params.parentWindowMetrics.isPortrait()
+ val windowLayoutInfo = params.parentWindowLayoutInfo
+ val isTabletop = windowLayoutInfo.isTabletop()
+ val isBookMode = windowLayoutInfo.isBookMode()
+ val config = params.parentConfiguration
+ // The SplitAttributes to occupy the whole task bounds
+ val expandContainersAttrs = SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.expandContainers())
+ .build()
+ val tag = params.splitRuleTag
+ val shouldReversed = tag?.contains(SUFFIX_REVERSED) ?: false
+ // Make a copy of the default splitAttributes, but replace the animation background
+ // color to what is configured in the Demo app.
+ val backgroundColor = mDemoActivityEmbeddingController.animationBackgroundColor
+ val defaultSplitAttributes = SplitAttributes.Builder()
+ .setLayoutDirection(params.defaultSplitAttributes.layoutDirection)
+ .setSplitType(params.defaultSplitAttributes.splitType)
+ .setAnimationBackgroundColor(backgroundColor)
+ .build()
+ when (tag?.substringBefore(SUFFIX_REVERSED)) {
+ TAG_USE_DEFAULT_SPLIT_ATTRIBUTES, null -> {
+ return if (params.areDefaultConstraintsSatisfied) {
+ defaultSplitAttributes
+ } else {
+ expandContainersAttrs
+ }
+ }
+ TAG_SHOW_FULLSCREEN_IN_PORTRAIT -> {
+ if (isPortrait) {
+ return expandContainersAttrs
+ }
+ }
+ TAG_SHOW_FULLSCREEN_IN_PORTRAIT + SUFFIX_AND_HORIZONTAL_LAYOUT_IN_TABLETOP -> {
+ if (isTabletop) {
+ return SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.splitByHinge())
+ .setLayoutDirection(
+ if (shouldReversed) {
+ BOTTOM_TO_TOP
+ } else {
+ TOP_TO_BOTTOM
+ }
+ )
+ .setAnimationBackgroundColor(backgroundColor)
+ .build()
+ } else if (isPortrait) {
+ return expandContainersAttrs
+ }
+ }
+ TAG_SHOW_HORIZONTAL_LAYOUT_IN_TABLETOP -> {
+ if (isTabletop) {
+ return SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.splitByHinge())
+ .setLayoutDirection(
+ if (shouldReversed) {
+ BOTTOM_TO_TOP
+ } else {
+ TOP_TO_BOTTOM
+ }
+ )
+ .setAnimationBackgroundColor(backgroundColor)
+ .build()
+ }
+ }
+ TAG_SHOW_DIFFERENT_LAYOUT_WITH_SIZE -> {
+ return SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.splitByHinge())
+ .setLayoutDirection(
+ if (shouldReversed) {
+ BOTTOM_TO_TOP
+ } else {
+ TOP_TO_BOTTOM
+ }
+ ).build()
+ }
+ TAG_SHOW_DIFFERENT_LAYOUT_WITH_SIZE + SUFFIX_AND_FULLSCREEN_IN_BOOK_MODE -> {
+ return if (isBookMode) {
+ expandContainersAttrs
+ } else if (config.screenWidthDp <= 600) {
+ SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.splitEqually())
+ .setLayoutDirection(
+ if (shouldReversed) {
+ BOTTOM_TO_TOP
+ } else {
+ TOP_TO_BOTTOM
+ }
+ )
+ .setAnimationBackgroundColor(backgroundColor)
+ .build()
+ } else {
+ SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.splitEqually())
+ .setLayoutDirection(
+ if (shouldReversed) {
+ RIGHT_TO_LEFT
+ } else {
+ LEFT_TO_RIGHT
+ }
+ )
+ .setAnimationBackgroundColor(backgroundColor)
+ .build()
+ }
+ }
+ TAG_SHOW_LAYOUT_FOLLOWING_HINGE_WHEN_SEPARATING -> {
+ val foldingState = windowLayoutInfo.getFoldingFeature()
+ if (foldingState != null) {
+ return SplitAttributes.Builder()
+ .setSplitType(
+ if (foldingState.isSeparating) {
+ SplitAttributes.SplitType.splitByHinge()
+ } else {
+ SplitAttributes.SplitType.ratio(0.3f)
+ }
+ ).setLayoutDirection(
+ if (
+ foldingState.orientation
+ == FoldingFeature.Orientation.HORIZONTAL
+ ) {
+ if (shouldReversed) BOTTOM_TO_TOP else TOP_TO_BOTTOM
+ } else {
+ if (shouldReversed) RIGHT_TO_LEFT else LEFT_TO_RIGHT
+ }
+ )
+ .setAnimationBackgroundColor(backgroundColor)
+ .build()
+ }
+ }
+ }
+ return defaultSplitAttributes
+ }
+
+ private fun WindowMetrics.isPortrait(): Boolean =
+ bounds.height() > bounds.width()
+
+ private fun WindowLayoutInfo.isTabletop(): Boolean {
+ val foldingFeature = getFoldingFeature()
+ return foldingFeature?.state == FoldingFeature.State.HALF_OPENED &&
+ foldingFeature.orientation == FoldingFeature.Orientation.HORIZONTAL
+ }
+
+ private fun WindowLayoutInfo.isBookMode(): Boolean {
+ val foldingFeature = getFoldingFeature()
+ return foldingFeature?.state == FoldingFeature.State.HALF_OPENED &&
+ foldingFeature.orientation == FoldingFeature.Orientation.VERTICAL
+ }
+
+ /**
+ * Returns the [FoldingFeature] if it is exactly the only [FoldingFeature] in
+ * [WindowLayoutInfo]. Otherwise, returns `null`.
+ */
+ private fun WindowLayoutInfo.getFoldingFeature(): FoldingFeature? {
+ val foldingFeatures = displayFeatures.filterIsInstance<FoldingFeature>()
+ return if (foldingFeatures.size == 1) foldingFeatures[0] else null
+ }
+
+ override fun dependencies(): List<Class<out Initializer<*>>> {
+ return emptyList()
+ }
+}
\ No newline at end of file
diff --git a/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/ExpandedDialogActivity.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/ExpandedDialogActivity.kt
new file mode 100644
index 0000000..3419fcb
--- /dev/null
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/ExpandedDialogActivity.kt
@@ -0,0 +1,44 @@
+/*
+ * 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 androidx.window.demo.embedding
+
+import android.os.Bundle
+import androidx.appcompat.app.AlertDialog
+import androidx.appcompat.app.AppCompatActivity
+
+/** Activity to show a dialog. */
+class ExpandedDialogActivity : AppCompatActivity() {
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ showDialog()
+ }
+
+ private fun showDialog() {
+ val dialog = AlertDialog.Builder(this)
+ .setTitle("Dialog in expanded activity")
+ .setMessage("To demo showing dialog that can expand over a split")
+ .setNeutralButton("Close") { _, _ ->
+ finish()
+ }
+ .setOnDismissListener {
+ finish()
+ }
+
+ dialog.show()
+ }
+}
\ No newline at end of file
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityA.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityA.kt
similarity index 93%
rename from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityA.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityA.kt
index 20a8056..94757d6 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityA.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityA.kt
@@ -14,6 +14,6 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+package androidx.window.demo.embedding
open class SplitActivityA : SplitActivityBase()
\ No newline at end of file
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityB.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityB.kt
similarity index 94%
rename from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityB.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityB.kt
index 6791b5c..90a67dd 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityB.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityB.kt
@@ -14,13 +14,13 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+package androidx.window.demo.embedding
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
-import androidx.window.sample.R
+import androidx.window.demo.R
open class SplitActivityB : SplitActivityBase() {
override fun onCreate(savedInstanceState: Bundle?) {
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityBase.java b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityBase.java
similarity index 62%
rename from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityBase.java
rename to window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityBase.java
index c3acc7a..59ca4ac 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityBase.java
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityBase.java
@@ -14,35 +14,42 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding;
+package androidx.window.demo.embedding;
import static android.app.PendingIntent.FLAG_IMMUTABLE;
+import static androidx.window.embedding.SplitRule.FinishBehavior.ADJACENT;
+import static androidx.window.embedding.SplitRule.FinishBehavior.ALWAYS;
+import static androidx.window.embedding.SplitRule.FinishBehavior.NEVER;
+
import android.app.Activity;
import android.app.PendingIntent;
+import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
+import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.util.Consumer;
+import androidx.window.demo.R;
+import androidx.window.demo.databinding.ActivitySplitActivityLayoutBinding;
import androidx.window.embedding.ActivityEmbeddingController;
import androidx.window.embedding.ActivityFilter;
import androidx.window.embedding.ActivityRule;
import androidx.window.embedding.EmbeddingRule;
import androidx.window.embedding.RuleController;
+import androidx.window.embedding.SplitAttributes;
import androidx.window.embedding.SplitController;
import androidx.window.embedding.SplitInfo;
import androidx.window.embedding.SplitPairFilter;
import androidx.window.embedding.SplitPairRule;
import androidx.window.embedding.SplitPlaceholderRule;
-import androidx.window.embedding.SplitRule;
-import androidx.window.sample.databinding.ActivitySplitActivityLayoutBinding;
import java.util.HashSet;
import java.util.List;
@@ -61,9 +68,7 @@
static final String EXTRA_LAUNCH_C_TO_SIDE = "launch_c_to_side";
private SplitController mSplitController;
-
- private final RuleController mRuleController = RuleController.getInstance(this);
-
+ private RuleController mRuleController;
private SplitInfoCallback mCallback;
private ActivitySplitActivityLayoutBinding mViewBinding;
@@ -77,7 +82,7 @@
mViewBinding = ActivitySplitActivityLayoutBinding.inflate(getLayoutInflater());
setContentView(mViewBinding.getRoot());
- // Setup activity launch buttons.
+ // Setup activity launch buttons and config options.
mViewBinding.launchB.setOnClickListener((View v) ->
startActivity(new Intent(this, SplitActivityB.class)));
mViewBinding.launchBAndC.setOnClickListener((View v) -> {
@@ -97,6 +102,50 @@
Log.e(TAG, e.getMessage());
}
});
+ mViewBinding.launchUid2Trusted.setOnClickListener((View v) -> {
+ final Intent intent = new Intent();
+ // Use an explicit package and class name to start an Activity from a different
+ // package/UID.
+ intent.setClassName(
+ "androidx.window.demo2",
+ "androidx.window.demo2.embedding.TrustedEmbeddingActivity"
+ );
+ try {
+ startActivity(intent);
+ } catch (ActivityNotFoundException e) {
+ Toast.makeText(this, R.string.install_samples_2, Toast.LENGTH_LONG).show();
+ }
+ });
+ mViewBinding.launchUid2Untrusted.setOnClickListener((View v) -> {
+ final Intent intent = new Intent();
+ // Use an explicit package and class name to start an Activity from a different
+ // package/UID.
+ intent.setClassName(
+ "androidx.window.demo2",
+ "androidx.window.demo2.embedding.UntrustedEmbeddingActivity"
+ );
+ try {
+ startActivity(intent);
+ } catch (ActivityNotFoundException e) {
+ Toast.makeText(this, R.string.install_samples_2, Toast.LENGTH_LONG).show();
+ }
+ });
+ mViewBinding.launchUid2UntrustedDisplayFeatures.setOnClickListener((View v) -> {
+ final Intent intent = new Intent();
+ // Use an explicit package and class name to start an Activity from a different
+ // package/UID.
+ intent.setClassName(
+ "androidx.window.demo2",
+ "androidx.window.demo.common.DisplayFeaturesActivity"
+ );
+ try {
+ startActivity(intent);
+ } catch (ActivityNotFoundException e) {
+ Toast.makeText(this, R.string.install_samples_2, Toast.LENGTH_LONG).show();
+ }
+ });
+ mViewBinding.launchExpandedDialogButton.setOnClickListener((View v) ->
+ startActivity(new Intent(this, ExpandedDialogActivity.class)));
// Listen for split configuration checkboxes to update the rules before launching
// activities.
@@ -109,6 +158,13 @@
mViewBinding.splitWithFCheckBox.setOnCheckedChangeListener(this);
mSplitController = SplitController.getInstance(this);
+ if (!mSplitController.isSplitSupported()) {
+ Toast.makeText(this, R.string.toast_split_not_support,
+ Toast.LENGTH_SHORT).show();
+ finish();
+ return;
+ }
+ mRuleController = RuleController.getInstance(this);
}
@Override
@@ -177,8 +233,8 @@
mViewBinding.splitBCCheckBox.setChecked(bAndCPairConfig != null);
mViewBinding.finishBCCheckBox.setEnabled(bAndCPairConfig != null);
mViewBinding.finishBCCheckBox.setChecked(bAndCPairConfig != null
- && bAndCPairConfig.getFinishPrimaryWithSecondary() == SplitRule.FINISH_ALWAYS
- && bAndCPairConfig.getFinishSecondaryWithPrimary() == SplitRule.FINISH_ALWAYS);
+ && bAndCPairConfig.getFinishPrimaryWithSecondary() == ALWAYS
+ && bAndCPairConfig.getFinishSecondaryWithPrimary() == ALWAYS);
SplitPairRule fConfig = getRuleFor(null, SplitActivityF.class);
mViewBinding.splitWithFCheckBox.setChecked(fConfig != null);
@@ -259,85 +315,102 @@
/** Updates the split rules based on the current selection on checkboxes. */
private void updateRulesFromCheckboxes() {
mRuleController.clearRules();
-
- Set<SplitPairFilter> pairFilters = new HashSet<>();
- pairFilters.add(new SplitPairFilter(componentName(SplitActivityA.class),
- componentName("*"), null));
- SplitPairRule rule = new SplitPairRule.Builder(pairFilters)
- .setMinWidthDp(MIN_SPLIT_WIDTH_DP)
- .setMinSmallestWidthDp(0)
- .setFinishPrimaryWithSecondary(SplitRule.FINISH_NEVER)
- .setFinishSecondaryWithPrimary(SplitRule.FINISH_NEVER)
- .setClearTop(true)
- .setSplitRatio(SPLIT_RATIO)
+ final SplitAttributes defaultSplitAttributes = new SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.ratio(SPLIT_RATIO))
.build();
+
if (mViewBinding.splitMainCheckBox.isChecked()) {
+ // Split main with any activity.
+ final Set<SplitPairFilter> pairFilters = new HashSet<>();
+ pairFilters.add(new SplitPairFilter(componentName(SplitActivityA.class),
+ new ComponentName("*", "*"), null));
+ final SplitPairRule rule = new SplitPairRule.Builder(pairFilters)
+ .setMinWidthDp(MIN_SPLIT_WIDTH_DP)
+ .setMinHeightDp(0)
+ .setMinSmallestWidthDp(0)
+ .setFinishPrimaryWithSecondary(NEVER)
+ .setFinishSecondaryWithPrimary(NEVER)
+ .setClearTop(true)
+ .setDefaultSplitAttributes(defaultSplitAttributes)
+ .build();
mRuleController.addRule(rule);
}
- Set<ActivityFilter> activityFilters = new HashSet<>();
- activityFilters.add(new ActivityFilter(componentName(SplitActivityB.class), null));
- Intent intent = new Intent();
- intent.setComponent(
- componentName("androidx.window.sample.embedding.SplitActivityPlaceholder"));
- SplitPlaceholderRule placeholderRule = new SplitPlaceholderRule.Builder(
- activityFilters,
- intent
- )
- .setMinWidthDp(MIN_SPLIT_WIDTH_DP)
- .setMinSmallestWidthDp(0)
- .setSticky(mViewBinding.useStickyPlaceholderCheckBox.isChecked())
- .setFinishPrimaryWithPlaceholder(SplitRule.FINISH_ADJACENT)
- .setSplitRatio(SPLIT_RATIO)
- .build();
if (mViewBinding.usePlaceholderCheckBox.isChecked()) {
- mRuleController.addRule(placeholderRule);
+ // Split B with placeholder.
+ final Set<ActivityFilter> activityFilters = new HashSet<>();
+ activityFilters.add(new ActivityFilter(componentName(SplitActivityB.class), null));
+ final Intent intent = new Intent();
+ intent.setComponent(componentName(SplitActivityPlaceholder.class));
+ final SplitPlaceholderRule rule = new SplitPlaceholderRule.Builder(
+ activityFilters,
+ intent
+ )
+ .setMinWidthDp(MIN_SPLIT_WIDTH_DP)
+ .setMinHeightDp(0)
+ .setMinSmallestWidthDp(0)
+ .setSticky(mViewBinding.useStickyPlaceholderCheckBox.isChecked())
+ .setFinishPrimaryWithPlaceholder(ADJACENT)
+ .setDefaultSplitAttributes(defaultSplitAttributes)
+ .build();
+ mRuleController.addRule(rule);
}
- pairFilters = new HashSet<>();
- pairFilters.add(new SplitPairFilter(componentName(SplitActivityB.class),
- componentName(SplitActivityC.class), null));
- rule = new SplitPairRule.Builder(pairFilters)
- .setMinWidthDp(MIN_SPLIT_WIDTH_DP)
- .setMinSmallestWidthDp(0)
- .setFinishPrimaryWithSecondary(
- mViewBinding.finishBCCheckBox.isChecked()
- ? SplitRule.FINISH_ALWAYS : SplitRule.FINISH_NEVER
- )
- .setFinishSecondaryWithPrimary(
- mViewBinding.finishBCCheckBox.isChecked()
- ? SplitRule.FINISH_ALWAYS : SplitRule.FINISH_NEVER
- )
- .setClearTop(true)
- .setSplitRatio(SPLIT_RATIO)
- .build();
if (mViewBinding.splitBCCheckBox.isChecked()) {
+ // Split B with C.
+ final Set<SplitPairFilter> pairFilters = new HashSet<>();
+ pairFilters.add(new SplitPairFilter(componentName(SplitActivityB.class),
+ componentName(SplitActivityC.class), null));
+ final SplitPairRule rule = new SplitPairRule.Builder(pairFilters)
+ .setMinWidthDp(MIN_SPLIT_WIDTH_DP)
+ .setMinHeightDp(0)
+ .setMinSmallestWidthDp(0)
+ .setFinishPrimaryWithSecondary(
+ mViewBinding.finishBCCheckBox.isChecked() ? ALWAYS : NEVER
+ )
+ .setFinishSecondaryWithPrimary(
+ mViewBinding.finishBCCheckBox.isChecked() ? ALWAYS : NEVER
+ )
+ .setClearTop(true)
+ .setDefaultSplitAttributes(defaultSplitAttributes)
+ .build();
mRuleController.addRule(rule);
}
- pairFilters = new HashSet<>();
- pairFilters.add(new SplitPairFilter(componentName("androidx.window.*"),
- componentName(SplitActivityF.class), null));
- rule = new SplitPairRule.Builder(pairFilters)
- .setMinWidthDp(MIN_SPLIT_WIDTH_DP)
- .setMinSmallestWidthDp(0)
- .setFinishPrimaryWithSecondary(SplitRule.FINISH_NEVER)
- .setFinishSecondaryWithPrimary(SplitRule.FINISH_NEVER)
- .setClearTop(true)
- .setSplitRatio(SPLIT_RATIO)
- .build();
if (mViewBinding.splitWithFCheckBox.isChecked()) {
+ // Split any activity with F.
+ final Set<SplitPairFilter> pairFilters = new HashSet<>();
+ pairFilters.add(new SplitPairFilter(new ComponentName("*", "*"),
+ componentName(SplitActivityF.class), null));
+ final SplitPairRule rule = new SplitPairRule.Builder(pairFilters)
+ .setMinWidthDp(MIN_SPLIT_WIDTH_DP)
+ .setMinHeightDp(0)
+ .setMinSmallestWidthDp(0)
+ .setFinishPrimaryWithSecondary(NEVER)
+ .setFinishSecondaryWithPrimary(NEVER)
+ .setClearTop(true)
+ .setDefaultSplitAttributes(defaultSplitAttributes)
+ .build();
mRuleController.addRule(rule);
}
- activityFilters = new HashSet<>();
- activityFilters.add(new ActivityFilter(componentName(SplitActivityE.class), null));
- ActivityRule activityRule = new ActivityRule.Builder(activityFilters)
- .setAlwaysExpand(true)
- .build();
if (mViewBinding.fullscreenECheckBox.isChecked()) {
+ // Launch E in fullscreen.
+ final Set<ActivityFilter> activityFilters = new HashSet<>();
+ activityFilters.add(new ActivityFilter(componentName(SplitActivityE.class), null));
+ final ActivityRule activityRule = new ActivityRule.Builder(activityFilters)
+ .setAlwaysExpand(true)
+ .build();
mRuleController.addRule(activityRule);
}
+
+ // Always expand the dialog activity.
+ final Set<ActivityFilter> dialogActivityFilters = new HashSet<>();
+ dialogActivityFilters.add(new ActivityFilter(componentName(
+ ExpandedDialogActivity.class), null));
+ mRuleController.addRule(new ActivityRule.Builder(dialogActivityFilters)
+ .setAlwaysExpand(true)
+ .build());
}
ComponentName componentName(Class<? extends Activity> activityClass) {
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityC.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityC.kt
similarity index 92%
rename from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityC.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityC.kt
index 413c6c3..dcbbb3b 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityC.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityC.kt
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+package androidx.window.demo.embedding
import android.graphics.Color
import android.os.Bundle
import android.view.View
-import androidx.window.sample.R
+import androidx.window.demo.R
open class SplitActivityC : SplitActivityBase() {
override fun onCreate(savedInstanceState: Bundle?) {
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityD.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityD.kt
similarity index 92%
rename from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityD.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityD.kt
index 9f919f0..a9ec11a 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityD.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityD.kt
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+package androidx.window.demo.embedding
import android.graphics.Color
import android.os.Bundle
import android.view.View
-import androidx.window.sample.R
+import androidx.window.demo.R
open class SplitActivityD : SplitActivityBase() {
override fun onCreate(savedInstanceState: Bundle?) {
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityDetail.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityDetail.kt
similarity index 95%
rename from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityDetail.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityDetail.kt
index 6c4897e..5db4314 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityDetail.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityDetail.kt
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+package androidx.window.demo.embedding
import android.content.Intent
import android.graphics.Color
@@ -22,7 +22,7 @@
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
-import androidx.window.sample.R
+import androidx.window.demo.R
open class SplitActivityDetail : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityE.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityE.kt
similarity index 92%
rename from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityE.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityE.kt
index 9960ef2..17c43b1 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityE.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityE.kt
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+package androidx.window.demo.embedding
import android.graphics.Color
import android.os.Bundle
import android.view.View
-import androidx.window.sample.R
+import androidx.window.demo.R
open class SplitActivityE : SplitActivityBase() {
override fun onCreate(savedInstanceState: Bundle?) {
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityF.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityF.kt
similarity index 92%
rename from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityF.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityF.kt
index 3243e5d..325524e 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityF.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityF.kt
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+package androidx.window.demo.embedding
import android.graphics.Color
import android.os.Bundle
import android.view.View
-import androidx.window.sample.R
+import androidx.window.demo.R
open class SplitActivityF : SplitActivityBase() {
override fun onCreate(savedInstanceState: Bundle?) {
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityList.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityList.kt
similarity index 88%
rename from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityList.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityList.kt
index cb64edf..49e119a 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityList.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityList.kt
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+package androidx.window.demo.embedding
import android.content.Intent
import android.graphics.Color
@@ -26,12 +26,12 @@
import androidx.core.util.Consumer
import androidx.window.embedding.SplitController
import androidx.window.embedding.SplitInfo
-import androidx.window.sample.R
-import androidx.window.sample.embedding.SplitActivityDetail.Companion.EXTRA_SELECTED_ITEM
+import androidx.window.demo.R
+import androidx.window.demo.embedding.SplitActivityDetail.Companion.EXTRA_SELECTED_ITEM
open class SplitActivityList : AppCompatActivity() {
- private lateinit var splitController: SplitController
- private val splitChangeListener = SplitStateChangeListener()
+ lateinit var splitController: SplitController
+ val splitChangeListener = SplitStateChangeListener()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityListPlaceholder.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityListPlaceholder.kt
similarity index 93%
rename from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityListPlaceholder.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityListPlaceholder.kt
index 754e11d8..ab08fe7 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityListPlaceholder.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityListPlaceholder.kt
@@ -14,6 +14,6 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+package androidx.window.demo.embedding
open class SplitActivityListPlaceholder : SplitActivityPlaceholder()
\ No newline at end of file
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityPlaceholder.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityPlaceholder.kt
similarity index 89%
rename from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityPlaceholder.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityPlaceholder.kt
index 7314921..380b5b7 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityPlaceholder.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityPlaceholder.kt
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+package androidx.window.demo.embedding
import android.graphics.Color
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
-import androidx.window.sample.databinding.ActivitySplitActivityPlaceholderLayoutBinding
+import androidx.window.demo.databinding.ActivitySplitActivityPlaceholderLayoutBinding
open class SplitActivityPlaceholder : AppCompatActivity() {
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityTrampoline.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityTrampoline.kt
similarity index 69%
rename from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityTrampoline.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityTrampoline.kt
index 212cbcb..3732156 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityTrampoline.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitActivityTrampoline.kt
@@ -14,14 +14,15 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+package androidx.window.demo.embedding
import android.content.Intent
import android.os.Bundle
import androidx.window.embedding.ActivityFilter
import androidx.window.embedding.RuleController
+import androidx.window.embedding.SplitAttributes
import androidx.window.embedding.SplitPlaceholderRule
-import androidx.window.embedding.SplitRule.Companion.FINISH_ADJACENT
+import androidx.window.embedding.SplitRule.FinishBehavior.Companion.ADJACENT
/**
* Example trampoline activity that launches a split and finishes itself.
@@ -31,20 +32,24 @@
super.onCreate(savedInstanceState)
val activityFilters = setOf(ActivityFilter(componentName(
- "androidx.window.sample.embedding.SplitActivityTrampolineTarget"), null))
+ "androidx.window.demo.embedding.SplitActivityTrampolineTarget"), null))
val placeholderIntent = Intent()
placeholderIntent.component =
- componentName("androidx.window.sample.embedding.SplitActivityPlaceholder")
+ componentName("androidx.window.demo.embedding.SplitActivityPlaceholder")
+ val defaultSplitAttributes = SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.ratio(SPLIT_RATIO))
+ .build()
val placeholderRule = SplitPlaceholderRule.Builder(activityFilters, placeholderIntent)
.setMinWidthDp(MIN_SPLIT_WIDTH_DP)
+ .setMinHeightDp(0)
.setMinSmallestWidthDp(0)
- .setFinishPrimaryWithPlaceholder(FINISH_ADJACENT)
- .setSplitRatio(SPLIT_RATIO)
+ .setFinishPrimaryWithPlaceholder(ADJACENT)
+ .setDefaultSplitAttributes(defaultSplitAttributes)
.build()
RuleController.getInstance(this).addRule(placeholderRule)
val activityIntent = Intent()
activityIntent.component = componentName(
- "androidx.window.sample.embedding.SplitActivityTrampolineTarget")
+ "androidx.window.demo.embedding.SplitActivityTrampolineTarget")
startActivity(activityIntent)
finish()
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityA.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitDeviceStateActivityA.kt
similarity index 85%
copy from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityA.kt
copy to window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitDeviceStateActivityA.kt
index 7053e2d..9ba2ac3 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityA.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitDeviceStateActivityA.kt
@@ -14,6 +14,6 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+package androidx.window.demo.embedding
-open class SplitPipActivityA : SplitPipActivityBase()
\ No newline at end of file
+class SplitDeviceStateActivityA : SplitDeviceStateActivityBase()
\ No newline at end of file
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityC.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitDeviceStateActivityB.kt
similarity index 76%
copy from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityC.kt
copy to window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitDeviceStateActivityB.kt
index 413c6c3..6711d76 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityC.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitDeviceStateActivityB.kt
@@ -1,5 +1,5 @@
/*
- * Copyright 2021 The Android Open Source Project
+ * 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.
@@ -14,17 +14,17 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+package androidx.window.demo.embedding
import android.graphics.Color
import android.os.Bundle
import android.view.View
-import androidx.window.sample.R
+import androidx.window.demo.R
-open class SplitActivityC : SplitActivityBase() {
+class SplitDeviceStateActivityB : SplitDeviceStateActivityBase() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
findViewById<View>(R.id.root_split_activity_layout)
- .setBackgroundColor(Color.parseColor("#e8f5e9"))
+ .setBackgroundColor(Color.parseColor("#fff3e0"))
}
-}
+}
\ No newline at end of file
diff --git a/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitDeviceStateActivityBase.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitDeviceStateActivityBase.kt
new file mode 100644
index 0000000..66d0e87
--- /dev/null
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitDeviceStateActivityBase.kt
@@ -0,0 +1,427 @@
+/*
+ * 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 androidx.window.demo.embedding
+
+import android.content.ComponentName
+import android.content.Intent
+import android.graphics.Color
+import android.os.Bundle
+import android.view.View
+import android.widget.AdapterView
+import android.widget.ArrayAdapter
+import android.widget.CompoundButton
+import android.widget.RadioGroup
+import android.widget.Toast
+import androidx.appcompat.app.AppCompatActivity
+import androidx.core.content.ContextCompat
+import androidx.core.util.Consumer
+import androidx.window.embedding.EmbeddingRule
+import androidx.window.embedding.SplitAttributes
+import androidx.window.embedding.SplitController
+import androidx.window.embedding.SplitInfo
+import androidx.window.embedding.SplitPairFilter
+import androidx.window.embedding.SplitPairRule
+import androidx.window.demo.R
+import androidx.window.demo.databinding.ActivitySplitDeviceStateLayoutBinding
+import androidx.window.embedding.RuleController
+
+open class SplitDeviceStateActivityBase : AppCompatActivity(), View.OnClickListener,
+ RadioGroup.OnCheckedChangeListener, CompoundButton.OnCheckedChangeListener,
+ AdapterView.OnItemSelectedListener {
+
+ private lateinit var splitController: SplitController
+ private lateinit var ruleController: RuleController
+
+ private val splitStateChangeListener = SplitStateChangeListener()
+
+ private lateinit var splitPairRule: SplitPairRule
+ private var shouldReverseContainerPosition = false
+ private var shouldShowHorizontalInTabletop = false
+ private var shouldShowFullscreenInBookMode = false
+
+ private lateinit var viewBinding: ActivitySplitDeviceStateLayoutBinding
+ private lateinit var activityA: ComponentName
+ private lateinit var activityB: ComponentName
+
+ /** Controller to manage the global configuration. */
+ private val demoActivityEmbeddingController = DemoActivityEmbeddingController.getInstance()
+
+ /** The last selected split rule id. */
+ private var lastCheckedRuleId = 0
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ viewBinding = ActivitySplitDeviceStateLayoutBinding.inflate(layoutInflater)
+ splitController = SplitController.getInstance(this)
+ if (!splitController.isSplitSupported()) {
+ Toast.makeText(
+ this, R.string.toast_split_not_support,
+ Toast.LENGTH_SHORT
+ ).show()
+ finish()
+ return
+ }
+ ruleController = RuleController.getInstance(this)
+
+ setContentView(viewBinding.root)
+
+ activityA = ComponentName(this, SplitDeviceStateActivityA::class.java.name)
+ activityB = ComponentName(this, SplitDeviceStateActivityB::class.java.name)
+
+ val radioGroup = viewBinding.splitAttributesOptionsRadioGroup
+ val animationBgColorDropdown = viewBinding.animationBackgroundColorDropdown
+ if (componentName == activityA) {
+ // Set to the first option
+ demoActivityEmbeddingController.animationBackgroundColor =
+ ANIMATION_BACKGROUND_COLORS_VALUE[0]
+ radioGroup.check(R.id.use_default_split_attributes)
+ onCheckedChanged(radioGroup, radioGroup.checkedRadioButtonId)
+ radioGroup.setOnCheckedChangeListener(this)
+ animationBgColorDropdown.adapter = ArrayAdapter(
+ this,
+ android.R.layout.simple_spinner_dropdown_item,
+ ANIMATION_BACKGROUND_COLORS_TEXT
+ )
+ animationBgColorDropdown.onItemSelectedListener = this
+ } else {
+ // Only update split pair rule on the primary Activity. The secondary Activity can only
+ // finish itself to prevent confusing users. We only apply the rule when the Activity is
+ // launched from the primary.
+ viewBinding.chooseLayoutTextView.visibility = View.GONE
+ radioGroup.visibility = View.GONE
+ animationBgColorDropdown.visibility = View.GONE
+ viewBinding.launchActivityToSide.text = "Finish this Activity"
+ }
+
+ viewBinding.showHorizontalLayoutInTabletopCheckBox.setOnCheckedChangeListener(this)
+ viewBinding.showFullscreenInBookModeCheckBox.setOnCheckedChangeListener(this)
+ viewBinding.swapPrimarySecondaryPositionCheckBox.setOnCheckedChangeListener(this)
+ viewBinding.launchActivityToSide.setOnClickListener(this)
+
+ val isCallbackSupported = splitController.isSplitAttributesCalculatorSupported()
+ if (!isCallbackSupported) {
+ // Disable the radioButtons that use SplitAttributesCalculator
+ viewBinding.showFullscreenInPortraitRadioButton.isEnabled = false
+ viewBinding.showHorizontalLayoutInTabletopRadioButton.isEnabled = false
+ viewBinding.showDifferentLayoutWithSizeRadioButton.isEnabled = false
+ viewBinding.splitByHingeWhenSeparatingRadioButton.isEnabled = false
+ hideAllSubCheckBoxes()
+ // Add the error message to notify the SplitAttributesCalculator is not available.
+ viewBinding.errorMessageTextView.text = "SplitAttributesCalculator is not supported!"
+ animationBgColorDropdown.isEnabled = false
+ }
+ }
+
+ override fun onStart() {
+ super.onStart()
+ splitController.addSplitListener(
+ this,
+ ContextCompat.getMainExecutor(this),
+ splitStateChangeListener
+ )
+ }
+
+ override fun onStop() {
+ super.onStop()
+ splitController.removeSplitListener(splitStateChangeListener)
+ }
+
+ override fun onClick(button: View) {
+ if (button.id != R.id.launch_activity_to_side) {
+ return
+ }
+ when (componentName) {
+ activityA -> {
+ startActivity(Intent(this, SplitDeviceStateActivityB::class.java))
+ }
+ activityB -> finish()
+ }
+ }
+
+ override fun onCheckedChanged(c: CompoundButton, isChecked: Boolean) {
+ when (c.id) {
+ R.id.swap_primary_secondary_position_check_box -> {
+ shouldReverseContainerPosition = isChecked
+ updateSplitPairRuleWithRadioButtonId(
+ viewBinding.splitAttributesOptionsRadioGroup.checkedRadioButtonId
+ )
+ }
+ R.id.show_horizontal_layout_in_tabletop_check_box -> {
+ shouldShowHorizontalInTabletop = isChecked
+ updateSplitPairRuleWithRadioButtonId(
+ R.id.show_fullscreen_in_portrait_radio_button
+ )
+ }
+ R.id.show_fullscreen_in_book_mode_check_box -> {
+ shouldShowFullscreenInBookMode = isChecked
+ updateSplitPairRuleWithRadioButtonId(
+ R.id.show_different_layout_with_size_radio_button
+ )
+ }
+ }
+ }
+
+ override fun onCheckedChanged(group: RadioGroup, id: Int) {
+ updateCheckboxWithRadioButton(id)
+ updateSplitPairRuleWithRadioButtonId(id)
+ }
+
+ override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
+ demoActivityEmbeddingController.animationBackgroundColor =
+ ANIMATION_BACKGROUND_COLORS_VALUE[position]
+ updateSplitPairRuleWithRadioButtonId(lastCheckedRuleId)
+ }
+
+ override fun onNothingSelected(view: AdapterView<*>?) {
+ // Auto-generated method stub
+ }
+
+ private fun updateCheckboxWithRadioButton(id: Int) {
+ when (id) {
+ R.id.show_fullscreen_in_portrait_radio_button -> {
+ showCheckBox(R.id.show_horizontal_layout_in_tabletop_check_box)
+ hideCheckBox(R.id.show_fullscreen_in_book_mode_check_box)
+ }
+ R.id.show_different_layout_with_size_radio_button -> {
+ hideCheckBox(R.id.show_horizontal_layout_in_tabletop_check_box)
+ showCheckBox(R.id.show_fullscreen_in_book_mode_check_box)
+ }
+ else -> hideAllSubCheckBoxes()
+ }
+ // Disable the checkbox because this won't be applied if users want to use the default rule
+ // behavior.
+ viewBinding.swapPrimarySecondaryPositionCheckBox.isEnabled =
+ id != R.id.use_default_split_attributes
+ }
+
+ private fun hideAllSubCheckBoxes() {
+ hideCheckBox(R.id.show_horizontal_layout_in_tabletop_check_box)
+ hideCheckBox(R.id.show_fullscreen_in_book_mode_check_box)
+ }
+
+ /** Show check box with [id] and also hides other check boxes. */
+ private fun showCheckBox(id: Int) {
+ when (id) {
+ R.id.show_horizontal_layout_in_tabletop_check_box -> {
+ viewBinding.showFullscreenInPortraitDividerTop.visibility = View.VISIBLE
+ viewBinding.showHorizontalLayoutInTabletopCheckBox.visibility = View.VISIBLE
+ viewBinding.showFullscreenInPortraitDividerBottom.visibility = View.VISIBLE
+ }
+ R.id.show_fullscreen_in_book_mode_check_box -> {
+ viewBinding.showDifferentLayoutWithSizeDividerTop.visibility = View.VISIBLE
+ viewBinding.showFullscreenInBookModeCheckBox.visibility = View.VISIBLE
+ viewBinding.showDifferentLayoutWithSizeDividerBottom.visibility = View.VISIBLE
+ }
+ }
+ }
+
+ private fun hideCheckBox(id: Int) {
+ when (id) {
+ R.id.show_horizontal_layout_in_tabletop_check_box -> {
+ viewBinding.showFullscreenInPortraitDividerTop.visibility = View.GONE
+ viewBinding.showHorizontalLayoutInTabletopCheckBox.visibility = View.GONE
+ viewBinding.showFullscreenInPortraitDividerBottom.visibility = View.GONE
+ shouldShowHorizontalInTabletop = false
+ }
+ R.id.show_fullscreen_in_book_mode_check_box -> {
+ viewBinding.showDifferentLayoutWithSizeDividerTop.visibility = View.GONE
+ viewBinding.showFullscreenInBookModeCheckBox.visibility = View.GONE
+ viewBinding.showDifferentLayoutWithSizeDividerBottom.visibility = View.GONE
+ shouldShowFullscreenInBookMode = false
+ }
+ }
+ }
+
+ private fun updateSplitPairRuleWithRadioButtonId(id: Int) {
+ lastCheckedRuleId = id
+ ruleController.clearRules()
+
+ val splitPairFilters = HashSet<SplitPairFilter>()
+ val splitPairFilter = SplitPairFilter(
+ activityA,
+ activityB,
+ secondaryActivityIntentAction = null
+ )
+ splitPairFilters.add(splitPairFilter)
+ val defaultSplitAttributes = SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.splitEqually())
+ .setLayoutDirection(SplitAttributes.LayoutDirection.LOCALE)
+ .setAnimationBackgroundColor(demoActivityEmbeddingController.animationBackgroundColor)
+ .build()
+ // Use the tag to control the rule how to change split attributes with the current state
+ var tag = when (id) {
+ R.id.use_default_split_attributes -> TAG_USE_DEFAULT_SPLIT_ATTRIBUTES
+ R.id.show_fullscreen_in_portrait_radio_button -> {
+ if (shouldShowHorizontalInTabletop) {
+ TAG_SHOW_FULLSCREEN_IN_PORTRAIT + SUFFIX_AND_HORIZONTAL_LAYOUT_IN_TABLETOP
+ } else {
+ TAG_SHOW_FULLSCREEN_IN_PORTRAIT
+ }
+ }
+ R.id.show_horizontal_layout_in_tabletop_radio_button -> {
+ if (shouldReverseContainerPosition) {
+ TAG_SHOW_HORIZONTAL_LAYOUT_IN_TABLETOP + SUFFIX_REVERSED
+ } else {
+ TAG_SHOW_HORIZONTAL_LAYOUT_IN_TABLETOP
+ }
+ }
+ R.id.show_different_layout_with_size_radio_button -> {
+ if (shouldShowFullscreenInBookMode) {
+ TAG_SHOW_DIFFERENT_LAYOUT_WITH_SIZE + SUFFIX_AND_FULLSCREEN_IN_BOOK_MODE
+ } else {
+ TAG_SHOW_DIFFERENT_LAYOUT_WITH_SIZE
+ }
+ }
+ R.id.split_by_hinge_when_separating_radio_button ->
+ TAG_SHOW_LAYOUT_FOLLOWING_HINGE_WHEN_SEPARATING
+ else -> null
+ }
+ if (shouldReverseContainerPosition) {
+ tag += SUFFIX_REVERSED
+ }
+
+ splitPairRule = SplitPairRule.Builder(splitPairFilters)
+ .setTag(tag)
+ .setMinWidthDp(DEFAULT_MINIMUM_WIDTH_DP)
+ .setMinSmallestWidthDp(DEFAULT_MINIMUM_WIDTH_DP)
+ .setDefaultSplitAttributes(defaultSplitAttributes)
+ .build()
+ ruleController.addRule(splitPairRule)
+ }
+
+ /** Updates split attributes when receives callback from the extension. */
+ inner class SplitStateChangeListener : Consumer<List<SplitInfo>> {
+ override fun accept(newSplitInfos: List<SplitInfo>) {
+ updateSplitAttributesText(newSplitInfos)
+ updateRadioGroupAndCheckBoxFromRule()
+ }
+ }
+
+ fun updateSplitAttributesText(newSplitInfos: List<SplitInfo>) {
+ var splitAttributes: SplitAttributes = SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.expandContainers())
+ .build()
+ var suggestToFinishItself = false
+ val isCallbackSupported = splitController.isSplitAttributesCalculatorSupported()
+ // Traverse SplitInfos from the end because last SplitInfo has the highest z-order.
+ for (info in newSplitInfos.reversed()) {
+ if (info.contains(this@SplitDeviceStateActivityBase)) {
+ splitAttributes = info.splitAttributes
+ if (componentName == activityB &&
+ splitAttributes.splitType
+ is SplitAttributes.SplitType.ExpandContainersSplitType
+ ) {
+ // We don't put any functionality on activity B. Suggest users to finish the
+ // activity if it fills the host task.
+ suggestToFinishItself = true
+ }
+ break
+ }
+ }
+ runOnUiThread {
+ viewBinding.activityPairSplitAttributesTextView.text =
+ resources.getString(R.string.current_split_attributes) + splitAttributes
+ if (!isCallbackSupported) {
+ // Don't update the error message if the callback is not supported.
+ return@runOnUiThread
+ }
+ viewBinding.errorMessageTextView.text =
+ if (suggestToFinishItself) {
+ "Please finish the activity to try other split configurations."
+ } else {
+ ""
+ }
+ }
+ }
+
+ fun updateRadioGroupAndCheckBoxFromRule() {
+ val splitPairRule = ruleController.getRules().firstOrNull { rule ->
+ isRuleForSplitActivityA(rule)
+ } ?: return
+ val tag = splitPairRule.tag
+ viewBinding.splitAttributesOptionsRadioGroup.check(
+ when (tag?.substringBefore(SUFFIX_REVERSED)) {
+ TAG_USE_DEFAULT_SPLIT_ATTRIBUTES -> R.id.use_default_split_attributes
+ TAG_SHOW_FULLSCREEN_IN_PORTRAIT,
+ TAG_SHOW_FULLSCREEN_IN_PORTRAIT + SUFFIX_AND_HORIZONTAL_LAYOUT_IN_TABLETOP ->
+ R.id.show_fullscreen_in_portrait_radio_button
+ TAG_SHOW_HORIZONTAL_LAYOUT_IN_TABLETOP,
+ TAG_SHOW_HORIZONTAL_LAYOUT_IN_TABLETOP + SUFFIX_REVERSED ->
+ R.id.show_horizontal_layout_in_tabletop_radio_button
+ TAG_SHOW_DIFFERENT_LAYOUT_WITH_SIZE,
+ TAG_SHOW_DIFFERENT_LAYOUT_WITH_SIZE + SUFFIX_AND_FULLSCREEN_IN_BOOK_MODE ->
+ R.id.show_different_layout_with_size_radio_button
+ TAG_SHOW_LAYOUT_FOLLOWING_HINGE_WHEN_SEPARATING ->
+ R.id.split_by_hinge_when_separating_radio_button
+ else -> 0
+ }
+ )
+ if (tag?.contains(TAG_SHOW_FULLSCREEN_IN_PORTRAIT) == true) {
+ showCheckBox(R.id.show_horizontal_layout_in_tabletop_check_box)
+ viewBinding.showHorizontalLayoutInTabletopCheckBox.isChecked =
+ tag.contains(SUFFIX_AND_HORIZONTAL_LAYOUT_IN_TABLETOP)
+ } else if (tag?.contains(TAG_SHOW_DIFFERENT_LAYOUT_WITH_SIZE) == true) {
+ showCheckBox(R.id.swap_primary_secondary_position_check_box)
+ viewBinding.showFullscreenInBookModeCheckBox.isChecked =
+ tag.contains(SUFFIX_AND_FULLSCREEN_IN_BOOK_MODE)
+ }
+
+ viewBinding.swapPrimarySecondaryPositionCheckBox.isChecked =
+ tag?.contains(SUFFIX_REVERSED) ?: false
+ }
+
+ private fun isRuleForSplitActivityA(rule: EmbeddingRule): Boolean {
+ if (rule !is SplitPairRule) {
+ return false
+ }
+ rule.filters.forEach { filter ->
+ if (filter.primaryActivityName == activityA &&
+ filter.secondaryActivityName == activityB
+ ) {
+ return true
+ }
+ }
+ return false
+ }
+
+ companion object {
+ const val TAG_USE_DEFAULT_SPLIT_ATTRIBUTES = "use_default_split_attributes"
+ const val TAG_SHOW_FULLSCREEN_IN_PORTRAIT = "show_fullscreen_in_portrait"
+ const val TAG_SHOW_HORIZONTAL_LAYOUT_IN_TABLETOP = "show_horizontal_layout_in_tabletop"
+ const val TAG_SHOW_DIFFERENT_LAYOUT_WITH_SIZE = "show_different_layout_with_size"
+ const val TAG_SHOW_LAYOUT_FOLLOWING_HINGE_WHEN_SEPARATING = "show_layout_following_hinge"
+ const val SUFFIX_REVERSED = "_reversed"
+ const val SUFFIX_AND_HORIZONTAL_LAYOUT_IN_TABLETOP = "_and_horizontal_layout_in_tabletop"
+ const val SUFFIX_AND_FULLSCREEN_IN_BOOK_MODE = "_and_fullscreen_in_book_mode"
+ val ANIMATION_BACKGROUND_COLORS_TEXT = arrayOf("BLACK", "BLUE", "GREEN", "YELLOW")
+ val ANIMATION_BACKGROUND_COLORS_VALUE = arrayOf(
+ Color.BLACK,
+ Color.BLUE,
+ Color.GREEN,
+ Color.YELLOW
+ )
+
+ /**
+ * The default minimum dimension for large screen devices.
+ *
+ * It is also the default value of [SplitPairRule.minWidthDp] and
+ * [SplitPairRule.minSmallestWidthDp] if the properties are not specified in static rule
+ * XML format.
+ */
+ const val DEFAULT_MINIMUM_WIDTH_DP = 600
+ }
+}
\ No newline at end of file
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityA.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitPipActivityA.kt
similarity index 93%
rename from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityA.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitPipActivityA.kt
index 7053e2d..eaffe18 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityA.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitPipActivityA.kt
@@ -14,6 +14,6 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+package androidx.window.demo.embedding
open class SplitPipActivityA : SplitPipActivityBase()
\ No newline at end of file
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityB.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitPipActivityB.kt
similarity index 95%
rename from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityB.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitPipActivityB.kt
index f47ab24..2446624 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityB.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitPipActivityB.kt
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+package androidx.window.demo.embedding
import android.graphics.Color
import android.os.Bundle
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityBase.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitPipActivityBase.kt
similarity index 87%
rename from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityBase.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitPipActivityBase.kt
index 9b76563..61c056c 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityBase.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitPipActivityBase.kt
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+package androidx.window.demo.embedding
import android.content.ComponentName
import android.content.Intent
@@ -27,19 +27,21 @@
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.util.Consumer
+import androidx.window.demo.R
+import androidx.window.demo.common.util.PictureInPictureUtil
+import androidx.window.demo.databinding.ActivitySplitPipActivityLayoutBinding
import androidx.window.embedding.ActivityFilter
import androidx.window.embedding.EmbeddingRule
import androidx.window.embedding.RuleController
+import androidx.window.embedding.SplitAttributes
import androidx.window.embedding.SplitController
import androidx.window.embedding.SplitInfo
import androidx.window.embedding.SplitPairFilter
import androidx.window.embedding.SplitPairRule
import androidx.window.embedding.SplitPlaceholderRule
-import androidx.window.embedding.SplitRule
-import androidx.window.sample.R
-import androidx.window.sample.databinding.ActivitySplitPipActivityLayoutBinding
-import androidx.window.sample.util.PictureInPictureUtil.setPictureInPictureParams
-import androidx.window.sample.util.PictureInPictureUtil.startPictureInPicture
+import androidx.window.embedding.SplitRule.FinishBehavior.Companion.ADJACENT
+import androidx.window.embedding.SplitRule.FinishBehavior.Companion.ALWAYS
+import androidx.window.embedding.SplitRule.FinishBehavior.Companion.NEVER
/**
* Sample showcase of split activity rules with picture-in-picture. Allows the user to select some
@@ -134,7 +136,7 @@
return
}
R.id.enter_pip_button -> {
- startPictureInPicture(this, autoEnterPip)
+ PictureInPictureUtil.startPictureInPicture(this, autoEnterPip)
}
}
}
@@ -159,14 +161,14 @@
}
}
}
- setPictureInPictureParams(this, autoEnterPip)
+ PictureInPictureUtil.setPictureInPictureParams(this, autoEnterPip)
}
/** Enters PiP if enterPipOnUserLeave checkbox is checked. */
override fun onUserLeaveHint() {
super.onUserLeaveHint()
if (enterPipOnUserLeave) {
- startPictureInPicture(this, autoEnterPip)
+ PictureInPictureUtil.startPictureInPicture(this, autoEnterPip)
}
}
@@ -182,10 +184,10 @@
viewBinding.splitMainCheckBox.isChecked = true
viewBinding.finishPrimaryWithSecondaryCheckBox.isEnabled = true
viewBinding.finishPrimaryWithSecondaryCheckBox.isChecked =
- splitRule.finishPrimaryWithSecondary == SplitRule.FINISH_ALWAYS
+ splitRule.finishPrimaryWithSecondary == ALWAYS
viewBinding.finishSecondaryWithPrimaryCheckBox.isEnabled = true
viewBinding.finishSecondaryWithPrimaryCheckBox.isChecked =
- splitRule.finishSecondaryWithPrimary == SplitRule.FINISH_ALWAYS
+ splitRule.finishSecondaryWithPrimary == ALWAYS
} else {
viewBinding.splitMainCheckBox.isChecked = false
viewBinding.finishPrimaryWithSecondaryCheckBox.isEnabled = false
@@ -236,7 +238,9 @@
/** Updates the split rules based on the current selection on checkboxes. */
private fun updateSplitRules() {
ruleController.clearRules()
-
+ val defaultSplitAttributes = SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.ratio(splitRatio))
+ .build()
if (viewBinding.splitMainCheckBox.isChecked) {
val pairFilters = HashSet<SplitPairFilter>()
pairFilters.add(SplitPairFilter(componentNameA, componentNameB, null))
@@ -245,13 +249,14 @@
val finishBWithA = viewBinding.finishSecondaryWithPrimaryCheckBox.isChecked
val rule = SplitPairRule.Builder(pairFilters)
.setMinWidthDp(0)
+ .setMinHeightDp(0)
.setMinSmallestWidthDp(0)
.setFinishPrimaryWithSecondary(
- if (finishAWithB) SplitRule.FINISH_ALWAYS else SplitRule.FINISH_NEVER)
+ if (finishAWithB) ALWAYS else NEVER)
.setFinishSecondaryWithPrimary(
- if (finishBWithA) SplitRule.FINISH_ALWAYS else SplitRule.FINISH_NEVER)
+ if (finishBWithA) ALWAYS else NEVER)
.setClearTop(true)
- .setSplitRatio(splitRatio)
+ .setDefaultSplitAttributes(defaultSplitAttributes)
.build()
ruleController.addRule(rule)
}
@@ -263,10 +268,11 @@
val isSticky = viewBinding.useStickyPlaceHolderCheckBox.isChecked
val rule = SplitPlaceholderRule.Builder(activityFilters, intent)
.setMinWidthDp(0)
+ .setMinHeightDp(0)
.setMinSmallestWidthDp(0)
.setSticky(isSticky)
- .setFinishPrimaryWithPlaceholder(SplitRule.FINISH_ADJACENT)
- .setSplitRatio(splitRatio)
+ .setFinishPrimaryWithPlaceholder(ADJACENT)
+ .setDefaultSplitAttributes(defaultSplitAttributes)
.build()
ruleController.addRule(rule)
}
@@ -291,7 +297,10 @@
override fun accept(newSplitInfos: List<SplitInfo>) {
var isInSplit = false
for (info in newSplitInfos) {
- if (info.contains(this@SplitPipActivityBase) && info.splitRatio > 0) {
+ if (info.contains(this@SplitPipActivityBase) &&
+ info.splitAttributes.splitType !is
+ SplitAttributes.SplitType.ExpandContainersSplitType
+ ) {
isInSplit = true
break
}
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityNoPip.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitPipActivityNoPip.kt
similarity index 95%
rename from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityNoPip.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitPipActivityNoPip.kt
index 3cfc28c..0af97fb 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityNoPip.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitPipActivityNoPip.kt
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+package androidx.window.demo.embedding
import android.os.Bundle
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityPlaceholder.kt b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitPipActivityPlaceholder.kt
similarity index 93%
rename from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityPlaceholder.kt
rename to window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitPipActivityPlaceholder.kt
index 7c8639b..5989917 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityPlaceholder.kt
+++ b/window/window-demos/demo/src/main/java/androidx/window/demo/embedding/SplitPipActivityPlaceholder.kt
@@ -14,6 +14,6 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+package androidx.window.demo.embedding
open class SplitPipActivityPlaceholder : SplitActivityPlaceholder()
\ No newline at end of file
diff --git a/window/window-samples/src/main/res/drawable/border.xml b/window/window-demos/demo/src/main/res/drawable/border.xml
similarity index 100%
rename from window/window-samples/src/main/res/drawable/border.xml
rename to window/window-demos/demo/src/main/res/drawable/border.xml
diff --git a/window/window-samples/src/main/res/drawable/ic_android_green_320dp.xml b/window/window-demos/demo/src/main/res/drawable/ic_android_green_320dp.xml
similarity index 100%
rename from window/window-samples/src/main/res/drawable/ic_android_green_320dp.xml
rename to window/window-demos/demo/src/main/res/drawable/ic_android_green_320dp.xml
diff --git a/window/window-samples/src/main/res/layout/activity_display_features_no_config_change.xml b/window/window-demos/demo/src/main/res/layout/activity_display_features_no_config_change.xml
similarity index 92%
copy from window/window-samples/src/main/res/layout/activity_display_features_no_config_change.xml
copy to window/window-demos/demo/src/main/res/layout/activity_display_features_no_config_change.xml
index 46ade36..3a86e95 100644
--- a/window/window-samples/src/main/res/layout/activity_display_features_no_config_change.xml
+++ b/window/window-demos/demo/src/main/res/layout/activity_display_features_no_config_change.xml
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
- Copyright 2021 The Android Open Source Project
+ 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.
@@ -22,7 +22,7 @@
android:id="@+id/rootLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
- tools:context="androidx.window.sample.DisplayFeaturesNoConfigChangeActivity">
+ tools:context="androidx.window.demo.DisplayFeaturesActivity">
<FrameLayout
android:id="@+id/feature_container_layout"
@@ -38,7 +38,7 @@
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@string/current_state"
- android:textAppearance="@style/TextAppearance.AppCompat.Large"
+ android:textAppearance="@style/TextAppearance.AppCompat"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
@@ -87,7 +87,7 @@
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toBottomOf="@+id/current_state"
+ app:layout_constraintTop_toBottomOf="@id/current_state"
app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
\ No newline at end of file
diff --git a/window/window-samples/src/main/res/layout/activity_foldin.xml b/window/window-demos/demo/src/main/res/layout/activity_foldin.xml
similarity index 100%
rename from window/window-samples/src/main/res/layout/activity_foldin.xml
rename to window/window-demos/demo/src/main/res/layout/activity_foldin.xml
diff --git a/window/window-samples/src/main/res/layout/activity_ime.xml b/window/window-demos/demo/src/main/res/layout/activity_ime.xml
similarity index 100%
rename from window/window-samples/src/main/res/layout/activity_ime.xml
rename to window/window-demos/demo/src/main/res/layout/activity_ime.xml
diff --git a/window/window-samples/src/main/res/layout/activity_organized_test_layout.xml b/window/window-demos/demo/src/main/res/layout/activity_organized_test_layout.xml
similarity index 100%
rename from window/window-samples/src/main/res/layout/activity_organized_test_layout.xml
rename to window/window-demos/demo/src/main/res/layout/activity_organized_test_layout.xml
diff --git a/window/window-demos/demo/src/main/res/layout/activity_rear_display.xml b/window/window-demos/demo/src/main/res/layout/activity_rear_display.xml
new file mode 100644
index 0000000..43bea60
--- /dev/null
+++ b/window/window-demos/demo/src/main/res/layout/activity_rear_display.xml
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="utf-8"?><!--
+ Copyright 2021 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.
+ -->
+
+<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ xmlns:app="http://schemas.android.com/apk/res-auto">
+
+ <androidx.recyclerview.widget.RecyclerView
+ android:id="@+id/rearStatusRecyclerView"
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
+ app:layout_constraintEnd_toEndOf="parent"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintTop_toTopOf="parent"/>
+
+ <Button
+ android:id="@+id/rear_display_button"
+ android:text="Enable RearDisplay"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:textAlignment="center"
+ android:layout_marginBottom="32dp"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintEnd_toEndOf="parent"
+ app:layout_constraintBottom_toBottomOf="parent" />
+
+</androidx.constraintlayout.widget.ConstraintLayout>
\ No newline at end of file
diff --git a/window/window-demos/demo/src/main/res/layout/activity_split_activity_layout.xml b/window/window-demos/demo/src/main/res/layout/activity_split_activity_layout.xml
new file mode 100644
index 0000000..0bbcddf
--- /dev/null
+++ b/window/window-demos/demo/src/main/res/layout/activity_split_activity_layout.xml
@@ -0,0 +1,191 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ Copyright 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.
+ -->
+
+<ScrollView
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/root_split_activity_layout"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent">
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="vertical"
+ android:padding="10dp">
+ <TextView
+ android:id="@+id/activity_embedded_status_text_view"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Activity is embedded" />
+
+ <CheckBox
+ android:id="@+id/splitMainCheckBox"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Split Main with other activities" />
+
+ <View
+ android:layout_width="match_parent"
+ android:layout_height="1dp"
+ android:layout_marginTop="10dp"
+ android:layout_marginBottom="10dp"
+ android:background="#AAAAAA" />
+
+ <Button
+ android:id="@+id/launch_b"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_centerHorizontal="true"
+ android:text="Launch B" />
+
+ <CheckBox
+ android:id="@+id/usePlaceholderCheckBox"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Use a placeholder for B" />
+
+ <CheckBox
+ android:id="@+id/useStickyPlaceholderCheckBox"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Placeholder is sticky" />
+
+ <View
+ android:layout_width="match_parent"
+ android:layout_height="1dp"
+ android:layout_marginTop="10dp"
+ android:layout_marginBottom="10dp"
+ android:background="#AAAAAA" />
+
+ <Button
+ android:id="@+id/launch_b_and_C"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_centerHorizontal="true"
+ android:text="Launch B and C" />
+
+ <CheckBox
+ android:id="@+id/splitBCCheckBox"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Split B with C" />
+
+ <CheckBox
+ android:id="@+id/finishBCCheckBox"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Finish B and C together"
+ android:enabled="false" />
+
+ <View
+ android:layout_width="match_parent"
+ android:layout_height="1dp"
+ android:layout_marginTop="10dp"
+ android:layout_marginBottom="10dp"
+ android:background="#AAAAAA" />
+
+ <Button
+ android:id="@+id/launch_e"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_centerHorizontal="true"
+ android:text="Launch E" />
+
+ <CheckBox
+ android:id="@+id/fullscreenECheckBox"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Always launch E in fullscreen" />
+
+ <View
+ android:layout_width="match_parent"
+ android:layout_height="1dp"
+ android:layout_marginTop="10dp"
+ android:layout_marginBottom="10dp"
+ android:background="#AAAAAA" />
+
+ <Button
+ android:id="@+id/launch_f"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_centerHorizontal="true"
+ android:text="Launch f" />
+
+ <Button
+ android:id="@+id/launch_f_pending_intent"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_centerHorizontal="true"
+ android:text="Launch F via Pending Intent" />
+
+ <CheckBox
+ android:id="@+id/splitWithFCheckBox"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Split everything with F" />
+
+ <View
+ android:layout_width="match_parent"
+ android:layout_height="1dp"
+ android:layout_marginTop="10dp"
+ android:layout_marginBottom="10dp"
+ android:background="#AAAAAA" />
+
+ <TextView
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="10dp"
+ android:layout_marginBottom="10dp"
+ android:text="Second app (UID)"
+ />
+
+ <Button
+ android:id="@+id/launch_uid2_trusted"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_centerHorizontal="true"
+ android:text="Launch with known certificate" />
+
+ <Button
+ android:id="@+id/launch_uid2_untrusted"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_centerHorizontal="true"
+ android:text="Launch in untrusted mode" />
+
+ <Button
+ android:id="@+id/launch_uid2_untrusted_display_features"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_centerHorizontal="true"
+ android:text="Launch display features" />
+
+ <View
+ android:layout_width="match_parent"
+ android:layout_height="1dp"
+ android:layout_marginTop="10dp"
+ android:layout_marginBottom="10dp"
+ android:background="#AAAAAA" />
+
+ <Button
+ android:id="@+id/launch_expanded_dialog_button"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_centerHorizontal="true"
+ android:text="Launch Expanded Dialog" />
+ </LinearLayout>
+</ScrollView>
\ No newline at end of file
diff --git a/window/window-samples/src/main/res/layout/activity_split_activity_list_detail_layout.xml b/window/window-demos/demo/src/main/res/layout/activity_split_activity_list_detail_layout.xml
similarity index 100%
rename from window/window-samples/src/main/res/layout/activity_split_activity_list_detail_layout.xml
rename to window/window-demos/demo/src/main/res/layout/activity_split_activity_list_detail_layout.xml
diff --git a/window/window-samples/src/main/res/layout/activity_split_activity_list_layout.xml b/window/window-demos/demo/src/main/res/layout/activity_split_activity_list_layout.xml
similarity index 100%
rename from window/window-samples/src/main/res/layout/activity_split_activity_list_layout.xml
rename to window/window-demos/demo/src/main/res/layout/activity_split_activity_list_layout.xml
diff --git a/window/window-samples/src/main/res/layout/activity_split_activity_placeholder_layout.xml b/window/window-demos/demo/src/main/res/layout/activity_split_activity_placeholder_layout.xml
similarity index 100%
rename from window/window-samples/src/main/res/layout/activity_split_activity_placeholder_layout.xml
rename to window/window-demos/demo/src/main/res/layout/activity_split_activity_placeholder_layout.xml
diff --git a/window/window-demos/demo/src/main/res/layout/activity_split_device_state_layout.xml b/window/window-demos/demo/src/main/res/layout/activity_split_device_state_layout.xml
new file mode 100644
index 0000000..eb67379
--- /dev/null
+++ b/window/window-demos/demo/src/main/res/layout/activity_split_device_state_layout.xml
@@ -0,0 +1,192 @@
+<?xml version="1.0" encoding="utf-8"?><!--
+ 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.
+ -->
+
+<ScrollView
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/root_split_activity_layout"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent">
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:orientation="vertical"
+ android:padding="10dp">
+
+ <TextView
+ android:id="@+id/activity_pair_split_attributes_text_view"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="@string/current_split_attributes"/>
+
+ <View
+ android:layout_width="match_parent"
+ android:layout_height="1dp"
+ android:layout_marginTop="10dp"
+ android:layout_marginBottom="10dp"
+ android:background="#AAAAAA" />
+
+ <TextView
+ android:id="@+id/choose_layout_text_view"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Choose the configuration to update the layout:" />
+
+ <RadioGroup
+ android:id="@+id/split_attributes_options_radio_group"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content">
+ <RadioButton
+ android:id="@+id/use_default_split_attributes"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:text="Use the default split attributes"
+ android:checked="true"/>
+
+ <!-- The fullscreen option group -->
+ <View
+ android:id="@+id/show_fullscreen_in_portrait_divider_top"
+ android:layout_width="match_parent"
+ android:layout_height="1dp"
+ android:layout_marginTop="10dp"
+ android:layout_marginBottom="10dp"
+ android:background="#AAAAAA"
+ android:visibility="gone"/>
+ <RadioButton
+ android:id="@+id/show_fullscreen_in_portrait_radio_button"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:text="Show fullscreen in portrait"
+ android:checked="true"/>
+ <CheckBox
+ android:id="@+id/show_horizontal_layout_in_tabletop_check_box"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:text="Also show horizontal layout in tabletop mode"
+ android:visibility="gone"/>
+ <View
+ android:id="@+id/show_fullscreen_in_portrait_divider_bottom"
+ android:layout_width="match_parent"
+ android:layout_height="1dp"
+ android:layout_marginTop="10dp"
+ android:layout_marginBottom="10dp"
+ android:background="#AAAAAA"
+ android:visibility="gone"/>
+ <!-- End of the fullscreen option group -->
+
+ <RadioButton
+ android:id="@+id/show_horizontal_layout_in_tabletop_radio_button"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:text="Show horizontal layout in tabletop mode"/>
+
+ <!-- The different layout option group -->
+ <View
+ android:id="@+id/show_different_layout_with_size_divider_top"
+ android:layout_width="match_parent"
+ android:layout_height="1dp"
+ android:layout_marginTop="10dp"
+ android:layout_marginBottom="10dp"
+ android:background="#AAAAAA"
+ android:visibility="gone"/>
+ <RadioButton
+ android:id="@+id/show_different_layout_with_size_radio_button"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:text="Show different layout with size"/>
+ <CheckBox
+ android:id="@+id/show_fullscreen_in_book_mode_check_box"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:text="Also show fullscreen in book mode"
+ android:visibility="gone"/>
+ <View
+ android:id="@+id/show_different_layout_with_size_divider_bottom"
+ android:layout_width="match_parent"
+ android:layout_height="1dp"
+ android:layout_marginTop="10dp"
+ android:layout_marginBottom="10dp"
+ android:background="#AAAAAA"
+ android:visibility="gone"/>
+ <!-- End of the different layout option group -->
+
+ <RadioButton
+ android:id="@+id/split_by_hinge_when_separating_radio_button"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:text="Show layout that follows the hinge when it is separated by hinge"/>
+ <CheckBox
+ android:id="@+id/swap_primary_secondary_position_check_box"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:text="Swap the position of primary and secondary container" />
+ </RadioGroup>
+
+ <View
+ android:layout_width="match_parent"
+ android:layout_height="1dp"
+ android:layout_marginTop="10dp"
+ android:layout_marginBottom="10dp"
+ android:background="#AAAAAA" />
+
+ <!-- Dropdown for animation background color -->
+
+ <TextView
+ android:id="@+id/animation_background_color_text_view"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="@string/current_animation_background_color"/>
+
+ <Spinner
+ android:id="@+id/animation_background_color_dropdown"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:spinnerMode="dropdown" />
+
+ <View
+ android:layout_width="match_parent"
+ android:layout_height="1dp"
+ android:layout_marginTop="10dp"
+ android:layout_marginBottom="10dp"
+ android:background="#AAAAAA" />
+
+ <Button
+ android:id="@+id/launch_activity_to_side"
+ android:layout_width="wrap_content"
+ android:layout_height="48dp"
+ android:layout_centerHorizontal="true"
+ android:text="Launch activity to side"/>
+
+ <View
+ android:layout_width="match_parent"
+ android:layout_height="1dp"
+ android:layout_marginTop="10dp"
+ android:layout_marginBottom="10dp"
+ android:background="#AAAAAA" />
+ <TextView
+ android:id="@+id/error_message_text_view"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"/>
+ </LinearLayout>
+</ScrollView>
\ No newline at end of file
diff --git a/window/window-samples/src/main/res/layout/activity_split_layout.xml b/window/window-demos/demo/src/main/res/layout/activity_split_layout.xml
similarity index 94%
rename from window/window-samples/src/main/res/layout/activity_split_layout.xml
rename to window/window-demos/demo/src/main/res/layout/activity_split_layout.xml
index 6950bf3..661df38 100644
--- a/window/window-samples/src/main/res/layout/activity_split_layout.xml
+++ b/window/window-demos/demo/src/main/res/layout/activity_split_layout.xml
@@ -24,7 +24,7 @@
android:layout_height="match_parent"
tools:context="SplitLayoutActivity">
- <androidx.window.sample.SplitLayout
+ <androidx.window.demo.SplitLayout
android:id="@+id/split_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
@@ -37,5 +37,5 @@
<include
android:id="@id/end_layout"
layout="@layout/split_layout_control" />
- </androidx.window.sample.SplitLayout>
+ </androidx.window.demo.SplitLayout>
</LinearLayout>
diff --git a/window/window-samples/src/main/res/layout/activity_split_pip_activity_layout.xml b/window/window-demos/demo/src/main/res/layout/activity_split_pip_activity_layout.xml
similarity index 100%
rename from window/window-samples/src/main/res/layout/activity_split_pip_activity_layout.xml
rename to window/window-demos/demo/src/main/res/layout/activity_split_pip_activity_layout.xml
diff --git a/window/window-samples/src/main/res/layout/activity_window_demos.xml b/window/window-demos/demo/src/main/res/layout/activity_window_demos.xml
similarity index 100%
rename from window/window-samples/src/main/res/layout/activity_window_demos.xml
rename to window/window-demos/demo/src/main/res/layout/activity_window_demos.xml
diff --git a/window/window-samples/src/main/res/layout/activity_window_metrics.xml b/window/window-demos/demo/src/main/res/layout/activity_window_metrics.xml
similarity index 100%
rename from window/window-samples/src/main/res/layout/activity_window_metrics.xml
rename to window/window-demos/demo/src/main/res/layout/activity_window_metrics.xml
diff --git a/window/window-samples/src/main/res/layout/presentation_second_display.xml b/window/window-demos/demo/src/main/res/layout/presentation_second_display.xml
similarity index 100%
rename from window/window-samples/src/main/res/layout/presentation_second_display.xml
rename to window/window-demos/demo/src/main/res/layout/presentation_second_display.xml
diff --git a/window/window-samples/src/main/res/layout/split_layout_content.xml b/window/window-demos/demo/src/main/res/layout/split_layout_content.xml
similarity index 100%
rename from window/window-samples/src/main/res/layout/split_layout_content.xml
rename to window/window-demos/demo/src/main/res/layout/split_layout_content.xml
diff --git a/window/window-samples/src/main/res/layout/split_layout_control.xml b/window/window-demos/demo/src/main/res/layout/split_layout_control.xml
similarity index 100%
rename from window/window-samples/src/main/res/layout/split_layout_control.xml
rename to window/window-demos/demo/src/main/res/layout/split_layout_control.xml
diff --git a/window/window-demos/demo/src/main/res/layout/test_ime.xml b/window/window-demos/demo/src/main/res/layout/test_ime.xml
new file mode 100644
index 0000000..07f5691
--- /dev/null
+++ b/window/window-demos/demo/src/main/res/layout/test_ime.xml
@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="utf-8"?><!--
+ 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.
+ -->
+
+<LinearLayout
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:app="http://schemas.android.com/apk/res-auto"
+ android:orientation="vertical"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:background="@color/imeBackground">
+
+ <androidx.recyclerview.widget.RecyclerView
+ android:id="@+id/recycler_view"
+ android:layout_width="match_parent"
+ android:layout_height="140dp"
+ app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
+
+ <LinearLayout
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:orientation="horizontal">
+
+ <Button
+ android:id="@+id/button_clear"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="@string/test_ime_button_clear"/>
+
+ <Button
+ android:id="@+id/button_close"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="@string/test_ime_button_close"/>
+
+ </LinearLayout>
+
+</LinearLayout>
\ No newline at end of file
diff --git a/window/window-samples/src/main/res/layout/view_holder_demo_item.xml b/window/window-demos/demo/src/main/res/layout/view_holder_demo_item.xml
similarity index 100%
rename from window/window-samples/src/main/res/layout/view_holder_demo_item.xml
rename to window/window-demos/demo/src/main/res/layout/view_holder_demo_item.xml
diff --git a/window/window-samples/src/main/res/menu/picture_in_picture_menu.xml b/window/window-demos/demo/src/main/res/menu/picture_in_picture_menu.xml
similarity index 100%
rename from window/window-samples/src/main/res/menu/picture_in_picture_menu.xml
rename to window/window-demos/demo/src/main/res/menu/picture_in_picture_menu.xml
diff --git a/window/window-samples/src/main/res/values/attrs.xml b/window/window-demos/demo/src/main/res/values/attrs.xml
similarity index 100%
rename from window/window-samples/src/main/res/values/attrs.xml
rename to window/window-demos/demo/src/main/res/values/attrs.xml
diff --git a/window/window-samples/src/main/res/values/colors.xml b/window/window-demos/demo/src/main/res/values/colors.xml
similarity index 95%
rename from window/window-samples/src/main/res/values/colors.xml
rename to window/window-demos/demo/src/main/res/values/colors.xml
index 41a72b2..95a6cfe 100644
--- a/window/window-samples/src/main/res/values/colors.xml
+++ b/window/window-demos/demo/src/main/res/values/colors.xml
@@ -24,4 +24,6 @@
<color name="colorSplitContentBackground">#3B6BDB4C</color>
<color name="colorSplitControlsBackground">#475ABFF3</color>
+
+ <color name="imeBackground">#EEEEEE</color>
</resources>
diff --git a/window/window-samples/src/main/res/values/strings.xml b/window/window-demos/demo/src/main/res/values/strings.xml
similarity index 83%
rename from window/window-samples/src/main/res/values/strings.xml
rename to window/window-demos/demo/src/main/res/values/strings.xml
index 45e3de2..1a86d90 100644
--- a/window/window-samples/src/main/res/values/strings.xml
+++ b/window/window-demos/demo/src/main/res/values/strings.xml
@@ -16,9 +16,7 @@
<resources>
<string name="app_name">WindowSamples</string>
- <string name="current_state">Current state</string>
<string name="deviceState">Device state</string>
- <string name="window_layout">Window layout</string>
<string name="fold">Fold</string>
<string name="legend">Legend:</string>
<string name="content_title">Content title</string>
@@ -43,15 +41,14 @@
<string name="show_all_display_features_no_config_change_description">Show all display features of the device on the screen and do not handle config changes. The activity is recreated instead on rotation or resize</string>
<string name="split_layout_demo_description">Demo of a layout that splits the content to sides of a fold or a hinge. If not present or minimal size requirements are not meant, it behave like a FrameLayout.</string>
<string name="presentation_demo_description">Demo of using Presentation API to show content on secondary display.</string>
- <string name="screens_are_separated">"Screens are separated"</string>
- <string name="screens_are_not_separated">"Screen is not separated"</string>
- <string name="screen_is_horizontal">"Hinge is horizontal"</string>
- <string name="screen_is_vertical">"Hinge is vertical"</string>
- <string name="occlusion_is_full">Occlusion is full</string>
- <string name="occlusion_is_none">Occlusion is none</string>
<string name="window_metrics">Window metrics</string>
<string name="window_metrics_description">Demo of using WindowMetrics API with activity handling rotations.</string>
+ <string name="rear_display">Rear Display Mode</string>
+ <string name="rear_display_description">Demo of observing to WindowAreaStatus and enabling/disabling RearDisplay mode</string>
+ <string name="current_split_attributes">Current SplitAttributes:</string>>
+ <string name="current_animation_background_color">Current Animation Background Color:</string>>
<string name="test_ime">Test IME</string>
+ <string name="test_ime_button_clear">Clear Logs</string>
<string name="test_ime_button_close">Close Test IME</string>
<string name="window_metrics_ime_hint">Tap to open IME</string>
<string name="ime">IME</string>
@@ -59,4 +56,6 @@
<string name="ime_demo_reminder">Reminder: To use the Test IME bundled with this application, remember to enable it in System Settings.</string>
<string name="ime_button_settings">System IME Settings</string>
<string name="ime_button_switch_default">Switch default IME</string>
+ <string name="install_samples_2">Install window-demos:demo-second-app to launch activities from a different UID.</string>
+ <string name="toast_split_not_support">Please enable PROPERTY_ACTIVITY_EMBEDDING_SPLITS_ENABLED and ensure device supports splits.</string>
</resources>
diff --git a/window/window-samples/src/main/res/values/styles.xml b/window/window-demos/demo/src/main/res/values/styles.xml
similarity index 78%
copy from window/window-samples/src/main/res/values/styles.xml
copy to window/window-demos/demo/src/main/res/values/styles.xml
index eaa9ab2..5586114 100644
--- a/window/window-samples/src/main/res/values/styles.xml
+++ b/window/window-demos/demo/src/main/res/values/styles.xml
@@ -24,4 +24,9 @@
<item name="colorAccent">@color/colorAccent</item>
</style>
+ <!-- Theme to show the expanded dialog Activity as transparent. -->
+ <style name="ExpandedDialogTheme" parent="Theme.AppCompat.Dialog.Alert">
+ <item name="windowNoTitle">true</item>
+ <item name="android:windowActionBar">false</item>
+ </style>
</resources>
diff --git a/window/window-samples/src/main/res/xml/main_split_config.xml b/window/window-demos/demo/src/main/res/xml/main_split_config.xml
similarity index 73%
rename from window/window-samples/src/main/res/xml/main_split_config.xml
rename to window/window-demos/demo/src/main/res/xml/main_split_config.xml
index 5b93a1c..e4b150d 100644
--- a/window/window-samples/src/main/res/xml/main_split_config.xml
+++ b/window/window-demos/demo/src/main/res/xml/main_split_config.xml
@@ -20,14 +20,14 @@
window:finishPrimaryWithSecondary="always"
window:finishSecondaryWithPrimary="adjacent">
<SplitPairFilter
- window:primaryActivityName="androidx.window.sample.embedding.SplitActivityList"
- window:secondaryActivityName="androidx.window.sample.embedding.SplitActivityDetail"/>
+ window:primaryActivityName="androidx.window.demo.embedding.SplitActivityList"
+ window:secondaryActivityName="androidx.window.demo.embedding.SplitActivityDetail"/>
</SplitPairRule>
<SplitPlaceholderRule
- window:placeholderActivityName="androidx.window.sample.embedding.SplitActivityListPlaceholder"
+ window:placeholderActivityName="androidx.window.demo.embedding.SplitActivityListPlaceholder"
window:stickyPlaceholder="true"
window:finishPrimaryWithSecondary="adjacent">
<ActivityFilter
- window:activityName="androidx.window.sample.embedding.SplitActivityList"/>
+ window:activityName="androidx.window.demo.embedding.SplitActivityList"/>
</SplitPlaceholderRule>
</resources>
\ No newline at end of file
diff --git a/window/window-samples/src/main/res/xml/method.xml b/window/window-demos/demo/src/main/res/xml/method.xml
similarity index 100%
rename from window/window-samples/src/main/res/xml/method.xml
rename to window/window-demos/demo/src/main/res/xml/method.xml
diff --git a/window/window-java/api/current.txt b/window/window-java/api/current.txt
index 709904b..39c35ac 100644
--- a/window/window-java/api/current.txt
+++ b/window/window-java/api/current.txt
@@ -4,6 +4,7 @@
public final class WindowInfoTrackerCallbackAdapter implements androidx.window.layout.WindowInfoTracker {
ctor public WindowInfoTrackerCallbackAdapter(androidx.window.layout.WindowInfoTracker tracker);
method public void addWindowLayoutInfoListener(android.app.Activity activity, java.util.concurrent.Executor executor, androidx.core.util.Consumer<androidx.window.layout.WindowLayoutInfo> consumer);
+ method public void addWindowLayoutInfoListener(@UiContext android.content.Context context, java.util.concurrent.Executor executor, androidx.core.util.Consumer<androidx.window.layout.WindowLayoutInfo> consumer);
method public void removeWindowLayoutInfoListener(androidx.core.util.Consumer<androidx.window.layout.WindowLayoutInfo> consumer);
}
diff --git a/window/window-java/api/public_plus_experimental_current.txt b/window/window-java/api/public_plus_experimental_current.txt
index 709904b..ded945be 100644
--- a/window/window-java/api/public_plus_experimental_current.txt
+++ b/window/window-java/api/public_plus_experimental_current.txt
@@ -1,9 +1,21 @@
// Signature format: 4.0
+package androidx.window.java.area {
+
+ @androidx.window.core.ExperimentalWindowApi public final class WindowAreaControllerJavaAdapter implements androidx.window.area.WindowAreaController {
+ ctor public WindowAreaControllerJavaAdapter(androidx.window.area.WindowAreaController controller);
+ method public void addRearDisplayStatusListener(java.util.concurrent.Executor executor, androidx.core.util.Consumer<androidx.window.area.WindowAreaStatus> consumer);
+ method public void removeRearDisplayStatusListener(androidx.core.util.Consumer<androidx.window.area.WindowAreaStatus> consumer);
+ method public void startRearDisplayModeSession(android.app.Activity activity, java.util.concurrent.Executor executor, androidx.window.area.WindowAreaSessionCallback windowAreaSessionCallback);
+ }
+
+}
+
package androidx.window.java.layout {
public final class WindowInfoTrackerCallbackAdapter implements androidx.window.layout.WindowInfoTracker {
ctor public WindowInfoTrackerCallbackAdapter(androidx.window.layout.WindowInfoTracker tracker);
method public void addWindowLayoutInfoListener(android.app.Activity activity, java.util.concurrent.Executor executor, androidx.core.util.Consumer<androidx.window.layout.WindowLayoutInfo> consumer);
+ method public void addWindowLayoutInfoListener(@UiContext android.content.Context context, java.util.concurrent.Executor executor, androidx.core.util.Consumer<androidx.window.layout.WindowLayoutInfo> consumer);
method public void removeWindowLayoutInfoListener(androidx.core.util.Consumer<androidx.window.layout.WindowLayoutInfo> consumer);
}
diff --git a/window/window-java/api/restricted_current.txt b/window/window-java/api/restricted_current.txt
index 709904b..39c35ac 100644
--- a/window/window-java/api/restricted_current.txt
+++ b/window/window-java/api/restricted_current.txt
@@ -4,6 +4,7 @@
public final class WindowInfoTrackerCallbackAdapter implements androidx.window.layout.WindowInfoTracker {
ctor public WindowInfoTrackerCallbackAdapter(androidx.window.layout.WindowInfoTracker tracker);
method public void addWindowLayoutInfoListener(android.app.Activity activity, java.util.concurrent.Executor executor, androidx.core.util.Consumer<androidx.window.layout.WindowLayoutInfo> consumer);
+ method public void addWindowLayoutInfoListener(@UiContext android.content.Context context, java.util.concurrent.Executor executor, androidx.core.util.Consumer<androidx.window.layout.WindowLayoutInfo> consumer);
method public void removeWindowLayoutInfoListener(androidx.core.util.Consumer<androidx.window.layout.WindowLayoutInfo> consumer);
}
diff --git a/window/window-java/src/androidTest/java/androidx/window/java/layout/WindowInfoTrackerCallbackAdapterTest.kt b/window/window-java/src/androidTest/java/androidx/window/java/layout/WindowInfoTrackerCallbackAdapterTest.kt
index 8c4fc81..74b3d87 100644
--- a/window/window-java/src/androidTest/java/androidx/window/java/layout/WindowInfoTrackerCallbackAdapterTest.kt
+++ b/window/window-java/src/androidTest/java/androidx/window/java/layout/WindowInfoTrackerCallbackAdapterTest.kt
@@ -17,6 +17,7 @@
package androidx.window.java.layout
import android.app.Activity
+import android.content.Context
import androidx.window.java.TestConsumer
import androidx.window.layout.FoldingFeature
import androidx.window.layout.WindowInfoTracker
@@ -52,6 +53,21 @@
}
@Test
+ public fun testRegisterListenerForUiContext() {
+ val context = mock<Context>()
+ val feature = mock<FoldingFeature>()
+ val expected = WindowLayoutInfo(listOf(feature))
+ val mockTracker = mock<WindowInfoTracker>()
+ whenever(mockTracker.windowLayoutInfo(context)).thenReturn(flowOf(expected))
+ val unitUnderTest = WindowInfoTrackerCallbackAdapter(mockTracker)
+ val testConsumer = TestConsumer<WindowLayoutInfo>()
+
+ unitUnderTest.addWindowLayoutInfoListener(context, Runnable::run, testConsumer)
+
+ testConsumer.assertValue(expected)
+ }
+
+ @Test
public fun testWindowLayoutInfo_registerMultipleIsNoOp() {
val activity = mock<Activity>()
val feature = mock<FoldingFeature>()
@@ -86,4 +102,24 @@
assertTrue(accepted)
testConsumer.assertEmpty()
}
+
+ @Test
+ public fun testWindowLayoutInfo_unregisterForUiContext() {
+ val context = mock<Context>()
+ val feature = mock<FoldingFeature>()
+ val info = WindowLayoutInfo(listOf(feature))
+ val mockTracker = mock<WindowInfoTracker>()
+ val channel = Channel<WindowLayoutInfo>()
+ whenever(mockTracker.windowLayoutInfo(context)).thenReturn(channel.receiveAsFlow())
+ val unitUnderTest = WindowInfoTrackerCallbackAdapter(mockTracker)
+ val testConsumer = TestConsumer<WindowLayoutInfo>()
+
+ unitUnderTest.addWindowLayoutInfoListener(context, Runnable::run, testConsumer)
+ unitUnderTest.addWindowLayoutInfoListener(context, Runnable::run, mock())
+ unitUnderTest.removeWindowLayoutInfoListener(testConsumer)
+ val accepted = channel.trySend(info).isSuccess
+
+ assertTrue(accepted)
+ testConsumer.assertEmpty()
+ }
}
diff --git a/window/window-java/src/main/java/androidx/window/java/area/WindowAreaControllerJavaAdapter.kt b/window/window-java/src/main/java/androidx/window/java/area/WindowAreaControllerJavaAdapter.kt
new file mode 100644
index 0000000..584445f
--- /dev/null
+++ b/window/window-java/src/main/java/androidx/window/java/area/WindowAreaControllerJavaAdapter.kt
@@ -0,0 +1,125 @@
+/*
+ * Copyright 2021 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 androidx.window.java.area
+
+import android.app.Activity
+import androidx.core.util.Consumer
+import androidx.window.area.WindowAreaSessionCallback
+import androidx.window.area.WindowAreaStatus
+import androidx.window.area.WindowAreaController
+import androidx.window.core.ExperimentalWindowApi
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.asCoroutineDispatcher
+import kotlinx.coroutines.flow.collect
+import kotlinx.coroutines.launch
+import java.util.concurrent.Executor
+import java.util.concurrent.locks.ReentrantLock
+import kotlin.concurrent.withLock
+
+/**
+ * An adapted interface for [WindowAreaController] that provides the information and
+ * functionality around RearDisplay Mode via a callback shaped API.
+ */
+@ExperimentalWindowApi
+class WindowAreaControllerJavaAdapter(
+ private val controller: WindowAreaController
+) : WindowAreaController by controller {
+
+ /**
+ * A [ReentrantLock] to protect against concurrent access to [consumerToJobMap].
+ */
+ private val lock = ReentrantLock()
+ private val consumerToJobMap = mutableMapOf<Consumer<*>, Job>()
+
+ /**
+ * Registers a listener to consume [WindowAreaStatus] values defined as
+ * [WindowAreaStatus.UNSUPPORTED], [WindowAreaStatus.UNAVAILABLE], and
+ * [WindowAreaStatus.AVAILABLE]. The values provided through this listener should be used
+ * to determine if you are able to enable rear display Mode at that time. You can use these
+ * values to modify your UI to show/hide controls and determine when to enable features
+ * that use rear display Mode. You should only try and enter rear display mode when your
+ * [consumer] is provided a value of [WindowAreaStatus.AVAILABLE].
+ *
+ * The [consumer] will be provided an initial value on registration, as well as any change
+ * to the status as they occur. This could happen due to hardware device state changes, or if
+ * another process has enabled RearDisplay Mode.
+ *
+ * @see WindowAreaController.rearDisplayStatus
+ */
+ fun addRearDisplayStatusListener(
+ executor: Executor,
+ consumer: Consumer<WindowAreaStatus>
+ ) {
+ val statusFlow = controller.rearDisplayStatus()
+ lock.withLock {
+ if (consumerToJobMap[consumer] == null) {
+ val scope = CoroutineScope(executor.asCoroutineDispatcher())
+ consumerToJobMap[consumer] = scope.launch {
+ statusFlow.collect { consumer.accept(it) }
+ }
+ }
+ }
+ }
+
+ /**
+ * Removes a listener of [WindowAreaStatus] values
+ * @see WindowAreaController.rearDisplayStatus
+ */
+ fun removeRearDisplayStatusListener(consumer: Consumer<WindowAreaStatus>) {
+ lock.withLock {
+ consumerToJobMap[consumer]?.cancel()
+ consumerToJobMap.remove(consumer)
+ }
+ }
+
+ /**
+ * Starts a RearDisplay Mode session and provides updates through the
+ * [WindowAreaSessionCallback] provided. Due to the nature of moving your Activity to a
+ * different display, your Activity will likely go through a configuration change. Because of
+ * this, if your Activity does not override configuration changes, this method should be called
+ * from a component that outlives the Activity lifecycle such as a
+ * [androidx.lifecycle.ViewModel]. If your Activity does override
+ * configuration changes, it is safe to call this method inside your Activity.
+ *
+ * This method should only be called if you have received a [WindowAreaStatus.AVAILABLE]
+ * value from the listener provided through the [addRearDisplayStatusListener] method. If
+ * you try and enable RearDisplay mode without it being available, you will receive an
+ * [UnsupportedOperationException].
+ *
+ * The [windowAreaSessionCallback] provided will receive a call to
+ * [WindowAreaSessionCallback.onSessionStarted] after your Activity has been moved to the
+ * display corresponding to this mode. RearDisplay mode will stay active until the session
+ * provided through [WindowAreaSessionCallback.onSessionStarted] is closed, or there is a device
+ * state change that makes RearDisplay mode incompatible such as if the device is closed so the
+ * outer-display is no longer in line with the rear camera. When this occurs,
+ * [WindowAreaSessionCallback.onSessionEnded] is called to notify you the session has been
+ * ended.
+ *
+ * @see addRearDisplayStatusListener
+ * @throws UnsupportedOperationException if you try and start a RearDisplay session when
+ * your [WindowAreaController.rearDisplayStatus] does not return a value of
+ * [WindowAreaStatus.AVAILABLE]
+ */
+ fun startRearDisplayModeSession(
+ activity: Activity,
+ executor: Executor,
+ windowAreaSessionCallback: WindowAreaSessionCallback
+ ) {
+ controller.rearDisplayMode(activity, executor, windowAreaSessionCallback)
+ }
+}
\ No newline at end of file
diff --git a/window/window-java/src/main/java/androidx/window/java/layout/WindowInfoTrackerCallbackAdapter.kt b/window/window-java/src/main/java/androidx/window/java/layout/WindowInfoTrackerCallbackAdapter.kt
index 5d716c6..5966d28 100644
--- a/window/window-java/src/main/java/androidx/window/java/layout/WindowInfoTrackerCallbackAdapter.kt
+++ b/window/window-java/src/main/java/androidx/window/java/layout/WindowInfoTrackerCallbackAdapter.kt
@@ -17,7 +17,10 @@
package androidx.window.java.layout
import android.app.Activity
+import android.content.Context
+import androidx.annotation.UiContext
import androidx.core.util.Consumer
+import android.inputmethodservice.InputMethodService
import androidx.window.layout.WindowInfoTracker
import androidx.window.layout.WindowLayoutInfo
import kotlinx.coroutines.CoroutineScope
@@ -45,8 +48,11 @@
private val consumerToJobMap = mutableMapOf<Consumer<*>, Job>()
/**
- * Register a listener to consume [WindowLayoutInfo] values. If the same consumer is
- * registered twice then this method is a no-op.
+ * Registers a listener to consume [WindowLayoutInfo] values of the [Activity] window. If the
+ * same consumer is registered twice then this method is a no-op.
+ * @param activity an [Activity] that hosts a [Window].
+ * @param executor that the consumer will invoke on.
+ * @param consumer for [WindowLayoutInfo] values.
* @see WindowInfoTracker.windowLayoutInfo
*/
fun addWindowLayoutInfoListener(
@@ -58,6 +64,23 @@
}
/**
+ * Registers a [UiContext] listener to consume [WindowLayoutInfo] values. If the same consumer
+ * is registered twice then this method is a no-op.
+ * @param context a [UiContext] such as an [Activity], created with
+ * [Context#createWindowContext] or is a [InputMethodService].
+ * @param executor that the consumer will invoke on.
+ * @param consumer for [WindowLayoutInfo] values.
+ * @see WindowInfoTracker.windowLayoutInfo
+ */
+ fun addWindowLayoutInfoListener(
+ @UiContext context: Context,
+ executor: Executor,
+ consumer: Consumer<WindowLayoutInfo>
+ ) {
+ addListener(executor, consumer, tracker.windowLayoutInfo(context))
+ }
+
+ /**
* Remove a listener to stop consuming [WindowLayoutInfo] values. If the listener has already
* been removed then this is a no-op.
* @see WindowInfoTracker.windowLayoutInfo
diff --git a/window/window-rxjava2/api/api_lint.ignore b/window/window-rxjava2/api/api_lint.ignore
new file mode 100644
index 0000000..636cfcc
--- /dev/null
+++ b/window/window-rxjava2/api/api_lint.ignore
@@ -0,0 +1,5 @@
+// Baseline format: 1.0
+ContextFirst: androidx.window.rxjava2.layout.WindowInfoTrackerRx#windowLayoutInfoFlowable(androidx.window.layout.WindowInfoTracker, android.content.Context) parameter #1:
+ Context is distinct, so it must be the first argument (method `windowLayoutInfoFlowable`)
+ContextFirst: androidx.window.rxjava2.layout.WindowInfoTrackerRx#windowLayoutInfoObservable(androidx.window.layout.WindowInfoTracker, android.content.Context) parameter #1:
+ Context is distinct, so it must be the first argument (method `windowLayoutInfoObservable`)
diff --git a/window/window-rxjava2/api/current.txt b/window/window-rxjava2/api/current.txt
index 8135cee..5250696 100644
--- a/window/window-rxjava2/api/current.txt
+++ b/window/window-rxjava2/api/current.txt
@@ -3,7 +3,9 @@
public final class WindowInfoTrackerRx {
method public static io.reactivex.Flowable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoFlowable(androidx.window.layout.WindowInfoTracker, android.app.Activity activity);
+ method public static io.reactivex.Flowable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoFlowable(androidx.window.layout.WindowInfoTracker, @UiContext android.content.Context context);
method public static io.reactivex.Observable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoObservable(androidx.window.layout.WindowInfoTracker, android.app.Activity activity);
+ method public static io.reactivex.Observable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoObservable(androidx.window.layout.WindowInfoTracker, @UiContext android.content.Context context);
}
}
diff --git a/window/window-rxjava2/api/public_plus_experimental_current.txt b/window/window-rxjava2/api/public_plus_experimental_current.txt
index 8135cee..5250696 100644
--- a/window/window-rxjava2/api/public_plus_experimental_current.txt
+++ b/window/window-rxjava2/api/public_plus_experimental_current.txt
@@ -3,7 +3,9 @@
public final class WindowInfoTrackerRx {
method public static io.reactivex.Flowable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoFlowable(androidx.window.layout.WindowInfoTracker, android.app.Activity activity);
+ method public static io.reactivex.Flowable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoFlowable(androidx.window.layout.WindowInfoTracker, @UiContext android.content.Context context);
method public static io.reactivex.Observable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoObservable(androidx.window.layout.WindowInfoTracker, android.app.Activity activity);
+ method public static io.reactivex.Observable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoObservable(androidx.window.layout.WindowInfoTracker, @UiContext android.content.Context context);
}
}
diff --git a/window/window-rxjava2/api/restricted_current.txt b/window/window-rxjava2/api/restricted_current.txt
index 8135cee..5250696 100644
--- a/window/window-rxjava2/api/restricted_current.txt
+++ b/window/window-rxjava2/api/restricted_current.txt
@@ -3,7 +3,9 @@
public final class WindowInfoTrackerRx {
method public static io.reactivex.Flowable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoFlowable(androidx.window.layout.WindowInfoTracker, android.app.Activity activity);
+ method public static io.reactivex.Flowable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoFlowable(androidx.window.layout.WindowInfoTracker, @UiContext android.content.Context context);
method public static io.reactivex.Observable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoObservable(androidx.window.layout.WindowInfoTracker, android.app.Activity activity);
+ method public static io.reactivex.Observable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoObservable(androidx.window.layout.WindowInfoTracker, @UiContext android.content.Context context);
}
}
diff --git a/window/window-rxjava2/build.gradle b/window/window-rxjava2/build.gradle
index 389a75c..dee2b16 100644
--- a/window/window-rxjava2/build.gradle
+++ b/window/window-rxjava2/build.gradle
@@ -37,6 +37,7 @@
api(libs.kotlinCoroutinesRx2)
api(libs.rxjava2)
api(project(":window:window"))
+ implementation 'androidx.annotation:annotation:1.5.0'
androidTestImplementation(libs.testExtJunit)
androidTestImplementation(libs.testRunner)
diff --git a/window/window-rxjava2/src/androidTest/java/androidx/window/rxjava2/layout/WindowInfoTrackerRxTest.kt b/window/window-rxjava2/src/androidTest/java/androidx/window/rxjava2/layout/WindowInfoTrackerRxTest.kt
index a22df89..418725d 100644
--- a/window/window-rxjava2/src/androidTest/java/androidx/window/rxjava2/layout/WindowInfoTrackerRxTest.kt
+++ b/window/window-rxjava2/src/androidTest/java/androidx/window/rxjava2/layout/WindowInfoTrackerRxTest.kt
@@ -17,6 +17,7 @@
package androidx.window.rxjava2.layout
import android.app.Activity
+import android.content.Context
import androidx.window.layout.FoldingFeature
import androidx.window.layout.WindowInfoTracker
import androidx.window.layout.WindowLayoutInfo
@@ -28,10 +29,10 @@
/**
* Tests for the RxJava 2 adapters.
*/
-public class WindowInfoTrackerRxTest {
+class WindowInfoTrackerRxTest {
@Test
- public fun testWindowLayoutInfoObservable() {
+ fun testWindowLayoutInfoObservable() {
val activity = mock<Activity>()
val feature = mock<FoldingFeature>()
val expected = WindowLayoutInfo(listOf(feature))
@@ -44,7 +45,7 @@
}
@Test
- public fun testWindowLayoutInfoFlowable() {
+ fun testWindowLayoutInfoFlowable() {
val activity = mock<Activity>()
val feature = mock<FoldingFeature>()
val expected = WindowLayoutInfo(listOf(feature))
@@ -55,4 +56,29 @@
testSubscriber.assertValue(expected)
}
+ @Test
+ fun testWindowLayoutInfoObservable_context() {
+ val activity = mock<Context>()
+ val feature = mock<FoldingFeature>()
+ val expected = WindowLayoutInfo(listOf(feature))
+ val mockTracker = mock<WindowInfoTracker>()
+ whenever(mockTracker.windowLayoutInfo(activity)).thenReturn(flowOf(expected))
+
+ val testSubscriber = mockTracker.windowLayoutInfoObservable(activity).test()
+
+ testSubscriber.assertValue(expected)
+ }
+
+ @Test
+ fun testWindowLayoutInfoFlowable_context() {
+ val activity = mock<Context>()
+ val feature = mock<FoldingFeature>()
+ val expected = WindowLayoutInfo(listOf(feature))
+ val mockTracker = mock<WindowInfoTracker>()
+ whenever(mockTracker.windowLayoutInfo(activity)).thenReturn(flowOf(expected))
+
+ val testSubscriber = mockTracker.windowLayoutInfoFlowable(activity).test()
+
+ testSubscriber.assertValue(expected)
+ }
}
diff --git a/window/window-rxjava2/src/main/java/androidx/window/rxjava2/layout/WindowInfoTrackerRx.kt b/window/window-rxjava2/src/main/java/androidx/window/rxjava2/layout/WindowInfoTrackerRx.kt
index 2a82d8c..d41cc80 100644
--- a/window/window-rxjava2/src/main/java/androidx/window/rxjava2/layout/WindowInfoTrackerRx.kt
+++ b/window/window-rxjava2/src/main/java/androidx/window/rxjava2/layout/WindowInfoTrackerRx.kt
@@ -18,6 +18,8 @@
package androidx.window.rxjava2.layout
import android.app.Activity
+import android.content.Context
+import androidx.annotation.UiContext
import androidx.window.layout.WindowInfoTracker
import androidx.window.layout.WindowLayoutInfo
import io.reactivex.Flowable
@@ -29,7 +31,7 @@
* Return an [Observable] stream of [WindowLayoutInfo].
* @see WindowInfoTracker.windowLayoutInfo
*/
-public fun WindowInfoTracker.windowLayoutInfoObservable(
+fun WindowInfoTracker.windowLayoutInfoObservable(
activity: Activity
): Observable<WindowLayoutInfo> {
return windowLayoutInfo(activity).asObservable()
@@ -39,8 +41,28 @@
* Return a [Flowable] stream of [WindowLayoutInfo].
* @see WindowInfoTracker.windowLayoutInfo
*/
-public fun WindowInfoTracker.windowLayoutInfoFlowable(
+fun WindowInfoTracker.windowLayoutInfoFlowable(
activity: Activity
): Flowable<WindowLayoutInfo> {
return windowLayoutInfo(activity).asFlowable()
}
+
+/**
+ * Return an [Observable] stream of [WindowLayoutInfo].
+ * @see WindowInfoTracker.windowLayoutInfo
+ */
+fun WindowInfoTracker.windowLayoutInfoObservable(
+ @UiContext context: Context
+): Observable<WindowLayoutInfo> {
+ return windowLayoutInfo(context).asObservable()
+}
+
+/**
+ * Return a [Flowable] stream of [WindowLayoutInfo].
+ * @see WindowInfoTracker.windowLayoutInfo
+ */
+fun WindowInfoTracker.windowLayoutInfoFlowable(
+ @UiContext context: Context
+): Flowable<WindowLayoutInfo> {
+ return windowLayoutInfo(context).asFlowable()
+}
diff --git a/window/window-rxjava3/api/api_lint.ignore b/window/window-rxjava3/api/api_lint.ignore
new file mode 100644
index 0000000..8c55c33
--- /dev/null
+++ b/window/window-rxjava3/api/api_lint.ignore
@@ -0,0 +1,5 @@
+// Baseline format: 1.0
+ContextFirst: androidx.window.rxjava3.layout.WindowInfoTrackerRx#windowLayoutInfoFlowable(androidx.window.layout.WindowInfoTracker, android.content.Context) parameter #1:
+ Context is distinct, so it must be the first argument (method `windowLayoutInfoFlowable`)
+ContextFirst: androidx.window.rxjava3.layout.WindowInfoTrackerRx#windowLayoutInfoObservable(androidx.window.layout.WindowInfoTracker, android.content.Context) parameter #1:
+ Context is distinct, so it must be the first argument (method `windowLayoutInfoObservable`)
diff --git a/window/window-rxjava3/api/current.txt b/window/window-rxjava3/api/current.txt
index 5700dd3..23510cc 100644
--- a/window/window-rxjava3/api/current.txt
+++ b/window/window-rxjava3/api/current.txt
@@ -3,7 +3,9 @@
public final class WindowInfoTrackerRx {
method public static io.reactivex.rxjava3.core.Flowable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoFlowable(androidx.window.layout.WindowInfoTracker, android.app.Activity activity);
+ method public static io.reactivex.rxjava3.core.Flowable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoFlowable(androidx.window.layout.WindowInfoTracker, @UiContext android.content.Context context);
method public static io.reactivex.rxjava3.core.Observable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoObservable(androidx.window.layout.WindowInfoTracker, android.app.Activity activity);
+ method public static io.reactivex.rxjava3.core.Observable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoObservable(androidx.window.layout.WindowInfoTracker, @UiContext android.content.Context context);
}
}
diff --git a/window/window-rxjava3/api/public_plus_experimental_current.txt b/window/window-rxjava3/api/public_plus_experimental_current.txt
index 5700dd3..23510cc 100644
--- a/window/window-rxjava3/api/public_plus_experimental_current.txt
+++ b/window/window-rxjava3/api/public_plus_experimental_current.txt
@@ -3,7 +3,9 @@
public final class WindowInfoTrackerRx {
method public static io.reactivex.rxjava3.core.Flowable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoFlowable(androidx.window.layout.WindowInfoTracker, android.app.Activity activity);
+ method public static io.reactivex.rxjava3.core.Flowable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoFlowable(androidx.window.layout.WindowInfoTracker, @UiContext android.content.Context context);
method public static io.reactivex.rxjava3.core.Observable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoObservable(androidx.window.layout.WindowInfoTracker, android.app.Activity activity);
+ method public static io.reactivex.rxjava3.core.Observable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoObservable(androidx.window.layout.WindowInfoTracker, @UiContext android.content.Context context);
}
}
diff --git a/window/window-rxjava3/api/restricted_current.txt b/window/window-rxjava3/api/restricted_current.txt
index 5700dd3..23510cc 100644
--- a/window/window-rxjava3/api/restricted_current.txt
+++ b/window/window-rxjava3/api/restricted_current.txt
@@ -3,7 +3,9 @@
public final class WindowInfoTrackerRx {
method public static io.reactivex.rxjava3.core.Flowable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoFlowable(androidx.window.layout.WindowInfoTracker, android.app.Activity activity);
+ method public static io.reactivex.rxjava3.core.Flowable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoFlowable(androidx.window.layout.WindowInfoTracker, @UiContext android.content.Context context);
method public static io.reactivex.rxjava3.core.Observable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoObservable(androidx.window.layout.WindowInfoTracker, android.app.Activity activity);
+ method public static io.reactivex.rxjava3.core.Observable<androidx.window.layout.WindowLayoutInfo> windowLayoutInfoObservable(androidx.window.layout.WindowInfoTracker, @UiContext android.content.Context context);
}
}
diff --git a/window/window-rxjava3/build.gradle b/window/window-rxjava3/build.gradle
index 6874507..32804c4 100644
--- a/window/window-rxjava3/build.gradle
+++ b/window/window-rxjava3/build.gradle
@@ -36,6 +36,7 @@
api(libs.kotlinCoroutinesRx3)
api(libs.rxjava3)
api(project(":window:window"))
+ implementation 'androidx.annotation:annotation:1.5.0'
androidTestImplementation(libs.testExtJunit)
androidTestImplementation(libs.testRunner)
diff --git a/window/window-rxjava3/src/androidTest/java/androidx/window/rxjava3/layout/WindowInfoTrackerRxTest.kt b/window/window-rxjava3/src/androidTest/java/androidx/window/rxjava3/layout/WindowInfoTrackerRxTest.kt
index 04c68fc..f4a4c4c 100644
--- a/window/window-rxjava3/src/androidTest/java/androidx/window/rxjava3/layout/WindowInfoTrackerRxTest.kt
+++ b/window/window-rxjava3/src/androidTest/java/androidx/window/rxjava3/layout/WindowInfoTrackerRxTest.kt
@@ -17,6 +17,7 @@
package androidx.window.rxjava3.layout
import android.app.Activity
+import android.content.Context
import androidx.window.layout.FoldingFeature
import androidx.window.layout.WindowInfoTracker
import androidx.window.layout.WindowLayoutInfo
@@ -30,10 +31,10 @@
* [io.reactivex.rxjava3.core.Flowable] and ensure that data is forwarded appropriately.
* @see WindowInfoTracker
*/
-public class WindowInfoTrackerRxTest {
+class WindowInfoTrackerRxTest {
@Test
- public fun testWindowLayoutInfoObservable() {
+ fun testWindowLayoutInfoObservable() {
val activity = mock<Activity>()
val feature = mock<FoldingFeature>()
val expected = WindowLayoutInfo(listOf(feature))
@@ -46,7 +47,7 @@
}
@Test
- public fun testWindowLayoutInfoFlowable() {
+ fun testWindowLayoutInfoFlowable() {
val activity = mock<Activity>()
val feature = mock<FoldingFeature>()
val expected = WindowLayoutInfo(listOf(feature))
@@ -57,4 +58,30 @@
testSubscriber.assertValue(expected)
}
+
+ @Test
+ fun testWindowLayoutInfoObservable_context() {
+ val activity = mock<Context>()
+ val feature = mock<FoldingFeature>()
+ val expected = WindowLayoutInfo(listOf(feature))
+ val mockTracker = mock<WindowInfoTracker>()
+ whenever(mockTracker.windowLayoutInfo(activity)).thenReturn(flowOf(expected))
+
+ val testSubscriber = mockTracker.windowLayoutInfoObservable(activity).test()
+
+ testSubscriber.assertValue(expected)
+ }
+
+ @Test
+ fun testWindowLayoutInfoFlowable_context() {
+ val activity = mock<Context>()
+ val feature = mock<FoldingFeature>()
+ val expected = WindowLayoutInfo(listOf(feature))
+ val mockTracker = mock<WindowInfoTracker>()
+ whenever(mockTracker.windowLayoutInfo(activity)).thenReturn(flowOf(expected))
+
+ val testSubscriber = mockTracker.windowLayoutInfoFlowable(activity).test()
+
+ testSubscriber.assertValue(expected)
+ }
}
diff --git a/window/window-rxjava3/src/main/java/androidx/window/rxjava3/layout/WindowInfoTrackerRx.kt b/window/window-rxjava3/src/main/java/androidx/window/rxjava3/layout/WindowInfoTrackerRx.kt
index 374bbbb..084292b 100644
--- a/window/window-rxjava3/src/main/java/androidx/window/rxjava3/layout/WindowInfoTrackerRx.kt
+++ b/window/window-rxjava3/src/main/java/androidx/window/rxjava3/layout/WindowInfoTrackerRx.kt
@@ -18,6 +18,8 @@
package androidx.window.rxjava3.layout
import android.app.Activity
+import android.content.Context
+import androidx.annotation.UiContext
import androidx.window.layout.WindowInfoTracker
import androidx.window.layout.WindowLayoutInfo
import io.reactivex.rxjava3.core.Flowable
@@ -29,7 +31,7 @@
* Return an [Observable] stream of [WindowLayoutInfo].
* @see WindowInfoTracker.windowLayoutInfo
*/
-public fun WindowInfoTracker.windowLayoutInfoObservable(
+fun WindowInfoTracker.windowLayoutInfoObservable(
activity: Activity
): Observable<WindowLayoutInfo> {
return windowLayoutInfo(activity).asObservable()
@@ -39,8 +41,28 @@
* Return a [Flowable] stream of [WindowLayoutInfo].
* @see WindowInfoTracker.windowLayoutInfo
*/
-public fun WindowInfoTracker.windowLayoutInfoFlowable(
+fun WindowInfoTracker.windowLayoutInfoFlowable(
activity: Activity
): Flowable<WindowLayoutInfo> {
return windowLayoutInfo(activity).asFlowable()
}
+
+/**
+ * Return an [Observable] stream of [WindowLayoutInfo].
+ * @see WindowInfoTracker.windowLayoutInfo
+ */
+fun WindowInfoTracker.windowLayoutInfoObservable(
+ @UiContext context: Context
+): Observable<WindowLayoutInfo> {
+ return windowLayoutInfo(context).asObservable()
+}
+
+/**
+ * Return a [Flowable] stream of [WindowLayoutInfo].
+ * @see WindowInfoTracker.windowLayoutInfo
+ */
+fun WindowInfoTracker.windowLayoutInfoFlowable(
+ @UiContext context: Context
+): Flowable<WindowLayoutInfo> {
+ return windowLayoutInfo(context).asFlowable()
+}
diff --git a/window/window-samples/src/main/java/androidx/window/sample/DisplayFeaturesConfigChangeActivity.kt b/window/window-samples/src/main/java/androidx/window/sample/DisplayFeaturesConfigChangeActivity.kt
deleted file mode 100644
index 7f07d24..0000000
--- a/window/window-samples/src/main/java/androidx/window/sample/DisplayFeaturesConfigChangeActivity.kt
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Copyright 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 androidx.window.sample
-
-import android.graphics.drawable.ColorDrawable
-import android.os.Bundle
-import android.view.Menu
-import android.view.MenuItem
-import android.view.View
-import android.widget.FrameLayout
-import androidx.appcompat.app.AppCompatActivity
-import androidx.lifecycle.Lifecycle
-import androidx.lifecycle.lifecycleScope
-import androidx.lifecycle.repeatOnLifecycle
-import androidx.recyclerview.widget.RecyclerView
-import androidx.window.layout.WindowInfoTracker
-import androidx.window.layout.WindowLayoutInfo
-import androidx.window.sample.infolog.InfoLogAdapter
-import androidx.window.sample.util.PictureInPictureUtil.appendPictureInPictureMenu
-import androidx.window.sample.util.PictureInPictureUtil.handlePictureInPictureMenuItem
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.launch
-import java.text.SimpleDateFormat
-import java.util.Date
-import java.util.Locale
-
-/** Demo activity that shows all display features and current device state on the screen. */
-class DisplayFeaturesConfigChangeActivity : AppCompatActivity() {
-
- private val infoLogAdapter = InfoLogAdapter()
- private val displayFeatureViews = ArrayList<View>()
-
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_display_features_config_change)
- val recyclerView = findViewById<RecyclerView>(R.id.infoLogRecyclerView)
- recyclerView.adapter = infoLogAdapter
-
- lifecycleScope.launch(Dispatchers.Main) {
- // The block passed to repeatOnLifecycle is executed when the lifecycle
- // is at least STARTED and is cancelled when the lifecycle is STOPPED.
- // It automatically restarts the block when the lifecycle is STARTED again.
- lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
- // Safely collect from windowInfoRepo when the lifecycle is STARTED
- // and stops collection when the lifecycle is STOPPED
- WindowInfoTracker.getOrCreate(this@DisplayFeaturesConfigChangeActivity)
- .windowLayoutInfo(this@DisplayFeaturesConfigChangeActivity)
- .collect { newLayoutInfo ->
- // New posture information
- updateStateLog(newLayoutInfo)
- updateCurrentState(newLayoutInfo)
- }
- }
- }
- }
-
- override fun onCreateOptionsMenu(menu: Menu): Boolean {
- appendPictureInPictureMenu(menuInflater, menu)
- return true
- }
-
- override fun onOptionsItemSelected(item: MenuItem): Boolean {
- return when {
- handlePictureInPictureMenuItem(this, item) -> true
- else -> super.onOptionsItemSelected(item)
- }
- }
-
- /** Updates the device state and display feature positions. */
- private fun updateCurrentState(windowLayoutInfo: WindowLayoutInfo) {
- // Cleanup previously added feature views
- val rootLayout = findViewById<FrameLayout>(R.id.featureContainerLayout)
- for (featureView in displayFeatureViews) {
- rootLayout.removeView(featureView)
- }
- displayFeatureViews.clear()
-
- // Add views that represent display features
- for (displayFeature in windowLayoutInfo.displayFeatures) {
- val lp = getLayoutParamsForFeatureInFrameLayout(displayFeature, rootLayout)
-
- // Make sure that zero-wide and zero-high features are still shown
- if (lp.width == 0) {
- lp.width = 1
- }
- if (lp.height == 0) {
- lp.height = 1
- }
-
- val featureView = View(this)
- val color = getColor(R.color.colorFeatureFold)
- featureView.foreground = ColorDrawable(color)
-
- rootLayout.addView(featureView, lp)
- featureView.id = View.generateViewId()
-
- displayFeatureViews.add(featureView)
- }
- }
-
- /** Adds the current state to the text log of changes on screen. */
- private fun updateStateLog(info: Any) {
- infoLogAdapter.append(getCurrentTimeString(), info.toString())
- infoLogAdapter.notifyDataSetChanged()
- }
-
- private fun getCurrentTimeString(): String {
- val sdf = SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault())
- val currentDate = sdf.format(Date())
- return currentDate.toString()
- }
-}
diff --git a/window/window-samples/src/main/java/androidx/window/sample/TestIme.kt b/window/window-samples/src/main/java/androidx/window/sample/TestIme.kt
deleted file mode 100644
index d337e11..0000000
--- a/window/window-samples/src/main/java/androidx/window/sample/TestIme.kt
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * 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 androidx.window.sample
-
-import android.inputmethodservice.InputMethodService
-import android.view.View
-import android.view.inputmethod.InputMethodManager
-import android.widget.Button
-
-/**
- * A test IME that currently provides a minimal UI containing a "Close" button. To use this, go to
- * "Settings > System > Languages & Input > On-screen keyboard" and enable "Test IME". Remember you
- * may still need to switch to this IME after the default on-screen keyboard pops up.
- */
-internal class TestIme : InputMethodService() {
-
- override fun onCreateInputView(): View {
- return layoutInflater.inflate(R.layout.test_ime, null).apply {
- findViewById<Button>(R.id.button_close).setOnClickListener {
- requestHideSelf(InputMethodManager.HIDE_NOT_ALWAYS)
- }
- }
- }
-
- override fun onEvaluateFullscreenMode(): Boolean {
- return false
- }
-}
\ No newline at end of file
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/ExampleWindowInitializer.kt b/window/window-samples/src/main/java/androidx/window/sample/embedding/ExampleWindowInitializer.kt
deleted file mode 100644
index 56f41445..0000000
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/ExampleWindowInitializer.kt
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright 2021 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 androidx.window.sample.embedding
-
-import android.content.Context
-import androidx.startup.Initializer
-import androidx.window.embedding.RuleController
-import androidx.window.sample.R
-
-/**
- * Initializes [RuleController] with a set of statically defined rules.
- */
-class ExampleWindowInitializer : Initializer<RuleController> {
- override fun create(context: Context): RuleController =
- RuleController.getInstance(context).apply {
- setRules(RuleController.parseRules(context, R.xml.main_split_config))
- }
-
- override fun dependencies(): List<Class<out Initializer<*>>> {
- return emptyList()
- }
-}
\ No newline at end of file
diff --git a/window/window-samples/src/main/res/layout/activity_display_features_config_change.xml b/window/window-samples/src/main/res/layout/activity_display_features_config_change.xml
deleted file mode 100644
index 0e877e4..0000000
--- a/window/window-samples/src/main/res/layout/activity_display_features_config_change.xml
+++ /dev/null
@@ -1,78 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- Copyright 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.
- -->
-
-<androidx.constraintlayout.widget.ConstraintLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto"
- xmlns:tools="http://schemas.android.com/tools"
- android:id="@+id/rootLayout"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context="androidx.window.sample.DisplayFeaturesConfigChangeActivity">
-
- <FrameLayout
- android:id="@+id/featureContainerLayout"
- android:layout_width="match_parent"
- android:layout_height="match_parent" />
-
- <LinearLayout
- android:id="@+id/legendLayout"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:orientation="vertical"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintStart_toStartOf="parent">
-
- <TextView
- android:id="@+id/legendTextView"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="@string/legend" />
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="horizontal">
-
- <ImageView
- android:id="@+id/foldColorImageView"
- android:layout_width="20dp"
- android:layout_height="20dp"
- android:foreground="@color/colorFeatureFold" />
-
- <TextView
- android:id="@+id/foldColorTextView"
- android:layout_width="0dp"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:text="@string/fold" />
- </LinearLayout>
-
- </LinearLayout>
-
- <androidx.recyclerview.widget.RecyclerView
- android:id="@+id/infoLogRecyclerView"
- android:layout_width="0dp"
- android:layout_height="0dp"
- app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toTopOf="parent"
- app:layout_constraintBottom_toBottomOf="parent"/>
-
-</androidx.constraintlayout.widget.ConstraintLayout>
\ No newline at end of file
diff --git a/window/window-samples/src/main/res/layout/activity_split_activity_layout.xml b/window/window-samples/src/main/res/layout/activity_split_activity_layout.xml
deleted file mode 100644
index d67eefc..0000000
--- a/window/window-samples/src/main/res/layout/activity_split_activity_layout.xml
+++ /dev/null
@@ -1,138 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- Copyright 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.
- -->
-
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/root_split_activity_layout"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- android:padding="10dp">
-
- <TextView
- android:id="@+id/activity_embedded_status_text_view"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Activity is embedded" />
-
- <CheckBox
- android:id="@+id/splitMainCheckBox"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Split Main with other activities" />
-
- <View
- android:layout_width="match_parent"
- android:layout_height="1dp"
- android:layout_marginTop="10dp"
- android:layout_marginBottom="10dp"
- android:background="#AAAAAA" />
-
- <Button
- android:id="@+id/launch_b"
- android:layout_width="wrap_content"
- android:layout_height="48dp"
- android:layout_centerHorizontal="true"
- android:text="Launch B" />
-
- <CheckBox
- android:id="@+id/usePlaceholderCheckBox"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Use a placeholder for B" />
-
- <CheckBox
- android:id="@+id/useStickyPlaceholderCheckBox"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Placeholder is sticky" />
-
- <View
- android:layout_width="match_parent"
- android:layout_height="1dp"
- android:layout_marginTop="10dp"
- android:layout_marginBottom="10dp"
- android:background="#AAAAAA" />
-
- <Button
- android:id="@+id/launch_b_and_C"
- android:layout_width="wrap_content"
- android:layout_height="48dp"
- android:layout_centerHorizontal="true"
- android:text="Launch B and C" />
-
- <CheckBox
- android:id="@+id/splitBCCheckBox"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Split B with C" />
-
- <CheckBox
- android:id="@+id/finishBCCheckBox"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Finish B and C together"
- android:enabled="false" />
-
- <View
- android:layout_width="match_parent"
- android:layout_height="1dp"
- android:layout_marginTop="10dp"
- android:layout_marginBottom="10dp"
- android:background="#AAAAAA" />
-
- <Button
- android:id="@+id/launch_e"
- android:layout_width="wrap_content"
- android:layout_height="48dp"
- android:layout_centerHorizontal="true"
- android:text="Launch E" />
-
- <CheckBox
- android:id="@+id/fullscreenECheckBox"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Always launch E in fullscreen" />
-
- <View
- android:layout_width="match_parent"
- android:layout_height="1dp"
- android:layout_marginTop="10dp"
- android:layout_marginBottom="10dp"
- android:background="#AAAAAA" />
-
- <Button
- android:id="@+id/launch_f"
- android:layout_width="wrap_content"
- android:layout_height="48dp"
- android:layout_centerHorizontal="true"
- android:text="Launch f" />
-
- <Button
- android:id="@+id/launch_f_pending_intent"
- android:layout_width="wrap_content"
- android:layout_height="48dp"
- android:layout_centerHorizontal="true"
- android:text="Launch F via Pending Intent" />
-
- <CheckBox
- android:id="@+id/splitWithFCheckBox"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Split everything with F" />
-
-</LinearLayout>
\ No newline at end of file
diff --git a/window/window-testing/api/current.txt b/window/window-testing/api/current.txt
index 12a7d20..baf8ef4 100644
--- a/window/window-testing/api/current.txt
+++ b/window/window-testing/api/current.txt
@@ -1,4 +1,17 @@
// Signature format: 4.0
+package androidx.window.testing.embedding {
+
+ public final class TestSplitAttributesCalculatorParams {
+ method public static androidx.window.embedding.SplitAttributesCalculatorParams createTestSplitAttributesCalculatorParams(androidx.window.layout.WindowMetrics parentWindowMetrics, optional android.content.res.Configuration parentConfiguration, optional androidx.window.layout.WindowLayoutInfo parentWindowLayoutInfo, optional androidx.window.embedding.SplitAttributes defaultSplitAttributes, optional boolean areDefaultConstraintsSatisfied, optional String? splitRuleTag);
+ method public static androidx.window.embedding.SplitAttributesCalculatorParams createTestSplitAttributesCalculatorParams(androidx.window.layout.WindowMetrics parentWindowMetrics, optional android.content.res.Configuration parentConfiguration, optional androidx.window.layout.WindowLayoutInfo parentWindowLayoutInfo, optional androidx.window.embedding.SplitAttributes defaultSplitAttributes, optional boolean areDefaultConstraintsSatisfied);
+ method public static androidx.window.embedding.SplitAttributesCalculatorParams createTestSplitAttributesCalculatorParams(androidx.window.layout.WindowMetrics parentWindowMetrics, optional android.content.res.Configuration parentConfiguration, optional androidx.window.layout.WindowLayoutInfo parentWindowLayoutInfo, optional androidx.window.embedding.SplitAttributes defaultSplitAttributes);
+ method public static androidx.window.embedding.SplitAttributesCalculatorParams createTestSplitAttributesCalculatorParams(androidx.window.layout.WindowMetrics parentWindowMetrics, optional android.content.res.Configuration parentConfiguration, optional androidx.window.layout.WindowLayoutInfo parentWindowLayoutInfo);
+ method public static androidx.window.embedding.SplitAttributesCalculatorParams createTestSplitAttributesCalculatorParams(androidx.window.layout.WindowMetrics parentWindowMetrics, optional android.content.res.Configuration parentConfiguration);
+ method public static androidx.window.embedding.SplitAttributesCalculatorParams createTestSplitAttributesCalculatorParams(androidx.window.layout.WindowMetrics parentWindowMetrics);
+ }
+
+}
+
package androidx.window.testing.layout {
public final class DisplayFeatureTesting {
diff --git a/window/window-testing/api/public_plus_experimental_current.txt b/window/window-testing/api/public_plus_experimental_current.txt
index 56856b4..aa96039 100644
--- a/window/window-testing/api/public_plus_experimental_current.txt
+++ b/window/window-testing/api/public_plus_experimental_current.txt
@@ -1,4 +1,17 @@
// Signature format: 4.0
+package androidx.window.testing.embedding {
+
+ public final class TestSplitAttributesCalculatorParams {
+ method public static androidx.window.embedding.SplitAttributesCalculatorParams createTestSplitAttributesCalculatorParams(androidx.window.layout.WindowMetrics parentWindowMetrics, optional android.content.res.Configuration parentConfiguration, optional androidx.window.layout.WindowLayoutInfo parentWindowLayoutInfo, optional androidx.window.embedding.SplitAttributes defaultSplitAttributes, optional boolean areDefaultConstraintsSatisfied, optional String? splitRuleTag);
+ method public static androidx.window.embedding.SplitAttributesCalculatorParams createTestSplitAttributesCalculatorParams(androidx.window.layout.WindowMetrics parentWindowMetrics, optional android.content.res.Configuration parentConfiguration, optional androidx.window.layout.WindowLayoutInfo parentWindowLayoutInfo, optional androidx.window.embedding.SplitAttributes defaultSplitAttributes, optional boolean areDefaultConstraintsSatisfied);
+ method public static androidx.window.embedding.SplitAttributesCalculatorParams createTestSplitAttributesCalculatorParams(androidx.window.layout.WindowMetrics parentWindowMetrics, optional android.content.res.Configuration parentConfiguration, optional androidx.window.layout.WindowLayoutInfo parentWindowLayoutInfo, optional androidx.window.embedding.SplitAttributes defaultSplitAttributes);
+ method public static androidx.window.embedding.SplitAttributesCalculatorParams createTestSplitAttributesCalculatorParams(androidx.window.layout.WindowMetrics parentWindowMetrics, optional android.content.res.Configuration parentConfiguration, optional androidx.window.layout.WindowLayoutInfo parentWindowLayoutInfo);
+ method public static androidx.window.embedding.SplitAttributesCalculatorParams createTestSplitAttributesCalculatorParams(androidx.window.layout.WindowMetrics parentWindowMetrics, optional android.content.res.Configuration parentConfiguration);
+ method public static androidx.window.embedding.SplitAttributesCalculatorParams createTestSplitAttributesCalculatorParams(androidx.window.layout.WindowMetrics parentWindowMetrics);
+ }
+
+}
+
package androidx.window.testing.layout {
public final class DisplayFeatureTesting {
diff --git a/window/window-testing/api/restricted_current.txt b/window/window-testing/api/restricted_current.txt
index 12a7d20..baf8ef4 100644
--- a/window/window-testing/api/restricted_current.txt
+++ b/window/window-testing/api/restricted_current.txt
@@ -1,4 +1,17 @@
// Signature format: 4.0
+package androidx.window.testing.embedding {
+
+ public final class TestSplitAttributesCalculatorParams {
+ method public static androidx.window.embedding.SplitAttributesCalculatorParams createTestSplitAttributesCalculatorParams(androidx.window.layout.WindowMetrics parentWindowMetrics, optional android.content.res.Configuration parentConfiguration, optional androidx.window.layout.WindowLayoutInfo parentWindowLayoutInfo, optional androidx.window.embedding.SplitAttributes defaultSplitAttributes, optional boolean areDefaultConstraintsSatisfied, optional String? splitRuleTag);
+ method public static androidx.window.embedding.SplitAttributesCalculatorParams createTestSplitAttributesCalculatorParams(androidx.window.layout.WindowMetrics parentWindowMetrics, optional android.content.res.Configuration parentConfiguration, optional androidx.window.layout.WindowLayoutInfo parentWindowLayoutInfo, optional androidx.window.embedding.SplitAttributes defaultSplitAttributes, optional boolean areDefaultConstraintsSatisfied);
+ method public static androidx.window.embedding.SplitAttributesCalculatorParams createTestSplitAttributesCalculatorParams(androidx.window.layout.WindowMetrics parentWindowMetrics, optional android.content.res.Configuration parentConfiguration, optional androidx.window.layout.WindowLayoutInfo parentWindowLayoutInfo, optional androidx.window.embedding.SplitAttributes defaultSplitAttributes);
+ method public static androidx.window.embedding.SplitAttributesCalculatorParams createTestSplitAttributesCalculatorParams(androidx.window.layout.WindowMetrics parentWindowMetrics, optional android.content.res.Configuration parentConfiguration, optional androidx.window.layout.WindowLayoutInfo parentWindowLayoutInfo);
+ method public static androidx.window.embedding.SplitAttributesCalculatorParams createTestSplitAttributesCalculatorParams(androidx.window.layout.WindowMetrics parentWindowMetrics, optional android.content.res.Configuration parentConfiguration);
+ method public static androidx.window.embedding.SplitAttributesCalculatorParams createTestSplitAttributesCalculatorParams(androidx.window.layout.WindowMetrics parentWindowMetrics);
+ }
+
+}
+
package androidx.window.testing.layout {
public final class DisplayFeatureTesting {
diff --git a/window/window-testing/src/androidTest/java/androidx/window/testing/emedding/SplitAttributesCalculatorParamsTestingJavaTest.java b/window/window-testing/src/androidTest/java/androidx/window/testing/emedding/SplitAttributesCalculatorParamsTestingJavaTest.java
new file mode 100644
index 0000000..cec8cb1
--- /dev/null
+++ b/window/window-testing/src/androidTest/java/androidx/window/testing/emedding/SplitAttributesCalculatorParamsTestingJavaTest.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright 2023 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 androidx.window.testing.emedding;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import android.content.res.Configuration;
+import android.graphics.Rect;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.OptIn;
+import androidx.core.view.WindowInsetsCompat;
+import androidx.window.core.ExperimentalWindowApi;
+import androidx.window.embedding.SplitAttributes;
+import androidx.window.embedding.SplitAttributesCalculatorParams;
+import androidx.window.layout.DisplayFeature;
+import androidx.window.layout.FoldingFeature;
+import androidx.window.layout.WindowLayoutInfo;
+import androidx.window.layout.WindowMetrics;
+import androidx.window.testing.embedding.TestSplitAttributesCalculatorParams;
+import androidx.window.testing.layout.DisplayFeatureTesting;
+import androidx.window.testing.layout.WindowLayoutInfoTesting;
+
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/** Test class to verify {@link TestSplitAttributesCalculatorParams} in Java. */
+public class SplitAttributesCalculatorParamsTestingJavaTest {
+ private static final Rect TEST_BOUNDS = new Rect(0, 0, 2000, 2000);
+ private static final WindowMetrics TEST_METRICS = new WindowMetrics(TEST_BOUNDS,
+ WindowInsetsCompat.CONSUMED);
+ private static final SplitAttributes DEFAULT_SPLIT_ATTRIBUTES =
+ new SplitAttributes.Builder().build();
+ private static final SplitAttributes TABLETOP_HINGE_ATTRIBUTES = new SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.splitByHinge(
+ SplitAttributes.SplitType.splitEqually()))
+ .setLayoutDirection(SplitAttributes.LayoutDirection.TOP_TO_BOTTOM)
+ .build();
+
+ /**
+ * Verifies if the default value of {@link TestSplitAttributesCalculatorParams} is as expected.
+ */
+ @Test
+ public void testDefaults() {
+ final SplitAttributesCalculatorParams params = TestSplitAttributesCalculatorParams
+ .createTestSplitAttributesCalculatorParams(TEST_METRICS);
+
+ assertEquals(TEST_METRICS, params.getParentWindowMetrics());
+ assertEquals(0, params.getParentConfiguration().diff(new Configuration()));
+ assertEquals(DEFAULT_SPLIT_ATTRIBUTES, params.getDefaultSplitAttributes());
+ assertTrue(params.areDefaultConstraintsSatisfied());
+ assertEquals(new WindowLayoutInfo(Collections.emptyList()),
+ params.getParentWindowLayoutInfo());
+ assertNull(params.getSplitRuleTag());
+
+ assertEquals(DEFAULT_SPLIT_ATTRIBUTES, testSplitAttributesCalculator(params));
+ }
+
+ @OptIn(markerClass = ExperimentalWindowApi.class)
+ @Test
+ public void testParamsWithTabletopFoldingFeature() {
+ final FoldingFeature tabletopFoldingFeature =
+ DisplayFeatureTesting.createFoldingFeature(TEST_BOUNDS);
+ final List<DisplayFeature> displayFeatures = new ArrayList<>();
+ displayFeatures.add(tabletopFoldingFeature);
+ final WindowLayoutInfo parentWindowLayoutInfo =
+ WindowLayoutInfoTesting.createWindowLayoutInfo(displayFeatures);
+ SplitAttributesCalculatorParams params = TestSplitAttributesCalculatorParams
+ .createTestSplitAttributesCalculatorParams(TEST_METRICS, new Configuration(),
+ parentWindowLayoutInfo, DEFAULT_SPLIT_ATTRIBUTES, true);
+
+ assertEquals(TABLETOP_HINGE_ATTRIBUTES, testSplitAttributesCalculator(params));
+ }
+
+ private SplitAttributes testSplitAttributesCalculator(
+ @NonNull SplitAttributesCalculatorParams params) {
+ List<DisplayFeature> displayFeatures = params.getParentWindowLayoutInfo()
+ .getDisplayFeatures();
+ List<FoldingFeature> foldingFeatures = new ArrayList<>();
+ for (DisplayFeature feature : displayFeatures) {
+ if (feature instanceof FoldingFeature) {
+ foldingFeatures.add((FoldingFeature) feature);
+ }
+ }
+ final FoldingFeature foldingFeature = (foldingFeatures.size() == 1)
+ ? foldingFeatures.get(0) : null;
+ if (foldingFeature != null
+ && foldingFeature.getState().equals(FoldingFeature.State.HALF_OPENED)
+ && foldingFeature.getOrientation().equals(
+ FoldingFeature.Orientation.HORIZONTAL)) {
+ return TABLETOP_HINGE_ATTRIBUTES;
+ }
+ if (params.areDefaultConstraintsSatisfied()) {
+ return params.getDefaultSplitAttributes();
+ } else {
+ return new SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.expandContainers())
+ .build();
+ }
+ }
+}
diff --git a/window/window-testing/src/androidTest/java/androidx/window/testing/emedding/SplitAttributesCalculatorParamsTestingTest.kt b/window/window-testing/src/androidTest/java/androidx/window/testing/emedding/SplitAttributesCalculatorParamsTestingTest.kt
new file mode 100644
index 0000000..ff94890
--- /dev/null
+++ b/window/window-testing/src/androidTest/java/androidx/window/testing/emedding/SplitAttributesCalculatorParamsTestingTest.kt
@@ -0,0 +1,107 @@
+/*
+ * Copyright 2023 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 androidx.window.testing.emedding
+
+import androidx.window.testing.layout.FoldingFeature as testFoldingFeature
+import android.content.res.Configuration
+import android.graphics.Rect
+import androidx.window.core.ExperimentalWindowApi
+import androidx.window.embedding.SplitAttributes
+import androidx.window.embedding.SplitAttributesCalculatorParams
+import androidx.window.layout.FoldingFeature
+import androidx.window.layout.WindowLayoutInfo
+import androidx.window.layout.WindowMetrics
+import androidx.window.testing.embedding.TestSplitAttributesCalculatorParams
+import androidx.window.testing.layout.TestWindowLayoutInfo
+import java.util.Collections
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** Test class to verify [TestSplitAttributesCalculatorParams]. */
+class SplitAttributesCalculatorParamsTestingTest {
+ /** Verifies if the default values of [TestSplitAttributesCalculatorParams] are as expected. */
+ @Test
+ fun testDefaults() {
+ val params = TestSplitAttributesCalculatorParams(TEST_METRICS)
+
+ assertEquals(TEST_METRICS, params.parentWindowMetrics)
+ assertEquals(0, params.parentConfiguration.diff(Configuration()))
+ assertEquals(DEFAULT_SPLIT_ATTRIBUTES, params.defaultSplitAttributes)
+ assertTrue(params.areDefaultConstraintsSatisfied)
+ assertEquals(WindowLayoutInfo(Collections.emptyList()), params.parentWindowLayoutInfo)
+ assertNull(params.splitRuleTag)
+
+ assertEquals(DEFAULT_SPLIT_ATTRIBUTES, testSplitAttributesCalculator(params))
+ }
+
+ @OptIn(ExperimentalWindowApi::class)
+ @Test
+ fun testParamsWithTabletopFoldingFeature() {
+ val tabletopFoldingFeature = testFoldingFeature(TEST_BOUNDS)
+ val parentWindowLayoutInfo = TestWindowLayoutInfo(listOf(tabletopFoldingFeature))
+ val params = TestSplitAttributesCalculatorParams(
+ parentWindowMetrics = TEST_METRICS,
+ parentWindowLayoutInfo = parentWindowLayoutInfo
+ )
+
+ assertEquals(TEST_METRICS, params.parentWindowMetrics)
+ assertEquals(0, params.parentConfiguration.diff(Configuration()))
+ assertEquals(DEFAULT_SPLIT_ATTRIBUTES, params.defaultSplitAttributes)
+ assertTrue(params.areDefaultConstraintsSatisfied)
+ assertEquals(parentWindowLayoutInfo, params.parentWindowLayoutInfo)
+ assertNull(params.splitRuleTag)
+
+ assertEquals(TABLETOP_HINGE_ATTRIBUTES, testSplitAttributesCalculator(params))
+ }
+
+ private fun testSplitAttributesCalculator(
+ params: SplitAttributesCalculatorParams
+ ): SplitAttributes {
+ val foldingFeatures = params.parentWindowLayoutInfo.displayFeatures
+ .filterIsInstance<FoldingFeature>()
+ val foldingFeature: FoldingFeature? =
+ if (foldingFeatures.size == 1) {
+ foldingFeatures.first()
+ } else {
+ null
+ }
+ if (foldingFeature?.state == FoldingFeature.State.HALF_OPENED &&
+ foldingFeature.orientation == FoldingFeature.Orientation.HORIZONTAL
+ ) {
+ return TABLETOP_HINGE_ATTRIBUTES
+ }
+ return if (params.areDefaultConstraintsSatisfied) {
+ params.defaultSplitAttributes
+ } else {
+ SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.expandContainers())
+ .build()
+ }
+ }
+
+ companion object {
+ private val TEST_BOUNDS = Rect(0, 0, 2000, 2000)
+ private val TEST_METRICS = WindowMetrics(TEST_BOUNDS)
+ private val DEFAULT_SPLIT_ATTRIBUTES = SplitAttributes.Builder().build()
+ private val TABLETOP_HINGE_ATTRIBUTES = SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.splitByHinge())
+ .setLayoutDirection(SplitAttributes.LayoutDirection.TOP_TO_BOTTOM)
+ .build()
+ }
+}
diff --git a/window/window-testing/src/androidTest/java/androidx/window/testing/layout/StubWindowMetricsCalculatorRuleTest.kt b/window/window-testing/src/androidTest/java/androidx/window/testing/layout/StubWindowMetricsCalculatorRuleTest.kt
index 2118436..3e6544d 100644
--- a/window/window-testing/src/androidTest/java/androidx/window/testing/layout/StubWindowMetricsCalculatorRuleTest.kt
+++ b/window/window-testing/src/androidTest/java/androidx/window/testing/layout/StubWindowMetricsCalculatorRuleTest.kt
@@ -16,6 +16,11 @@
package androidx.window.testing.layout
+import android.content.Context
+import android.graphics.Point
+import android.os.Build
+import android.view.WindowManager
+import androidx.annotation.RequiresApi
import androidx.test.core.app.ActivityScenario
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.window.core.ExperimentalWindowApi
@@ -75,6 +80,81 @@
}
}
+ @RequiresApi(Build.VERSION_CODES.R)
+ @Test
+ fun testCurrentWindowMetrics_context_matchesWindowMetricsMetrics_30AndAbove() {
+ Utils.assumePlatformAtOrAbove(Build.VERSION_CODES.R)
+
+ activityRule.scenario.onActivity { activity ->
+ val calculator = WindowMetricsCalculator.getOrCreate()
+ val wm = activity.getSystemService(WindowManager::class.java)
+ val windowMetrics = wm.currentWindowMetrics.bounds
+ val actual = calculator.computeCurrentWindowMetrics(activity as Context)
+
+ assertEquals(0, actual.bounds.left)
+ assertEquals(0, actual.bounds.top)
+ assertEquals(windowMetrics.width(), actual.bounds.right)
+ assertEquals(windowMetrics.height(), actual.bounds.bottom)
+ }
+ }
+
+ @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
+ @Test
+ fun testCurrentWindowMetrics_context_matchesDisplayRealSize_17to29() {
+ Utils.assumePlatformAtOrBelow(Build.VERSION_CODES.Q)
+ Utils.assumePlatformAtOrAbove(Build.VERSION_CODES.JELLY_BEAN_MR1)
+
+ activityRule.scenario.onActivity { activity ->
+ val calculator = WindowMetricsCalculator.getOrCreate()
+ val wm = activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager
+ val displaySize = Point()
+ // DefaultDisplay#getRealSize is used in StubWindowMetricsCalculator for compatibility
+ // with older versions. We're just asserting that the value via
+ // StubWindowMetricsCalculator#computeCurrentWindowMetrics is equal to this.
+ @Suppress("DEPRECATION")
+ wm.defaultDisplay.getRealSize(displaySize)
+ val actual = calculator.computeCurrentWindowMetrics(activity as Context)
+
+ assertEquals(0, actual.bounds.left)
+ assertEquals(0, actual.bounds.top)
+ assertEquals(displaySize.x, actual.bounds.right)
+ assertEquals(displaySize.y, actual.bounds.bottom)
+ }
+ }
+
+ // DefaultDisplay width/height used in tests for API16 and lower
+ @Suppress("DEPRECATION")
+ @Test
+ fun testCurrentWindowMetrics_context_matchesDisplayMetrics_16AndBelow() {
+ Utils.assumePlatformAtOrBelow(Build.VERSION_CODES.JELLY_BEAN)
+
+ activityRule.scenario.onActivity { activity ->
+ val calculator = WindowMetricsCalculator.getOrCreate()
+ val wm = activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager
+ val actual = calculator.computeCurrentWindowMetrics(activity as Context)
+
+ assertEquals(0, actual.bounds.left)
+ assertEquals(0, actual.bounds.top)
+ assertEquals(wm.defaultDisplay.width, actual.bounds.right)
+ assertEquals(wm.defaultDisplay.height, actual.bounds.bottom)
+ }
+ }
+
+ @Test
+ fun testCurrentWindowMetrics_context_matchesMaximumMetrics() {
+ activityRule.scenario.onActivity { activity ->
+ val calculator = WindowMetricsCalculator.getOrCreate()
+
+ val currentMetrics = calculator.computeCurrentWindowMetrics(activity as Context)
+ val maximumMetrics = calculator.computeMaximumWindowMetrics(activity as Context)
+
+ assertEquals(currentMetrics.bounds.left, maximumMetrics.bounds.left)
+ assertEquals(currentMetrics.bounds.top, maximumMetrics.bounds.top)
+ assertEquals(currentMetrics.bounds.right, maximumMetrics.bounds.right)
+ assertEquals(currentMetrics.bounds.bottom, maximumMetrics.bounds.bottom)
+ }
+ }
+
/**
* Tests that when applying a [Statement] then the decorator is removed. This is necessary to
* keep tests hermetic. If this fails on the last test run then the fake implementation of
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityB.kt b/window/window-testing/src/androidTest/java/androidx/window/testing/layout/Utils.kt
similarity index 64%
copy from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityB.kt
copy to window/window-testing/src/androidTest/java/androidx/window/testing/layout/Utils.kt
index f47ab24..9c57994 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityB.kt
+++ b/window/window-testing/src/androidTest/java/androidx/window/testing/layout/Utils.kt
@@ -14,14 +14,17 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+package androidx.window.testing.layout
-import android.graphics.Color
-import android.os.Bundle
+import android.os.Build
+import org.junit.Assume
-open class SplitPipActivityB : SplitPipActivityBase() {
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- viewBinding.rootSplitActivityLayout.setBackgroundColor(Color.parseColor("#fff3e0"))
+internal object Utils {
+ fun assumePlatformAtOrAbove(version: Int) {
+ Assume.assumeTrue(Build.VERSION.SDK_INT >= version)
+ }
+
+ fun assumePlatformAtOrBelow(version: Int) {
+ Assume.assumeTrue(Build.VERSION.SDK_INT <= version)
}
}
\ No newline at end of file
diff --git a/window/window-testing/src/main/java/androidx/window/testing/embedding/SplitAttributesCalculatorParamsTesting.kt b/window/window-testing/src/main/java/androidx/window/testing/embedding/SplitAttributesCalculatorParamsTesting.kt
new file mode 100644
index 0000000..4b39749
--- /dev/null
+++ b/window/window-testing/src/main/java/androidx/window/testing/embedding/SplitAttributesCalculatorParamsTesting.kt
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2023 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.
+ */
+@file:JvmName("TestSplitAttributesCalculatorParams")
+
+package androidx.window.testing.embedding
+
+import android.content.res.Configuration
+import androidx.window.embedding.SplitAttributes
+import androidx.window.embedding.SplitAttributesCalculatorParams
+import androidx.window.embedding.SplitController
+import androidx.window.embedding.SplitPairRule
+import androidx.window.embedding.SplitPlaceholderRule
+import androidx.window.layout.WindowLayoutInfo
+import androidx.window.layout.WindowMetrics
+import java.util.Collections
+
+/**
+ * Returns an instance of [SplitAttributesCalculatorParams] for testing. It is used to verify the
+ * developer implemented callback set by [SplitController.setSplitAttributesCalculator] by setting
+ * the relevant values in [SplitAttributesCalculatorParams] with this method.
+ *
+ * @param parentWindowMetrics The [WindowMetrics] of the host task. See
+ * [SplitAttributesCalculatorParams.parentWindowMetrics].
+ * @param parentConfiguration The [Configuration] of the host task with empty [Configuration] as
+ * the default value. See [SplitAttributesCalculatorParams.parentConfiguration]
+ * @param parentWindowLayoutInfo Used for reporting the
+ * [androidx.window.layout.FoldingFeature] with empty [WindowLayoutInfo] as the default value.
+ * See [androidx.window.testing.layout.TestWindowLayoutInfo] and
+ * [androidx.window.testing.layout.FoldingFeature] for how to create test
+ * [WindowLayoutInfo] with [androidx.window.layout.FoldingFeature].
+ * @param defaultSplitAttributes The [SplitPairRule.defaultSplitAttributes] or
+ * the [SplitPlaceholderRule.defaultSplitAttributes] that the callback is applied a vertical
+ * equal [SplitAttributes] as the default value.
+ * See [SplitAttributesCalculatorParams.defaultSplitAttributes]
+ * @param areDefaultConstraintsSatisfied `true` to indicate that the [parentWindowMetrics] satisfies
+ * the constraints of [SplitPairRule] or [SplitPlaceholderRule] which defaults to `true`.
+ * See [SplitAttributesCalculatorParams.areDefaultConstraintsSatisfied]
+ * @param splitRuleTag The [SplitPairRule.tag] or the [SplitPlaceholderRule.tag] that the callback
+ * is applied with `null` as the default value.
+ * See [SplitAttributesCalculatorParams.splitRuleTag].
+ *
+ * @see SplitAttributesCalculatorParams
+ */
+@Suppress("FunctionName")
+@JvmName("createTestSplitAttributesCalculatorParams")
+@JvmOverloads
+fun TestSplitAttributesCalculatorParams(
+ parentWindowMetrics: WindowMetrics,
+ parentConfiguration: Configuration = Configuration(),
+ parentWindowLayoutInfo: WindowLayoutInfo = WindowLayoutInfo(Collections.emptyList()),
+ defaultSplitAttributes: SplitAttributes = SplitAttributes.Builder().build(),
+ areDefaultConstraintsSatisfied: Boolean = true,
+ splitRuleTag: String? = null,
+): SplitAttributesCalculatorParams =
+ SplitAttributesCalculatorParams(
+ parentWindowMetrics,
+ parentConfiguration,
+ parentWindowLayoutInfo,
+ defaultSplitAttributes,
+ areDefaultConstraintsSatisfied,
+ splitRuleTag
+ )
diff --git a/window/window-testing/src/main/java/androidx/window/testing/layout/StubMetricDecorator.kt b/window/window-testing/src/main/java/androidx/window/testing/layout/StubMetricDecorator.kt
index d02349a..14bf0c7 100644
--- a/window/window-testing/src/main/java/androidx/window/testing/layout/StubMetricDecorator.kt
+++ b/window/window-testing/src/main/java/androidx/window/testing/layout/StubMetricDecorator.kt
@@ -26,6 +26,6 @@
@ExperimentalWindowApi
internal object StubMetricDecorator : WindowMetricsCalculatorDecorator {
override fun decorate(calculator: WindowMetricsCalculator): WindowMetricsCalculator {
- return StubWindowMetricsCalculator
+ return StubWindowMetricsCalculator()
}
}
\ No newline at end of file
diff --git a/window/window-testing/src/main/java/androidx/window/testing/layout/StubWindowMetricsCalculator.kt b/window/window-testing/src/main/java/androidx/window/testing/layout/StubWindowMetricsCalculator.kt
index c9b994e..5a040ab 100644
--- a/window/window-testing/src/main/java/androidx/window/testing/layout/StubWindowMetricsCalculator.kt
+++ b/window/window-testing/src/main/java/androidx/window/testing/layout/StubWindowMetricsCalculator.kt
@@ -17,17 +17,25 @@
package androidx.window.testing.layout
import android.app.Activity
+import android.content.Context
+import android.graphics.Point
import android.graphics.Rect
+import android.os.Build
+import android.view.Display
+import android.view.WindowManager
+import androidx.annotation.RequiresApi
+import androidx.annotation.UiContext
import androidx.window.layout.WindowMetrics
import androidx.window.layout.WindowMetricsCalculator
/**
- * A stub implementation of [WindowMetricsCalculator] that returns the
- * [android.util.DisplayMetrics] for the current and maximum [WindowMetrics]. This is not correct
- * in general terms, as an application may be running in multi-window or otherwise adjusted to not
+ * A stub implementation of [WindowMetricsCalculator] that's intended to be used by Robolectric.
+ * [computeCurrentWindowMetrics] and [computeMaximumWindowMetrics] returns reasonable
+ * [WindowMetrics] for all supported SDK levels, but is not correct in general terms, as an
+ * application or [UiContext] may be running in multi-window mode, or otherwise adjusted to not
* occupy the entire display.
*/
-internal object StubWindowMetricsCalculator : WindowMetricsCalculator {
+internal class StubWindowMetricsCalculator : WindowMetricsCalculator {
override fun computeCurrentWindowMetrics(activity: Activity): WindowMetrics {
val displayMetrics = activity.resources.displayMetrics
@@ -40,4 +48,52 @@
val bounds = Rect(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels)
return WindowMetrics(bounds)
}
+
+ // WindowManager#getDefaultDisplay is deprecated but we have this for compatibility with
+ // older versions.
+ @Suppress("DEPRECATION")
+ override fun computeCurrentWindowMetrics(@UiContext context: Context): WindowMetrics {
+ val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
+
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ Api30Impl.getWindowMetrics(wm)
+ } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
+ val displaySize = Point()
+ // We use getRealSize instead of getSize here because:
+ // 1) computeCurrentWindowMetrics and computeMaximumWindowMetrics in this class
+ // always return a measurement equal to the entire display (see class-level
+ // documentation).
+ // 2) getRealSize returns the largest region of the display, whereas getSize returns
+ // the current app window. So to stay consistent with class documentation, we use
+ // getRealSize.
+ Api17Impl.getRealSize(wm.defaultDisplay, displaySize)
+ val bounds = Rect(0, 0, displaySize.x, displaySize.y)
+ WindowMetrics(bounds)
+ } else {
+ val width = wm.defaultDisplay.width
+ val height = wm.defaultDisplay.height
+ val bounds = Rect(0, 0, width, height)
+ WindowMetrics(bounds)
+ }
+ }
+
+ override fun computeMaximumWindowMetrics(@UiContext context: Context): WindowMetrics {
+ return computeCurrentWindowMetrics(context)
+ }
+
+ @RequiresApi(Build.VERSION_CODES.R)
+ private object Api30Impl {
+ fun getWindowMetrics(windowManager: WindowManager): WindowMetrics {
+ return WindowMetrics(windowManager.currentWindowMetrics.bounds)
+ }
+ }
+
+ @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
+ private object Api17Impl {
+ // getRealSize is deprecated but we have this for compatibility with older versions.
+ @Suppress("DEPRECATION")
+ fun getRealSize(display: Display, point: Point) {
+ display.getRealSize(point)
+ }
+ }
}
\ No newline at end of file
diff --git a/window/window/api/current.txt b/window/window/api/current.txt
index 4c43822..ee2f53d 100644
--- a/window/window/api/current.txt
+++ b/window/window/api/current.txt
@@ -4,6 +4,7 @@
public final class WindowProperties {
field public static final androidx.window.WindowProperties INSTANCE;
field public static final String PROPERTY_ACTIVITY_EMBEDDING_ALLOW_SYSTEM_OVERRIDE = "android.window.PROPERTY_ACTIVITY_EMBEDDING_ALLOW_SYSTEM_OVERRIDE";
+ field public static final String PROPERTY_ACTIVITY_EMBEDDING_SPLITS_ENABLED = "android.window.PROPERTY_ACTIVITY_EMBEDDING_SPLITS_ENABLED";
}
}
@@ -41,6 +42,7 @@
ctor public ActivityRule.Builder(java.util.Set<androidx.window.embedding.ActivityFilter> filters);
method public androidx.window.embedding.ActivityRule build();
method public androidx.window.embedding.ActivityRule.Builder setAlwaysExpand(boolean alwaysExpand);
+ method public androidx.window.embedding.ActivityRule.Builder setTag(String tag);
}
public final class ActivityStack {
@@ -64,6 +66,8 @@
}
public abstract class EmbeddingRule {
+ method public final String? getTag();
+ property public final String? tag;
}
public final class RuleController {
@@ -82,11 +86,90 @@
method public java.util.Set<androidx.window.embedding.EmbeddingRule> parseRules(android.content.Context context, @XmlRes int staticRuleResourceId);
}
+ public final class SplitAttributes {
+ method public int getAnimationBackgroundColor();
+ method public androidx.window.embedding.SplitAttributes.LayoutDirection getLayoutDirection();
+ method public androidx.window.embedding.SplitAttributes.SplitType getSplitType();
+ property public final int animationBackgroundColor;
+ property public final androidx.window.embedding.SplitAttributes.LayoutDirection layoutDirection;
+ property public final androidx.window.embedding.SplitAttributes.SplitType splitType;
+ field public static final androidx.window.embedding.SplitAttributes.Companion Companion;
+ }
+
+ public static final class SplitAttributes.Builder {
+ ctor public SplitAttributes.Builder();
+ method public androidx.window.embedding.SplitAttributes build();
+ method public androidx.window.embedding.SplitAttributes.Builder setAnimationBackgroundColor(@ColorInt int color);
+ method public androidx.window.embedding.SplitAttributes.Builder setLayoutDirection(androidx.window.embedding.SplitAttributes.LayoutDirection layoutDirection);
+ method public androidx.window.embedding.SplitAttributes.Builder setSplitType(androidx.window.embedding.SplitAttributes.SplitType type);
+ }
+
+ public static final class SplitAttributes.Companion {
+ }
+
+ public static final class SplitAttributes.LayoutDirection {
+ field public static final androidx.window.embedding.SplitAttributes.LayoutDirection BOTTOM_TO_TOP;
+ field public static final androidx.window.embedding.SplitAttributes.LayoutDirection.Companion Companion;
+ field public static final androidx.window.embedding.SplitAttributes.LayoutDirection LEFT_TO_RIGHT;
+ field public static final androidx.window.embedding.SplitAttributes.LayoutDirection LOCALE;
+ field public static final androidx.window.embedding.SplitAttributes.LayoutDirection RIGHT_TO_LEFT;
+ field public static final androidx.window.embedding.SplitAttributes.LayoutDirection TOP_TO_BOTTOM;
+ }
+
+ public static final class SplitAttributes.LayoutDirection.Companion {
+ }
+
+ public static class SplitAttributes.SplitType {
+ method public static final androidx.window.embedding.SplitAttributes.SplitType.ExpandContainersSplitType expandContainers();
+ method public static final androidx.window.embedding.SplitAttributes.SplitType.RatioSplitType ratio(@FloatRange(from=0.0, to=1.0, fromInclusive=false, toInclusive=false) float ratio);
+ method public static final androidx.window.embedding.SplitAttributes.SplitType.HingeSplitType splitByHinge(optional androidx.window.embedding.SplitAttributes.SplitType fallbackSplitType);
+ method public static final androidx.window.embedding.SplitAttributes.SplitType.RatioSplitType splitEqually();
+ field public static final androidx.window.embedding.SplitAttributes.SplitType.Companion Companion;
+ }
+
+ public static final class SplitAttributes.SplitType.Companion {
+ method public androidx.window.embedding.SplitAttributes.SplitType.ExpandContainersSplitType expandContainers();
+ method public androidx.window.embedding.SplitAttributes.SplitType.RatioSplitType ratio(@FloatRange(from=0.0, to=1.0, fromInclusive=false, toInclusive=false) float ratio);
+ method public androidx.window.embedding.SplitAttributes.SplitType.HingeSplitType splitByHinge(optional androidx.window.embedding.SplitAttributes.SplitType fallbackSplitType);
+ method public androidx.window.embedding.SplitAttributes.SplitType.RatioSplitType splitEqually();
+ }
+
+ public static final class SplitAttributes.SplitType.ExpandContainersSplitType extends androidx.window.embedding.SplitAttributes.SplitType {
+ }
+
+ public static final class SplitAttributes.SplitType.HingeSplitType extends androidx.window.embedding.SplitAttributes.SplitType {
+ method public androidx.window.embedding.SplitAttributes.SplitType getFallbackSplitType();
+ property public final androidx.window.embedding.SplitAttributes.SplitType fallbackSplitType;
+ }
+
+ public static final class SplitAttributes.SplitType.RatioSplitType extends androidx.window.embedding.SplitAttributes.SplitType {
+ method public float getRatio();
+ property public final float ratio;
+ }
+
+ public final class SplitAttributesCalculatorParams {
+ method public boolean getAreDefaultConstraintsSatisfied();
+ method public androidx.window.embedding.SplitAttributes getDefaultSplitAttributes();
+ method public android.content.res.Configuration getParentConfiguration();
+ method public androidx.window.layout.WindowLayoutInfo getParentWindowLayoutInfo();
+ method public androidx.window.layout.WindowMetrics getParentWindowMetrics();
+ method public String? getSplitRuleTag();
+ property public final boolean areDefaultConstraintsSatisfied;
+ property public final androidx.window.embedding.SplitAttributes defaultSplitAttributes;
+ property public final android.content.res.Configuration parentConfiguration;
+ property public final androidx.window.layout.WindowLayoutInfo parentWindowLayoutInfo;
+ property public final androidx.window.layout.WindowMetrics parentWindowMetrics;
+ property public final String? splitRuleTag;
+ }
+
public final class SplitController {
method public void addSplitListener(android.app.Activity activity, java.util.concurrent.Executor executor, androidx.core.util.Consumer<java.util.List<androidx.window.embedding.SplitInfo>> consumer);
+ method public void clearSplitAttributesCalculator();
method public static androidx.window.embedding.SplitController getInstance(android.content.Context context);
+ method public boolean isSplitAttributesCalculatorSupported();
method public boolean isSplitSupported();
method public void removeSplitListener(androidx.core.util.Consumer<java.util.List<androidx.window.embedding.SplitInfo>> consumer);
+ method public void setSplitAttributesCalculator(kotlin.jvm.functions.Function1<? super androidx.window.embedding.SplitAttributesCalculatorParams,androidx.window.embedding.SplitAttributes> calculator);
field public static final androidx.window.embedding.SplitController.Companion Companion;
}
@@ -98,10 +181,10 @@
method public operator boolean contains(android.app.Activity activity);
method public androidx.window.embedding.ActivityStack getPrimaryActivityStack();
method public androidx.window.embedding.ActivityStack getSecondaryActivityStack();
- method public float getSplitRatio();
+ method public androidx.window.embedding.SplitAttributes getSplitAttributes();
property public final androidx.window.embedding.ActivityStack primaryActivityStack;
property public final androidx.window.embedding.ActivityStack secondaryActivityStack;
- property public final float splitRatio;
+ property public final androidx.window.embedding.SplitAttributes splitAttributes;
}
public final class SplitPairFilter {
@@ -119,35 +202,36 @@
public final class SplitPairRule extends androidx.window.embedding.SplitRule {
method public boolean getClearTop();
method public java.util.Set<androidx.window.embedding.SplitPairFilter> getFilters();
- method public int getFinishPrimaryWithSecondary();
- method public int getFinishSecondaryWithPrimary();
+ method public androidx.window.embedding.SplitRule.FinishBehavior getFinishPrimaryWithSecondary();
+ method public androidx.window.embedding.SplitRule.FinishBehavior getFinishSecondaryWithPrimary();
property public final boolean clearTop;
property public final java.util.Set<androidx.window.embedding.SplitPairFilter> filters;
- property public final int finishPrimaryWithSecondary;
- property public final int finishSecondaryWithPrimary;
+ property public final androidx.window.embedding.SplitRule.FinishBehavior finishPrimaryWithSecondary;
+ property public final androidx.window.embedding.SplitRule.FinishBehavior finishSecondaryWithPrimary;
}
public static final class SplitPairRule.Builder {
ctor public SplitPairRule.Builder(java.util.Set<androidx.window.embedding.SplitPairFilter> filters);
method public androidx.window.embedding.SplitPairRule build();
method public androidx.window.embedding.SplitPairRule.Builder setClearTop(boolean clearTop);
- method public androidx.window.embedding.SplitPairRule.Builder setFinishPrimaryWithSecondary(int finishPrimaryWithSecondary);
- method public androidx.window.embedding.SplitPairRule.Builder setFinishSecondaryWithPrimary(int finishSecondaryWithPrimary);
- method public androidx.window.embedding.SplitPairRule.Builder setLayoutDirection(int layoutDirection);
+ method public androidx.window.embedding.SplitPairRule.Builder setDefaultSplitAttributes(androidx.window.embedding.SplitAttributes defaultSplitAttributes);
+ method public androidx.window.embedding.SplitPairRule.Builder setFinishPrimaryWithSecondary(androidx.window.embedding.SplitRule.FinishBehavior finishPrimaryWithSecondary);
+ method public androidx.window.embedding.SplitPairRule.Builder setFinishSecondaryWithPrimary(androidx.window.embedding.SplitRule.FinishBehavior finishSecondaryWithPrimary);
method public androidx.window.embedding.SplitPairRule.Builder setMaxAspectRatioInLandscape(androidx.window.embedding.EmbeddingAspectRatio aspectRatio);
method public androidx.window.embedding.SplitPairRule.Builder setMaxAspectRatioInPortrait(androidx.window.embedding.EmbeddingAspectRatio aspectRatio);
+ method public androidx.window.embedding.SplitPairRule.Builder setMinHeightDp(@IntRange(from=0L) int minHeightDp);
method public androidx.window.embedding.SplitPairRule.Builder setMinSmallestWidthDp(@IntRange(from=0L) int minSmallestWidthDp);
method public androidx.window.embedding.SplitPairRule.Builder setMinWidthDp(@IntRange(from=0L) int minWidthDp);
- method public androidx.window.embedding.SplitPairRule.Builder setSplitRatio(@FloatRange(from=0.0, to=1.0) float splitRatio);
+ method public androidx.window.embedding.SplitPairRule.Builder setTag(String? tag);
}
public final class SplitPlaceholderRule extends androidx.window.embedding.SplitRule {
method public java.util.Set<androidx.window.embedding.ActivityFilter> getFilters();
- method public int getFinishPrimaryWithPlaceholder();
+ method public androidx.window.embedding.SplitRule.FinishBehavior getFinishPrimaryWithPlaceholder();
method public android.content.Intent getPlaceholderIntent();
method public boolean isSticky();
property public final java.util.Set<androidx.window.embedding.ActivityFilter> filters;
- property public final int finishPrimaryWithPlaceholder;
+ property public final androidx.window.embedding.SplitRule.FinishBehavior finishPrimaryWithPlaceholder;
property public final boolean isSticky;
property public final android.content.Intent placeholderIntent;
}
@@ -155,33 +239,31 @@
public static final class SplitPlaceholderRule.Builder {
ctor public SplitPlaceholderRule.Builder(java.util.Set<androidx.window.embedding.ActivityFilter> filters, android.content.Intent placeholderIntent);
method public androidx.window.embedding.SplitPlaceholderRule build();
- method public androidx.window.embedding.SplitPlaceholderRule.Builder setFinishPrimaryWithPlaceholder(int finishPrimaryWithPlaceholder);
- method public androidx.window.embedding.SplitPlaceholderRule.Builder setLayoutDirection(int layoutDirection);
+ method public androidx.window.embedding.SplitPlaceholderRule.Builder setDefaultSplitAttributes(androidx.window.embedding.SplitAttributes defaultSplitAttributes);
+ method public androidx.window.embedding.SplitPlaceholderRule.Builder setFinishPrimaryWithPlaceholder(androidx.window.embedding.SplitRule.FinishBehavior finishPrimaryWithPlaceholder);
method public androidx.window.embedding.SplitPlaceholderRule.Builder setMaxAspectRatioInLandscape(androidx.window.embedding.EmbeddingAspectRatio aspectRatio);
method public androidx.window.embedding.SplitPlaceholderRule.Builder setMaxAspectRatioInPortrait(androidx.window.embedding.EmbeddingAspectRatio aspectRatio);
+ method public androidx.window.embedding.SplitPlaceholderRule.Builder setMinHeightDp(@IntRange(from=0L) int minHeightDp);
method public androidx.window.embedding.SplitPlaceholderRule.Builder setMinSmallestWidthDp(@IntRange(from=0L) int minSmallestWidthDp);
method public androidx.window.embedding.SplitPlaceholderRule.Builder setMinWidthDp(@IntRange(from=0L) int minWidthDp);
- method public androidx.window.embedding.SplitPlaceholderRule.Builder setSplitRatio(@FloatRange(from=0.0, to=1.0) float splitRatio);
method public androidx.window.embedding.SplitPlaceholderRule.Builder setSticky(boolean isSticky);
+ method public androidx.window.embedding.SplitPlaceholderRule.Builder setTag(String? tag);
}
public class SplitRule extends androidx.window.embedding.EmbeddingRule {
- method public final int getLayoutDirection();
+ method public final androidx.window.embedding.SplitAttributes getDefaultSplitAttributes();
method public final androidx.window.embedding.EmbeddingAspectRatio getMaxAspectRatioInLandscape();
method public final androidx.window.embedding.EmbeddingAspectRatio getMaxAspectRatioInPortrait();
+ method public final int getMinHeightDp();
method public final int getMinSmallestWidthDp();
method public final int getMinWidthDp();
- method public final float getSplitRatio();
- property public final int layoutDirection;
+ property public final androidx.window.embedding.SplitAttributes defaultSplitAttributes;
property public final androidx.window.embedding.EmbeddingAspectRatio maxAspectRatioInLandscape;
property public final androidx.window.embedding.EmbeddingAspectRatio maxAspectRatioInPortrait;
+ property public final int minHeightDp;
property public final int minSmallestWidthDp;
property public final int minWidthDp;
- property public final float splitRatio;
field public static final androidx.window.embedding.SplitRule.Companion Companion;
- field public static final int FINISH_ADJACENT = 2; // 0x2
- field public static final int FINISH_ALWAYS = 1; // 0x1
- field public static final int FINISH_NEVER = 0; // 0x0
field public static final androidx.window.embedding.EmbeddingAspectRatio SPLIT_MAX_ASPECT_RATIO_LANDSCAPE_DEFAULT;
field public static final androidx.window.embedding.EmbeddingAspectRatio SPLIT_MAX_ASPECT_RATIO_PORTRAIT_DEFAULT;
field public static final int SPLIT_MIN_DIMENSION_ALWAYS_ALLOW = 0; // 0x0
@@ -191,6 +273,16 @@
public static final class SplitRule.Companion {
}
+ public static final class SplitRule.FinishBehavior {
+ field public static final androidx.window.embedding.SplitRule.FinishBehavior ADJACENT;
+ field public static final androidx.window.embedding.SplitRule.FinishBehavior ALWAYS;
+ field public static final androidx.window.embedding.SplitRule.FinishBehavior.Companion Companion;
+ field public static final androidx.window.embedding.SplitRule.FinishBehavior NEVER;
+ }
+
+ public static final class SplitRule.FinishBehavior.Companion {
+ }
+
}
package androidx.window.layout {
@@ -240,6 +332,7 @@
public interface WindowInfoTracker {
method public default static androidx.window.layout.WindowInfoTracker getOrCreate(android.content.Context context);
+ method public default kotlinx.coroutines.flow.Flow<androidx.window.layout.WindowLayoutInfo> windowLayoutInfo(@UiContext android.content.Context context);
method public kotlinx.coroutines.flow.Flow<androidx.window.layout.WindowLayoutInfo> windowLayoutInfo(android.app.Activity activity);
field public static final androidx.window.layout.WindowInfoTracker.Companion Companion;
}
@@ -260,7 +353,9 @@
public interface WindowMetricsCalculator {
method public androidx.window.layout.WindowMetrics computeCurrentWindowMetrics(android.app.Activity activity);
+ method public default androidx.window.layout.WindowMetrics computeCurrentWindowMetrics(@UiContext android.content.Context context);
method public androidx.window.layout.WindowMetrics computeMaximumWindowMetrics(android.app.Activity activity);
+ method public default androidx.window.layout.WindowMetrics computeMaximumWindowMetrics(@UiContext android.content.Context context);
method public default static androidx.window.layout.WindowMetricsCalculator getOrCreate();
field public static final androidx.window.layout.WindowMetricsCalculator.Companion Companion;
}
diff --git a/window/window/api/public_plus_experimental_current.txt b/window/window/api/public_plus_experimental_current.txt
index da9c818..8d4cb95 100644
--- a/window/window/api/public_plus_experimental_current.txt
+++ b/window/window/api/public_plus_experimental_current.txt
@@ -4,6 +4,39 @@
public final class WindowProperties {
field public static final androidx.window.WindowProperties INSTANCE;
field public static final String PROPERTY_ACTIVITY_EMBEDDING_ALLOW_SYSTEM_OVERRIDE = "android.window.PROPERTY_ACTIVITY_EMBEDDING_ALLOW_SYSTEM_OVERRIDE";
+ field public static final String PROPERTY_ACTIVITY_EMBEDDING_SPLITS_ENABLED = "android.window.PROPERTY_ACTIVITY_EMBEDDING_SPLITS_ENABLED";
+ }
+
+}
+
+package androidx.window.area {
+
+ @androidx.window.core.ExperimentalWindowApi public interface WindowAreaController {
+ method public default static androidx.window.area.WindowAreaController getOrCreate();
+ field public static final androidx.window.area.WindowAreaController.Companion Companion;
+ }
+
+ public static final class WindowAreaController.Companion {
+ method public androidx.window.area.WindowAreaController getOrCreate();
+ }
+
+ @androidx.window.core.ExperimentalWindowApi public interface WindowAreaSession {
+ method public void close();
+ }
+
+ @androidx.window.core.ExperimentalWindowApi public interface WindowAreaSessionCallback {
+ method public void onSessionEnded();
+ method public void onSessionStarted(androidx.window.area.WindowAreaSession session);
+ }
+
+ @androidx.window.core.ExperimentalWindowApi public final class WindowAreaStatus {
+ field public static final androidx.window.area.WindowAreaStatus AVAILABLE;
+ field public static final androidx.window.area.WindowAreaStatus.Companion Companion;
+ field public static final androidx.window.area.WindowAreaStatus UNAVAILABLE;
+ field public static final androidx.window.area.WindowAreaStatus UNSUPPORTED;
+ }
+
+ public static final class WindowAreaStatus.Companion {
}
}
@@ -48,6 +81,7 @@
ctor public ActivityRule.Builder(java.util.Set<androidx.window.embedding.ActivityFilter> filters);
method public androidx.window.embedding.ActivityRule build();
method public androidx.window.embedding.ActivityRule.Builder setAlwaysExpand(boolean alwaysExpand);
+ method public androidx.window.embedding.ActivityRule.Builder setTag(String tag);
}
public final class ActivityStack {
@@ -71,6 +105,8 @@
}
public abstract class EmbeddingRule {
+ method public final String? getTag();
+ property public final String? tag;
}
public final class RuleController {
@@ -89,11 +125,90 @@
method public java.util.Set<androidx.window.embedding.EmbeddingRule> parseRules(android.content.Context context, @XmlRes int staticRuleResourceId);
}
+ public final class SplitAttributes {
+ method public int getAnimationBackgroundColor();
+ method public androidx.window.embedding.SplitAttributes.LayoutDirection getLayoutDirection();
+ method public androidx.window.embedding.SplitAttributes.SplitType getSplitType();
+ property public final int animationBackgroundColor;
+ property public final androidx.window.embedding.SplitAttributes.LayoutDirection layoutDirection;
+ property public final androidx.window.embedding.SplitAttributes.SplitType splitType;
+ field public static final androidx.window.embedding.SplitAttributes.Companion Companion;
+ }
+
+ public static final class SplitAttributes.Builder {
+ ctor public SplitAttributes.Builder();
+ method public androidx.window.embedding.SplitAttributes build();
+ method public androidx.window.embedding.SplitAttributes.Builder setAnimationBackgroundColor(@ColorInt int color);
+ method public androidx.window.embedding.SplitAttributes.Builder setLayoutDirection(androidx.window.embedding.SplitAttributes.LayoutDirection layoutDirection);
+ method public androidx.window.embedding.SplitAttributes.Builder setSplitType(androidx.window.embedding.SplitAttributes.SplitType type);
+ }
+
+ public static final class SplitAttributes.Companion {
+ }
+
+ public static final class SplitAttributes.LayoutDirection {
+ field public static final androidx.window.embedding.SplitAttributes.LayoutDirection BOTTOM_TO_TOP;
+ field public static final androidx.window.embedding.SplitAttributes.LayoutDirection.Companion Companion;
+ field public static final androidx.window.embedding.SplitAttributes.LayoutDirection LEFT_TO_RIGHT;
+ field public static final androidx.window.embedding.SplitAttributes.LayoutDirection LOCALE;
+ field public static final androidx.window.embedding.SplitAttributes.LayoutDirection RIGHT_TO_LEFT;
+ field public static final androidx.window.embedding.SplitAttributes.LayoutDirection TOP_TO_BOTTOM;
+ }
+
+ public static final class SplitAttributes.LayoutDirection.Companion {
+ }
+
+ public static class SplitAttributes.SplitType {
+ method public static final androidx.window.embedding.SplitAttributes.SplitType.ExpandContainersSplitType expandContainers();
+ method public static final androidx.window.embedding.SplitAttributes.SplitType.RatioSplitType ratio(@FloatRange(from=0.0, to=1.0, fromInclusive=false, toInclusive=false) float ratio);
+ method public static final androidx.window.embedding.SplitAttributes.SplitType.HingeSplitType splitByHinge(optional androidx.window.embedding.SplitAttributes.SplitType fallbackSplitType);
+ method public static final androidx.window.embedding.SplitAttributes.SplitType.RatioSplitType splitEqually();
+ field public static final androidx.window.embedding.SplitAttributes.SplitType.Companion Companion;
+ }
+
+ public static final class SplitAttributes.SplitType.Companion {
+ method public androidx.window.embedding.SplitAttributes.SplitType.ExpandContainersSplitType expandContainers();
+ method public androidx.window.embedding.SplitAttributes.SplitType.RatioSplitType ratio(@FloatRange(from=0.0, to=1.0, fromInclusive=false, toInclusive=false) float ratio);
+ method public androidx.window.embedding.SplitAttributes.SplitType.HingeSplitType splitByHinge(optional androidx.window.embedding.SplitAttributes.SplitType fallbackSplitType);
+ method public androidx.window.embedding.SplitAttributes.SplitType.RatioSplitType splitEqually();
+ }
+
+ public static final class SplitAttributes.SplitType.ExpandContainersSplitType extends androidx.window.embedding.SplitAttributes.SplitType {
+ }
+
+ public static final class SplitAttributes.SplitType.HingeSplitType extends androidx.window.embedding.SplitAttributes.SplitType {
+ method public androidx.window.embedding.SplitAttributes.SplitType getFallbackSplitType();
+ property public final androidx.window.embedding.SplitAttributes.SplitType fallbackSplitType;
+ }
+
+ public static final class SplitAttributes.SplitType.RatioSplitType extends androidx.window.embedding.SplitAttributes.SplitType {
+ method public float getRatio();
+ property public final float ratio;
+ }
+
+ public final class SplitAttributesCalculatorParams {
+ method public boolean getAreDefaultConstraintsSatisfied();
+ method public androidx.window.embedding.SplitAttributes getDefaultSplitAttributes();
+ method public android.content.res.Configuration getParentConfiguration();
+ method public androidx.window.layout.WindowLayoutInfo getParentWindowLayoutInfo();
+ method public androidx.window.layout.WindowMetrics getParentWindowMetrics();
+ method public String? getSplitRuleTag();
+ property public final boolean areDefaultConstraintsSatisfied;
+ property public final androidx.window.embedding.SplitAttributes defaultSplitAttributes;
+ property public final android.content.res.Configuration parentConfiguration;
+ property public final androidx.window.layout.WindowLayoutInfo parentWindowLayoutInfo;
+ property public final androidx.window.layout.WindowMetrics parentWindowMetrics;
+ property public final String? splitRuleTag;
+ }
+
public final class SplitController {
method public void addSplitListener(android.app.Activity activity, java.util.concurrent.Executor executor, androidx.core.util.Consumer<java.util.List<androidx.window.embedding.SplitInfo>> consumer);
+ method public void clearSplitAttributesCalculator();
method public static androidx.window.embedding.SplitController getInstance(android.content.Context context);
+ method public boolean isSplitAttributesCalculatorSupported();
method public boolean isSplitSupported();
method public void removeSplitListener(androidx.core.util.Consumer<java.util.List<androidx.window.embedding.SplitInfo>> consumer);
+ method public void setSplitAttributesCalculator(kotlin.jvm.functions.Function1<? super androidx.window.embedding.SplitAttributesCalculatorParams,androidx.window.embedding.SplitAttributes> calculator);
field public static final androidx.window.embedding.SplitController.Companion Companion;
}
@@ -105,10 +220,10 @@
method public operator boolean contains(android.app.Activity activity);
method public androidx.window.embedding.ActivityStack getPrimaryActivityStack();
method public androidx.window.embedding.ActivityStack getSecondaryActivityStack();
- method public float getSplitRatio();
+ method public androidx.window.embedding.SplitAttributes getSplitAttributes();
property public final androidx.window.embedding.ActivityStack primaryActivityStack;
property public final androidx.window.embedding.ActivityStack secondaryActivityStack;
- property public final float splitRatio;
+ property public final androidx.window.embedding.SplitAttributes splitAttributes;
}
public final class SplitPairFilter {
@@ -126,35 +241,36 @@
public final class SplitPairRule extends androidx.window.embedding.SplitRule {
method public boolean getClearTop();
method public java.util.Set<androidx.window.embedding.SplitPairFilter> getFilters();
- method public int getFinishPrimaryWithSecondary();
- method public int getFinishSecondaryWithPrimary();
+ method public androidx.window.embedding.SplitRule.FinishBehavior getFinishPrimaryWithSecondary();
+ method public androidx.window.embedding.SplitRule.FinishBehavior getFinishSecondaryWithPrimary();
property public final boolean clearTop;
property public final java.util.Set<androidx.window.embedding.SplitPairFilter> filters;
- property public final int finishPrimaryWithSecondary;
- property public final int finishSecondaryWithPrimary;
+ property public final androidx.window.embedding.SplitRule.FinishBehavior finishPrimaryWithSecondary;
+ property public final androidx.window.embedding.SplitRule.FinishBehavior finishSecondaryWithPrimary;
}
public static final class SplitPairRule.Builder {
ctor public SplitPairRule.Builder(java.util.Set<androidx.window.embedding.SplitPairFilter> filters);
method public androidx.window.embedding.SplitPairRule build();
method public androidx.window.embedding.SplitPairRule.Builder setClearTop(boolean clearTop);
- method public androidx.window.embedding.SplitPairRule.Builder setFinishPrimaryWithSecondary(int finishPrimaryWithSecondary);
- method public androidx.window.embedding.SplitPairRule.Builder setFinishSecondaryWithPrimary(int finishSecondaryWithPrimary);
- method public androidx.window.embedding.SplitPairRule.Builder setLayoutDirection(int layoutDirection);
+ method public androidx.window.embedding.SplitPairRule.Builder setDefaultSplitAttributes(androidx.window.embedding.SplitAttributes defaultSplitAttributes);
+ method public androidx.window.embedding.SplitPairRule.Builder setFinishPrimaryWithSecondary(androidx.window.embedding.SplitRule.FinishBehavior finishPrimaryWithSecondary);
+ method public androidx.window.embedding.SplitPairRule.Builder setFinishSecondaryWithPrimary(androidx.window.embedding.SplitRule.FinishBehavior finishSecondaryWithPrimary);
method public androidx.window.embedding.SplitPairRule.Builder setMaxAspectRatioInLandscape(androidx.window.embedding.EmbeddingAspectRatio aspectRatio);
method public androidx.window.embedding.SplitPairRule.Builder setMaxAspectRatioInPortrait(androidx.window.embedding.EmbeddingAspectRatio aspectRatio);
+ method public androidx.window.embedding.SplitPairRule.Builder setMinHeightDp(@IntRange(from=0L) int minHeightDp);
method public androidx.window.embedding.SplitPairRule.Builder setMinSmallestWidthDp(@IntRange(from=0L) int minSmallestWidthDp);
method public androidx.window.embedding.SplitPairRule.Builder setMinWidthDp(@IntRange(from=0L) int minWidthDp);
- method public androidx.window.embedding.SplitPairRule.Builder setSplitRatio(@FloatRange(from=0.0, to=1.0) float splitRatio);
+ method public androidx.window.embedding.SplitPairRule.Builder setTag(String? tag);
}
public final class SplitPlaceholderRule extends androidx.window.embedding.SplitRule {
method public java.util.Set<androidx.window.embedding.ActivityFilter> getFilters();
- method public int getFinishPrimaryWithPlaceholder();
+ method public androidx.window.embedding.SplitRule.FinishBehavior getFinishPrimaryWithPlaceholder();
method public android.content.Intent getPlaceholderIntent();
method public boolean isSticky();
property public final java.util.Set<androidx.window.embedding.ActivityFilter> filters;
- property public final int finishPrimaryWithPlaceholder;
+ property public final androidx.window.embedding.SplitRule.FinishBehavior finishPrimaryWithPlaceholder;
property public final boolean isSticky;
property public final android.content.Intent placeholderIntent;
}
@@ -162,33 +278,31 @@
public static final class SplitPlaceholderRule.Builder {
ctor public SplitPlaceholderRule.Builder(java.util.Set<androidx.window.embedding.ActivityFilter> filters, android.content.Intent placeholderIntent);
method public androidx.window.embedding.SplitPlaceholderRule build();
- method public androidx.window.embedding.SplitPlaceholderRule.Builder setFinishPrimaryWithPlaceholder(int finishPrimaryWithPlaceholder);
- method public androidx.window.embedding.SplitPlaceholderRule.Builder setLayoutDirection(int layoutDirection);
+ method public androidx.window.embedding.SplitPlaceholderRule.Builder setDefaultSplitAttributes(androidx.window.embedding.SplitAttributes defaultSplitAttributes);
+ method public androidx.window.embedding.SplitPlaceholderRule.Builder setFinishPrimaryWithPlaceholder(androidx.window.embedding.SplitRule.FinishBehavior finishPrimaryWithPlaceholder);
method public androidx.window.embedding.SplitPlaceholderRule.Builder setMaxAspectRatioInLandscape(androidx.window.embedding.EmbeddingAspectRatio aspectRatio);
method public androidx.window.embedding.SplitPlaceholderRule.Builder setMaxAspectRatioInPortrait(androidx.window.embedding.EmbeddingAspectRatio aspectRatio);
+ method public androidx.window.embedding.SplitPlaceholderRule.Builder setMinHeightDp(@IntRange(from=0L) int minHeightDp);
method public androidx.window.embedding.SplitPlaceholderRule.Builder setMinSmallestWidthDp(@IntRange(from=0L) int minSmallestWidthDp);
method public androidx.window.embedding.SplitPlaceholderRule.Builder setMinWidthDp(@IntRange(from=0L) int minWidthDp);
- method public androidx.window.embedding.SplitPlaceholderRule.Builder setSplitRatio(@FloatRange(from=0.0, to=1.0) float splitRatio);
method public androidx.window.embedding.SplitPlaceholderRule.Builder setSticky(boolean isSticky);
+ method public androidx.window.embedding.SplitPlaceholderRule.Builder setTag(String? tag);
}
public class SplitRule extends androidx.window.embedding.EmbeddingRule {
- method public final int getLayoutDirection();
+ method public final androidx.window.embedding.SplitAttributes getDefaultSplitAttributes();
method public final androidx.window.embedding.EmbeddingAspectRatio getMaxAspectRatioInLandscape();
method public final androidx.window.embedding.EmbeddingAspectRatio getMaxAspectRatioInPortrait();
+ method public final int getMinHeightDp();
method public final int getMinSmallestWidthDp();
method public final int getMinWidthDp();
- method public final float getSplitRatio();
- property public final int layoutDirection;
+ property public final androidx.window.embedding.SplitAttributes defaultSplitAttributes;
property public final androidx.window.embedding.EmbeddingAspectRatio maxAspectRatioInLandscape;
property public final androidx.window.embedding.EmbeddingAspectRatio maxAspectRatioInPortrait;
+ property public final int minHeightDp;
property public final int minSmallestWidthDp;
property public final int minWidthDp;
- property public final float splitRatio;
field public static final androidx.window.embedding.SplitRule.Companion Companion;
- field public static final int FINISH_ADJACENT = 2; // 0x2
- field public static final int FINISH_ALWAYS = 1; // 0x1
- field public static final int FINISH_NEVER = 0; // 0x0
field public static final androidx.window.embedding.EmbeddingAspectRatio SPLIT_MAX_ASPECT_RATIO_LANDSCAPE_DEFAULT;
field public static final androidx.window.embedding.EmbeddingAspectRatio SPLIT_MAX_ASPECT_RATIO_PORTRAIT_DEFAULT;
field public static final int SPLIT_MIN_DIMENSION_ALWAYS_ALLOW = 0; // 0x0
@@ -198,6 +312,16 @@
public static final class SplitRule.Companion {
}
+ public static final class SplitRule.FinishBehavior {
+ field public static final androidx.window.embedding.SplitRule.FinishBehavior ADJACENT;
+ field public static final androidx.window.embedding.SplitRule.FinishBehavior ALWAYS;
+ field public static final androidx.window.embedding.SplitRule.FinishBehavior.Companion Companion;
+ field public static final androidx.window.embedding.SplitRule.FinishBehavior NEVER;
+ }
+
+ public static final class SplitRule.FinishBehavior.Companion {
+ }
+
}
package androidx.window.layout {
@@ -247,6 +371,7 @@
public interface WindowInfoTracker {
method public default static androidx.window.layout.WindowInfoTracker getOrCreate(android.content.Context context);
+ method public default kotlinx.coroutines.flow.Flow<androidx.window.layout.WindowLayoutInfo> windowLayoutInfo(@UiContext android.content.Context context);
method public kotlinx.coroutines.flow.Flow<androidx.window.layout.WindowLayoutInfo> windowLayoutInfo(android.app.Activity activity);
field public static final androidx.window.layout.WindowInfoTracker.Companion Companion;
}
@@ -268,7 +393,9 @@
public interface WindowMetricsCalculator {
method public androidx.window.layout.WindowMetrics computeCurrentWindowMetrics(android.app.Activity activity);
+ method public default androidx.window.layout.WindowMetrics computeCurrentWindowMetrics(@UiContext android.content.Context context);
method public androidx.window.layout.WindowMetrics computeMaximumWindowMetrics(android.app.Activity activity);
+ method public default androidx.window.layout.WindowMetrics computeMaximumWindowMetrics(@UiContext android.content.Context context);
method public default static androidx.window.layout.WindowMetricsCalculator getOrCreate();
field public static final androidx.window.layout.WindowMetricsCalculator.Companion Companion;
}
diff --git a/window/window/api/res-current.txt b/window/window/api/res-current.txt
index e69de29..185352b 100644
--- a/window/window/api/res-current.txt
+++ b/window/window/api/res-current.txt
@@ -0,0 +1,21 @@
+attr activityAction
+attr activityName
+attr alwaysExpand
+attr animationBackgroundColor
+attr clearTop
+attr finishPrimaryWithPlaceholder
+attr finishPrimaryWithSecondary
+attr finishSecondaryWithPrimary
+attr placeholderActivityName
+attr primaryActivityName
+attr secondaryActivityAction
+attr secondaryActivityName
+attr splitLayoutDirection
+attr splitMaxAspectRatioInLandscape
+attr splitMaxAspectRatioInPortrait
+attr splitMinHeightDp
+attr splitMinSmallestWidthDp
+attr splitMinWidthDp
+attr splitRatio
+attr stickyPlaceholder
+attr tag
diff --git a/window/window/api/restricted_current.txt b/window/window/api/restricted_current.txt
index 4c43822..ee2f53d 100644
--- a/window/window/api/restricted_current.txt
+++ b/window/window/api/restricted_current.txt
@@ -4,6 +4,7 @@
public final class WindowProperties {
field public static final androidx.window.WindowProperties INSTANCE;
field public static final String PROPERTY_ACTIVITY_EMBEDDING_ALLOW_SYSTEM_OVERRIDE = "android.window.PROPERTY_ACTIVITY_EMBEDDING_ALLOW_SYSTEM_OVERRIDE";
+ field public static final String PROPERTY_ACTIVITY_EMBEDDING_SPLITS_ENABLED = "android.window.PROPERTY_ACTIVITY_EMBEDDING_SPLITS_ENABLED";
}
}
@@ -41,6 +42,7 @@
ctor public ActivityRule.Builder(java.util.Set<androidx.window.embedding.ActivityFilter> filters);
method public androidx.window.embedding.ActivityRule build();
method public androidx.window.embedding.ActivityRule.Builder setAlwaysExpand(boolean alwaysExpand);
+ method public androidx.window.embedding.ActivityRule.Builder setTag(String tag);
}
public final class ActivityStack {
@@ -64,6 +66,8 @@
}
public abstract class EmbeddingRule {
+ method public final String? getTag();
+ property public final String? tag;
}
public final class RuleController {
@@ -82,11 +86,90 @@
method public java.util.Set<androidx.window.embedding.EmbeddingRule> parseRules(android.content.Context context, @XmlRes int staticRuleResourceId);
}
+ public final class SplitAttributes {
+ method public int getAnimationBackgroundColor();
+ method public androidx.window.embedding.SplitAttributes.LayoutDirection getLayoutDirection();
+ method public androidx.window.embedding.SplitAttributes.SplitType getSplitType();
+ property public final int animationBackgroundColor;
+ property public final androidx.window.embedding.SplitAttributes.LayoutDirection layoutDirection;
+ property public final androidx.window.embedding.SplitAttributes.SplitType splitType;
+ field public static final androidx.window.embedding.SplitAttributes.Companion Companion;
+ }
+
+ public static final class SplitAttributes.Builder {
+ ctor public SplitAttributes.Builder();
+ method public androidx.window.embedding.SplitAttributes build();
+ method public androidx.window.embedding.SplitAttributes.Builder setAnimationBackgroundColor(@ColorInt int color);
+ method public androidx.window.embedding.SplitAttributes.Builder setLayoutDirection(androidx.window.embedding.SplitAttributes.LayoutDirection layoutDirection);
+ method public androidx.window.embedding.SplitAttributes.Builder setSplitType(androidx.window.embedding.SplitAttributes.SplitType type);
+ }
+
+ public static final class SplitAttributes.Companion {
+ }
+
+ public static final class SplitAttributes.LayoutDirection {
+ field public static final androidx.window.embedding.SplitAttributes.LayoutDirection BOTTOM_TO_TOP;
+ field public static final androidx.window.embedding.SplitAttributes.LayoutDirection.Companion Companion;
+ field public static final androidx.window.embedding.SplitAttributes.LayoutDirection LEFT_TO_RIGHT;
+ field public static final androidx.window.embedding.SplitAttributes.LayoutDirection LOCALE;
+ field public static final androidx.window.embedding.SplitAttributes.LayoutDirection RIGHT_TO_LEFT;
+ field public static final androidx.window.embedding.SplitAttributes.LayoutDirection TOP_TO_BOTTOM;
+ }
+
+ public static final class SplitAttributes.LayoutDirection.Companion {
+ }
+
+ public static class SplitAttributes.SplitType {
+ method public static final androidx.window.embedding.SplitAttributes.SplitType.ExpandContainersSplitType expandContainers();
+ method public static final androidx.window.embedding.SplitAttributes.SplitType.RatioSplitType ratio(@FloatRange(from=0.0, to=1.0, fromInclusive=false, toInclusive=false) float ratio);
+ method public static final androidx.window.embedding.SplitAttributes.SplitType.HingeSplitType splitByHinge(optional androidx.window.embedding.SplitAttributes.SplitType fallbackSplitType);
+ method public static final androidx.window.embedding.SplitAttributes.SplitType.RatioSplitType splitEqually();
+ field public static final androidx.window.embedding.SplitAttributes.SplitType.Companion Companion;
+ }
+
+ public static final class SplitAttributes.SplitType.Companion {
+ method public androidx.window.embedding.SplitAttributes.SplitType.ExpandContainersSplitType expandContainers();
+ method public androidx.window.embedding.SplitAttributes.SplitType.RatioSplitType ratio(@FloatRange(from=0.0, to=1.0, fromInclusive=false, toInclusive=false) float ratio);
+ method public androidx.window.embedding.SplitAttributes.SplitType.HingeSplitType splitByHinge(optional androidx.window.embedding.SplitAttributes.SplitType fallbackSplitType);
+ method public androidx.window.embedding.SplitAttributes.SplitType.RatioSplitType splitEqually();
+ }
+
+ public static final class SplitAttributes.SplitType.ExpandContainersSplitType extends androidx.window.embedding.SplitAttributes.SplitType {
+ }
+
+ public static final class SplitAttributes.SplitType.HingeSplitType extends androidx.window.embedding.SplitAttributes.SplitType {
+ method public androidx.window.embedding.SplitAttributes.SplitType getFallbackSplitType();
+ property public final androidx.window.embedding.SplitAttributes.SplitType fallbackSplitType;
+ }
+
+ public static final class SplitAttributes.SplitType.RatioSplitType extends androidx.window.embedding.SplitAttributes.SplitType {
+ method public float getRatio();
+ property public final float ratio;
+ }
+
+ public final class SplitAttributesCalculatorParams {
+ method public boolean getAreDefaultConstraintsSatisfied();
+ method public androidx.window.embedding.SplitAttributes getDefaultSplitAttributes();
+ method public android.content.res.Configuration getParentConfiguration();
+ method public androidx.window.layout.WindowLayoutInfo getParentWindowLayoutInfo();
+ method public androidx.window.layout.WindowMetrics getParentWindowMetrics();
+ method public String? getSplitRuleTag();
+ property public final boolean areDefaultConstraintsSatisfied;
+ property public final androidx.window.embedding.SplitAttributes defaultSplitAttributes;
+ property public final android.content.res.Configuration parentConfiguration;
+ property public final androidx.window.layout.WindowLayoutInfo parentWindowLayoutInfo;
+ property public final androidx.window.layout.WindowMetrics parentWindowMetrics;
+ property public final String? splitRuleTag;
+ }
+
public final class SplitController {
method public void addSplitListener(android.app.Activity activity, java.util.concurrent.Executor executor, androidx.core.util.Consumer<java.util.List<androidx.window.embedding.SplitInfo>> consumer);
+ method public void clearSplitAttributesCalculator();
method public static androidx.window.embedding.SplitController getInstance(android.content.Context context);
+ method public boolean isSplitAttributesCalculatorSupported();
method public boolean isSplitSupported();
method public void removeSplitListener(androidx.core.util.Consumer<java.util.List<androidx.window.embedding.SplitInfo>> consumer);
+ method public void setSplitAttributesCalculator(kotlin.jvm.functions.Function1<? super androidx.window.embedding.SplitAttributesCalculatorParams,androidx.window.embedding.SplitAttributes> calculator);
field public static final androidx.window.embedding.SplitController.Companion Companion;
}
@@ -98,10 +181,10 @@
method public operator boolean contains(android.app.Activity activity);
method public androidx.window.embedding.ActivityStack getPrimaryActivityStack();
method public androidx.window.embedding.ActivityStack getSecondaryActivityStack();
- method public float getSplitRatio();
+ method public androidx.window.embedding.SplitAttributes getSplitAttributes();
property public final androidx.window.embedding.ActivityStack primaryActivityStack;
property public final androidx.window.embedding.ActivityStack secondaryActivityStack;
- property public final float splitRatio;
+ property public final androidx.window.embedding.SplitAttributes splitAttributes;
}
public final class SplitPairFilter {
@@ -119,35 +202,36 @@
public final class SplitPairRule extends androidx.window.embedding.SplitRule {
method public boolean getClearTop();
method public java.util.Set<androidx.window.embedding.SplitPairFilter> getFilters();
- method public int getFinishPrimaryWithSecondary();
- method public int getFinishSecondaryWithPrimary();
+ method public androidx.window.embedding.SplitRule.FinishBehavior getFinishPrimaryWithSecondary();
+ method public androidx.window.embedding.SplitRule.FinishBehavior getFinishSecondaryWithPrimary();
property public final boolean clearTop;
property public final java.util.Set<androidx.window.embedding.SplitPairFilter> filters;
- property public final int finishPrimaryWithSecondary;
- property public final int finishSecondaryWithPrimary;
+ property public final androidx.window.embedding.SplitRule.FinishBehavior finishPrimaryWithSecondary;
+ property public final androidx.window.embedding.SplitRule.FinishBehavior finishSecondaryWithPrimary;
}
public static final class SplitPairRule.Builder {
ctor public SplitPairRule.Builder(java.util.Set<androidx.window.embedding.SplitPairFilter> filters);
method public androidx.window.embedding.SplitPairRule build();
method public androidx.window.embedding.SplitPairRule.Builder setClearTop(boolean clearTop);
- method public androidx.window.embedding.SplitPairRule.Builder setFinishPrimaryWithSecondary(int finishPrimaryWithSecondary);
- method public androidx.window.embedding.SplitPairRule.Builder setFinishSecondaryWithPrimary(int finishSecondaryWithPrimary);
- method public androidx.window.embedding.SplitPairRule.Builder setLayoutDirection(int layoutDirection);
+ method public androidx.window.embedding.SplitPairRule.Builder setDefaultSplitAttributes(androidx.window.embedding.SplitAttributes defaultSplitAttributes);
+ method public androidx.window.embedding.SplitPairRule.Builder setFinishPrimaryWithSecondary(androidx.window.embedding.SplitRule.FinishBehavior finishPrimaryWithSecondary);
+ method public androidx.window.embedding.SplitPairRule.Builder setFinishSecondaryWithPrimary(androidx.window.embedding.SplitRule.FinishBehavior finishSecondaryWithPrimary);
method public androidx.window.embedding.SplitPairRule.Builder setMaxAspectRatioInLandscape(androidx.window.embedding.EmbeddingAspectRatio aspectRatio);
method public androidx.window.embedding.SplitPairRule.Builder setMaxAspectRatioInPortrait(androidx.window.embedding.EmbeddingAspectRatio aspectRatio);
+ method public androidx.window.embedding.SplitPairRule.Builder setMinHeightDp(@IntRange(from=0L) int minHeightDp);
method public androidx.window.embedding.SplitPairRule.Builder setMinSmallestWidthDp(@IntRange(from=0L) int minSmallestWidthDp);
method public androidx.window.embedding.SplitPairRule.Builder setMinWidthDp(@IntRange(from=0L) int minWidthDp);
- method public androidx.window.embedding.SplitPairRule.Builder setSplitRatio(@FloatRange(from=0.0, to=1.0) float splitRatio);
+ method public androidx.window.embedding.SplitPairRule.Builder setTag(String? tag);
}
public final class SplitPlaceholderRule extends androidx.window.embedding.SplitRule {
method public java.util.Set<androidx.window.embedding.ActivityFilter> getFilters();
- method public int getFinishPrimaryWithPlaceholder();
+ method public androidx.window.embedding.SplitRule.FinishBehavior getFinishPrimaryWithPlaceholder();
method public android.content.Intent getPlaceholderIntent();
method public boolean isSticky();
property public final java.util.Set<androidx.window.embedding.ActivityFilter> filters;
- property public final int finishPrimaryWithPlaceholder;
+ property public final androidx.window.embedding.SplitRule.FinishBehavior finishPrimaryWithPlaceholder;
property public final boolean isSticky;
property public final android.content.Intent placeholderIntent;
}
@@ -155,33 +239,31 @@
public static final class SplitPlaceholderRule.Builder {
ctor public SplitPlaceholderRule.Builder(java.util.Set<androidx.window.embedding.ActivityFilter> filters, android.content.Intent placeholderIntent);
method public androidx.window.embedding.SplitPlaceholderRule build();
- method public androidx.window.embedding.SplitPlaceholderRule.Builder setFinishPrimaryWithPlaceholder(int finishPrimaryWithPlaceholder);
- method public androidx.window.embedding.SplitPlaceholderRule.Builder setLayoutDirection(int layoutDirection);
+ method public androidx.window.embedding.SplitPlaceholderRule.Builder setDefaultSplitAttributes(androidx.window.embedding.SplitAttributes defaultSplitAttributes);
+ method public androidx.window.embedding.SplitPlaceholderRule.Builder setFinishPrimaryWithPlaceholder(androidx.window.embedding.SplitRule.FinishBehavior finishPrimaryWithPlaceholder);
method public androidx.window.embedding.SplitPlaceholderRule.Builder setMaxAspectRatioInLandscape(androidx.window.embedding.EmbeddingAspectRatio aspectRatio);
method public androidx.window.embedding.SplitPlaceholderRule.Builder setMaxAspectRatioInPortrait(androidx.window.embedding.EmbeddingAspectRatio aspectRatio);
+ method public androidx.window.embedding.SplitPlaceholderRule.Builder setMinHeightDp(@IntRange(from=0L) int minHeightDp);
method public androidx.window.embedding.SplitPlaceholderRule.Builder setMinSmallestWidthDp(@IntRange(from=0L) int minSmallestWidthDp);
method public androidx.window.embedding.SplitPlaceholderRule.Builder setMinWidthDp(@IntRange(from=0L) int minWidthDp);
- method public androidx.window.embedding.SplitPlaceholderRule.Builder setSplitRatio(@FloatRange(from=0.0, to=1.0) float splitRatio);
method public androidx.window.embedding.SplitPlaceholderRule.Builder setSticky(boolean isSticky);
+ method public androidx.window.embedding.SplitPlaceholderRule.Builder setTag(String? tag);
}
public class SplitRule extends androidx.window.embedding.EmbeddingRule {
- method public final int getLayoutDirection();
+ method public final androidx.window.embedding.SplitAttributes getDefaultSplitAttributes();
method public final androidx.window.embedding.EmbeddingAspectRatio getMaxAspectRatioInLandscape();
method public final androidx.window.embedding.EmbeddingAspectRatio getMaxAspectRatioInPortrait();
+ method public final int getMinHeightDp();
method public final int getMinSmallestWidthDp();
method public final int getMinWidthDp();
- method public final float getSplitRatio();
- property public final int layoutDirection;
+ property public final androidx.window.embedding.SplitAttributes defaultSplitAttributes;
property public final androidx.window.embedding.EmbeddingAspectRatio maxAspectRatioInLandscape;
property public final androidx.window.embedding.EmbeddingAspectRatio maxAspectRatioInPortrait;
+ property public final int minHeightDp;
property public final int minSmallestWidthDp;
property public final int minWidthDp;
- property public final float splitRatio;
field public static final androidx.window.embedding.SplitRule.Companion Companion;
- field public static final int FINISH_ADJACENT = 2; // 0x2
- field public static final int FINISH_ALWAYS = 1; // 0x1
- field public static final int FINISH_NEVER = 0; // 0x0
field public static final androidx.window.embedding.EmbeddingAspectRatio SPLIT_MAX_ASPECT_RATIO_LANDSCAPE_DEFAULT;
field public static final androidx.window.embedding.EmbeddingAspectRatio SPLIT_MAX_ASPECT_RATIO_PORTRAIT_DEFAULT;
field public static final int SPLIT_MIN_DIMENSION_ALWAYS_ALLOW = 0; // 0x0
@@ -191,6 +273,16 @@
public static final class SplitRule.Companion {
}
+ public static final class SplitRule.FinishBehavior {
+ field public static final androidx.window.embedding.SplitRule.FinishBehavior ADJACENT;
+ field public static final androidx.window.embedding.SplitRule.FinishBehavior ALWAYS;
+ field public static final androidx.window.embedding.SplitRule.FinishBehavior.Companion Companion;
+ field public static final androidx.window.embedding.SplitRule.FinishBehavior NEVER;
+ }
+
+ public static final class SplitRule.FinishBehavior.Companion {
+ }
+
}
package androidx.window.layout {
@@ -240,6 +332,7 @@
public interface WindowInfoTracker {
method public default static androidx.window.layout.WindowInfoTracker getOrCreate(android.content.Context context);
+ method public default kotlinx.coroutines.flow.Flow<androidx.window.layout.WindowLayoutInfo> windowLayoutInfo(@UiContext android.content.Context context);
method public kotlinx.coroutines.flow.Flow<androidx.window.layout.WindowLayoutInfo> windowLayoutInfo(android.app.Activity activity);
field public static final androidx.window.layout.WindowInfoTracker.Companion Companion;
}
@@ -260,7 +353,9 @@
public interface WindowMetricsCalculator {
method public androidx.window.layout.WindowMetrics computeCurrentWindowMetrics(android.app.Activity activity);
+ method public default androidx.window.layout.WindowMetrics computeCurrentWindowMetrics(@UiContext android.content.Context context);
method public androidx.window.layout.WindowMetrics computeMaximumWindowMetrics(android.app.Activity activity);
+ method public default androidx.window.layout.WindowMetrics computeMaximumWindowMetrics(@UiContext android.content.Context context);
method public default static androidx.window.layout.WindowMetricsCalculator getOrCreate();
field public static final androidx.window.layout.WindowMetricsCalculator.Companion Companion;
}
diff --git a/window/window/build.gradle b/window/window/build.gradle
index 5236d42..1880963 100644
--- a/window/window/build.gradle
+++ b/window/window/build.gradle
@@ -45,12 +45,13 @@
dependencies {
api(libs.kotlinStdlib)
api(libs.kotlinCoroutinesAndroid)
- implementation("androidx.annotation:annotation:1.2.0")
+ implementation("androidx.annotation:annotation:1.3.0")
implementation("androidx.collection:collection:1.1.0")
implementation("androidx.core:core:1.8.0")
+ implementation("androidx.window.extensions.core:core:1.0.0-alpha01")
compileOnly(project(":window:sidecar:sidecar"))
- compileOnly("androidx.window.extensions:extensions:1.1.0-alpha02")
+ compileOnly(project(":window:extensions:extensions"))
testImplementation(libs.testCore)
testImplementation(libs.testRunner)
@@ -61,7 +62,8 @@
testImplementation(libs.mockitoKotlin4)
testImplementation(libs.kotlinCoroutinesTest)
testImplementation(compileOnly(project(":window:sidecar:sidecar")))
- testImplementation(compileOnly("androidx.window.extensions:extensions:1.1.0-alpha02"))
+ testImplementation(compileOnly(project(":window:extensions:extensions")))
+ testImplementation(implementation("androidx.window.extensions.core:core:1.0.0-alpha01"))
androidTestImplementation(libs.testCore)
androidTestImplementation(libs.kotlinTestJunit)
@@ -75,9 +77,9 @@
androidTestImplementation(libs.multidex)
androidTestImplementation(libs.truth)
androidTestImplementation(libs.junit) // Needed for Assert.assertThrows
+ androidTestImplementation(compileOnly(project(":window:extensions:extensions")))
androidTestImplementation(compileOnly(project(":window:sidecar:sidecar")))
- androidTestImplementation(compileOnly("androidx.window.extensions:extensions:1.1.0-alpha02"))
- samples(project(":window:window-samples"))
+ androidTestImplementation(implementation("androidx.window.extensions.core:core:1.0.0-alpha01"))
}
androidx {
diff --git a/window/window/samples/build.gradle b/window/window/samples/build.gradle
new file mode 100644
index 0000000..a391e0a
--- /dev/null
+++ b/window/window/samples/build.gradle
@@ -0,0 +1,42 @@
+/*
+ * 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.
+ */
+
+
+import androidx.build.LibraryType
+
+plugins {
+ id("AndroidXPlugin")
+ id("com.android.library")
+ id("kotlin-android")
+}
+
+dependencies {
+ api(libs.kotlinStdlib)
+ api(project(":window:window"))
+
+ compileOnly(project(":annotation:annotation-sampled"))
+}
+
+android {
+ namespace "androidx.window.samples"
+}
+
+androidx {
+ name = "Jetpack WindowManager Library Samples"
+ type = LibraryType.SAMPLES
+ inceptionYear = "2022"
+ description = "Code samples for WindowManager Jetpack library."
+}
diff --git a/window/window/samples/src/main/java/androidx.window.samples.embedding/SplitAttributesCalculatorSamples.kt b/window/window/samples/src/main/java/androidx.window.samples.embedding/SplitAttributesCalculatorSamples.kt
new file mode 100644
index 0000000..ddbbf0d
--- /dev/null
+++ b/window/window/samples/src/main/java/androidx.window.samples.embedding/SplitAttributesCalculatorSamples.kt
@@ -0,0 +1,140 @@
+/*
+ * 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 androidx.window.samples.embedding
+
+import android.app.Application
+import android.graphics.Color
+import androidx.annotation.Sampled
+import androidx.window.embedding.SplitAttributes
+import androidx.window.embedding.SplitController
+import androidx.window.layout.FoldingFeature
+
+@Sampled
+fun splitAttributesCalculatorSample() {
+ SplitController.getInstance(context)
+ .setSplitAttributesCalculator { params ->
+ val tag = params.splitRuleTag
+ val parentWindowMetrics = params.parentWindowMetrics
+ val parentConfig = params.parentConfiguration
+ val foldingFeatures = params.parentWindowLayoutInfo.displayFeatures
+ .filterIsInstance<FoldingFeature>()
+ val foldingState = if (foldingFeatures.size == 1) foldingFeatures[0] else null
+ // Tag can be used to filter the SplitRule to apply the SplitAttributes
+ if (TAG_SPLIT_RULE_MAIN != tag && params.areDefaultConstraintsSatisfied) {
+ return@setSplitAttributesCalculator params.defaultSplitAttributes
+ }
+
+ // This sample will make the app show a layout to
+ // - split the task bounds vertically if the device is in landscape
+ // - fill the task bounds if the device is in portrait and its folding state does not
+ // split the screen
+ // - split the task bounds horizontally in tabletop mode
+ val bounds = parentWindowMetrics.bounds
+ if (foldingState?.isSeparating == true) {
+ // Split the parent container that followed by the hinge if the hinge separates the
+ // parent window.
+ return@setSplitAttributesCalculator SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.splitByHinge())
+ .setLayoutDirection(
+ if (foldingState.orientation == FoldingFeature.Orientation.HORIZONTAL) {
+ SplitAttributes.LayoutDirection.TOP_TO_BOTTOM
+ } else {
+ SplitAttributes.LayoutDirection.LOCALE
+ }
+ )
+ // Set the color to use when switching between vertical and horizontal
+ .setAnimationBackgroundColor(Color.GRAY)
+ .build()
+ }
+ return@setSplitAttributesCalculator if (
+ parentConfig.screenWidthDp >= 600 && bounds.width() >= bounds.height()
+ ) {
+ // Split the parent container equally and vertically if the device is in landscape.
+ SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.splitEqually())
+ .setLayoutDirection(SplitAttributes.LayoutDirection.LOCALE)
+ .setAnimationBackgroundColor(Color.GRAY)
+ .build()
+ } else {
+ // Expand containers if the device is in portrait or the width is less than 600 dp.
+ SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.expandContainers())
+ .build()
+ }
+ }
+}
+
+@Sampled
+fun splitWithOrientations() {
+ SplitController.getInstance(context)
+ .setSplitAttributesCalculator { params ->
+ // A sample to split with the dimension that larger than 600 DP. If there's no dimension
+ // larger than 600 DP, show the presentation to fill the task bounds.
+ val parentConfiguration = params.parentConfiguration
+ val builder = SplitAttributes.Builder()
+ return@setSplitAttributesCalculator if (parentConfiguration.screenWidthDp >= 600) {
+ builder
+ .setLayoutDirection(SplitAttributes.LayoutDirection.LOCALE)
+ // Set the color to use when switching between vertical and horizontal
+ .setAnimationBackgroundColor(Color.GRAY)
+ .build()
+ } else if (parentConfiguration.screenHeightDp >= 600) {
+ builder
+ .setLayoutDirection(SplitAttributes.LayoutDirection.TOP_TO_BOTTOM)
+ // Set the color to use when switching between vertical and horizontal
+ .setAnimationBackgroundColor(Color.GRAY)
+ .build()
+ } else {
+ // Fallback to expand the secondary container
+ builder
+ .setSplitType(SplitAttributes.SplitType.expandContainers())
+ .build()
+ }
+ }
+}
+
+@Sampled
+fun expandContainersInPortrait() {
+ SplitController.getInstance(context)
+ .setSplitAttributesCalculator { params ->
+ // A sample to always fill task bounds when the device is in portrait.
+ val tag = params.splitRuleTag
+ val bounds = params.parentWindowMetrics.bounds
+ val defaultSplitAttributes = params.defaultSplitAttributes
+ val areDefaultConstraintsSatisfied = params.areDefaultConstraintsSatisfied
+
+ val expandContainersAttrs = SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.expandContainers())
+ .build()
+ if (!areDefaultConstraintsSatisfied) {
+ return@setSplitAttributesCalculator expandContainersAttrs
+ }
+ // Always expand containers for the splitRule tagged as
+ // TAG_SPLIT_RULE_EXPAND_IN_PORTRAIT if the device is in portrait
+ // even if [areDefaultConstraintsSatisfied] reports true.
+ if (bounds.height() > bounds.width() && TAG_SPLIT_RULE_EXPAND_IN_PORTRAIT.equals(tag)) {
+ return@setSplitAttributesCalculator expandContainersAttrs
+ }
+ // Otherwise, use the default splitAttributes.
+ return@setSplitAttributesCalculator defaultSplitAttributes
+ }
+}
+
+/** Assume it's a valid [Application]... */
+val context = Application()
+const val TAG_SPLIT_RULE_MAIN = "main"
+const val TAG_SPLIT_RULE_EXPAND_IN_PORTRAIT = "expand_in_portrait"
\ No newline at end of file
diff --git a/window/window/src/androidTest/AndroidManifest.xml b/window/window/src/androidTest/AndroidManifest.xml
index d543136..cd1d81e 100644
--- a/window/window/src/androidTest/AndroidManifest.xml
+++ b/window/window/src/androidTest/AndroidManifest.xml
@@ -25,5 +25,8 @@
<property
android:name="android.window.PROPERTY_ACTIVITY_EMBEDDING_ALLOW_SYSTEM_OVERRIDE"
android:value="true" />
+ <property
+ android:name="android.window.PROPERTY_ACTIVITY_EMBEDDING_SPLITS_ENABLED"
+ android:value="true" />
</application>
</manifest>
diff --git a/window/window/src/androidTest/java/androidx/window/WindowPropertiesTest.kt b/window/window/src/androidTest/java/androidx/window/WindowPropertiesTest.kt
index b1c97d0..34eb50f 100644
--- a/window/window/src/androidTest/java/androidx/window/WindowPropertiesTest.kt
+++ b/window/window/src/androidTest/java/androidx/window/WindowPropertiesTest.kt
@@ -49,6 +49,24 @@
}
}
+ @Test
+ fun test_property_activity_embedding_splits() {
+ assumeTrue(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
+ // No-op, but to suppress lint
+ return
+ }
+ activityRule.scenario.onActivity { activity ->
+ // Should be true as defined in AndroidManifest.xml
+ assertTrue(
+ getProperty(
+ activity,
+ WindowProperties.PROPERTY_ACTIVITY_EMBEDDING_SPLITS_ENABLED
+ )
+ )
+ }
+ }
+
@RequiresApi(Build.VERSION_CODES.S)
@Throws(PackageManager.NameNotFoundException::class)
private fun getProperty(context: Context, propertyName: String): Boolean {
diff --git a/window/window/src/androidTest/java/androidx/window/WindowTestUtils.kt b/window/window/src/androidTest/java/androidx/window/WindowTestUtils.kt
new file mode 100644
index 0000000..d9ae80b
--- /dev/null
+++ b/window/window/src/androidTest/java/androidx/window/WindowTestUtils.kt
@@ -0,0 +1,42 @@
+package androidx.window
+
+import android.app.Application
+import android.content.Context
+import android.hardware.display.DisplayManager
+import android.os.Build
+import android.view.Display
+import android.view.WindowManager
+import androidx.annotation.RequiresApi
+import androidx.test.core.app.ApplicationProvider
+import androidx.window.core.ExtensionsUtil
+import org.junit.Assume.assumeTrue
+
+open class WindowTestUtils {
+ companion object {
+
+ @RequiresApi(Build.VERSION_CODES.R)
+ fun createOverlayWindowContext(): Context {
+ val context = ApplicationProvider.getApplicationContext<Application>()
+ return context.createDisplayContext(
+ context.getSystemService(DisplayManager::class.java)
+ .getDisplay(Display.DEFAULT_DISPLAY)
+ ).createWindowContext(
+ WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
+ /* options= */ null
+ )
+ }
+
+ @OptIn(androidx.window.core.ExperimentalWindowApi::class)
+ fun assumeAtLeastVendorApiLevel(min: Int) {
+ val apiLevel = ExtensionsUtil.safeVendorApiLevel
+ assumeTrue(apiLevel >= min)
+ }
+
+ @OptIn(androidx.window.core.ExperimentalWindowApi::class)
+ fun assumeBeforeVendorApiLevel(max: Int) {
+ val apiLevel = ExtensionsUtil.safeVendorApiLevel
+ assumeTrue(apiLevel < max)
+ assumeTrue(apiLevel > 0)
+ }
+ }
+}
\ No newline at end of file
diff --git a/window/window/src/androidTest/java/androidx/window/area/WindowAreaControllerImplTest.kt b/window/window/src/androidTest/java/androidx/window/area/WindowAreaControllerImplTest.kt
new file mode 100644
index 0000000..0432ad5
--- /dev/null
+++ b/window/window/src/androidTest/java/androidx/window/area/WindowAreaControllerImplTest.kt
@@ -0,0 +1,215 @@
+/*
+ * Copyright 2021 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 androidx.window.area
+
+import android.annotation.TargetApi
+import android.app.Activity
+import android.content.pm.ActivityInfo
+import android.os.Build
+import androidx.annotation.RequiresApi
+import androidx.test.ext.junit.rules.ActivityScenarioRule
+import androidx.window.TestActivity
+import androidx.window.TestConsumer
+import androidx.window.core.ExperimentalWindowApi
+import androidx.window.extensions.area.WindowAreaComponent
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.launch
+import org.junit.Assume.assumeTrue
+import org.junit.Rule
+import org.junit.Test
+import java.util.function.Consumer
+import kotlin.test.assertFailsWith
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.test.TestScope
+import kotlinx.coroutines.test.UnconfinedTestDispatcher
+import kotlinx.coroutines.test.runTest
+
+@OptIn(ExperimentalCoroutinesApi::class, ExperimentalWindowApi::class)
+class WindowAreaControllerImplTest {
+
+ @get:Rule
+ public val activityScenario: ActivityScenarioRule<TestActivity> =
+ ActivityScenarioRule(TestActivity::class.java)
+
+ private val testScope = TestScope(UnconfinedTestDispatcher())
+
+ @TargetApi(Build.VERSION_CODES.N)
+ @Test
+ public fun testRearDisplayStatus(): Unit = testScope.runTest {
+ assumeTrue(Build.VERSION.SDK_INT > Build.VERSION_CODES.N)
+ activityScenario.scenario.onActivity {
+ val extensionComponent = FakeWindowAreaComponent()
+ val repo = WindowAreaControllerImpl(extensionComponent)
+ val collector = TestConsumer<WindowAreaStatus>()
+ extensionComponent
+ .updateStatusListeners(WindowAreaComponent.STATUS_UNAVAILABLE)
+ testScope.launch(Job()) {
+ repo.rearDisplayStatus().collect(collector::accept)
+ }
+ collector.assertValue(WindowAreaStatus.UNAVAILABLE)
+ extensionComponent
+ .updateStatusListeners(WindowAreaComponent.STATUS_AVAILABLE)
+ collector.assertValues(
+ WindowAreaStatus.UNAVAILABLE,
+ WindowAreaStatus.AVAILABLE
+ )
+ }
+ }
+
+ @Test
+ public fun testRearDisplayStatusNullComponent(): Unit = testScope.runTest {
+ activityScenario.scenario.onActivity {
+ val repo = EmptyWindowAreaControllerImpl()
+ val collector = TestConsumer<WindowAreaStatus>()
+ testScope.launch(Job()) {
+ repo.rearDisplayStatus().collect(collector::accept)
+ }
+ collector.assertValue(WindowAreaStatus.UNSUPPORTED)
+ }
+ }
+
+ /**
+ * Tests the rear display mode flow works as expected. Tests the flow
+ * through WindowAreaControllerImpl with a fake extension. This fake extension
+ * changes the orientation of the activity to landscape when rear display mode is enabled
+ * and then returns it back to portrait when it's disabled.
+ */
+ @TargetApi(Build.VERSION_CODES.N)
+ @Test
+ public fun testRearDisplayMode(): Unit = testScope.runTest {
+ assumeTrue(Build.VERSION.SDK_INT > Build.VERSION_CODES.N)
+ val extensions = FakeWindowAreaComponent()
+ val repo = WindowAreaControllerImpl(extensions)
+ extensions.currentStatus = WindowAreaComponent.STATUS_AVAILABLE
+ val callback = TestWindowAreaSessionCallback()
+ activityScenario.scenario.onActivity { testActivity ->
+ testActivity.resetLayoutCounter()
+ testActivity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
+ testActivity.waitForLayout()
+ }
+
+ activityScenario.scenario.onActivity { testActivity ->
+ assert(testActivity.requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
+ testActivity.resetLayoutCounter()
+ repo.rearDisplayMode(testActivity, Runnable::run, callback)
+ }
+
+ activityScenario.scenario.onActivity { testActivity ->
+ assert(testActivity.requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
+ assert(callback.currentSession != null)
+ testActivity.resetLayoutCounter()
+ callback.endSession()
+ }
+ activityScenario.scenario.onActivity { testActivity ->
+ assert(testActivity.requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
+ assert(callback.currentSession == null)
+ }
+ }
+
+ @TargetApi(Build.VERSION_CODES.N)
+ @Test
+ public fun testRearDisplayModeReturnsError(): Unit = testScope.runTest {
+ assumeTrue(Build.VERSION.SDK_INT > Build.VERSION_CODES.N)
+ val extensionComponent = FakeWindowAreaComponent()
+ extensionComponent.currentStatus = WindowAreaComponent.STATUS_UNAVAILABLE
+ val repo = WindowAreaControllerImpl(extensionComponent)
+ val callback = TestWindowAreaSessionCallback()
+ activityScenario.scenario.onActivity { testActivity ->
+ assertFailsWith(
+ exceptionClass = UnsupportedOperationException::class,
+ block = { repo.rearDisplayMode(testActivity, Runnable::run, callback) }
+ )
+ }
+ }
+
+ @TargetApi(Build.VERSION_CODES.N)
+ @Test
+ public fun testRearDisplayModeNullComponent(): Unit = testScope.runTest {
+ assumeTrue(Build.VERSION.SDK_INT > Build.VERSION_CODES.N)
+ val repo = EmptyWindowAreaControllerImpl()
+ val callback = TestWindowAreaSessionCallback()
+ activityScenario.scenario.onActivity { testActivity ->
+ assertFailsWith(
+ exceptionClass = UnsupportedOperationException::class,
+ block = { repo.rearDisplayMode(testActivity, Runnable::run, callback) }
+ )
+ }
+ }
+
+ private class FakeWindowAreaComponent : WindowAreaComponent {
+ val statusListeners = mutableListOf<Consumer<Int>>()
+ var currentStatus = WindowAreaComponent.STATUS_UNSUPPORTED
+ var testActivity: Activity? = null
+ var sessionConsumer: Consumer<Int>? = null
+
+ @RequiresApi(Build.VERSION_CODES.N)
+ override fun addRearDisplayStatusListener(consumer: Consumer<Int>) {
+ statusListeners.add(consumer)
+ consumer.accept(currentStatus)
+ }
+
+ override fun removeRearDisplayStatusListener(consumer: Consumer<Int>) {
+ statusListeners.remove(consumer)
+ }
+
+ // Fake WindowAreaComponent will change the orientation of the activity to signal
+ // entering rear display mode, as well as ending the session
+ @RequiresApi(Build.VERSION_CODES.N)
+ override fun startRearDisplaySession(
+ activity: Activity,
+ rearDisplaySessionConsumer: Consumer<Int>
+ ) {
+ if (currentStatus != WindowAreaComponent.STATUS_AVAILABLE) {
+ throw WindowAreaController.REAR_DISPLAY_ERROR
+ }
+ testActivity = activity
+ sessionConsumer = rearDisplaySessionConsumer
+ testActivity!!.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
+ rearDisplaySessionConsumer.accept(WindowAreaComponent.SESSION_STATE_ACTIVE)
+ }
+
+ @RequiresApi(Build.VERSION_CODES.N)
+ override fun endRearDisplaySession() {
+ testActivity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
+ sessionConsumer?.accept(WindowAreaComponent.SESSION_STATE_INACTIVE)
+ }
+
+ @RequiresApi(Build.VERSION_CODES.N)
+ fun updateStatusListeners(newStatus: Int) {
+ currentStatus = newStatus
+ for (consumer in statusListeners) {
+ consumer.accept(currentStatus)
+ }
+ }
+ }
+
+ private class TestWindowAreaSessionCallback : WindowAreaSessionCallback {
+
+ var currentSession: WindowAreaSession? = null
+ var error: Throwable? = null
+
+ override fun onSessionStarted(session: WindowAreaSession) {
+ currentSession = session
+ }
+
+ override fun onSessionEnded() {
+ currentSession = null
+ }
+
+ fun endSession() = currentSession?.close()
+ }
+}
\ No newline at end of file
diff --git a/window/window/src/androidTest/java/androidx/window/embedding/EmbeddingAdapterTest.kt b/window/window/src/androidTest/java/androidx/window/embedding/EmbeddingAdapterTest.kt
new file mode 100644
index 0000000..be61996
--- /dev/null
+++ b/window/window/src/androidTest/java/androidx/window/embedding/EmbeddingAdapterTest.kt
@@ -0,0 +1,139 @@
+/*
+ * 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 androidx.window.embedding
+
+import androidx.window.extensions.embedding.ActivityStack as OEMActivityStack
+import androidx.window.extensions.embedding.SplitAttributes as OEMSplitAttributes
+import androidx.window.extensions.embedding.SplitInfo as OEMSplitInfo
+import android.app.Activity
+import android.graphics.Color
+import androidx.window.WindowTestUtils
+import androidx.window.core.PredicateAdapter
+import androidx.window.embedding.SplitAttributes.SplitType
+import androidx.window.extensions.WindowExtensions
+import com.nhaarman.mockitokotlin2.doReturn
+import org.junit.Assert.assertEquals
+import org.junit.Before
+import org.junit.Test
+import org.mockito.Mockito.mock
+
+/** Tests for [EmbeddingAdapter] */
+class EmbeddingAdapterTest {
+ private lateinit var adapter: EmbeddingAdapter
+
+ @Before
+ fun setUp() {
+ adapter = EmbeddingBackend::class.java.classLoader?.let { loader ->
+ EmbeddingAdapter(PredicateAdapter(loader))
+ }!!
+ }
+
+ @Test
+ fun testTranslateSplitInfoWithDefaultAttrs() {
+ WindowTestUtils.assumeAtLeastVendorApiLevel(WindowExtensions.VENDOR_API_LEVEL_2)
+
+ val oemSplitInfo = OEMSplitInfo(
+ OEMActivityStack(ArrayList(), true),
+ OEMActivityStack(ArrayList(), true),
+ OEMSplitAttributes.Builder().build(),
+ )
+ val expectedSplitInfo = SplitInfo(
+ ActivityStack(ArrayList(), isEmpty = true),
+ ActivityStack(ArrayList(), isEmpty = true),
+ SplitAttributes.Builder()
+ .setSplitType(SplitType.splitEqually())
+ .setLayoutDirection(SplitAttributes.LayoutDirection.LOCALE)
+ .setAnimationBackgroundColor(0)
+ .build()
+ )
+ assertEquals(listOf(expectedSplitInfo), adapter.translate(listOf(oemSplitInfo)))
+ }
+
+ @Test
+ fun testTranslateSplitInfoWithExpandingContainers() {
+ WindowTestUtils.assumeAtLeastVendorApiLevel(WindowExtensions.VENDOR_API_LEVEL_2)
+
+ val oemSplitInfo = OEMSplitInfo(
+ OEMActivityStack(ArrayList(), true),
+ OEMActivityStack(ArrayList(), true),
+ OEMSplitAttributes.Builder()
+ .setSplitType(OEMSplitAttributes.SplitType.ExpandContainersSplitType())
+ .build(),
+ )
+ val expectedSplitInfo = SplitInfo(
+ ActivityStack(ArrayList(), isEmpty = true),
+ ActivityStack(ArrayList(), isEmpty = true),
+ SplitAttributes.Builder()
+ .setSplitType(SplitType.expandContainers())
+ .setLayoutDirection(SplitAttributes.LayoutDirection.LOCALE)
+ .build()
+ )
+ assertEquals(listOf(expectedSplitInfo), adapter.translate(listOf(oemSplitInfo)))
+ }
+
+ @Suppress("DEPRECATION")
+ @Test
+ fun testTranslateSplitInfoWithApiLevel1() {
+ WindowTestUtils.assumeBeforeVendorApiLevel(WindowExtensions.VENDOR_API_LEVEL_2)
+
+ val activityStack = OEMActivityStack(ArrayList<Activity>(), true)
+ val expectedSplitRatio = 0.3f
+ val oemSplitInfo = mock(OEMSplitInfo::class.java)
+ doReturn(activityStack).`when`(oemSplitInfo).primaryActivityStack
+ doReturn(activityStack).`when`(oemSplitInfo).secondaryActivityStack
+ doReturn(expectedSplitRatio).`when`(oemSplitInfo).splitRatio
+
+ val expectedSplitInfo = SplitInfo(
+ ActivityStack(ArrayList(), isEmpty = true),
+ ActivityStack(ArrayList(), isEmpty = true),
+ SplitAttributes.Builder()
+ .setSplitType(SplitType.ratio(expectedSplitRatio))
+ // OEMSplitInfo with Vendor API level 1 doesn't provide layoutDirection.
+ .setLayoutDirection(SplitAttributes.LayoutDirection.LOCALE)
+ .build()
+ )
+ assertEquals(listOf(expectedSplitInfo), adapter.translate(listOf(oemSplitInfo)))
+ }
+
+ @Test
+ fun testTranslateSplitInfoWithApiLevel2() {
+ WindowTestUtils.assumeAtLeastVendorApiLevel(WindowExtensions.VENDOR_API_LEVEL_2)
+
+ val oemSplitInfo = OEMSplitInfo(
+ OEMActivityStack(ArrayList<Activity>(), true),
+ OEMActivityStack(ArrayList<Activity>(), true),
+ OEMSplitAttributes.Builder()
+ .setSplitType(
+ OEMSplitAttributes.SplitType.HingeSplitType(
+ OEMSplitAttributes.SplitType.RatioSplitType(0.3f)
+ )
+ ).setLayoutDirection(OEMSplitAttributes.LayoutDirection.TOP_TO_BOTTOM)
+ .setAnimationBackgroundColor(Color.YELLOW)
+ .build(),
+ )
+ val expectedSplitInfo = SplitInfo(
+ ActivityStack(ArrayList(), isEmpty = true),
+ ActivityStack(ArrayList(), isEmpty = true),
+ SplitAttributes.Builder()
+ .setSplitType(SplitType.splitByHinge(SplitType.ratio(0.3f)))
+ .setLayoutDirection(SplitAttributes.LayoutDirection.TOP_TO_BOTTOM)
+ .setAnimationBackgroundColor(Color.YELLOW)
+ .build()
+ )
+ assertEquals(listOf(expectedSplitInfo), adapter.translate(listOf(oemSplitInfo)))
+ }
+}
\ No newline at end of file
diff --git a/window/window/src/androidTest/java/androidx/window/embedding/EmbeddingRuleConstructionTests.kt b/window/window/src/androidTest/java/androidx/window/embedding/EmbeddingRuleConstructionTests.kt
index 8203078..f97930b 100644
--- a/window/window/src/androidTest/java/androidx/window/embedding/EmbeddingRuleConstructionTests.kt
+++ b/window/window/src/androidTest/java/androidx/window/embedding/EmbeddingRuleConstructionTests.kt
@@ -19,24 +19,34 @@
import android.content.ComponentName
import android.content.Context
import android.content.Intent
+import android.graphics.Color
import android.graphics.Rect
-import android.util.LayoutDirection
+import android.os.Build
+import androidx.annotation.RequiresApi
import androidx.test.core.app.ApplicationProvider
import androidx.window.embedding.EmbeddingAspectRatio.Companion.alwaysAllow
import androidx.window.embedding.EmbeddingAspectRatio.Companion.alwaysDisallow
import androidx.window.embedding.EmbeddingAspectRatio.Companion.ratio
+import androidx.window.embedding.SplitAttributes.LayoutDirection.Companion.BOTTOM_TO_TOP
+import androidx.window.embedding.SplitAttributes.LayoutDirection.Companion.LEFT_TO_RIGHT
+import androidx.window.embedding.SplitAttributes.LayoutDirection.Companion.LOCALE
+import androidx.window.embedding.SplitAttributes.LayoutDirection.Companion.RIGHT_TO_LEFT
+import androidx.window.embedding.SplitAttributes.LayoutDirection.Companion.TOP_TO_BOTTOM
import androidx.window.embedding.SplitRule.Companion.SPLIT_MAX_ASPECT_RATIO_LANDSCAPE_DEFAULT
import androidx.window.embedding.SplitRule.Companion.SPLIT_MAX_ASPECT_RATIO_PORTRAIT_DEFAULT
-import androidx.window.embedding.SplitRule.Companion.SPLIT_MIN_DIMENSION_DP_DEFAULT
-import androidx.window.embedding.SplitRule.Companion.FINISH_ADJACENT
-import androidx.window.embedding.SplitRule.Companion.FINISH_ALWAYS
-import androidx.window.embedding.SplitRule.Companion.FINISH_NEVER
import androidx.window.embedding.SplitRule.Companion.SPLIT_MIN_DIMENSION_ALWAYS_ALLOW
+import androidx.window.embedding.SplitRule.Companion.SPLIT_MIN_DIMENSION_DP_DEFAULT
+import androidx.window.embedding.SplitRule.FinishBehavior.Companion.ADJACENT
+import androidx.window.embedding.SplitRule.FinishBehavior.Companion.ALWAYS
+import androidx.window.embedding.SplitRule.FinishBehavior.Companion.NEVER
import androidx.window.test.R
+import junit.framework.TestCase.assertNull
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
+import org.junit.Assume.assumeTrue
+import org.junit.Before
import org.junit.Test
/**
@@ -47,7 +57,17 @@
*/
class EmbeddingRuleConstructionTests {
private val application = ApplicationProvider.getApplicationContext<Context>()
+ private val ruleController = RuleController.getInstance(application)
private val density = application.resources.displayMetrics.density
+ private lateinit var validBounds: Rect
+ private lateinit var invalidBounds: Rect
+
+ @Before
+ fun setUp() {
+ validBounds = minValidWindowBounds()
+ invalidBounds = almostValidWindowBounds()
+ ruleController.clearRules()
+ }
/**
* Verifies that default params are set correctly when reading {@link SplitPairRule} from XML.
@@ -58,17 +78,23 @@
.parseRules(application, R.xml.test_split_config_default_split_pair_rule)
assertEquals(1, rules.size)
val rule: SplitPairRule = rules.first() as SplitPairRule
+ val expectedSplitLayout = SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.ratio(0.5f))
+ .setLayoutDirection(LOCALE)
+ .setAnimationBackgroundColor(0)
+ .build()
+ assertNull(rule.tag)
assertEquals(SPLIT_MIN_DIMENSION_DP_DEFAULT, rule.minWidthDp)
+ assertEquals(SPLIT_MIN_DIMENSION_DP_DEFAULT, rule.minHeightDp)
assertEquals(SPLIT_MIN_DIMENSION_DP_DEFAULT, rule.minSmallestWidthDp)
assertEquals(SPLIT_MAX_ASPECT_RATIO_PORTRAIT_DEFAULT, rule.maxAspectRatioInPortrait)
assertEquals(SPLIT_MAX_ASPECT_RATIO_LANDSCAPE_DEFAULT, rule.maxAspectRatioInLandscape)
- assertEquals(FINISH_NEVER, rule.finishPrimaryWithSecondary)
- assertEquals(FINISH_ALWAYS, rule.finishSecondaryWithPrimary)
+ assertEquals(NEVER, rule.finishPrimaryWithSecondary)
+ assertEquals(ALWAYS, rule.finishSecondaryWithPrimary)
assertEquals(false, rule.clearTop)
- assertEquals(0.5f, rule.splitRatio)
- assertEquals(LayoutDirection.LOCALE, rule.layoutDirection)
- assertTrue(rule.checkParentBounds(density, minValidWindowBounds()))
- assertFalse(rule.checkParentBounds(density, almostValidWindowBounds()))
+ assertEquals(expectedSplitLayout, rule.defaultSplitAttributes)
+ assertTrue(rule.checkParentBounds(density, validBounds))
+ assertFalse(rule.checkParentBounds(density, invalidBounds))
}
/**
@@ -81,15 +107,41 @@
.parseRules(application, R.xml.test_split_config_custom_split_pair_rule)
assertEquals(1, rules.size)
val rule: SplitPairRule = rules.first() as SplitPairRule
+ val expectedSplitLayout = SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.ratio(0.1f))
+ .setLayoutDirection(RIGHT_TO_LEFT)
+ .build()
+ assertEquals("rule2", rule.tag)
assertEquals(123, rule.minWidthDp)
- assertEquals(456, rule.minSmallestWidthDp)
+ assertEquals(456, rule.minHeightDp)
+ assertEquals(789, rule.minSmallestWidthDp)
assertEquals(1.23f, rule.maxAspectRatioInPortrait.value)
assertEquals(alwaysDisallow(), rule.maxAspectRatioInLandscape)
- assertEquals(FINISH_ALWAYS, rule.finishPrimaryWithSecondary)
- assertEquals(FINISH_NEVER, rule.finishSecondaryWithPrimary)
+ assertEquals(ALWAYS, rule.finishPrimaryWithSecondary)
+ assertEquals(NEVER, rule.finishSecondaryWithPrimary)
assertEquals(true, rule.clearTop)
- assertEquals(0.1f, rule.splitRatio)
- assertEquals(LayoutDirection.RTL, rule.layoutDirection)
+ assertEquals(expectedSplitLayout, rule.defaultSplitAttributes)
+ }
+
+ /** Verifies that horizontal layout are set correctly when reading [SplitPairRule] from XML. */
+ @Test
+ fun testHorizontalLayout_SplitPairRule_Xml() {
+ val rules = RuleController
+ .parseRules(application, R.xml.test_split_config_split_pair_rule_horizontal_layout)
+ assertEquals(1, rules.size)
+ val rule: SplitPairRule = rules.first() as SplitPairRule
+ val expectedSplitLayout = SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.ratio(0.3f))
+ .setLayoutDirection(TOP_TO_BOTTOM)
+ .setAnimationBackgroundColor(Color.BLUE)
+ .build()
+ assertEquals(TEST_TAG, rule.tag)
+ assertEquals(NEVER, rule.finishPrimaryWithSecondary)
+ assertEquals(ALWAYS, rule.finishSecondaryWithPrimary)
+ assertEquals(false, rule.clearTop)
+ assertEquals(expectedSplitLayout, rule.defaultSplitAttributes)
+ assertTrue(rule.checkParentBounds(density, validBounds))
+ assertFalse(rule.checkParentBounds(density, invalidBounds))
}
/**
@@ -99,17 +151,23 @@
@Test
fun testDefaults_SplitPairRule_Builder() {
val rule = SplitPairRule.Builder(HashSet()).build()
+ val expectedSplitLayout = SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.ratio(0.5f))
+ .setLayoutDirection(LOCALE)
+ .setAnimationBackgroundColor(0)
+ .build()
+ assertNull(rule.tag)
assertEquals(SPLIT_MIN_DIMENSION_DP_DEFAULT, rule.minWidthDp)
+ assertEquals(SPLIT_MIN_DIMENSION_DP_DEFAULT, rule.minHeightDp)
assertEquals(SPLIT_MIN_DIMENSION_DP_DEFAULT, rule.minSmallestWidthDp)
assertEquals(SPLIT_MAX_ASPECT_RATIO_PORTRAIT_DEFAULT, rule.maxAspectRatioInPortrait)
assertEquals(SPLIT_MAX_ASPECT_RATIO_LANDSCAPE_DEFAULT, rule.maxAspectRatioInLandscape)
- assertEquals(FINISH_NEVER, rule.finishPrimaryWithSecondary)
- assertEquals(FINISH_ALWAYS, rule.finishSecondaryWithPrimary)
+ assertEquals(NEVER, rule.finishPrimaryWithSecondary)
+ assertEquals(ALWAYS, rule.finishSecondaryWithPrimary)
assertEquals(false, rule.clearTop)
- assertEquals(0.5f, rule.splitRatio)
- assertEquals(LayoutDirection.LOCALE, rule.layoutDirection)
- assertTrue(rule.checkParentBounds(density, minValidWindowBounds()))
- assertFalse(rule.checkParentBounds(density, almostValidWindowBounds()))
+ assertEquals(expectedSplitLayout, rule.defaultSplitAttributes)
+ assertTrue(rule.checkParentBounds(density, validBounds))
+ assertFalse(rule.checkParentBounds(density, invalidBounds))
}
/**
@@ -119,6 +177,11 @@
@Test
fun test_SplitPairRule_Builder() {
val filters = HashSet<SplitPairFilter>()
+ val expectedSplitLayout = SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.ratio(0.3f))
+ .setLayoutDirection(LEFT_TO_RIGHT)
+ .setAnimationBackgroundColor(Color.GREEN)
+ .build()
filters.add(
SplitPairFilter(
ComponentName("a", "b"),
@@ -128,23 +191,25 @@
)
val rule = SplitPairRule.Builder(filters)
.setMinWidthDp(123)
- .setMinSmallestWidthDp(456)
+ .setMinHeightDp(456)
+ .setMinSmallestWidthDp(789)
.setMaxAspectRatioInPortrait(ratio(1.23f))
.setMaxAspectRatioInLandscape(ratio(4.56f))
- .setFinishPrimaryWithSecondary(FINISH_ADJACENT)
- .setFinishSecondaryWithPrimary(FINISH_ADJACENT)
+ .setFinishPrimaryWithSecondary(ADJACENT)
+ .setFinishSecondaryWithPrimary(ADJACENT)
.setClearTop(true)
- .setSplitRatio(0.3f)
- .setLayoutDirection(LayoutDirection.LTR)
+ .setDefaultSplitAttributes(expectedSplitLayout)
+ .setTag(TEST_TAG)
.build()
- assertEquals(FINISH_ADJACENT, rule.finishPrimaryWithSecondary)
- assertEquals(FINISH_ADJACENT, rule.finishSecondaryWithPrimary)
+ assertEquals(ADJACENT, rule.finishPrimaryWithSecondary)
+ assertEquals(ADJACENT, rule.finishSecondaryWithPrimary)
assertEquals(true, rule.clearTop)
- assertEquals(0.3f, rule.splitRatio)
- assertEquals(LayoutDirection.LTR, rule.layoutDirection)
+ assertEquals(expectedSplitLayout, rule.defaultSplitAttributes)
+ assertEquals(TEST_TAG, rule.tag)
assertEquals(filters, rule.filters)
assertEquals(123, rule.minWidthDp)
- assertEquals(456, rule.minSmallestWidthDp)
+ assertEquals(456, rule.minHeightDp)
+ assertEquals(789, rule.minSmallestWidthDp)
assertEquals(1.23f, rule.maxAspectRatioInPortrait.value)
assertEquals(4.56f, rule.maxAspectRatioInLandscape.value)
}
@@ -158,31 +223,26 @@
assertThrows(IllegalArgumentException::class.java) {
SplitPairRule.Builder(HashSet())
.setMinWidthDp(-1)
- .setMinSmallestWidthDp(456)
+ .setMinHeightDp(456)
+ .setMinSmallestWidthDp(789)
.build()
}
assertThrows(IllegalArgumentException::class.java) {
SplitPairRule.Builder(HashSet())
.setMinWidthDp(123)
+ .setMinHeightDp(-1)
+ .setMinSmallestWidthDp(789)
+ .build()
+ }
+ assertThrows(IllegalArgumentException::class.java) {
+ SplitPairRule.Builder(HashSet())
+ .setMinWidthDp(123)
+ .setMinHeightDp(456)
.setMinSmallestWidthDp(-1)
.build()
}
assertThrows(IllegalArgumentException::class.java) {
SplitPairRule.Builder(HashSet())
- .setMinWidthDp(123)
- .setMinSmallestWidthDp(456)
- .setSplitRatio(-1.0f)
- .build()
- }
- assertThrows(IllegalArgumentException::class.java) {
- SplitPairRule.Builder(HashSet())
- .setMinWidthDp(123)
- .setMinSmallestWidthDp(456)
- .setSplitRatio(1.1f)
- .build()
- }
- assertThrows(IllegalArgumentException::class.java) {
- SplitPairRule.Builder(HashSet())
.setMaxAspectRatioInPortrait(ratio(-1f))
.build()
}
@@ -202,6 +262,7 @@
// Always allow split
var rule = SplitPairRule.Builder(HashSet())
.setMinWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
+ .setMinHeightDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMinSmallestWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMaxAspectRatioInLandscape(alwaysAllow())
.setMaxAspectRatioInPortrait(alwaysAllow())
@@ -214,6 +275,7 @@
// Always disallow split in portrait
rule = SplitPairRule.Builder(HashSet())
.setMinWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
+ .setMinHeightDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMinSmallestWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMaxAspectRatioInLandscape(alwaysAllow())
.setMaxAspectRatioInPortrait(alwaysDisallow())
@@ -229,6 +291,7 @@
// Compare the aspect ratio in portrait
rule = SplitPairRule.Builder(HashSet())
.setMinWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
+ .setMinHeightDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMinSmallestWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMaxAspectRatioInLandscape(alwaysAllow())
.setMaxAspectRatioInPortrait(ratio(1.1f))
@@ -257,6 +320,7 @@
// Always allow split
var rule = SplitPairRule.Builder(HashSet())
.setMinWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
+ .setMinHeightDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMinSmallestWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMaxAspectRatioInPortrait(alwaysAllow())
.setMaxAspectRatioInLandscape(alwaysAllow())
@@ -269,6 +333,7 @@
// Always disallow split in landscape
rule = SplitPairRule.Builder(HashSet())
.setMinWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
+ .setMinHeightDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMinSmallestWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMaxAspectRatioInPortrait(alwaysAllow())
.setMaxAspectRatioInLandscape(alwaysDisallow())
@@ -284,6 +349,7 @@
// Compare the aspect ratio in landscape
rule = SplitPairRule.Builder(HashSet())
.setMinWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
+ .setMinHeightDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMinSmallestWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMaxAspectRatioInPortrait(alwaysAllow())
.setMaxAspectRatioInLandscape(ratio(1.1f))
@@ -313,16 +379,22 @@
.parseRules(application, R.xml.test_split_config_default_split_placeholder_rule)
assertEquals(1, rules.size)
val rule: SplitPlaceholderRule = rules.first() as SplitPlaceholderRule
+ val expectedSplitLayout = SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.ratio(0.5f))
+ .setLayoutDirection(LOCALE)
+ .setAnimationBackgroundColor(0)
+ .build()
+ assertNull(rule.tag)
assertEquals(SPLIT_MIN_DIMENSION_DP_DEFAULT, rule.minWidthDp)
+ assertEquals(SPLIT_MIN_DIMENSION_DP_DEFAULT, rule.minHeightDp)
assertEquals(SPLIT_MIN_DIMENSION_DP_DEFAULT, rule.minSmallestWidthDp)
assertEquals(SPLIT_MAX_ASPECT_RATIO_PORTRAIT_DEFAULT, rule.maxAspectRatioInPortrait)
assertEquals(SPLIT_MAX_ASPECT_RATIO_LANDSCAPE_DEFAULT, rule.maxAspectRatioInLandscape)
- assertEquals(FINISH_ALWAYS, rule.finishPrimaryWithPlaceholder)
+ assertEquals(ALWAYS, rule.finishPrimaryWithPlaceholder)
assertEquals(false, rule.isSticky)
- assertEquals(0.5f, rule.splitRatio)
- assertEquals(LayoutDirection.LOCALE, rule.layoutDirection)
- assertTrue(rule.checkParentBounds(density, minValidWindowBounds()))
- assertFalse(rule.checkParentBounds(density, almostValidWindowBounds()))
+ assertEquals(expectedSplitLayout, rule.defaultSplitAttributes)
+ assertTrue(rule.checkParentBounds(density, validBounds))
+ assertFalse(rule.checkParentBounds(density, invalidBounds))
}
/**
@@ -335,14 +407,44 @@
.parseRules(application, R.xml.test_split_config_custom_split_placeholder_rule)
assertEquals(1, rules.size)
val rule: SplitPlaceholderRule = rules.first() as SplitPlaceholderRule
+ val expectedSplitLayout = SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.ratio(0.1f))
+ .setLayoutDirection(RIGHT_TO_LEFT)
+ .build()
+ assertEquals("rule3", rule.tag)
assertEquals(123, rule.minWidthDp)
- assertEquals(456, rule.minSmallestWidthDp)
+ assertEquals(456, rule.minHeightDp)
+ assertEquals(789, rule.minSmallestWidthDp)
assertEquals(1.23f, rule.maxAspectRatioInPortrait.value)
assertEquals(alwaysDisallow(), rule.maxAspectRatioInLandscape)
- assertEquals(FINISH_ADJACENT, rule.finishPrimaryWithPlaceholder)
+ assertEquals(ADJACENT, rule.finishPrimaryWithPlaceholder)
assertEquals(true, rule.isSticky)
- assertEquals(0.1f, rule.splitRatio)
- assertEquals(LayoutDirection.RTL, rule.layoutDirection)
+ assertEquals(expectedSplitLayout, rule.defaultSplitAttributes)
+ }
+
+ /**
+ * Verifies that horizontal layout are set correctly when reading [SplitPlaceholderRule]
+ * from XML.
+ */
+ @RequiresApi(Build.VERSION_CODES.M)
+ @Test
+ fun testHorizontalLayout_SplitPlaceholderRule_Xml() {
+ assumeTrue(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
+ val rules = RuleController
+ .parseRules(application, R.xml.test_split_config_split_placeholder_horizontal_layout)
+ assertEquals(1, rules.size)
+ val rule: SplitPlaceholderRule = rules.first() as SplitPlaceholderRule
+ val expectedSplitLayout = SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.ratio(0.3f))
+ .setLayoutDirection(BOTTOM_TO_TOP)
+ .setAnimationBackgroundColor(application.resources.getColor(R.color.testColor, null))
+ .build()
+ assertEquals(TEST_TAG, rule.tag)
+ assertEquals(ALWAYS, rule.finishPrimaryWithPlaceholder)
+ assertEquals(false, rule.isSticky)
+ assertEquals(expectedSplitLayout, rule.defaultSplitAttributes)
+ assertTrue(rule.checkParentBounds(density, validBounds))
+ assertFalse(rule.checkParentBounds(density, invalidBounds))
}
/**
@@ -352,14 +454,20 @@
@Test
fun testDefaults_SplitPlaceholderRule_Builder() {
val rule = SplitPlaceholderRule.Builder(HashSet(), Intent()).build()
+ assertNull(rule.tag)
assertEquals(SPLIT_MIN_DIMENSION_DP_DEFAULT, rule.minWidthDp)
+ assertEquals(SPLIT_MIN_DIMENSION_DP_DEFAULT, rule.minHeightDp)
assertEquals(SPLIT_MIN_DIMENSION_DP_DEFAULT, rule.minSmallestWidthDp)
assertEquals(SPLIT_MAX_ASPECT_RATIO_PORTRAIT_DEFAULT, rule.maxAspectRatioInPortrait)
assertEquals(SPLIT_MAX_ASPECT_RATIO_LANDSCAPE_DEFAULT, rule.maxAspectRatioInLandscape)
- assertEquals(FINISH_ALWAYS, rule.finishPrimaryWithPlaceholder)
+ assertEquals(ALWAYS, rule.finishPrimaryWithPlaceholder)
assertEquals(false, rule.isSticky)
- assertEquals(0.5f, rule.splitRatio)
- assertEquals(LayoutDirection.LOCALE, rule.layoutDirection)
+ val expectedSplitLayout = SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.ratio(0.5f))
+ .setLayoutDirection(LOCALE)
+ .setAnimationBackgroundColor(0)
+ .build()
+ assertEquals(expectedSplitLayout, rule.defaultSplitAttributes)
assertTrue(rule.checkParentBounds(density, minValidWindowBounds()))
assertFalse(rule.checkParentBounds(density, almostValidWindowBounds()))
}
@@ -378,24 +486,31 @@
)
)
val intent = Intent("ACTION")
+ val expectedSplitLayout = SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.ratio(0.3f))
+ .setLayoutDirection(LEFT_TO_RIGHT)
+ .setAnimationBackgroundColor(Color.GREEN)
+ .build()
val rule = SplitPlaceholderRule.Builder(filters, intent)
.setMinWidthDp(123)
- .setMinSmallestWidthDp(456)
+ .setMinHeightDp(456)
+ .setMinSmallestWidthDp(789)
.setMaxAspectRatioInPortrait(ratio(1.23f))
.setMaxAspectRatioInLandscape(ratio(4.56f))
- .setFinishPrimaryWithPlaceholder(FINISH_ADJACENT)
+ .setFinishPrimaryWithPlaceholder(ADJACENT)
.setSticky(true)
- .setSplitRatio(0.3f)
- .setLayoutDirection(LayoutDirection.LTR)
+ .setDefaultSplitAttributes(expectedSplitLayout)
+ .setTag(TEST_TAG)
.build()
- assertEquals(FINISH_ADJACENT, rule.finishPrimaryWithPlaceholder)
+ assertEquals(ADJACENT, rule.finishPrimaryWithPlaceholder)
assertEquals(true, rule.isSticky)
- assertEquals(0.3f, rule.splitRatio)
- assertEquals(LayoutDirection.LTR, rule.layoutDirection)
+ assertEquals(expectedSplitLayout, rule.defaultSplitAttributes)
assertEquals(filters, rule.filters)
assertEquals(intent, rule.placeholderIntent)
assertEquals(123, rule.minWidthDp)
- assertEquals(456, rule.minSmallestWidthDp)
+ assertEquals(456, rule.minHeightDp)
+ assertEquals(789, rule.minSmallestWidthDp)
+ assertEquals(TEST_TAG, rule.tag)
assertEquals(1.23f, rule.maxAspectRatioInPortrait.value)
assertEquals(4.56f, rule.maxAspectRatioInLandscape.value)
}
@@ -409,34 +524,30 @@
assertThrows(IllegalArgumentException::class.java) {
SplitPlaceholderRule.Builder(HashSet(), Intent())
.setMinWidthDp(-1)
- .setMinSmallestWidthDp(456)
+ .setMinHeightDp(456)
+ .setMinSmallestWidthDp(789)
.build()
}
assertThrows(IllegalArgumentException::class.java) {
SplitPlaceholderRule.Builder(HashSet(), Intent())
.setMinWidthDp(123)
+ .setMinHeightDp(-1)
+ .setMinSmallestWidthDp(789)
+ .build()
+ }
+ assertThrows(IllegalArgumentException::class.java) {
+ SplitPlaceholderRule.Builder(HashSet(), Intent())
+ .setMinWidthDp(123)
+ .setMinHeightDp(456)
.setMinSmallestWidthDp(-1)
.build()
}
assertThrows(IllegalArgumentException::class.java) {
SplitPlaceholderRule.Builder(HashSet(), Intent())
.setMinWidthDp(123)
- .setMinSmallestWidthDp(456)
- .setFinishPrimaryWithPlaceholder(FINISH_NEVER)
- .build()
- }
- assertThrows(IllegalArgumentException::class.java) {
- SplitPlaceholderRule.Builder(HashSet(), Intent())
- .setMinWidthDp(123)
- .setMinSmallestWidthDp(456)
- .setSplitRatio(-1.0f)
- .build()
- }
- assertThrows(IllegalArgumentException::class.java) {
- SplitPlaceholderRule.Builder(HashSet(), Intent())
- .setMinWidthDp(123)
- .setMinSmallestWidthDp(456)
- .setSplitRatio(1.1f)
+ .setMinHeightDp(456)
+ .setMinSmallestWidthDp(789)
+ .setFinishPrimaryWithPlaceholder(NEVER)
.build()
}
assertThrows(IllegalArgumentException::class.java) {
@@ -460,6 +571,7 @@
// Always allow split
var rule = SplitPlaceholderRule.Builder(HashSet(), Intent())
.setMinWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
+ .setMinHeightDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMinSmallestWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMaxAspectRatioInLandscape(alwaysAllow())
.setMaxAspectRatioInPortrait(alwaysAllow())
@@ -472,6 +584,7 @@
// Always disallow split in portrait
rule = SplitPlaceholderRule.Builder(HashSet(), Intent())
.setMinWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
+ .setMinHeightDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMinSmallestWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMaxAspectRatioInLandscape(alwaysAllow())
.setMaxAspectRatioInPortrait(alwaysDisallow())
@@ -487,6 +600,7 @@
// Compare the aspect ratio in portrait
rule = SplitPlaceholderRule.Builder(HashSet(), Intent())
.setMinWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
+ .setMinHeightDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMinSmallestWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMaxAspectRatioInLandscape(alwaysAllow())
.setMaxAspectRatioInPortrait(ratio(1.1f))
@@ -515,6 +629,7 @@
// Always allow split
var rule = SplitPlaceholderRule.Builder(HashSet(), Intent())
.setMinWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
+ .setMinHeightDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMinSmallestWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMaxAspectRatioInPortrait(alwaysAllow())
.setMaxAspectRatioInLandscape(alwaysAllow())
@@ -530,6 +645,7 @@
// Always disallow split in landscape
rule = SplitPlaceholderRule.Builder(HashSet(), Intent())
.setMinWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
+ .setMinHeightDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMinSmallestWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMaxAspectRatioInPortrait(alwaysAllow())
.setMaxAspectRatioInLandscape(alwaysDisallow())
@@ -545,6 +661,7 @@
// Compare the aspect ratio in landscape
rule = SplitPlaceholderRule.Builder(HashSet(), Intent())
.setMinWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
+ .setMinHeightDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMinSmallestWidthDp(SPLIT_MIN_DIMENSION_ALWAYS_ALLOW)
.setMaxAspectRatioInPortrait(alwaysAllow())
.setMaxAspectRatioInLandscape(ratio(1.1f))
@@ -573,7 +690,8 @@
.parseRules(application, R.xml.test_split_config_default_activity_rule)
assertEquals(1, rules.size)
val rule: ActivityRule = rules.first() as ActivityRule
- assertEquals(false, rule.alwaysExpand)
+ assertNull(rule.tag)
+ assertFalse(rule.alwaysExpand)
}
/**
@@ -586,7 +704,22 @@
.parseRules(application, R.xml.test_split_config_custom_activity_rule)
assertEquals(1, rules.size)
val rule: ActivityRule = rules.first() as ActivityRule
- assertEquals(true, rule.alwaysExpand)
+ assertEquals("rule1", rule.tag)
+ assertTrue(rule.alwaysExpand)
+ }
+
+ /**
+ * Verifies that [ActivityRule.tag] and [ActivityRule.alwaysExpand] are set correctly when
+ * reading [ActivityRule] from XML.
+ */
+ @Test
+ fun testSetTagAndAlwaysExpand_ActivityRule_Xml() {
+ val rules = RuleController
+ .parseRules(application, R.xml.test_split_config_activity_rule_with_tag)
+ assertEquals(1, rules.size)
+ val rule: ActivityRule = rules.first() as ActivityRule
+ assertEquals(TEST_TAG, rule.tag)
+ assertTrue(rule.alwaysExpand)
}
/**
@@ -596,7 +729,7 @@
@Test
fun testDefaults_ActivityRule_Builder() {
val rule = ActivityRule.Builder(HashSet()).build()
- assertEquals(false, rule.alwaysExpand)
+ assertFalse(rule.alwaysExpand)
}
/**
@@ -613,8 +746,10 @@
)
val rule = ActivityRule.Builder(filters)
.setAlwaysExpand(true)
+ .setTag(TEST_TAG)
.build()
- assertEquals(true, rule.alwaysExpand)
+ assertTrue(rule.alwaysExpand)
+ assertEquals(TEST_TAG, rule.tag)
assertEquals(filters, rule.filters)
}
@@ -635,4 +770,60 @@
return Rect(0, 0, minValidWidthPx, minValidWidthPx)
}
+
+ @Test
+ fun testIllegalTag_XML() {
+ assertThrows(IllegalArgumentException::class.java) {
+ RuleController.parseRules(application, R.xml.test_split_config_duplicated_tag)
+ }
+ }
+
+ @Test
+ fun testReplacingRuleWithTag() {
+ var rules = RuleController
+ .parseRules(application, R.xml.test_split_config_activity_rule_with_tag)
+ assertEquals(1, rules.size)
+ var rule = rules.first()
+ assertEquals(TEST_TAG, rule.tag)
+ val staticRule = rule as ActivityRule
+ assertTrue(staticRule.alwaysExpand)
+ ruleController.setRules(rules)
+
+ val filters = HashSet<ActivityFilter>()
+ filters.add(
+ ActivityFilter(
+ ComponentName("a", "b"),
+ "ACTION"
+ )
+ )
+ val rule1 = ActivityRule.Builder(filters)
+ .setAlwaysExpand(true)
+ .setTag(TEST_TAG)
+ .build()
+ ruleController.addRule(rule1)
+
+ rules = ruleController.getRules()
+ assertEquals(1, rules.size)
+ rule = rules.first()
+ assertEquals(rule1, rule)
+
+ val intent = Intent("ACTION")
+ val rule2 = SplitPlaceholderRule.Builder(filters, intent)
+ .setMinWidthDp(123)
+ .setMinHeightDp(456)
+ .setMinSmallestWidthDp(789)
+ .setTag(TEST_TAG)
+ .build()
+
+ ruleController.addRule(rule2)
+
+ rules = ruleController.getRules()
+ assertEquals(1, rules.size)
+ rule = rules.first()
+ assertEquals(rule2, rule)
+ }
+
+ companion object {
+ const val TEST_TAG = "test"
+ }
}
\ No newline at end of file
diff --git a/window/window/src/androidTest/java/androidx/window/layout/ContextUtilsTest.kt b/window/window/src/androidTest/java/androidx/window/layout/ContextUtilsTest.kt
new file mode 100644
index 0000000..7cb4812
--- /dev/null
+++ b/window/window/src/androidTest/java/androidx/window/layout/ContextUtilsTest.kt
@@ -0,0 +1,55 @@
+/*
+ * 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 androidx.window.layout
+
+import android.app.Activity
+import android.content.ContextWrapper
+import android.inputmethodservice.InputMethodService
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import androidx.window.layout.util.ContextUtils
+import androidx.window.layout.util.ContextUtils.unwrapUiContext
+import org.junit.Assert.assertEquals
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.Mockito.mock
+
+/**
+ * Instrumentation tests for [ContextUtils].
+ */
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class ContextUtilsTest {
+
+ @Test
+ fun testUnwrapUiContext_noContextWrapper_activity() {
+ val context = mock(Activity::class.java)
+ assertEquals(context, unwrapUiContext(context))
+ }
+
+ @Test
+ fun testUnwrapUiContext_noContextWrapper_inputMethodService() {
+ val context = mock(InputMethodService::class.java)
+ assertEquals(context, unwrapUiContext(context))
+ }
+
+ @Test
+ fun testUnwrapUiContext_contextWrapper_null() {
+ val contextWrapper = ContextWrapper(null)
+ assertEquals(contextWrapper, unwrapUiContext(contextWrapper))
+ }
+}
\ No newline at end of file
diff --git a/window/window/src/androidTest/java/androidx/window/layout/WindowInfoTrackerImplTest.kt b/window/window/src/androidTest/java/androidx/window/layout/WindowInfoTrackerImplTest.kt
index 16dbdf6..1d86ece 100644
--- a/window/window/src/androidTest/java/androidx/window/layout/WindowInfoTrackerImplTest.kt
+++ b/window/window/src/androidTest/java/androidx/window/layout/WindowInfoTrackerImplTest.kt
@@ -16,21 +16,24 @@
package androidx.window.layout
-import android.app.Activity
+import android.content.Context
+import android.os.Build
import androidx.core.util.Consumer
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.window.TestActivity
import androidx.window.TestConsumer
+import androidx.window.WindowTestUtils
+import androidx.window.WindowTestUtils.Companion.assumeAtLeastVendorApiLevel
import androidx.window.layout.adapter.WindowBackend
+import java.util.concurrent.Executor
import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
-import kotlinx.coroutines.Job
import org.junit.Rule
import org.junit.Test
-import java.util.concurrent.Executor
@OptIn(ExperimentalCoroutinesApi::class)
public class WindowInfoTrackerImplTest {
@@ -60,6 +63,25 @@
}
@Test
+ public fun testWindowLayoutFeatures_contextAsListener(): Unit = testScope.runTest {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
+ return@runTest
+ }
+ assumeAtLeastVendorApiLevel(2)
+ val fakeBackend = FakeWindowBackend()
+ val repo = WindowInfoTrackerImpl(WindowMetricsCalculatorCompat, fakeBackend)
+ val collector = TestConsumer<WindowLayoutInfo>()
+
+ val windowContext =
+ WindowTestUtils.createOverlayWindowContext()
+ testScope.launch(Job()) {
+ repo.windowLayoutInfo(windowContext).collect(collector::accept)
+ }
+ fakeBackend.triggerSignal(WindowLayoutInfo(emptyList()))
+ collector.assertValue(WindowLayoutInfo(emptyList()))
+ }
+
+ @Test
public fun testWindowLayoutFeatures_multicasting(): Unit = testScope.runTest {
activityScenario.scenario.onActivity { testActivity ->
val windowMetricsCalculator = WindowMetricsCalculatorCompat
@@ -77,10 +99,44 @@
repo.windowLayoutInfo(testActivity).collect(collector::accept)
}
fakeBackend.triggerSignal(WindowLayoutInfo(emptyList()))
- collector.assertValues(WindowLayoutInfo(emptyList()), WindowLayoutInfo(emptyList()))
+ collector.assertValues(
+ WindowLayoutInfo(emptyList()),
+ WindowLayoutInfo(emptyList())
+ )
}
}
+ @Test
+ public fun testWindowLayoutFeatures_multicastingWithContext(): Unit = testScope.runTest {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
+ return@runTest
+ }
+ assumeAtLeastVendorApiLevel(2)
+ val windowMetricsCalculator = WindowMetricsCalculatorCompat
+ val fakeBackend = FakeWindowBackend()
+ val repo = WindowInfoTrackerImpl(
+ windowMetricsCalculator,
+ fakeBackend
+ )
+ val collector = TestConsumer<WindowLayoutInfo>()
+ val job = Job()
+
+ val windowContext = WindowTestUtils.createOverlayWindowContext()
+
+ launch(job) {
+ repo.windowLayoutInfo(windowContext).collect(collector::accept)
+ }
+ launch(job) {
+ repo.windowLayoutInfo(windowContext).collect(collector::accept)
+ }
+
+ fakeBackend.triggerSignal(WindowLayoutInfo(emptyList()))
+ collector.assertValues(
+ WindowLayoutInfo(emptyList()),
+ WindowLayoutInfo(emptyList())
+ )
+ }
+
private class FakeWindowBackend : WindowBackend {
private class CallbackHolder(
@@ -100,7 +156,7 @@
}
override fun registerLayoutChangeCallback(
- activity: Activity,
+ context: Context,
executor: Executor,
callback: Consumer<WindowLayoutInfo>
) {
diff --git a/window/window/src/androidTest/java/androidx/window/layout/adapter/extensions/ExtensionWindowLayoutInfoBackendTest.kt b/window/window/src/androidTest/java/androidx/window/layout/adapter/extensions/ExtensionWindowLayoutInfoBackendTest.kt
index 1cdf333..2b80d87 100644
--- a/window/window/src/androidTest/java/androidx/window/layout/adapter/extensions/ExtensionWindowLayoutInfoBackendTest.kt
+++ b/window/window/src/androidTest/java/androidx/window/layout/adapter/extensions/ExtensionWindowLayoutInfoBackendTest.kt
@@ -16,18 +16,27 @@
package androidx.window.layout.adapter.extensions
+import androidx.window.extensions.core.util.function.Consumer as OEMConsumer
import androidx.window.extensions.layout.FoldingFeature as OEMFoldingFeature
import androidx.window.extensions.layout.WindowLayoutInfo as OEMWindowLayoutInfo
import java.util.function.Consumer as JavaConsumer
import android.annotation.SuppressLint
import android.app.Activity
+import android.content.Context
import android.graphics.Rect
import android.os.Build
+import androidx.annotation.RequiresApi
+import androidx.annotation.UiContext
import androidx.core.util.Consumer
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.window.TestActivity
import androidx.window.TestConsumer
+import androidx.window.WindowTestUtils
+import androidx.window.WindowTestUtils.Companion.assumeAtLeastVendorApiLevel
+import androidx.window.WindowTestUtils.Companion.assumeBeforeVendorApiLevel
import androidx.window.core.ConsumerAdapter
+import androidx.window.core.ExtensionsUtil
+import androidx.window.extensions.WindowExtensions
import androidx.window.extensions.layout.FoldingFeature.STATE_FLAT
import androidx.window.extensions.layout.FoldingFeature.TYPE_HINGE
import androidx.window.extensions.layout.WindowLayoutComponent
@@ -67,6 +76,7 @@
@Test
public fun testExtensionWindowBackend_delegatesToWindowLayoutComponent() {
+ assumeAtLeastVendorApiLevel(1)
val component = RequestTrackingWindowComponent()
val backend = ExtensionWindowLayoutInfoBackend(component, consumerAdapter)
@@ -80,7 +90,35 @@
}
@Test
+ public fun testExtensionWindowBackend_delegatesToWindowLayoutComponentWithContext() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
+ return
+ }
+ assumeAtLeastVendorApiLevel(2)
+
+ val component = RequestTrackingWindowComponent()
+
+ val backend = ExtensionWindowLayoutInfoBackend(component, consumerAdapter)
+
+ val windowContext = WindowTestUtils.createOverlayWindowContext()
+ val windowContextConsumer = TestConsumer<WindowLayoutInfo>()
+
+ backend.registerLayoutChangeCallback(windowContext, Runnable::run, windowContextConsumer)
+ assertTrue(
+ "Expected call with Context: $windowContext",
+ component.hasAddCall(windowContext)
+ )
+ }
+
+ /**
+ * After {@link WindowExtensions#VENDOR_API_LEVEL_2} registerLayoutChangeCallback calls
+ * addWindowLayoutInfoListener(context) instead.
+ * {@link testExtensionWindowBackend_registerAtMostOnceWithContext} verifies the same behavior.
+ */
+ @Suppress("Deprecation")
+ @Test
public fun testExtensionWindowBackend_registerAtMostOnce() {
+ assumeBeforeVendorApiLevel(2)
val component = mock<WindowLayoutComponent>()
val backend = ExtensionWindowLayoutInfoBackend(component, consumerAdapter)
@@ -90,22 +128,59 @@
backend.registerLayoutChangeCallback(activity, Runnable::run, consumer)
backend.registerLayoutChangeCallback(activity, Runnable::run, mock())
- verify(component).addWindowLayoutInfoListener(eq(activity), any())
+ val consumerCaptor = argumentCaptor<JavaConsumer<OEMWindowLayoutInfo>>()
+ verify(component).addWindowLayoutInfoListener(eq(activity), consumerCaptor.capture())
+ }
+ }
+
+ @Test
+ public fun testExtensionWindowBackend_registerAtMostOnceWithContext() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
+ return
+ }
+ assumeAtLeastVendorApiLevel(2)
+
+ val component = mock<WindowLayoutComponent>()
+
+ val backend = ExtensionWindowLayoutInfoBackend(component, consumerAdapter)
+
+ val windowContext = WindowTestUtils.createOverlayWindowContext()
+ val windowContextConsumer = TestConsumer<WindowLayoutInfo>()
+
+ val consumerCaptor = argumentCaptor<OEMConsumer<OEMWindowLayoutInfo>>()
+
+ backend.registerLayoutChangeCallback(windowContext, Runnable::run, windowContextConsumer)
+ backend.registerLayoutChangeCallback(windowContext, Runnable::run, mock())
+ verify(component).addWindowLayoutInfoListener(
+ eq(windowContext),
+ consumerCaptor.capture(),
+ )
+
+ activityScenario.scenario.onActivity { activity ->
+ val consumer = TestConsumer<WindowLayoutInfo>()
+ backend.registerLayoutChangeCallback(activity, Runnable::run, consumer)
+ backend.registerLayoutChangeCallback(activity, Runnable::run, mock())
+ verify(component).addWindowLayoutInfoListener(
+ eq(activity as Context),
+ consumerCaptor.capture()
+ )
}
}
@Ignore // b/260647675, b/260648288
- @SuppressLint("NewApi") // java.util.function.Consumer was added in API 24 (N)
+ @Suppress("NewApi", "Deprecation") // java.util.function.Consumer was added in API 24 (N)
@Test
public fun testExtensionWindowBackend_translateValues() {
assumeTrue(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
val component = mock<WindowLayoutComponent>()
- whenever(component.addWindowLayoutInfoListener(any(), any()))
- .thenAnswer { invocation ->
- val consumer = invocation.getArgument(1) as JavaConsumer<OEMWindowLayoutInfo>
- consumer.accept(OEMWindowLayoutInfo(emptyList()))
- }
+ whenever(component.addWindowLayoutInfoListener(
+ any(),
+ any<JavaConsumer<OEMWindowLayoutInfo>>())
+ ).thenAnswer { invocation ->
+ val consumer = invocation.getArgument(1) as JavaConsumer<OEMWindowLayoutInfo>
+ consumer.accept(OEMWindowLayoutInfo(emptyList()))
+ }
val backend = ExtensionWindowLayoutInfoBackend(component, consumerAdapter)
activityScenario.scenario.onActivity { activity ->
@@ -116,17 +191,51 @@
}
}
- @SuppressLint("NewApi") // java.util.function.Consumer was added in API 24 (N)
@Test
- public fun testExtensionWindowBackend_infoReplayedForAdditionalListener() {
+ public fun testExtensionWindowBackend_translateValuesWithContext() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
+ return
+ }
+ assumeAtLeastVendorApiLevel(2)
+
+ val component = FakeWindowComponent()
+ val windowContext = WindowTestUtils.createOverlayWindowContext()
+ val windowContextConsumer = TestConsumer<WindowLayoutInfo>()
+ val windowLayoutInfoFromContext = newTestOEMWindowLayoutInfo(windowContext)
+
+ val backend = ExtensionWindowLayoutInfoBackend(component, consumerAdapter)
+ backend.registerLayoutChangeCallback(windowContext, Runnable::run, windowContextConsumer)
+ component.emit(windowLayoutInfoFromContext)
+ windowContextConsumer.assertValue(
+ translate(
+ windowContext,
+ windowLayoutInfoFromContext
+ )
+ )
+
+ val consumer = TestConsumer<WindowLayoutInfo>()
+ activityScenario.scenario.onActivity { activity ->
+ val windowLayoutInfoFromActivity = newTestOEMWindowLayoutInfo(activity)
+ backend.registerLayoutChangeCallback(activity, Runnable::run, consumer)
+ component.emit(newTestOEMWindowLayoutInfo(activity))
+ consumer.assertValues(listOf(translate(activity, windowLayoutInfoFromActivity)))
+ }
+ }
+
+ @Suppress("NewApi", "Deprecation") // java.util.function.Consumer was added in API 24 (N)
+ @Test
+ fun testExtensionWindowBackend_infoReplayedForAdditionalListener() {
+ assumeBeforeVendorApiLevel(2)
assumeTrue(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
val component = mock<WindowLayoutComponent>()
- whenever(component.addWindowLayoutInfoListener(any(), any()))
- .thenAnswer { invocation ->
- val consumer = invocation.getArgument(1) as JavaConsumer<OEMWindowLayoutInfo>
- consumer.accept(OEMWindowLayoutInfo(emptyList()))
- }
+ whenever(component.addWindowLayoutInfoListener(
+ any(),
+ any<JavaConsumer<OEMWindowLayoutInfo>>())
+ ).thenAnswer { invocation ->
+ val consumer = invocation.getArgument(1) as JavaConsumer<OEMWindowLayoutInfo>
+ consumer.accept(OEMWindowLayoutInfo(emptyList()))
+ }
val backend = ExtensionWindowLayoutInfoBackend(component, consumerAdapter)
activityScenario.scenario.onActivity { activity ->
@@ -139,7 +248,48 @@
}
@Test
- public fun testExtensionWindowBackend_removeMatchingCallback() {
+ public fun testExtensionWindowBackend_infoReplayedForAdditionalListenerWithContext() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
+ return
+ }
+ assumeAtLeastVendorApiLevel(2)
+
+ val component = mock<WindowLayoutComponent>()
+ whenever(component.addWindowLayoutInfoListener(
+ any(),
+ any<OEMConsumer<OEMWindowLayoutInfo>>())
+ ).thenAnswer { invocation ->
+ val consumer = invocation.getArgument(1) as OEMConsumer<OEMWindowLayoutInfo>
+ consumer.accept(OEMWindowLayoutInfo(emptyList()))
+ }
+ whenever(component.addWindowLayoutInfoListener(
+ any(),
+ any<OEMConsumer<OEMWindowLayoutInfo>>())
+ ).thenAnswer { invocation ->
+ val consumer = invocation.getArgument(1) as OEMConsumer<OEMWindowLayoutInfo>
+ consumer.accept(OEMWindowLayoutInfo(emptyList()))
+ }
+ val backend = ExtensionWindowLayoutInfoBackend(component, consumerAdapter)
+
+ activityScenario.scenario.onActivity { activity ->
+ val consumer = TestConsumer<WindowLayoutInfo>()
+ backend.registerLayoutChangeCallback(activity, Runnable::run, mock())
+ backend.registerLayoutChangeCallback(activity, Runnable::run, consumer)
+
+ consumer.assertValue(WindowLayoutInfo(emptyList()))
+ }
+
+ val windowContext = WindowTestUtils.createOverlayWindowContext()
+ val windowContextConsumer = TestConsumer<WindowLayoutInfo>()
+ backend.registerLayoutChangeCallback(windowContext, Runnable::run, windowContextConsumer)
+ backend.registerLayoutChangeCallback(windowContext, Runnable::run, mock())
+ windowContextConsumer.assertValue(WindowLayoutInfo(emptyList()))
+ }
+
+ @Suppress("Deprecation")
+ @Test
+ fun testExtensionWindowBackend_removeMatchingCallback() {
+ assumeBeforeVendorApiLevel(2)
val component = mock<WindowLayoutComponent>()
val backend = ExtensionWindowLayoutInfoBackend(component, consumerAdapter)
@@ -156,8 +306,10 @@
}
}
+ @Suppress("Deprecation")
@Test
- public fun testExtensionWindowBackend_removesMultipleCallback() {
+ fun testExtensionWindowBackend_removesMultipleCallback() {
+ assumeBeforeVendorApiLevel(2)
val component = mock<WindowLayoutComponent>()
val backend = ExtensionWindowLayoutInfoBackend(component, consumerAdapter)
@@ -177,8 +329,116 @@
}
}
+ /**
+ * Verifies context and consumer registration can be registered with using either
+ * addWindowLayoutInfoListener(context) or addWindowLayoutInfoListener(activity),
+ * but all registration are cleaned up by removeWindowLayoutInfoListener().
+ * Note: addWindowLayoutInfoListener(context) is added in
+ * {@link WindowExtensions#VENDOR_API_LEVEL_2}.
+ */
@Test
- public fun testExtensionWindowBackend_reRegisterCallback() {
+ fun testExtensionWindowBackend_removeMatchingCallbackWithContext() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
+ // createWindowContext is available after R.
+ return
+ }
+ assumeAtLeastVendorApiLevel(2)
+
+ val component = mock<WindowLayoutComponent>()
+
+ val backend = ExtensionWindowLayoutInfoBackend(component, consumerAdapter)
+
+ activityScenario.scenario.onActivity { activity ->
+ val consumer = TestConsumer<WindowLayoutInfo>()
+ backend.registerLayoutChangeCallback(activity, Runnable::run, consumer)
+ backend.unregisterLayoutChangeCallback(consumer)
+ val windowContext = WindowTestUtils.createOverlayWindowContext()
+ val windowContextConsumer = TestConsumer<WindowLayoutInfo>()
+ backend.registerLayoutChangeCallback(
+ windowContext,
+ Runnable::run,
+ windowContextConsumer
+ )
+ backend.unregisterLayoutChangeCallback(windowContextConsumer)
+
+ val consumerCaptor = argumentCaptor<OEMConsumer<OEMWindowLayoutInfo>>()
+ verify(component).addWindowLayoutInfoListener(
+ eq(activity as Context),
+ consumerCaptor.capture()
+ )
+ verify(component).removeWindowLayoutInfoListener(
+ consumerCaptor.firstValue
+ )
+
+ verify(component).addWindowLayoutInfoListener(
+ eq(windowContext),
+ consumerCaptor.capture()
+ )
+ verify(component).removeWindowLayoutInfoListener(
+ consumerCaptor.lastValue
+ )
+ }
+ }
+
+ @Test
+ fun testExtensionWindowBackend_removeMultipleCallbackWithContext() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
+ // createWindowContext is available after R.
+ return
+ }
+ assumeAtLeastVendorApiLevel(2)
+
+ val component = mock<WindowLayoutComponent>()
+
+ val backend = ExtensionWindowLayoutInfoBackend(component, consumerAdapter)
+
+ activityScenario.scenario.onActivity { activity ->
+ val consumer = TestConsumer<WindowLayoutInfo>()
+ val consumer2 = TestConsumer<WindowLayoutInfo>()
+ backend.registerLayoutChangeCallback(activity, Runnable::run, consumer)
+ backend.registerLayoutChangeCallback(activity, Runnable::run, consumer2)
+ backend.unregisterLayoutChangeCallback(consumer)
+ backend.unregisterLayoutChangeCallback(consumer2)
+ val windowContext = WindowTestUtils.createOverlayWindowContext()
+ val windowContextConsumer = TestConsumer<WindowLayoutInfo>()
+ val windowContextConsumer2 = TestConsumer<WindowLayoutInfo>()
+ backend.registerLayoutChangeCallback(
+ windowContext,
+ Runnable::run,
+ windowContextConsumer
+ )
+ backend.registerLayoutChangeCallback(
+ windowContext,
+ Runnable::run,
+ windowContextConsumer2
+ )
+ backend.unregisterLayoutChangeCallback(windowContextConsumer)
+ backend.unregisterLayoutChangeCallback(windowContextConsumer2)
+
+ val consumerCaptor = argumentCaptor<OEMConsumer<OEMWindowLayoutInfo>>()
+ verify(component).addWindowLayoutInfoListener(
+ eq(activity as Context),
+ consumerCaptor.capture()
+ )
+ verify(component).removeWindowLayoutInfoListener(
+ consumerCaptor.firstValue
+ )
+
+ verify(component).addWindowLayoutInfoListener(
+ eq(windowContext),
+ consumerCaptor.capture()
+ )
+ verify(component).removeWindowLayoutInfoListener(
+ consumerCaptor.lastValue
+ )
+ assertFalse(backend.hasRegisteredListeners())
+ }
+ }
+
+ @Suppress("Deprecation")
+ @Test
+ fun testExtensionWindowBackend_reRegisterCallback() {
+ assumeBeforeVendorApiLevel(2)
val component = mock<WindowLayoutComponent>()
val backend = ExtensionWindowLayoutInfoBackend(component, consumerAdapter)
@@ -198,8 +458,58 @@
}
}
+ /**
+ * Verifies that a [WindowLayoutInfo] is published to the consumer upon each registration.
+ * Note: addWindowLayoutInfoListener(context) is added in
+ * {@link WindowExtensions#VENDOR_API_LEVEL_2}
+ */
+ @Test
+ fun testExtensionWindowBackend_reRegisterCallbackWithContext() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
+ return
+ }
+ assumeAtLeastVendorApiLevel(2)
+
+ val component = mock<WindowLayoutComponent>()
+
+ val backend = ExtensionWindowLayoutInfoBackend(component, consumerAdapter)
+
+ val windowContext = WindowTestUtils.createOverlayWindowContext()
+ val windowContextConsumer = TestConsumer<WindowLayoutInfo>()
+
+ backend.registerLayoutChangeCallback(windowContext, Runnable::run, windowContextConsumer)
+ backend.unregisterLayoutChangeCallback(windowContextConsumer)
+ backend.registerLayoutChangeCallback(windowContext, Runnable::run, windowContextConsumer)
+
+ val consumerCaptor = argumentCaptor<OEMConsumer<OEMWindowLayoutInfo>>()
+ verify(component, times(2)).addWindowLayoutInfoListener(
+ eq(windowContext),
+ consumerCaptor.capture()
+ )
+ verify(component).removeWindowLayoutInfoListener(
+ consumerCaptor.firstValue
+ )
+
+ activityScenario.scenario.onActivity { activity ->
+ val consumer = TestConsumer<WindowLayoutInfo>()
+ backend.registerLayoutChangeCallback(activity, Runnable::run, consumer)
+ backend.unregisterLayoutChangeCallback(consumer)
+ backend.registerLayoutChangeCallback(activity, Runnable::run, consumer)
+
+ verify(component, times(2))
+ .addWindowLayoutInfoListener(
+ eq(activity as Context),
+ consumerCaptor.capture()
+ )
+ verify(component).removeWindowLayoutInfoListener(
+ consumerCaptor.firstValue
+ )
+ }
+ }
+
@Test
public fun testRegisterLayoutChangeCallback_clearListeners() {
+ assumeBeforeVendorApiLevel(2)
activityScenario.scenario.onActivity { activity ->
val component = FakeWindowComponent()
val backend = ExtensionWindowLayoutInfoBackend(component, consumerAdapter)
@@ -213,12 +523,12 @@
{ obj: Runnable -> obj.run() },
firstConsumer
)
+
backend.registerLayoutChangeCallback(
activity,
{ obj: Runnable -> obj.run() },
secondConsumer
)
-
assertEquals("Expected one registration for same Activity", 1, component.consumers.size)
// Check unregistering the layout change callback
backend.unregisterLayoutChangeCallback(firstConsumer)
@@ -227,8 +537,50 @@
}
}
+ /**
+ * Verifies that both [Activity] and [UiContext] can be independently registered as listeners to
+ * [WindowLayoutInfo].
+ * Note: addWindowLayoutInfoListener(context) is added in
+ * {@link WindowExtensions#VENDOR_API_LEVEL_2}
+ */
+ @Test
+ public fun testRegisterLayoutChangeCallback_clearListenersWithContext() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
+ return
+ }
+ assumeAtLeastVendorApiLevel(2)
+
+ activityScenario.scenario.onActivity { activity ->
+ val component = FakeWindowComponent()
+ val backend = ExtensionWindowLayoutInfoBackend(component, consumerAdapter)
+
+ // Check registering the layout change callback
+ val firstConsumer = mock<Consumer<WindowLayoutInfo>>()
+ val secondConsumer = mock<Consumer<WindowLayoutInfo>>()
+ val thirdConsumer = mock<Consumer<WindowLayoutInfo>>()
+ val windowContext = WindowTestUtils.createOverlayWindowContext()
+
+ backend.registerLayoutChangeCallback(activity, Runnable::run, firstConsumer)
+ backend.registerLayoutChangeCallback(activity, Runnable::run, secondConsumer)
+ backend.registerLayoutChangeCallback(windowContext, Runnable::run, thirdConsumer)
+
+ assertEquals(
+ "Expected one registration for same Activity",
+ 2 /* expected */,
+ component.oemConsumers.size
+ )
+ // Check unregistering the layout change callback
+ backend.unregisterLayoutChangeCallback(firstConsumer)
+ backend.unregisterLayoutChangeCallback(secondConsumer)
+ backend.unregisterLayoutChangeCallback(thirdConsumer)
+ assertTrue("Expected all listeners to be removed", component.oemConsumers.isEmpty())
+ }
+ }
+
+ @RequiresApi(Build.VERSION_CODES.R)
@Test
public fun testLayoutChangeCallback_emitNewValue() {
+ assumeBeforeVendorApiLevel(2)
activityScenario.scenario.onActivity { activity ->
val component = FakeWindowComponent()
val backend = ExtensionWindowLayoutInfoBackend(component, consumerAdapter)
@@ -245,7 +597,31 @@
}
@Test
+ public fun testExtensionWindowBackend_emitNewValueWithContext() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
+ return
+ }
+ assumeAtLeastVendorApiLevel(2)
+
+ val component = FakeWindowComponent()
+ val backend = ExtensionWindowLayoutInfoBackend(component, consumerAdapter)
+
+ // Check that callbacks from the extension are propagated for WindowContext.
+ val consumer = mock<Consumer<WindowLayoutInfo>>()
+ val windowContext = WindowTestUtils.createOverlayWindowContext()
+ backend.registerLayoutChangeCallback(
+ windowContext, Runnable::run, consumer
+ )
+ val windowLayoutInfo = newTestOEMWindowLayoutInfo(windowContext)
+
+ component.emit(windowLayoutInfo)
+ verify(consumer).accept(translate(windowContext, windowLayoutInfo))
+ }
+
+ @RequiresApi(Build.VERSION_CODES.R)
+ @Test
public fun testWindowLayoutInfo_updatesOnSubsequentRegistration() {
+ assumeAtLeastVendorApiLevel(1)
activityScenario.scenario.onActivity { activity ->
val component = FakeWindowComponent()
val backend = ExtensionWindowLayoutInfoBackend(component, consumerAdapter)
@@ -266,8 +642,36 @@
}
}
- internal companion object {
+ @Test
+ public fun testWindowLayoutInfo_updatesOnSubsequentRegistrationWithContext() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
+ return
+ }
+ assumeAtLeastVendorApiLevel(2)
+ val component = FakeWindowComponent()
+ val backend = ExtensionWindowLayoutInfoBackend(component, consumerAdapter)
+ val consumer = TestConsumer<WindowLayoutInfo>()
+ val windowContext = WindowTestUtils.createOverlayWindowContext()
+
+ val oemWindowLayoutInfo = newTestOEMWindowLayoutInfo(windowContext)
+
+ val expected = listOf(
+ translate(windowContext, oemWindowLayoutInfo),
+ translate(windowContext, oemWindowLayoutInfo)
+ )
+
+ backend.registerLayoutChangeCallback(windowContext, Runnable::run, consumer)
+ component.emit(newTestOEMWindowLayoutInfo(windowContext))
+ backend.unregisterLayoutChangeCallback(consumer)
+
+ backend.registerLayoutChangeCallback(windowContext, Runnable::run, consumer)
+ component.emit(newTestOEMWindowLayoutInfo(windowContext))
+ backend.unregisterLayoutChangeCallback(consumer)
+ consumer.assertValues(expected)
+ }
+
+ internal companion object {
private fun newTestOEMWindowLayoutInfo(activity: Activity): OEMWindowLayoutInfo {
val bounds = WindowMetricsCalculatorCompat.computeCurrentWindowMetrics(activity).bounds
val featureBounds = Rect(0, bounds.centerY(), bounds.width(), bounds.centerY())
@@ -275,6 +679,20 @@
val displayFeatures = listOf(feature)
return OEMWindowLayoutInfo(displayFeatures)
}
+
+ /**
+ * Creates an empty OEMWindowLayoutInfo. Note that before R context needs to be an
+ * [Activity]. After R Context can be an [Activity] or a [UiContext] created with
+ * [Context#createWindowContext] or [InputMethodService].
+ */
+ @RequiresApi(Build.VERSION_CODES.R)
+ private fun newTestOEMWindowLayoutInfo(@UiContext context: Context): OEMWindowLayoutInfo {
+ val bounds = WindowMetricsCalculatorCompat.computeCurrentWindowMetrics(context).bounds
+ val featureBounds = Rect(0, bounds.centerY(), bounds.width(), bounds.centerY())
+ val feature = OEMFoldingFeature(featureBounds, TYPE_HINGE, STATE_FLAT)
+ val displayFeatures = listOf(feature)
+ return OEMWindowLayoutInfo(displayFeatures)
+ }
}
private class RequestTrackingWindowComponent : WindowLayoutComponent {
@@ -288,19 +706,27 @@
records.add(AddCall(activity))
}
+ override fun addWindowLayoutInfoListener(
+ context: Context,
+ consumer: OEMConsumer<OEMWindowLayoutInfo>,
+ ) {
+ records.add(AddCall(context))
+ }
+
override fun removeWindowLayoutInfoListener(consumer: JavaConsumer<OEMWindowLayoutInfo>) {
}
- class AddCall(val activity: Activity)
+ class AddCall(val context: Context)
- fun hasAddCall(activity: Activity): Boolean {
- return records.any { addRecord -> addRecord.activity == activity }
+ fun hasAddCall(context: Context): Boolean {
+ return records.any { addRecord -> addRecord.context == context }
}
}
private class FakeWindowComponent : WindowLayoutComponent {
val consumers = mutableListOf<JavaConsumer<OEMWindowLayoutInfo>>()
+ val oemConsumers = mutableListOf<OEMConsumer<OEMWindowLayoutInfo>>()
override fun addWindowLayoutInfoListener(
activity: Activity,
@@ -309,13 +735,30 @@
consumers.add(consumer)
}
+ override fun addWindowLayoutInfoListener(
+ context: Context,
+ consumer: OEMConsumer<OEMWindowLayoutInfo>
+ ) {
+ oemConsumers.add(consumer)
+ }
+
override fun removeWindowLayoutInfoListener(consumer: JavaConsumer<OEMWindowLayoutInfo>) {
consumers.remove(consumer)
}
+ override fun removeWindowLayoutInfoListener(
+ consumer: OEMConsumer<OEMWindowLayoutInfo>
+ ) {
+ oemConsumers.remove(consumer)
+ }
+
@SuppressLint("NewApi")
fun emit(info: OEMWindowLayoutInfo) {
- consumers.forEach { it.accept(info) }
+ if (ExtensionsUtil.safeVendorApiLevel < WindowExtensions.VENDOR_API_LEVEL_2) {
+ consumers.forEach { it.accept(info) }
+ } else {
+ oemConsumers.forEach { it.accept(info) }
+ }
}
}
}
diff --git a/window/window/src/androidTest/java/androidx/window/layout/adapter/extensions/ExtensionsWindowLayoutInfoAdapterTest.kt b/window/window/src/androidTest/java/androidx/window/layout/adapter/extensions/ExtensionsWindowLayoutInfoAdapterTest.kt
index f1d8f53..376cf74 100644
--- a/window/window/src/androidTest/java/androidx/window/layout/adapter/extensions/ExtensionsWindowLayoutInfoAdapterTest.kt
+++ b/window/window/src/androidTest/java/androidx/window/layout/adapter/extensions/ExtensionsWindowLayoutInfoAdapterTest.kt
@@ -16,26 +16,30 @@
package androidx.window.layout.adapter.extensions
+import androidx.window.extensions.layout.FoldingFeature as OEMFoldingFeature
+import androidx.window.extensions.layout.WindowLayoutInfo as OEMWindowLayoutInfo
import android.graphics.Rect
+import android.os.Build
+import androidx.annotation.RequiresApi
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.window.TestActivity
+import androidx.window.WindowTestUtils
import androidx.window.core.Bounds
import androidx.window.extensions.layout.FoldingFeature.STATE_HALF_OPENED
import androidx.window.extensions.layout.FoldingFeature.TYPE_HINGE
import androidx.window.layout.FoldingFeature.State.Companion.HALF_OPENED
+import androidx.window.layout.HardwareFoldingFeature
import androidx.window.layout.HardwareFoldingFeature.Type.Companion.HINGE
import androidx.window.layout.TestFoldingFeatureUtil.invalidNonZeroFoldBounds
+import androidx.window.layout.WindowLayoutInfo
import androidx.window.layout.WindowMetricsCalculatorCompat.computeCurrentWindowMetrics
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
+import org.junit.Assume.assumeTrue
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
-import androidx.window.extensions.layout.FoldingFeature as OEMFoldingFeature
-import androidx.window.extensions.layout.WindowLayoutInfo as OEMWindowLayoutInfo
-import androidx.window.layout.HardwareFoldingFeature
-import androidx.window.layout.WindowLayoutInfo
class ExtensionsWindowLayoutInfoAdapterTest {
@@ -46,12 +50,13 @@
@Test
fun testTranslate_foldingFeature() {
activityScenario.scenario.onActivity { activity ->
- val bounds = computeCurrentWindowMetrics(activity).bounds
+ val windowMetrics = computeCurrentWindowMetrics(activity)
+ val bounds = windowMetrics.bounds
val featureBounds = Rect(0, bounds.centerY(), bounds.width(), bounds.centerY())
val oemFeature = OEMFoldingFeature(featureBounds, TYPE_HINGE, STATE_HALF_OPENED)
val expected = HardwareFoldingFeature(Bounds(featureBounds), HINGE, HALF_OPENED)
- val actual = ExtensionsWindowLayoutInfoAdapter.translate(activity, oemFeature)
+ val actual = ExtensionsWindowLayoutInfoAdapter.translate(windowMetrics, oemFeature)
assertEquals(expected, actual)
}
@@ -74,14 +79,34 @@
}
}
+ @RequiresApi(Build.VERSION_CODES.S)
@Test
- fun testTranslate_foldingFeature_invalidType() {
+ fun testTranslate_windowLayoutInfoFromContext() {
+ assumeTrue(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
activityScenario.scenario.onActivity { activity ->
val bounds = computeCurrentWindowMetrics(activity).bounds
val featureBounds = Rect(0, bounds.centerY(), bounds.width(), bounds.centerY())
+ val oemFeature = OEMFoldingFeature(featureBounds, TYPE_HINGE, STATE_HALF_OPENED)
+ val oemInfo = OEMWindowLayoutInfo(listOf(oemFeature))
+ val localFeature = HardwareFoldingFeature(Bounds(featureBounds), HINGE, HALF_OPENED)
+ val expected = WindowLayoutInfo(listOf(localFeature))
+
+ val windowContext = WindowTestUtils.createOverlayWindowContext()
+
+ val fromContext = ExtensionsWindowLayoutInfoAdapter.translate(windowContext, oemInfo)
+ assertEquals(expected, fromContext)
+ }
+ }
+
+ @Test
+ fun testTranslate_foldingFeature_invalidType() {
+ activityScenario.scenario.onActivity { activity ->
+ val windowMetrics = computeCurrentWindowMetrics(activity)
+ val bounds = windowMetrics.bounds
+ val featureBounds = Rect(0, bounds.centerY(), bounds.width(), bounds.centerY())
val oemFeature = OEMFoldingFeature(featureBounds, -1, STATE_HALF_OPENED)
- val actual = ExtensionsWindowLayoutInfoAdapter.translate(activity, oemFeature)
+ val actual = ExtensionsWindowLayoutInfoAdapter.translate(windowMetrics, oemFeature)
assertNull(actual)
}
@@ -90,11 +115,12 @@
@Test
fun testTranslate_foldingFeature_invalidState() {
activityScenario.scenario.onActivity { activity ->
- val bounds = computeCurrentWindowMetrics(activity).bounds
+ val windowMetrics = computeCurrentWindowMetrics(activity)
+ val bounds = windowMetrics.bounds
val featureBounds = Rect(0, bounds.centerY(), bounds.width(), bounds.centerY())
val oemFeature = OEMFoldingFeature(featureBounds, TYPE_HINGE, -1)
- val actual = ExtensionsWindowLayoutInfoAdapter.translate(activity, oemFeature)
+ val actual = ExtensionsWindowLayoutInfoAdapter.translate(windowMetrics, oemFeature)
assertNull(actual)
}
@@ -103,7 +129,8 @@
@Test
fun testTranslate_foldingFeature_invalidBounds() {
activityScenario.scenario.onActivity { activity ->
- val windowBounds = computeCurrentWindowMetrics(activity).bounds
+ val windowMetrics = computeCurrentWindowMetrics(activity)
+ val windowBounds = windowMetrics.bounds
val source = invalidNonZeroFoldBounds(windowBounds)
.map { featureBounds ->
@@ -111,7 +138,7 @@
}
val invalidFeatures = source.mapNotNull { feature ->
- ExtensionsWindowLayoutInfoAdapter.translate(activity, feature)
+ ExtensionsWindowLayoutInfoAdapter.translate(windowMetrics, feature)
}
assertTrue(source.isNotEmpty())
@@ -121,4 +148,4 @@
)
}
}
-}
\ No newline at end of file
+}
diff --git a/window/window-samples/src/main/res/values/colors.xml b/window/window/src/androidTest/res/values/colors.xml
similarity index 62%
copy from window/window-samples/src/main/res/values/colors.xml
copy to window/window/src/androidTest/res/values/colors.xml
index 41a72b2..939eec6 100644
--- a/window/window-samples/src/main/res/values/colors.xml
+++ b/window/window/src/androidTest/res/values/colors.xml
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
- Copyright 2020 The Android Open Source Project
+ 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.
@@ -14,14 +14,6 @@
See the License for the specific language governing permissions and
limitations under the License.
-->
-
<resources>
- <color name="colorPrimary">#6200EE</color>
- <color name="colorPrimaryDark">#3700B3</color>
- <color name="colorAccent">#03DAC5</color>
-
- <color name="colorFeatureFold">#7700FF00</color>
-
- <color name="colorSplitContentBackground">#3B6BDB4C</color>
- <color name="colorSplitControlsBackground">#475ABFF3</color>
-</resources>
+ <color name="testColor">#00FF00</color>
+</resources>
\ No newline at end of file
diff --git a/window/window-samples/src/main/res/values/colors.xml b/window/window/src/androidTest/res/xml/test_split_config_activity_rule_with_tag.xml
similarity index 60%
copy from window/window-samples/src/main/res/values/colors.xml
copy to window/window/src/androidTest/res/xml/test_split_config_activity_rule_with_tag.xml
index 41a72b2..d7e0025 100644
--- a/window/window-samples/src/main/res/values/colors.xml
+++ b/window/window/src/androidTest/res/xml/test_split_config_activity_rule_with_tag.xml
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
- Copyright 2020 The Android Open Source Project
+ 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.
@@ -14,14 +14,12 @@
See the License for the specific language governing permissions and
limitations under the License.
-->
-
-<resources>
- <color name="colorPrimary">#6200EE</color>
- <color name="colorPrimaryDark">#3700B3</color>
- <color name="colorAccent">#03DAC5</color>
-
- <color name="colorFeatureFold">#7700FF00</color>
-
- <color name="colorSplitContentBackground">#3B6BDB4C</color>
- <color name="colorSplitControlsBackground">#475ABFF3</color>
-</resources>
+<resources
+ xmlns:window="http://schemas.android.com/apk/res-auto">
+ <ActivityRule
+ window:tag="test"
+ window:alwaysExpand="true">
+ <ActivityFilter
+ window:activityName="androidx.window.sample.embedding.SplitActivityList"/>
+ </ActivityRule>
+</resources>
\ No newline at end of file
diff --git a/window/window/src/androidTest/res/xml/test_split_config_custom_activity_rule.xml b/window/window/src/androidTest/res/xml/test_split_config_custom_activity_rule.xml
index 63e54b6..f651baf 100644
--- a/window/window/src/androidTest/res/xml/test_split_config_custom_activity_rule.xml
+++ b/window/window/src/androidTest/res/xml/test_split_config_custom_activity_rule.xml
@@ -17,6 +17,7 @@
<resources
xmlns:window="http://schemas.android.com/apk/res-auto">
<ActivityRule
+ window:tag="rule1"
window:alwaysExpand="true">
<ActivityFilter
window:activityName="androidx.window.sample.embedding.SplitActivityList"/>
diff --git a/window/window/src/androidTest/res/xml/test_split_config_custom_split_pair_rule.xml b/window/window/src/androidTest/res/xml/test_split_config_custom_split_pair_rule.xml
index 128eeaa..face30c 100644
--- a/window/window/src/androidTest/res/xml/test_split_config_custom_split_pair_rule.xml
+++ b/window/window/src/androidTest/res/xml/test_split_config_custom_split_pair_rule.xml
@@ -17,9 +17,11 @@
<resources
xmlns:window="http://schemas.android.com/apk/res-auto">
<SplitPairRule
+ window:tag="rule2"
window:splitRatio="0.1"
window:splitMinWidthDp="123"
- window:splitMinSmallestWidthDp="456"
+ window:splitMinHeightDp="456"
+ window:splitMinSmallestWidthDp="789"
window:splitMaxAspectRatioInPortrait="1.23"
window:splitMaxAspectRatioInLandscape="alwaysDisallow"
window:splitLayoutDirection="rtl"
diff --git a/window/window/src/androidTest/res/xml/test_split_config_custom_split_placeholder_rule.xml b/window/window/src/androidTest/res/xml/test_split_config_custom_split_placeholder_rule.xml
index 3a0716e..273c855 100644
--- a/window/window/src/androidTest/res/xml/test_split_config_custom_split_placeholder_rule.xml
+++ b/window/window/src/androidTest/res/xml/test_split_config_custom_split_placeholder_rule.xml
@@ -17,9 +17,11 @@
<resources
xmlns:window="http://schemas.android.com/apk/res-auto">
<SplitPlaceholderRule
+ window:tag="rule3"
window:splitRatio="0.1"
window:splitMinWidthDp="123"
- window:splitMinSmallestWidthDp="456"
+ window:splitMinHeightDp="456"
+ window:splitMinSmallestWidthDp="789"
window:splitMaxAspectRatioInPortrait="1.23"
window:splitMaxAspectRatioInLandscape="alwaysDisallow"
window:splitLayoutDirection="rtl"
diff --git a/window/window/src/androidTest/res/xml/test_split_config_default_activity_rule.xml b/window/window/src/androidTest/res/xml/test_split_config_default_activity_rule.xml
index 3ae66aa..e47b93e 100644
--- a/window/window/src/androidTest/res/xml/test_split_config_default_activity_rule.xml
+++ b/window/window/src/androidTest/res/xml/test_split_config_default_activity_rule.xml
@@ -18,6 +18,6 @@
xmlns:window="http://schemas.android.com/apk/res-auto">
<ActivityRule>
<ActivityFilter
- window:activityName="androidx.window.sample.embedding.SplitActivityList"/>
+ window:activityName="SplitActivityList"/>
</ActivityRule>
</resources>
\ No newline at end of file
diff --git a/window/window/src/androidTest/res/xml/test_split_config_default_split_placeholder_rule.xml b/window/window/src/androidTest/res/xml/test_split_config_default_split_placeholder_rule.xml
index ffbc6ca..e67acb3 100644
--- a/window/window/src/androidTest/res/xml/test_split_config_default_split_placeholder_rule.xml
+++ b/window/window/src/androidTest/res/xml/test_split_config_default_split_placeholder_rule.xml
@@ -19,6 +19,6 @@
<SplitPlaceholderRule
window:placeholderActivityName="C">
<ActivityFilter
- window:activityName="androidx.window.sample.embedding.SplitActivityList"/>
+ window:activityName="SplitActivityList"/>
</SplitPlaceholderRule>
</resources>
\ No newline at end of file
diff --git a/window/window/src/androidTest/res/xml/test_split_config_duplicated_tag.xml b/window/window/src/androidTest/res/xml/test_split_config_duplicated_tag.xml
new file mode 100644
index 0000000..aba63db
--- /dev/null
+++ b/window/window/src/androidTest/res/xml/test_split_config_duplicated_tag.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ 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.
+ -->
+<resources
+ xmlns:window="http://schemas.android.com/apk/res-auto">
+ <ActivityRule
+ window:tag="test">
+ <ActivityFilter
+ window:activityName="A"/>
+ </ActivityRule>
+ <SplitPairRule
+ window:tag="test">
+ <SplitPairFilter
+ window:primaryActivityName="A"
+ window:secondaryActivityName="B"/>
+ </SplitPairRule>
+</resources>
\ No newline at end of file
diff --git a/window/window/src/androidTest/res/xml/test_split_config_split_pair_rule_horizontal_layout.xml b/window/window/src/androidTest/res/xml/test_split_config_split_pair_rule_horizontal_layout.xml
new file mode 100644
index 0000000..5e75a12
--- /dev/null
+++ b/window/window/src/androidTest/res/xml/test_split_config_split_pair_rule_horizontal_layout.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ 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.
+ -->
+<resources
+ xmlns:window="http://schemas.android.com/apk/res-auto">
+ <SplitPairRule
+ window:splitRatio="0.3"
+ window:tag="test"
+ window:splitMinWidthDp="0"
+ window:splitMinHeightDp="600"
+ window:splitMinSmallestWidthDp="0"
+ window:splitLayoutDirection="topToBottom"
+ window:animationBackgroundColor="#0000FF">
+ <SplitPairFilter
+ window:primaryActivityName="A"
+ window:secondaryActivityName="B"/>
+ </SplitPairRule>
+</resources>
\ No newline at end of file
diff --git a/window/window/src/androidTest/res/xml/test_split_config_split_placeholder_horizontal_layout.xml b/window/window/src/androidTest/res/xml/test_split_config_split_placeholder_horizontal_layout.xml
new file mode 100644
index 0000000..df0871f
--- /dev/null
+++ b/window/window/src/androidTest/res/xml/test_split_config_split_placeholder_horizontal_layout.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ 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.
+ -->
+<resources
+ xmlns:window="http://schemas.android.com/apk/res-auto">
+ <SplitPlaceholderRule
+ window:tag="test"
+ window:placeholderActivityName="C"
+ window:splitRatio="0.3"
+ window:splitMinWidthDp="0"
+ window:splitMinHeightDp="600"
+ window:splitMinSmallestWidthDp="0"
+ window:splitLayoutDirection="bottomToTop"
+ window:animationBackgroundColor="@color/testColor">
+ <ActivityFilter
+ window:activityName="androidx.window.sample.embedding.SplitActivityList"/>
+ </SplitPlaceholderRule>
+</resources>
\ No newline at end of file
diff --git a/window/window/src/main/java/androidx/window/WindowProperties.kt b/window/window/src/main/java/androidx/window/WindowProperties.kt
index 226430b..156652f 100644
--- a/window/window/src/main/java/androidx/window/WindowProperties.kt
+++ b/window/window/src/main/java/androidx/window/WindowProperties.kt
@@ -30,9 +30,10 @@
*
* If `true`, the system is permitted to override the app's windowing
* behavior and implement activity embedding split rules, such as displaying
- * activities side by side. A system override informs the app that the
- * activity embedding APIs are disabled so the app will not provide its own
- * activity embedding rules, which would conflict with the system's rules.
+ * activities adjacent to each other. A system override informs the app that
+ * the activity embedding APIs are disabled so the app will not provide its
+ * own activity embedding rules, which would conflict with the system's
+ * rules.
*
* If `false`, the system is not permitted to override the windowing
* behavior of the app. Set the property to `false` if the app provides its
@@ -62,4 +63,28 @@
*/
const val PROPERTY_ACTIVITY_EMBEDDING_ALLOW_SYSTEM_OVERRIDE =
"android.window.PROPERTY_ACTIVITY_EMBEDDING_ALLOW_SYSTEM_OVERRIDE"
+
+ /**
+ * Application level
+ * [PackageManager][android.content.pm.PackageManager.Property] tag
+ * that an app must specify to inform the system that the app is ActivityEmbedding
+ * split feature enabled. In other words, the ActivityEmbedding splits feature cannot be
+ * used if the app has no property set.
+ *
+ * With this property, the system could provide custom behaviors for the apps that
+ * have ActivityEmbedding split feature enabled. For example, the fixed-portrait orientation
+ * requests of the activities could be ignored by the system in order to provide seamless
+ * ActivityEmbedding split experiences while holding the large-screen devices in landscape mode.
+ *
+ * **Syntax:**
+ * <pre>
+ * <application>
+ * <property
+ * android:name="android.window.PROPERTY_ACTIVITY_EMBEDDING_SPLITS_ENABLED"
+ * android:value="true|false"/>
+ * </application>
+ * </pre>
+ */
+ const val PROPERTY_ACTIVITY_EMBEDDING_SPLITS_ENABLED =
+ "android.window.PROPERTY_ACTIVITY_EMBEDDING_SPLITS_ENABLED"
}
\ No newline at end of file
diff --git a/window/window/src/main/java/androidx/window/area/EmptyWindowAreaControllerImpl.kt b/window/window/src/main/java/androidx/window/area/EmptyWindowAreaControllerImpl.kt
new file mode 100644
index 0000000..996c7ad
--- /dev/null
+++ b/window/window/src/main/java/androidx/window/area/EmptyWindowAreaControllerImpl.kt
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2021 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 androidx.window.area
+
+import android.app.Activity
+import androidx.window.core.ExperimentalWindowApi
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.flowOf
+import java.util.concurrent.Executor
+
+/**
+ * Empty Implementation for devices that do not
+ * support the [WindowAreaController] functionality
+ */
+@ExperimentalWindowApi
+internal class EmptyWindowAreaControllerImpl : WindowAreaController {
+ override fun rearDisplayStatus(): Flow<WindowAreaStatus> {
+ return flowOf(WindowAreaStatus.UNSUPPORTED)
+ }
+
+ override fun rearDisplayMode(
+ activity: Activity,
+ executor: Executor,
+ windowAreaSessionCallback: WindowAreaSessionCallback
+ ) {
+ throw WindowAreaController.REAR_DISPLAY_ERROR
+ }
+}
\ No newline at end of file
diff --git a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityListPlaceholder.kt b/window/window/src/main/java/androidx/window/area/RearDisplaySessionImpl.kt
similarity index 62%
copy from window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityListPlaceholder.kt
copy to window/window/src/main/java/androidx/window/area/RearDisplaySessionImpl.kt
index 754e11d8..9a5bbd3 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/embedding/SplitActivityListPlaceholder.kt
+++ b/window/window/src/main/java/androidx/window/area/RearDisplaySessionImpl.kt
@@ -14,6 +14,17 @@
* limitations under the License.
*/
-package androidx.window.sample.embedding
+package androidx.window.area
-open class SplitActivityListPlaceholder : SplitActivityPlaceholder()
\ No newline at end of file
+import androidx.window.core.ExperimentalWindowApi
+import androidx.window.extensions.area.WindowAreaComponent
+
+@ExperimentalWindowApi
+internal class RearDisplaySessionImpl(
+ private val windowAreaComponent: WindowAreaComponent
+) : WindowAreaSession {
+
+ override fun close() {
+ windowAreaComponent.endRearDisplaySession()
+ }
+}
diff --git a/window/window/src/main/java/androidx/window/area/WindowAreaController.kt b/window/window/src/main/java/androidx/window/area/WindowAreaController.kt
new file mode 100644
index 0000000..30ca792
--- /dev/null
+++ b/window/window/src/main/java/androidx/window/area/WindowAreaController.kt
@@ -0,0 +1,125 @@
+/*
+ * Copyright 2021 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 androidx.window.area
+
+import android.app.Activity
+import android.os.Build
+import android.util.Log
+import androidx.annotation.RestrictTo
+import androidx.window.core.BuildConfig
+import androidx.window.core.ExperimentalWindowApi
+import androidx.window.core.VerificationMode
+import androidx.window.extensions.WindowExtensionsProvider
+import androidx.window.extensions.area.WindowAreaComponent
+import java.util.concurrent.Executor
+import kotlinx.coroutines.flow.Flow
+
+/**
+ * An interface to provide the information and behavior around moving windows between
+ * displays or display areas on a device.
+ */
+@ExperimentalWindowApi
+interface WindowAreaController {
+
+ /*
+ Marked with RestrictTo as we iterate and define the
+ Kotlin API we want to provide.
+ */
+ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+ public fun rearDisplayStatus(): Flow<WindowAreaStatus>
+
+ /*
+ Marked with RestrictTo as we iterate and define the
+ Kotlin API we want to provide.
+ */
+ @Throws(UnsupportedOperationException::class)
+ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+ public fun rearDisplayMode(
+ activity: Activity,
+ executor: Executor,
+ windowAreaSessionCallback: WindowAreaSessionCallback
+ )
+
+ public companion object {
+ internal val REAR_DISPLAY_ERROR =
+ UnsupportedOperationException("Rear Display mode cannot be enabled currently")
+
+ private val TAG = WindowAreaController::class.simpleName
+
+ private var decorator: WindowAreaControllerDecorator = EmptyDecorator
+
+ /**
+ * Provides an instance of [WindowAreaController].
+ */
+ @JvmName("getOrCreate")
+ @JvmStatic
+ public fun getOrCreate(): WindowAreaController {
+ var windowAreaComponentExtensions: WindowAreaComponent?
+ try {
+ windowAreaComponentExtensions = WindowExtensionsProvider
+ .getWindowExtensions()
+ .windowAreaComponent
+ } catch (t: Throwable) {
+ if (BuildConfig.verificationMode == VerificationMode.STRICT) {
+ Log.d(TAG, "Failed to load WindowExtensions")
+ }
+ windowAreaComponentExtensions = null
+ }
+ val controller =
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N ||
+ windowAreaComponentExtensions == null) {
+ EmptyWindowAreaControllerImpl()
+ } else {
+ WindowAreaControllerImpl(windowAreaComponentExtensions)
+ }
+ return decorator.decorate(controller)
+ }
+
+ @JvmStatic
+ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+ public fun overrideDecorator(overridingDecorator: WindowAreaControllerDecorator) {
+ decorator = overridingDecorator
+ }
+
+ @JvmStatic
+ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+ public fun reset() {
+ decorator = EmptyDecorator
+ }
+ }
+}
+
+/**
+ * Decorator that allows us to provide different functionality
+ * in our window-testing artifact.
+ */
+@ExperimentalWindowApi
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public interface WindowAreaControllerDecorator {
+ /**
+ * Returns an instance of [WindowAreaController] associated to the [Activity]
+ */
+ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+ public fun decorate(controller: WindowAreaController): WindowAreaController
+}
+
+@ExperimentalWindowApi
+private object EmptyDecorator : WindowAreaControllerDecorator {
+ override fun decorate(controller: WindowAreaController): WindowAreaController {
+ return controller
+ }
+}
diff --git a/window/window/src/main/java/androidx/window/area/WindowAreaControllerImpl.kt b/window/window/src/main/java/androidx/window/area/WindowAreaControllerImpl.kt
new file mode 100644
index 0000000..2da99db
--- /dev/null
+++ b/window/window/src/main/java/androidx/window/area/WindowAreaControllerImpl.kt
@@ -0,0 +1,162 @@
+/*
+ * Copyright 2021 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 androidx.window.area
+
+import android.app.Activity
+import android.os.Build
+import android.util.Log
+import androidx.annotation.RequiresApi
+import androidx.window.core.BuildConfig
+import androidx.window.core.ConsumerAdapter
+import androidx.window.core.ExperimentalWindowApi
+import androidx.window.core.VerificationMode
+import androidx.window.extensions.area.WindowAreaComponent
+import java.lang.reflect.InvocationTargetException
+import java.util.concurrent.Executor
+import java.util.function.Consumer
+import kotlinx.coroutines.channels.BufferOverflow
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.flow
+
+/**
+ * Implementation of WindowAreaController for devices
+ * that do implement the WindowAreaComponent on device.
+ *
+ * Requires [Build.VERSION_CODES.N] due to the use of [Consumer].
+ * Will not be created though on API levels lower than
+ * [Build.VERSION_CODES.S] as that's the min level of support for
+ * this functionality.
+ */
+@ExperimentalWindowApi
+@RequiresApi(Build.VERSION_CODES.N)
+internal class WindowAreaControllerImpl(
+ private val windowAreaComponent: WindowAreaComponent
+) : WindowAreaController {
+
+ private lateinit var rearDisplaySessionConsumer: Consumer<Int>
+ private var currentStatus: WindowAreaStatus? = null
+
+ override fun rearDisplayStatus(): Flow<WindowAreaStatus> {
+ return flow {
+ val channel = Channel<WindowAreaStatus>(
+ capacity = BUFFER_CAPACITY,
+ onBufferOverflow = BufferOverflow.DROP_OLDEST
+ )
+ val listener = Consumer<Int> { status ->
+ currentStatus = WindowAreaStatus.translate(status)
+ channel.trySend(currentStatus ?: WindowAreaStatus.UNSUPPORTED)
+ }
+ val loader = WindowAreaControllerImpl::class.java.classLoader
+ if (loader == null) {
+ channel.trySend(WindowAreaStatus.UNSUPPORTED)
+ } else {
+ val consumerAdapter = ConsumerAdapter(loader)
+ val subscription = consumerAdapter.createSubscriptionNoActivity(
+ windowAreaComponent,
+ Int::class,
+ "addRearDisplayStatusListener",
+ "removeRearDisplayStatusListener",
+ ) { value ->
+ listener.accept(value)
+ }
+ try {
+ for (item in channel) {
+ emit(item)
+ }
+ } finally {
+ subscription.dispose()
+ }
+ }
+ }.distinctUntilChanged()
+ }
+
+ override fun rearDisplayMode(
+ activity: Activity,
+ executor: Executor,
+ windowAreaSessionCallback: WindowAreaSessionCallback
+ ) {
+ // If we already have a status value that is not [WindowAreaStatus.AVAILABLE]
+ // we should throw an exception quick to indicate they tried to enable
+ // RearDisplay mode when it was not available.
+ if (currentStatus != null && currentStatus != WindowAreaStatus.AVAILABLE) {
+ throw WindowAreaController.REAR_DISPLAY_ERROR
+ }
+ rearDisplaySessionConsumer =
+ RearDisplaySessionConsumer(windowAreaSessionCallback, windowAreaComponent)
+ val loader = WindowAreaControllerImpl::class.java.classLoader
+ loader?.let {
+ val consumerAdapter = ConsumerAdapter(it)
+ try {
+ consumerAdapter.createConsumer(
+ windowAreaComponent,
+ Int::class,
+ "startRearDisplaySession",
+ activity
+ ) { value ->
+ rearDisplaySessionConsumer.accept(value)
+ }
+ } catch (exception: InvocationTargetException) {
+ // Rethrow the underlying exception when available because Java reflection wraps
+ // the actual exception with InvocationTargetException.
+ throw exception.cause ?: exception
+ }
+ }
+ }
+
+ internal class RearDisplaySessionConsumer(
+ private val appCallback: WindowAreaSessionCallback,
+ private val extensionsComponent: WindowAreaComponent
+ ) : Consumer<Int> {
+
+ private var session: WindowAreaSession? = null
+
+ override fun accept(sessionStatus: Int) {
+ when (sessionStatus) {
+ WindowAreaComponent.SESSION_STATE_ACTIVE -> onSessionStarted()
+ WindowAreaComponent.SESSION_STATE_INACTIVE -> onSessionFinished()
+ else -> {
+ if (BuildConfig.verificationMode == VerificationMode.STRICT) {
+ Log.d(TAG, "Received an unknown session status value: $sessionStatus")
+ }
+ onSessionFinished()
+ }
+ }
+ }
+
+ private fun onSessionStarted() {
+ session = RearDisplaySessionImpl(extensionsComponent)
+ session?.let { appCallback.onSessionStarted(it) }
+ }
+
+ private fun onSessionFinished() {
+ session = null
+ appCallback.onSessionEnded()
+ }
+ }
+
+ internal companion object {
+ private val TAG = WindowAreaControllerImpl::class.simpleName
+ /*
+ Chosen as 10 for a base default value. We shouldn't be receiving
+ many changes to window area status so this is enough capacity
+ to not end up blocking.
+ */
+ private const val BUFFER_CAPACITY = 10
+ }
+}
diff --git a/window/window-samples/src/main/java/androidx/window/sample/infolog/InfoLog.kt b/window/window/src/main/java/androidx/window/area/WindowAreaSession.kt
similarity index 68%
copy from window/window-samples/src/main/java/androidx/window/sample/infolog/InfoLog.kt
copy to window/window/src/main/java/androidx/window/area/WindowAreaSession.kt
index e69a77b..6cdbd12 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/infolog/InfoLog.kt
+++ b/window/window/src/main/java/androidx/window/area/WindowAreaSession.kt
@@ -14,10 +14,16 @@
* limitations under the License.
*/
-package androidx.window.sample.infolog
+package androidx.window.area
+
+import androidx.window.core.ExperimentalWindowApi
/**
- * A data class to hold a title and a detail or subtitle that can be shown using [InfoLogAdapter]
- * . This can be used to create samples with an ordered timeline of events.
+ * Session interface to represent a long-standing
+ * WindowArea mode or feature that provides a handle
+ * to close the session.
*/
-data class InfoLog(val title: String, val detail: String, val id: Int)
\ No newline at end of file
+@ExperimentalWindowApi
+public interface WindowAreaSession {
+ fun close()
+}
\ No newline at end of file
diff --git a/window/window-samples/src/main/java/androidx/window/sample/infolog/InfoLog.kt b/window/window/src/main/java/androidx/window/area/WindowAreaSessionCallback.kt
similarity index 61%
copy from window/window-samples/src/main/java/androidx/window/sample/infolog/InfoLog.kt
copy to window/window/src/main/java/androidx/window/area/WindowAreaSessionCallback.kt
index e69a77b..80842c4 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/infolog/InfoLog.kt
+++ b/window/window/src/main/java/androidx/window/area/WindowAreaSessionCallback.kt
@@ -14,10 +14,18 @@
* limitations under the License.
*/
-package androidx.window.sample.infolog
+package androidx.window.area
-/**
- * A data class to hold a title and a detail or subtitle that can be shown using [InfoLogAdapter]
- * . This can be used to create samples with an ordered timeline of events.
+import androidx.window.core.ExperimentalWindowApi
+
+/** Callback to update the client on the WindowArea Session being
+ * started and ended.
+ * TODO(b/207720511) Move to window-java module when Kotlin API Finalized
*/
-data class InfoLog(val title: String, val detail: String, val id: Int)
\ No newline at end of file
+@ExperimentalWindowApi
+interface WindowAreaSessionCallback {
+
+ fun onSessionStarted(session: WindowAreaSession)
+
+ fun onSessionEnded()
+}
\ No newline at end of file
diff --git a/window/window/src/main/java/androidx/window/area/WindowAreaStatus.kt b/window/window/src/main/java/androidx/window/area/WindowAreaStatus.kt
new file mode 100644
index 0000000..f60d8f5
--- /dev/null
+++ b/window/window/src/main/java/androidx/window/area/WindowAreaStatus.kt
@@ -0,0 +1,62 @@
+/*
+ * Copyright 2021 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 androidx.window.area
+
+import androidx.window.core.ExperimentalWindowApi
+import androidx.window.extensions.area.WindowAreaComponent
+
+/**
+ * Represents a window area status.
+ */
+@ExperimentalWindowApi
+class WindowAreaStatus private constructor(private val mDescription: String) {
+ override fun toString(): String {
+ return mDescription
+ }
+
+ companion object {
+ /**
+ * Status representing that the WindowArea feature is not a supported
+ * feature on the device.
+ */
+ @JvmField
+ val UNSUPPORTED = WindowAreaStatus("UNSUPPORTED")
+
+ /**
+ * Status representing that the WindowArea feature is currently not available
+ * to be enabled. This could be due to another process has enabled it, or that the
+ * current device configuration doesn't allow it.
+ */
+ @JvmField
+ val UNAVAILABLE = WindowAreaStatus("UNAVAILABLE")
+
+ /**
+ * Status representing that the WindowArea feature is available to be enabled.
+ */
+ @JvmField
+ val AVAILABLE = WindowAreaStatus("AVAILABLE")
+
+ @JvmStatic
+ internal fun translate(status: Int): WindowAreaStatus {
+ return when (status) {
+ WindowAreaComponent.STATUS_AVAILABLE -> AVAILABLE
+ WindowAreaComponent.STATUS_UNAVAILABLE -> UNAVAILABLE
+ else -> UNSUPPORTED
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/window/window/src/main/java/androidx/window/core/ConsumerAdapter.kt b/window/window/src/main/java/androidx/window/core/ConsumerAdapter.kt
index e81e16e..af51cd0 100644
--- a/window/window/src/main/java/androidx/window/core/ConsumerAdapter.kt
+++ b/window/window/src/main/java/androidx/window/core/ConsumerAdapter.kt
@@ -18,6 +18,7 @@
import android.annotation.SuppressLint
import android.app.Activity
+import android.content.Context
import androidx.annotation.CheckResult
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
@@ -84,6 +85,61 @@
}
}
+ @CheckResult
+ fun <T : Any> createSubscriptionNoActivity(
+ obj: Any,
+ clazz: KClass<T>,
+ addMethodName: String,
+ removeMethodName: String,
+ consumer: (T) -> Unit
+ ): Subscription {
+ val javaConsumer = buildConsumer(clazz, consumer)
+ obj.javaClass.getMethod(addMethodName, unsafeConsumerClass())
+ .invoke(obj, javaConsumer)
+ val removeMethod = obj.javaClass.getMethod(removeMethodName, unsafeConsumerClass())
+ return object : Subscription {
+ override fun dispose() {
+ removeMethod.invoke(obj, javaConsumer)
+ }
+ }
+ }
+
+ @CheckResult
+ fun <T : Any> createSubscription(
+ obj: Any,
+ clazz: KClass<T>,
+ addMethodName: String,
+ removeMethodName: String,
+ context: Context,
+ consumer: (T) -> Unit
+ ): Subscription {
+ val javaConsumer = buildConsumer(clazz, consumer)
+ obj.javaClass.getMethod(addMethodName, Context::class.java, unsafeConsumerClass())
+ .invoke(obj, context, javaConsumer)
+ val removeMethod = obj.javaClass.getMethod(removeMethodName, unsafeConsumerClass())
+ return object : Subscription {
+ override fun dispose() {
+ removeMethod.invoke(obj, javaConsumer)
+ }
+ }
+ }
+
+ /**
+ * Similar to {@link #createSubscription} but without needing to provide
+ * a {@code removeMethodName} due to it being handled on the extensions side
+ */
+ fun <T : Any> createConsumer(
+ obj: Any,
+ clazz: KClass<T>,
+ addMethodName: String,
+ activity: Activity,
+ consumer: (T) -> Unit
+ ) {
+ val javaConsumer = buildConsumer(clazz, consumer)
+ obj.javaClass.getMethod(addMethodName, Activity::class.java, unsafeConsumerClass())
+ .invoke(obj, activity, javaConsumer)
+ }
+
private class ConsumerHandler<T : Any>(
private val clazz: KClass<T>,
private val consumer: (T) -> Unit
diff --git a/window/window/src/main/java/androidx/window/embedding/ActivityRule.kt b/window/window/src/main/java/androidx/window/embedding/ActivityRule.kt
index d38b78d..0aa0f09 100644
--- a/window/window/src/main/java/androidx/window/embedding/ActivityRule.kt
+++ b/window/window/src/main/java/androidx/window/embedding/ActivityRule.kt
@@ -21,6 +21,7 @@
* [SplitPairRule].
*/
class ActivityRule internal constructor(
+ tag: String?,
/**
* Filters used to choose when to apply this rule. The rule will be applied if any one of the
* provided filters matches.
@@ -32,7 +33,7 @@
* activity that blocks all user interactions, like a warning dialog.
*/
val alwaysExpand: Boolean = false
-) : EmbeddingRule() {
+) : EmbeddingRule(tag) {
/**
* Builder for [ActivityRule].
@@ -40,8 +41,9 @@
* @param filters See [ActivityRule.filters].
*/
class Builder(
- private val filters: Set<ActivityFilter>
+ private val filters: Set<ActivityFilter>,
) {
+ private var tag: String? = null
private var alwaysExpand: Boolean = false
/**
@@ -51,7 +53,11 @@
fun setAlwaysExpand(alwaysExpand: Boolean): Builder =
apply { this.alwaysExpand = alwaysExpand }
- fun build() = ActivityRule(filters, alwaysExpand)
+ /** @see ActivityRule.tag */
+ fun setTag(tag: String): Builder =
+ apply { this.tag = tag }
+
+ fun build() = ActivityRule(tag, filters, alwaysExpand)
}
/**
@@ -59,16 +65,14 @@
* @see filters
*/
internal operator fun plus(filter: ActivityFilter): ActivityRule {
- return ActivityRule(
- filters + filter,
- alwaysExpand
- )
+ return ActivityRule(tag, filters + filter, alwaysExpand)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ActivityRule) return false
+ if (!super.equals(other)) return false
if (filters != other.filters) return false
if (alwaysExpand != other.alwaysExpand) return false
@@ -76,8 +80,16 @@
}
override fun hashCode(): Int {
- var result = filters.hashCode()
+ var result = super.hashCode()
+ result = 31 * result + filters.hashCode()
result = 31 * result + alwaysExpand.hashCode()
return result
}
-}
\ No newline at end of file
+
+ override fun toString(): String {
+ return "ActivityRule:{" +
+ "tag={$tag}," +
+ "filters={$filters}, " +
+ "alwaysExpand={$alwaysExpand}}"
+ }
+}
diff --git a/window/window/src/main/java/androidx/window/embedding/ActivityStack.kt b/window/window/src/main/java/androidx/window/embedding/ActivityStack.kt
index bd90e21..dde5517 100644
--- a/window/window/src/main/java/androidx/window/embedding/ActivityStack.kt
+++ b/window/window/src/main/java/androidx/window/embedding/ActivityStack.kt
@@ -69,11 +69,9 @@
return result
}
- override fun toString(): String {
- return buildString {
- append("ActivityStack{")
- append("activitiesInProcess=$activitiesInProcess")
- append("isEmpty=$isEmpty}")
- }
- }
-}
\ No newline at end of file
+ override fun toString(): String =
+ "ActivityStack{" +
+ "activitiesInProcess=$activitiesInProcess" +
+ ", isEmpty=$isEmpty" +
+ "}"
+}
diff --git a/window/window/src/main/java/androidx/window/embedding/EmbeddingAdapter.kt b/window/window/src/main/java/androidx/window/embedding/EmbeddingAdapter.kt
index 1700d8d..c96432f 100644
--- a/window/window/src/main/java/androidx/window/embedding/EmbeddingAdapter.kt
+++ b/window/window/src/main/java/androidx/window/embedding/EmbeddingAdapter.kt
@@ -16,9 +16,13 @@
package androidx.window.embedding
+import android.util.Pair as AndroidPair
import androidx.window.extensions.embedding.ActivityRule as OEMActivityRule
import androidx.window.extensions.embedding.ActivityRule.Builder as ActivityRuleBuilder
import androidx.window.extensions.embedding.EmbeddingRule as OEMEmbeddingRule
+import androidx.window.extensions.embedding.SplitAttributes as OEMSplitAttributes
+import androidx.window.extensions.embedding.SplitAttributes.SplitType as OEMSplitType
+import androidx.window.extensions.embedding.SplitAttributesCalculatorParams as OEMSplitAttributesCalculatorParams
import androidx.window.extensions.embedding.SplitInfo as OEMSplitInfo
import androidx.window.extensions.embedding.SplitPairRule as OEMSplitPairRule
import androidx.window.extensions.embedding.SplitPairRule.Builder as SplitPairRuleBuilder
@@ -28,9 +32,24 @@
import android.app.Activity
import android.content.Context
import android.content.Intent
+import android.util.LayoutDirection
import android.view.WindowMetrics
+import androidx.window.core.ExtensionsUtil
import androidx.window.core.PredicateAdapter
-import androidx.window.extensions.WindowExtensionsProvider
+import androidx.window.embedding.SplitAttributes.LayoutDirection.Companion.BOTTOM_TO_TOP
+import androidx.window.embedding.SplitAttributes.LayoutDirection.Companion.LEFT_TO_RIGHT
+import androidx.window.embedding.SplitAttributes.LayoutDirection.Companion.LOCALE
+import androidx.window.embedding.SplitAttributes.LayoutDirection.Companion.RIGHT_TO_LEFT
+import androidx.window.embedding.SplitAttributes.LayoutDirection.Companion.TOP_TO_BOTTOM
+import androidx.window.embedding.SplitAttributes.SplitType
+import androidx.window.extensions.WindowExtensions
+import androidx.window.extensions.core.util.function.Function
+import androidx.window.extensions.core.util.function.Predicate
+import androidx.window.extensions.embedding.SplitPairRule.FINISH_ADJACENT
+import androidx.window.extensions.embedding.SplitPairRule.FINISH_ALWAYS
+import androidx.window.extensions.embedding.SplitPairRule.FINISH_NEVER
+import androidx.window.layout.WindowMetricsCalculator
+import androidx.window.layout.adapter.extensions.ExtensionsWindowLayoutInfoAdapter
/**
* Adapter class that translates data classes between Extension and Jetpack interfaces.
@@ -38,9 +57,11 @@
internal class EmbeddingAdapter(
private val predicateAdapter: PredicateAdapter
) {
+ private val vendorApiLevel = ExtensionsUtil.safeVendorApiLevel
+ private val vendorApiLevel1Impl = VendorApiLevel1Impl(predicateAdapter)
fun translate(splitInfoList: List<OEMSplitInfo>): List<SplitInfo> {
- return splitInfoList.map(::translate)
+ return splitInfoList.map(this::translate)
}
private fun translate(splitInfo: OEMSplitInfo): SplitInfo {
@@ -66,125 +87,240 @@
secondaryActivityStack.activities,
isSecondaryStackEmpty
)
- return SplitInfo(primaryFragment, secondaryFragment, splitInfo.splitRatio)
- }
- @SuppressLint("ClassVerificationFailure", "NewApi")
- private fun translateActivityPairPredicates(splitPairFilters: Set<SplitPairFilter>): Any {
- return predicateAdapter.buildPairPredicate(
- Activity::class,
- Activity::class
- ) { first: Activity, second: Activity ->
- splitPairFilters.any { filter -> filter.matchesActivityPair(first, second) }
+ val splitAttributes = if (vendorApiLevel >= WindowExtensions.VENDOR_API_LEVEL_2) {
+ translate(splitInfo.splitAttributes)
+ } else {
+ vendorApiLevel1Impl.getSplitAttributesCompat(splitInfo)
}
+ return SplitInfo(primaryFragment, secondaryFragment, splitAttributes)
}
- @SuppressLint("ClassVerificationFailure", "NewApi")
- private fun translateActivityIntentPredicates(splitPairFilters: Set<SplitPairFilter>): Any {
- return predicateAdapter.buildPairPredicate(
- Activity::class,
- Intent::class
- ) { first, second ->
- splitPairFilters.any { filter -> filter.matchesActivityIntentPair(first, second) }
+ private fun translate(splitAttributes: OEMSplitAttributes): SplitAttributes =
+ SplitAttributes.Builder()
+ .setSplitType(translate(splitAttributes.splitType))
+ .setLayoutDirection(
+ when (val layoutDirection = splitAttributes.layoutDirection) {
+ OEMSplitAttributes.LayoutDirection.LEFT_TO_RIGHT -> LEFT_TO_RIGHT
+ OEMSplitAttributes.LayoutDirection.RIGHT_TO_LEFT -> RIGHT_TO_LEFT
+ OEMSplitAttributes.LayoutDirection.LOCALE -> LOCALE
+ OEMSplitAttributes.LayoutDirection.TOP_TO_BOTTOM -> TOP_TO_BOTTOM
+ OEMSplitAttributes.LayoutDirection.BOTTOM_TO_TOP -> BOTTOM_TO_TOP
+ else -> throw IllegalArgumentException(
+ "Unknown layout direction: $layoutDirection"
+ )
+ }
+ )
+ .setAnimationBackgroundColor(splitAttributes.animationBackgroundColor)
+ .build()
+
+ private fun translate(splitType: OEMSplitType): SplitType =
+ when (splitType) {
+ is OEMSplitType.RatioSplitType -> translate(splitType)
+ is OEMSplitType.ExpandContainersSplitType -> SplitType.expandContainers()
+ is OEMSplitType.HingeSplitType -> translate(splitType)
+ else -> throw IllegalArgumentException("Unsupported split type: $splitType")
}
- }
- @SuppressLint("ClassVerificationFailure", "NewApi")
- private fun translateParentMetricsPredicate(context: Context, splitRule: SplitRule): Any {
- return predicateAdapter.buildPredicate(WindowMetrics::class) { windowMetrics ->
- splitRule.checkParentMetrics(context, windowMetrics)
+ private fun translate(hinge: OEMSplitType.HingeSplitType): SplitType.HingeSplitType =
+ SplitType.splitByHinge(
+ when (val splitType = hinge.fallbackSplitType) {
+ is OEMSplitType.ExpandContainersSplitType -> SplitType.expandContainers()
+ is OEMSplitType.RatioSplitType -> translate(splitType)
+ else -> throw IllegalArgumentException("Unsupported split type: $splitType")
+ }
+ )
+
+ private fun translate(splitRatio: OEMSplitType.RatioSplitType): SplitType.RatioSplitType =
+ SplitType.ratio(splitRatio.ratio)
+
+ fun translateSplitAttributesCalculator(
+ calculator: (SplitAttributesCalculatorParams) -> SplitAttributes
+ ): Function<OEMSplitAttributesCalculatorParams, OEMSplitAttributes> = Function { oemParams ->
+ translateSplitAttributes(calculator.invoke(translate(oemParams)))
}
+
+ @SuppressLint("NewApi")
+ fun translate(
+ params: OEMSplitAttributesCalculatorParams
+ ): SplitAttributesCalculatorParams = let {
+ val taskWindowMetrics = params.parentWindowMetrics
+ val taskConfiguration = params.parentConfiguration
+ val windowLayoutInfo = params.parentWindowLayoutInfo
+ val defaultSplitAttributes = params.defaultSplitAttributes
+ val areDefaultConstraintsSatisfied = params.areDefaultConstraintsSatisfied()
+ val splitRuleTag = params.splitRuleTag
+ val windowMetrics = WindowMetricsCalculator.translateWindowMetrics(taskWindowMetrics)
+
+ SplitAttributesCalculatorParams(
+ windowMetrics,
+ taskConfiguration,
+ ExtensionsWindowLayoutInfoAdapter.translate(windowMetrics, windowLayoutInfo),
+ translate(defaultSplitAttributes),
+ areDefaultConstraintsSatisfied,
+ splitRuleTag,
+ )
}
- @SuppressLint("ClassVerificationFailure", "NewApi")
- private fun translateActivityPredicates(activityFilters: Set<ActivityFilter>): Any {
- return predicateAdapter.buildPredicate(Activity::class) { activity ->
- activityFilters.any { filter -> filter.matchesActivity(activity) }
- }
- }
-
- @SuppressLint("ClassVerificationFailure", "NewApi")
- private fun translateIntentPredicates(activityFilters: Set<ActivityFilter>): Any {
- return predicateAdapter.buildPredicate(Intent::class) { intent ->
- activityFilters.any { filter -> filter.matchesIntent(intent) }
- }
- }
-
- @SuppressLint("WrongConstant") // Converting from Jetpack to Extensions constants
private fun translateSplitPairRule(
context: Context,
rule: SplitPairRule,
predicateClass: Class<*>
): OEMSplitPairRule {
- val builder = SplitPairRuleBuilder::class.java.getConstructor(
- predicateClass,
- predicateClass,
- predicateClass
- ).newInstance(
- translateActivityPairPredicates(rule.filters),
- translateActivityIntentPredicates(rule.filters),
- translateParentMetricsPredicate(context, rule)
- )
- .setSplitRatio(rule.splitRatio)
- .setLayoutDirection(rule.layoutDirection)
- .setShouldClearTop(rule.clearTop)
- .setFinishPrimaryWithSecondary(rule.finishPrimaryWithSecondary)
- .setFinishSecondaryWithPrimary(rule.finishSecondaryWithPrimary)
- return builder.build()
+ if (vendorApiLevel < WindowExtensions.VENDOR_API_LEVEL_2) {
+ return vendorApiLevel1Impl.translateSplitPairRuleCompat(context, rule, predicateClass)
+ } else {
+ val activitiesPairPredicate =
+ Predicate<AndroidPair<Activity, Activity>> { activitiesPair ->
+ rule.filters.any { filter ->
+ filter.matchesActivityPair(activitiesPair.first, activitiesPair.second)
+ }
+ }
+ val activityIntentPredicate =
+ Predicate<AndroidPair<Activity, Intent>> { activityIntentPair ->
+ rule.filters.any { filter ->
+ filter.matchesActivityIntentPair(
+ activityIntentPair.first,
+ activityIntentPair.second
+ )
+ }
+ }
+ val windowMetricsPredicate = Predicate<WindowMetrics> { windowMetrics ->
+ rule.checkParentMetrics(context, windowMetrics)
+ }
+ val tag = rule.tag
+ val builder = SplitPairRuleBuilder(
+ activitiesPairPredicate,
+ activityIntentPredicate,
+ windowMetricsPredicate,
+ )
+ .setDefaultSplitAttributes(translateSplitAttributes(rule.defaultSplitAttributes))
+ .setFinishPrimaryWithSecondary(
+ translateFinishBehavior(rule.finishPrimaryWithSecondary)
+ ).setFinishSecondaryWithPrimary(
+ translateFinishBehavior(rule.finishSecondaryWithPrimary)
+ ).setShouldClearTop(rule.clearTop)
+
+ if (tag != null) {
+ builder.setTag(tag)
+ }
+ return builder.build()
+ }
}
- @SuppressLint("WrongConstant") // Converting from Jetpack to Extensions constants
+ private fun translateSplitAttributes(splitAttributes: SplitAttributes): OEMSplitAttributes {
+ require(vendorApiLevel >= WindowExtensions.VENDOR_API_LEVEL_2)
+ // To workaround the "unused" error in ktlint. It is necessary to translate SplitAttributes
+ // from WM Jetpack version to WM extension version.
+ return androidx.window.extensions.embedding.SplitAttributes.Builder()
+ .setSplitType(translateSplitType(splitAttributes.splitType))
+ .setLayoutDirection(
+ when (splitAttributes.layoutDirection) {
+ LOCALE -> OEMSplitAttributes.LayoutDirection.LOCALE
+ LEFT_TO_RIGHT -> OEMSplitAttributes.LayoutDirection.LEFT_TO_RIGHT
+ RIGHT_TO_LEFT -> OEMSplitAttributes.LayoutDirection.RIGHT_TO_LEFT
+ TOP_TO_BOTTOM -> OEMSplitAttributes.LayoutDirection.TOP_TO_BOTTOM
+ BOTTOM_TO_TOP -> OEMSplitAttributes.LayoutDirection.BOTTOM_TO_TOP
+ else -> throw IllegalArgumentException("Unsupported layoutDirection:" +
+ "$splitAttributes.layoutDirection"
+ )
+ }
+ )
+ .setAnimationBackgroundColor(splitAttributes.animationBackgroundColor)
+ .build()
+ }
+
+ private fun translateSplitType(splitType: SplitType): OEMSplitType {
+ require(vendorApiLevel >= WindowExtensions.VENDOR_API_LEVEL_2)
+ return when (splitType) {
+ is SplitType.HingeSplitType -> translateHinge(splitType)
+ is SplitType.ExpandContainersSplitType -> OEMSplitType.ExpandContainersSplitType()
+ is SplitType.RatioSplitType -> translateRatio(splitType)
+ else -> throw IllegalArgumentException("Unsupported splitType: $splitType")
+ }
+ }
+
+ private fun translateHinge(hinge: SplitType.HingeSplitType): OEMSplitType.HingeSplitType =
+ OEMSplitType.HingeSplitType(
+ when (val splitType = hinge.fallbackSplitType) {
+ is SplitType.ExpandContainersSplitType -> OEMSplitType.ExpandContainersSplitType()
+ is SplitType.RatioSplitType -> translateRatio(splitType)
+ else -> throw IllegalArgumentException("Unsupported splitType: $splitType")
+ }
+ )
+
+ private fun translateRatio(splitRatio: SplitType.RatioSplitType): OEMSplitType.RatioSplitType =
+ OEMSplitType.RatioSplitType(splitRatio.ratio)
+
private fun translateSplitPlaceholderRule(
context: Context,
rule: SplitPlaceholderRule,
predicateClass: Class<*>
): OEMSplitPlaceholderRule {
- val builder = SplitPlaceholderRuleBuilder::class.java.getConstructor(
- Intent::class.java,
- predicateClass,
- predicateClass,
- predicateClass
- ).newInstance(
- rule.placeholderIntent,
- translateActivityPredicates(rule.filters),
- translateIntentPredicates(rule.filters),
- translateParentMetricsPredicate(context, rule)
- )
- .setSplitRatio(rule.splitRatio)
- .setLayoutDirection(rule.layoutDirection)
- .setSticky(rule.isSticky)
- .safeSetFinishPrimaryWithPlaceholder(rule.finishPrimaryWithPlaceholder)
- return builder.build()
- }
-
- @Suppress("DEPRECATION")
- // setFinishPrimaryWithSecondary is to be deprecated but we want to make a safe fallback
- // behavior here for compatibility reason.
- // Suppressing deprecation warning to prevent breaking build.
- private fun SplitPlaceholderRuleBuilder.safeSetFinishPrimaryWithPlaceholder(
- behavior: @SplitPlaceholderRule.SplitPlaceholderFinishBehavior Int
- ): SplitPlaceholderRuleBuilder {
- var extensionApiLevel: Int = WindowExtensionsProvider.getWindowExtensions().vendorApiLevel
- return if (extensionApiLevel >= 2) {
- setFinishPrimaryWithPlaceholder(behavior)
+ if (vendorApiLevel < WindowExtensions.VENDOR_API_LEVEL_2) {
+ return vendorApiLevel1Impl.translateSplitPlaceholderRuleCompat(
+ context,
+ rule,
+ predicateClass
+ )
} else {
- setFinishPrimaryWithSecondary(behavior)
+ val activityPredicate = Predicate<Activity> { activity ->
+ rule.filters.any { filter -> filter.matchesActivity(activity) }
+ }
+ val intentPredicate = Predicate<Intent> { intent ->
+ rule.filters.any { filter -> filter.matchesIntent(intent) }
+ }
+ val windowMetricsPredicate = Predicate<WindowMetrics> { windowMetrics ->
+ rule.checkParentMetrics(context, windowMetrics)
+ }
+ val tag = rule.tag
+ val builder = SplitPlaceholderRuleBuilder(
+ rule.placeholderIntent,
+ activityPredicate,
+ intentPredicate,
+ windowMetricsPredicate
+ )
+ .setSticky(rule.isSticky)
+ .setDefaultSplitAttributes(translateSplitAttributes(rule.defaultSplitAttributes))
+ .setFinishPrimaryWithPlaceholder(
+ translateFinishBehavior(rule.finishPrimaryWithPlaceholder)
+ )
+ if (tag != null) {
+ builder.setTag(tag)
+ }
+ return builder.build()
}
}
+ fun translateFinishBehavior(behavior: SplitRule.FinishBehavior): Int =
+ when (behavior) {
+ SplitRule.FinishBehavior.NEVER -> FINISH_NEVER
+ SplitRule.FinishBehavior.ALWAYS -> FINISH_ALWAYS
+ SplitRule.FinishBehavior.ADJACENT -> FINISH_ADJACENT
+ else -> throw IllegalArgumentException("Unknown finish behavior:$behavior")
+ }
+
private fun translateActivityRule(
rule: ActivityRule,
predicateClass: Class<*>
): OEMActivityRule {
- return ActivityRuleBuilder::class.java.getConstructor(
- predicateClass,
- predicateClass
- ).newInstance(
- translateActivityPredicates(rule.filters),
- translateIntentPredicates(rule.filters)
- )
- .setShouldAlwaysExpand(rule.alwaysExpand)
- .build()
+ if (vendorApiLevel < WindowExtensions.VENDOR_API_LEVEL_2) {
+ return vendorApiLevel1Impl.translateActivityRuleCompat(rule, predicateClass)
+ } else {
+ val activityPredicate = Predicate<Activity> { activity ->
+ rule.filters.any { filter -> filter.matchesActivity(activity) }
+ }
+ val intentPredicate = Predicate<Intent> { intent ->
+ rule.filters.any { filter -> filter.matchesIntent(intent) }
+ }
+ val builder = ActivityRuleBuilder(activityPredicate, intentPredicate)
+ .setShouldAlwaysExpand(rule.alwaysExpand)
+ val tag = rule.tag
+ if (tag != null) {
+ builder.setTag(tag)
+ }
+ return builder.build()
+ }
}
fun translate(context: Context, rules: Set<EmbeddingRule>): Set<OEMEmbeddingRule> {
@@ -199,4 +335,164 @@
}
}.toSet()
}
+
+ /**
+ * Provides backward compatibility for Window extensions with
+ * [WindowExtensions.VENDOR_API_LEVEL_1]
+ * @see WindowExtensions.getVendorApiLevel
+ */
+ // Suppress deprecation because this object is to provide backward compatibility.
+ @Suppress("DEPRECATION")
+ private inner class VendorApiLevel1Impl(val predicateAdapter: PredicateAdapter) {
+ /**
+ * Obtains [SplitAttributes] from [OEMSplitInfo] with [WindowExtensions.VENDOR_API_LEVEL_1]
+ */
+ fun getSplitAttributesCompat(splitInfo: OEMSplitInfo): SplitAttributes =
+ SplitAttributes.Builder()
+ .setSplitType(SplitType.buildSplitTypeFromValue(splitInfo.splitRatio))
+ .setLayoutDirection(LOCALE)
+ .build()
+
+ fun translateActivityRuleCompat(
+ rule: ActivityRule,
+ predicateClass: Class<*>
+ ): OEMActivityRule = ActivityRuleBuilder::class.java.getConstructor(
+ predicateClass,
+ predicateClass
+ ).newInstance(
+ translateActivityPredicates(rule.filters),
+ translateIntentPredicates(rule.filters)
+ )
+ .setShouldAlwaysExpand(rule.alwaysExpand)
+ .build()
+
+ fun translateSplitPlaceholderRuleCompat(
+ context: Context,
+ rule: SplitPlaceholderRule,
+ predicateClass: Class<*>
+ ): OEMSplitPlaceholderRule = SplitPlaceholderRuleBuilder::class.java.getConstructor(
+ Intent::class.java,
+ predicateClass,
+ predicateClass,
+ predicateClass
+ ).newInstance(
+ rule.placeholderIntent,
+ translateActivityPredicates(rule.filters),
+ translateIntentPredicates(rule.filters),
+ translateParentMetricsPredicate(context, rule)
+ )
+ .setSticky(rule.isSticky)
+ .setFinishPrimaryWithSecondary(
+ translateFinishBehavior(rule.finishPrimaryWithPlaceholder)
+ ).setDefaultSplitAttributesCompat(rule.defaultSplitAttributes)
+ .build()
+
+ private fun SplitPlaceholderRuleBuilder.setDefaultSplitAttributesCompat(
+ defaultAttrs: SplitAttributes,
+ ): SplitPlaceholderRuleBuilder = apply {
+ val (splitRatio, layoutDirection) = translateSplitAttributesCompatInternal(defaultAttrs)
+ // #setDefaultAttributes or SplitAttributes ctr weren't supported.
+ setSplitRatio(splitRatio)
+ setLayoutDirection(layoutDirection)
+ }
+
+ fun translateSplitPairRuleCompat(
+ context: Context,
+ rule: SplitPairRule,
+ predicateClass: Class<*>
+ ): OEMSplitPairRule = SplitPairRuleBuilder::class.java.getConstructor(
+ predicateClass,
+ predicateClass,
+ predicateClass,
+ ).newInstance(
+ translateActivityPairPredicates(rule.filters),
+ translateActivityIntentPredicates(rule.filters),
+ translateParentMetricsPredicate(context, rule)
+ )
+ .setDefaultSplitAttributesCompat(rule.defaultSplitAttributes)
+ .setShouldClearTop(rule.clearTop)
+ .setFinishPrimaryWithSecondary(
+ translateFinishBehavior(rule.finishPrimaryWithSecondary)
+ ).setFinishSecondaryWithPrimary(
+ translateFinishBehavior(rule.finishSecondaryWithPrimary)
+ ).build()
+
+ @SuppressLint("ClassVerificationFailure", "NewApi")
+ private fun translateActivityPairPredicates(splitPairFilters: Set<SplitPairFilter>): Any {
+ return predicateAdapter.buildPairPredicate(
+ Activity::class,
+ Activity::class
+ ) { first: Activity, second: Activity ->
+ splitPairFilters.any { filter -> filter.matchesActivityPair(first, second) }
+ }
+ }
+
+ @SuppressLint("ClassVerificationFailure", "NewApi")
+ private fun translateActivityIntentPredicates(splitPairFilters: Set<SplitPairFilter>): Any {
+ return predicateAdapter.buildPairPredicate(
+ Activity::class,
+ Intent::class
+ ) { first, second ->
+ splitPairFilters.any { filter -> filter.matchesActivityIntentPair(first, second) }
+ }
+ }
+
+ private fun SplitPairRuleBuilder.setDefaultSplitAttributesCompat(
+ defaultAttrs: SplitAttributes,
+ ): SplitPairRuleBuilder = apply {
+ val (splitRatio, layoutDirection) = translateSplitAttributesCompatInternal(defaultAttrs)
+ setSplitRatio(splitRatio)
+ setLayoutDirection(layoutDirection)
+ }
+
+ private fun translateSplitAttributesCompatInternal(
+ attrs: SplitAttributes
+ ): Pair<Float, Int> = // Use a (Float, Integer) pair since SplitAttributes weren't supported
+ if (!isSplitAttributesSupported(attrs)) {
+ // Fallback to expand the secondary container if the SplitAttributes are not
+ // supported.
+ Pair(0.0f, LayoutDirection.LOCALE)
+ } else {
+ Pair(
+ attrs.splitType.value,
+ when (attrs.layoutDirection) {
+ // Legacy LayoutDirection uses LayoutDirection constants in framework APIs.
+ LOCALE -> LayoutDirection.LOCALE
+ LEFT_TO_RIGHT -> LayoutDirection.LTR
+ RIGHT_TO_LEFT -> LayoutDirection.RTL
+ else -> throw IllegalStateException("Unsupported layout direction must be" +
+ " covered in @isSplitAttributesSupported!")
+ }
+ )
+ }
+
+ /**
+ * Returns `true` if `attrs` is compatible with [WindowExtensions.VENDOR_API_LEVEL_1] and
+ * doesn't use the new features introduced in [WindowExtensions.VENDOR_API_LEVEL_2] or
+ * higher.
+ */
+ private fun isSplitAttributesSupported(attrs: SplitAttributes) =
+ attrs.splitType is SplitType.RatioSplitType &&
+ attrs.layoutDirection in arrayOf(LEFT_TO_RIGHT, RIGHT_TO_LEFT, LOCALE)
+
+ @SuppressLint("ClassVerificationFailure", "NewApi")
+ private fun translateActivityPredicates(activityFilters: Set<ActivityFilter>): Any {
+ return predicateAdapter.buildPredicate(Activity::class) { activity ->
+ activityFilters.any { filter -> filter.matchesActivity(activity) }
+ }
+ }
+
+ @SuppressLint("ClassVerificationFailure", "NewApi")
+ private fun translateIntentPredicates(activityFilters: Set<ActivityFilter>): Any {
+ return predicateAdapter.buildPredicate(Intent::class) { intent ->
+ activityFilters.any { filter -> filter.matchesIntent(intent) }
+ }
+ }
+
+ @SuppressLint("ClassVerificationFailure", "NewApi")
+ private fun translateParentMetricsPredicate(context: Context, splitRule: SplitRule): Any =
+ predicateAdapter.buildPredicate(WindowMetrics::class) { windowMetrics ->
+ splitRule.checkParentMetrics(context, windowMetrics)
+ }
+ }
}
diff --git a/window/window/src/main/java/androidx/window/embedding/EmbeddingAspectRatio.kt b/window/window/src/main/java/androidx/window/embedding/EmbeddingAspectRatio.kt
index 643e6fb..936eaea 100644
--- a/window/window/src/main/java/androidx/window/embedding/EmbeddingAspectRatio.kt
+++ b/window/window/src/main/java/androidx/window/embedding/EmbeddingAspectRatio.kt
@@ -19,7 +19,7 @@
import androidx.annotation.FloatRange
/**
- * The aspect ratio of the parent window bounds to allow embedding with the rule.
+ * The aspect ratio of the parent window bound to allow embedding with the rule.
*
* @see SplitRule.maxAspectRatioInPortrait
* @see SplitRule.maxAspectRatioInLandscape
diff --git a/window/window/src/main/java/androidx/window/embedding/EmbeddingBackend.kt b/window/window/src/main/java/androidx/window/embedding/EmbeddingBackend.kt
index 539e69d..77ed5ef 100644
--- a/window/window/src/main/java/androidx/window/embedding/EmbeddingBackend.kt
+++ b/window/window/src/main/java/androidx/window/embedding/EmbeddingBackend.kt
@@ -43,4 +43,12 @@
fun isSplitSupported(): Boolean
fun isActivityEmbedded(activity: Activity): Boolean
+
+ fun setSplitAttributesCalculator(
+ calculator: (SplitAttributesCalculatorParams) -> SplitAttributes
+ )
+
+ fun clearSplitAttributesCalculator()
+
+ fun isSplitAttributesCalculatorSupported(): Boolean
}
\ No newline at end of file
diff --git a/window/window/src/main/java/androidx/window/embedding/EmbeddingCompat.kt b/window/window/src/main/java/androidx/window/embedding/EmbeddingCompat.kt
index ea701a1..0109ecf 100644
--- a/window/window/src/main/java/androidx/window/embedding/EmbeddingCompat.kt
+++ b/window/window/src/main/java/androidx/window/embedding/EmbeddingCompat.kt
@@ -21,8 +21,12 @@
import android.content.Context
import android.util.Log
import androidx.window.core.ConsumerAdapter
+import androidx.window.core.ExtensionsUtil
import androidx.window.embedding.EmbeddingInterfaceCompat.EmbeddingCallbackInterface
+import androidx.window.extensions.WindowExtensions
+import androidx.window.extensions.WindowExtensions.VENDOR_API_LEVEL_2
import androidx.window.extensions.WindowExtensionsProvider
+import androidx.window.extensions.core.util.function.Consumer
import androidx.window.extensions.embedding.ActivityEmbeddingComponent
import java.lang.reflect.Proxy
@@ -38,18 +42,40 @@
) : EmbeddingInterfaceCompat {
override fun setRules(rules: Set<EmbeddingRule>) {
+ var hasSplitRule = false
+ for (rule in rules) {
+ if (rule is SplitRule) {
+ hasSplitRule = true
+ break
+ }
+ }
+ if (hasSplitRule && !SplitController.getInstance(applicationContext).isSplitSupported()) {
+ Log.e(
+ TAG, "Cannot set SplitRule because ActivityEmbedding Split is not supported" +
+ " or PROPERTY_ACTIVITY_EMBEDDING_SPLITS_ENABLED is not set."
+ )
+ return
+ }
+
val r = adapter.translate(applicationContext, rules)
embeddingExtension.setEmbeddingRules(r)
}
override fun setEmbeddingCallback(embeddingCallback: EmbeddingCallbackInterface) {
- consumerAdapter.addConsumer(
- embeddingExtension,
- List::class,
- "setSplitInfoCallback"
- ) { values ->
- val splitInfoList = values.filterIsInstance<OEMSplitInfo>()
- embeddingCallback.onSplitInfoChanged(adapter.translate(splitInfoList))
+ if (ExtensionsUtil.safeVendorApiLevel < VENDOR_API_LEVEL_2) {
+ consumerAdapter.addConsumer(
+ embeddingExtension,
+ List::class,
+ "setSplitInfoCallback"
+ ) { values ->
+ val splitInfoList = values.filterIsInstance<OEMSplitInfo>()
+ embeddingCallback.onSplitInfoChanged(adapter.translate(splitInfoList))
+ }
+ } else {
+ val callback = Consumer<List<OEMSplitInfo>> { splitInfoList ->
+ embeddingCallback.onSplitInfoChanged(adapter.translate(splitInfoList))
+ }
+ embeddingExtension.setSplitInfoCallback(callback)
}
}
@@ -57,6 +83,29 @@
return embeddingExtension.isActivityEmbedded(activity)
}
+ override fun setSplitAttributesCalculator(
+ calculator: (SplitAttributesCalculatorParams) -> SplitAttributes
+ ) {
+ if (!isSplitAttributesCalculatorSupported()) {
+ throw UnsupportedOperationException("#setSplitAttributesCalculator is not supported " +
+ "on the device.")
+ }
+ return embeddingExtension.setSplitAttributesCalculator(
+ adapter.translateSplitAttributesCalculator(calculator)
+ )
+ }
+
+ override fun clearSplitAttributesCalculator() {
+ if (!isSplitAttributesCalculatorSupported()) {
+ throw UnsupportedOperationException("#clearSplitAttributesCalculator is not " +
+ "supported on the device.")
+ }
+ return embeddingExtension.clearSplitAttributesCalculator()
+ }
+
+ override fun isSplitAttributesCalculatorSupported(): Boolean =
+ ExtensionsUtil.safeVendorApiLevel >= WindowExtensions.VENDOR_API_LEVEL_2
+
companion object {
const val DEBUG = true
private const val TAG = "EmbeddingCompat"
diff --git a/window/window/src/main/java/androidx/window/embedding/EmbeddingInterfaceCompat.kt b/window/window/src/main/java/androidx/window/embedding/EmbeddingInterfaceCompat.kt
index ff0f50f..8c74aec 100644
--- a/window/window/src/main/java/androidx/window/embedding/EmbeddingInterfaceCompat.kt
+++ b/window/window/src/main/java/androidx/window/embedding/EmbeddingInterfaceCompat.kt
@@ -34,4 +34,12 @@
}
fun isActivityEmbedded(activity: Activity): Boolean
+
+ fun setSplitAttributesCalculator(
+ calculator: (SplitAttributesCalculatorParams) -> SplitAttributes
+ )
+
+ fun clearSplitAttributesCalculator()
+
+ fun isSplitAttributesCalculatorSupported(): Boolean
}
\ No newline at end of file
diff --git a/window/window/src/main/java/androidx/window/embedding/EmbeddingRule.kt b/window/window/src/main/java/androidx/window/embedding/EmbeddingRule.kt
index e3ff7dd..987360f 100644
--- a/window/window/src/main/java/androidx/window/embedding/EmbeddingRule.kt
+++ b/window/window/src/main/java/androidx/window/embedding/EmbeddingRule.kt
@@ -20,4 +20,26 @@
* Base abstract class for activity embedding presentation rules, such as [SplitPairRule] and
* [ActivityRule]. Allows grouping different rule types together when updating.
*/
-abstract class EmbeddingRule internal constructor()
+abstract class EmbeddingRule internal constructor(
+ /**
+ * A unique string to identify this [EmbeddingRule], which defaults to `null`.
+ * The suggested usage is to set the tag in the corresponding rule builder to be able to
+ * differentiate between different rules in the callbacks. For example, it can be used to
+ * compute the right [SplitAttributes] for the right split rule in callback set in
+ * [SplitController.setSplitAttributesCalculator].
+ *
+ * @see androidx.window.embedding.RuleController.addRule
+ */
+ val tag: String?
+) {
+ override fun equals(other: Any?): Boolean {
+ if (this === other) return true
+ if (other !is EmbeddingRule) return false
+
+ return tag == other.tag
+ }
+
+ override fun hashCode(): Int {
+ return tag.hashCode()
+ }
+}
\ No newline at end of file
diff --git a/window/window/src/main/java/androidx/window/embedding/ExtensionEmbeddingBackend.kt b/window/window/src/main/java/androidx/window/embedding/ExtensionEmbeddingBackend.kt
index 7fb48ffc..666b488 100644
--- a/window/window/src/main/java/androidx/window/embedding/ExtensionEmbeddingBackend.kt
+++ b/window/window/src/main/java/androidx/window/embedding/ExtensionEmbeddingBackend.kt
@@ -21,13 +21,13 @@
import android.util.Log
import androidx.annotation.GuardedBy
import androidx.annotation.VisibleForTesting
+import androidx.collection.ArraySet
import androidx.core.util.Consumer
import androidx.window.core.ConsumerAdapter
import androidx.window.core.ExtensionsUtil
import androidx.window.core.PredicateAdapter
import androidx.window.embedding.EmbeddingInterfaceCompat.EmbeddingCallbackInterface
import java.util.concurrent.CopyOnWriteArrayList
-import java.util.concurrent.CopyOnWriteArraySet
import java.util.concurrent.Executor
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
@@ -116,30 +116,109 @@
}
}
- private val rules: CopyOnWriteArraySet<EmbeddingRule> =
- CopyOnWriteArraySet<EmbeddingRule>()
+ @GuardedBy("globalLock")
+ private val ruleTracker = RuleTracker()
+ @GuardedBy("globalLock")
override fun getRules(): Set<EmbeddingRule> {
- return rules
+ globalLock.withLock { return ruleTracker.splitRules }
}
+ @GuardedBy("globalLock")
override fun setRules(rules: Set<EmbeddingRule>) {
- this.rules.clear()
- this.rules.addAll(rules)
- embeddingExtension?.setRules(this.rules)
- }
-
- override fun addRule(rule: EmbeddingRule) {
- if (!rules.contains(rule)) {
- rules.add(rule)
- embeddingExtension?.setRules(rules)
+ globalLock.withLock {
+ ruleTracker.setRules(rules)
+ embeddingExtension?.setRules(getRules())
}
}
+ @GuardedBy("globalLock")
+ override fun addRule(rule: EmbeddingRule) {
+ globalLock.withLock {
+ if (rule !in ruleTracker) {
+ ruleTracker.addOrUpdateRule(rule)
+ embeddingExtension?.setRules(getRules())
+ }
+ }
+ }
+
+ @GuardedBy("globalLock")
override fun removeRule(rule: EmbeddingRule) {
- if (rules.contains(rule)) {
- rules.remove(rule)
- embeddingExtension?.setRules(rules)
+ globalLock.withLock {
+ if (rule in ruleTracker) {
+ ruleTracker.removeRule(rule)
+ embeddingExtension?.setRules(getRules())
+ }
+ }
+ }
+
+ /**
+ * A helper class to manage the registered [tags][EmbeddingRule.tag] and [rules][EmbeddingRule]
+ * It supports:
+ * - Add a set of [rules][EmbeddingRule] and verify if there's duplicated [EmbeddingRule.tag]
+ * if needed.
+ * - Clears all registered [rules][EmbeddingRule]
+ * - Add a runtime [rule][EmbeddingRule] or update an existing [rule][EmbeddingRule] by
+ * [tag][EmbeddingRule.tag] if the tag has been registered.
+ * - Remove a runtime [rule][EmbeddingRule]
+ */
+ private class RuleTracker {
+ val splitRules = ArraySet<EmbeddingRule>()
+ private val tagRuleMap = HashMap<String, EmbeddingRule>()
+
+ fun setRules(rules: Set<EmbeddingRule>) {
+ clearRules()
+ rules.forEach { rule -> addOrUpdateRule(rule, throwOnDuplicateTag = true) }
+ }
+
+ fun clearRules() {
+ splitRules.clear()
+ tagRuleMap.clear()
+ }
+
+ /**
+ * Adds a rule to [RuleTracker] or update an existing rule if the [tag][EmbeddingRule.tag]
+ * has been registered and `throwOnDuplicateTag` is `false`
+ * @throws IllegalArgumentException if `throwOnDuplicateTag` is `true` and the
+ * [tag][EmbeddingRule.tag] has been registered.
+ */
+ fun addOrUpdateRule(rule: EmbeddingRule, throwOnDuplicateTag: Boolean = false) {
+ if (rule in splitRules) {
+ return
+ }
+ val tag = rule.tag
+ if (tag == null) {
+ splitRules.add(rule)
+ } else if (tagRuleMap.containsKey(tag)) {
+ if (throwOnDuplicateTag) {
+ throw IllegalArgumentException("Duplicated tag: $tag. Tag must be unique " +
+ "among all registered rules")
+ } else {
+ // Update the rule if throwOnDuplicateTag = false
+ val oldRule = tagRuleMap[tag]
+ splitRules.remove(oldRule)
+ tagRuleMap[tag] = rule
+ splitRules.add(rule)
+ }
+ } else {
+ tagRuleMap[tag] = rule
+ splitRules.add(rule)
+ }
+ }
+
+ fun removeRule(rule: EmbeddingRule) {
+ if (rule !in splitRules) {
+ return
+ }
+ splitRules.remove(rule)
+ val tag = rule.tag
+ if (tag != null) {
+ tagRuleMap.remove(rule.tag)
+ }
+ }
+
+ operator fun contains(rule: EmbeddingRule): Boolean {
+ return splitRules.contains(rule)
}
}
@@ -223,4 +302,21 @@
override fun isActivityEmbedded(activity: Activity): Boolean {
return embeddingExtension?.isActivityEmbedded(activity) ?: false
}
+
+ override fun setSplitAttributesCalculator(
+ calculator: (SplitAttributesCalculatorParams) -> SplitAttributes
+ ) {
+ globalLock.withLock {
+ embeddingExtension?.setSplitAttributesCalculator(calculator)
+ }
+ }
+
+ override fun clearSplitAttributesCalculator() {
+ globalLock.withLock {
+ embeddingExtension?.clearSplitAttributesCalculator()
+ }
+ }
+
+ override fun isSplitAttributesCalculatorSupported(): Boolean =
+ embeddingExtension?.isSplitAttributesCalculatorSupported() ?: false
}
\ No newline at end of file
diff --git a/window/window/src/main/java/androidx/window/embedding/RuleController.kt b/window/window/src/main/java/androidx/window/embedding/RuleController.kt
index 867a1a1..17eac14 100644
--- a/window/window/src/main/java/androidx/window/embedding/RuleController.kt
+++ b/window/window/src/main/java/androidx/window/embedding/RuleController.kt
@@ -38,7 +38,8 @@
private val embeddingBackend: EmbeddingBackend = ExtensionEmbeddingBackend
.getInstance(applicationContext)
- // TODO(b/258356512): Make this a coroutine API that returns Flow<Set<EmbeddingRule>>.
+ // TODO(b/258356512): Make this API a make this a coroutine API that returns
+ // Flow<Set<EmbeddingRule>>.
/**
* Returns a copy of the currently registered rules.
*/
@@ -47,11 +48,17 @@
}
/**
- * Registers a new rule. Will be cleared automatically when the process is stopped.
+ * Registers a new rule, or updates an existing rule if the [tag][EmbeddingRule.tag] has been
+ * registered with [RuleController]. Will be cleared automatically when the process is stopped.
*
- * Note that added rules will **not** be applied to any existing split activity
- * container, and will only be used for new split containers created with future activity
- * launches.
+ * Registering a `SplitRule` may fail if the [SplitController.isSplitSupported]
+ * returns `false`. If not supported, it could be either because
+ * [androidx.window.WindowProperties.PROPERTY_ACTIVITY_EMBEDDING_SPLITS_ENABLED] not enabled
+ * in AndroidManifest or the feature not available on the device.
+ *
+ * Note that registering a new rule or updating the existing rule will **not** be applied to any
+ * existing split activity container, and will only be used for new split containers created
+ * with future activity launches.
*
* @param rule new [EmbeddingRule] to register.
*/
@@ -81,6 +88,11 @@
* - [SplitPlaceholderRule.Builder]
* - [ActivityRule.Builder]
*
+ * Registering `SplitRule`s may fail if the [SplitController.isSplitSupported]
+ * returns `false`. If not supported, it could be either because
+ * [androidx.window.WindowProperties.PROPERTY_ACTIVITY_EMBEDDING_SPLITS_ENABLED] not enabled
+ * in AndroidManifest or the feature not available on the device.
+ *
* Note that updating the existing rules will **not** be applied to any existing split activity
* container, and will only be used for new split containers created with future activity
* launches.
diff --git a/window/window/src/main/java/androidx/window/embedding/RuleParser.kt b/window/window/src/main/java/androidx/window/embedding/RuleParser.kt
index 5d3cea3..c3334c0 100644
--- a/window/window/src/main/java/androidx/window/embedding/RuleParser.kt
+++ b/window/window/src/main/java/androidx/window/embedding/RuleParser.kt
@@ -21,14 +21,13 @@
import android.content.Intent
import android.content.res.Resources
import android.content.res.XmlResourceParser
-import android.util.LayoutDirection
import androidx.annotation.XmlRes
-
import androidx.window.R
import androidx.window.embedding.EmbeddingAspectRatio.Companion.buildAspectRatioFromValue
-import androidx.window.embedding.SplitRule.Companion.FINISH_ALWAYS
-import androidx.window.embedding.SplitRule.Companion.FINISH_NEVER
-
+import androidx.window.embedding.SplitAttributes.LayoutDirection.Companion.LOCALE
+import androidx.window.embedding.SplitRule.FinishBehavior.Companion.ALWAYS
+import androidx.window.embedding.SplitRule.FinishBehavior.Companion.NEVER
+import androidx.window.embedding.SplitRule.FinishBehavior.Companion.getFinishBehaviorFromValue
import org.xmlpull.v1.XmlPullParser
/**
@@ -67,14 +66,14 @@
"SplitPairRule" -> {
val splitConfig = parseSplitPairRule(context, parser)
lastSplitPairRule = splitConfig
- rules.add(lastSplitPairRule)
+ rules.addRuleWithDuplicatedTagCheck(lastSplitPairRule)
lastSplitPlaceholderRule = null
lastActivityRule = null
}
"SplitPlaceholderRule" -> {
val placeholderConfig = parseSplitPlaceholderRule(context, parser)
lastSplitPlaceholderRule = placeholderConfig
- rules.add(lastSplitPlaceholderRule)
+ rules.addRuleWithDuplicatedTagCheck(lastSplitPlaceholderRule)
lastActivityRule = null
lastSplitPairRule = null
}
@@ -87,11 +86,11 @@
val splitFilter = parseSplitPairFilter(context, parser)
rules.remove(lastSplitPairRule)
lastSplitPairRule += splitFilter
- rules.add(lastSplitPairRule)
+ rules.addRuleWithDuplicatedTagCheck(lastSplitPairRule)
}
"ActivityRule" -> {
val activityConfig = parseActivityRule(context, parser)
- rules.add(activityConfig)
+ rules.addRuleWithDuplicatedTagCheck(activityConfig)
lastSplitPairRule = null
lastSplitPlaceholderRule = null
lastActivityRule = activityConfig
@@ -106,154 +105,191 @@
if (lastActivityRule != null) {
rules.remove(lastActivityRule)
lastActivityRule += activityFilter
- rules.add(lastActivityRule)
+ rules.addRuleWithDuplicatedTagCheck(lastActivityRule)
} else if (lastSplitPlaceholderRule != null) {
rules.remove(lastSplitPlaceholderRule)
lastSplitPlaceholderRule += activityFilter
- rules.add(lastSplitPlaceholderRule)
+ rules.addRuleWithDuplicatedTagCheck(lastSplitPlaceholderRule)
}
}
}
type = parser.next()
}
-
return rules
}
+ private fun HashSet<EmbeddingRule>.addRuleWithDuplicatedTagCheck(rule: EmbeddingRule) {
+ val tag = rule.tag
+ forEach { addedRule ->
+ if (tag != null && tag == addedRule.tag) {
+ throw IllegalArgumentException("Duplicated tag: $tag for $rule. " +
+ "The tag must be unique in XML rule definition.")
+ }
+ }
+ add(rule)
+ }
+
private fun parseSplitPairRule(
context: Context,
parser: XmlResourceParser
- ): SplitPairRule {
- val ratio: Float
- val minWidthDp: Int
- val minSmallestWidthDp: Int
- val maxAspectRatioInPortrait: Float
- val maxAspectRatioInLandscape: Float
- val layoutDir: Int
- val finishPrimaryWithSecondary: Int
- val finishSecondaryWithPrimary: Int
- val clearTop: Boolean
+ ): SplitPairRule =
context.theme.obtainStyledAttributes(
parser,
R.styleable.SplitPairRule,
0,
0
- ).apply {
- ratio = getFloat(R.styleable.SplitPairRule_splitRatio, 0.5f)
- minWidthDp = getInteger(
+ ).let { typedArray ->
+ val tag = typedArray.getString(R.styleable.SplitPairRule_tag)
+ val ratio = typedArray.getFloat(R.styleable.SplitPairRule_splitRatio, 0.5f)
+ val minWidthDp = typedArray.getInteger(
R.styleable.SplitPairRule_splitMinWidthDp,
SplitRule.SPLIT_MIN_DIMENSION_DP_DEFAULT
)
- minSmallestWidthDp = getInteger(
+ val minHeightDp = typedArray.getInteger(
+ R.styleable.SplitPairRule_splitMinHeightDp,
+ SplitRule.SPLIT_MIN_DIMENSION_DP_DEFAULT
+ )
+ val minSmallestWidthDp = typedArray.getInteger(
R.styleable.SplitPairRule_splitMinSmallestWidthDp,
SplitRule.SPLIT_MIN_DIMENSION_DP_DEFAULT
)
- maxAspectRatioInPortrait = getFloat(
+ val maxAspectRatioInPortrait = typedArray.getFloat(
R.styleable.SplitPairRule_splitMaxAspectRatioInPortrait,
SplitRule.SPLIT_MAX_ASPECT_RATIO_PORTRAIT_DEFAULT.value
)
- maxAspectRatioInLandscape = getFloat(
+ val maxAspectRatioInLandscape = typedArray.getFloat(
R.styleable.SplitPairRule_splitMaxAspectRatioInLandscape,
SplitRule.SPLIT_MAX_ASPECT_RATIO_LANDSCAPE_DEFAULT.value
)
- layoutDir = getInt(
+ val layoutDir = typedArray.getInt(
R.styleable.SplitPairRule_splitLayoutDirection,
- LayoutDirection.LOCALE
+ LOCALE.value
)
- finishPrimaryWithSecondary =
- getInt(R.styleable.SplitPairRule_finishPrimaryWithSecondary, FINISH_NEVER)
- finishSecondaryWithPrimary =
- getInt(R.styleable.SplitPairRule_finishSecondaryWithPrimary, FINISH_ALWAYS)
- clearTop =
- getBoolean(R.styleable.SplitPairRule_clearTop, false)
+ val finishPrimaryWithSecondary = typedArray.getInt(
+ R.styleable.SplitPairRule_finishPrimaryWithSecondary,
+ NEVER.value
+ )
+ val finishSecondaryWithPrimary = typedArray.getInt(
+ R.styleable.SplitPairRule_finishSecondaryWithPrimary,
+ ALWAYS.value
+ )
+ val clearTop = typedArray.getBoolean(R.styleable.SplitPairRule_clearTop, false)
+ val animationBackgroundColor = typedArray.getColor(
+ R.styleable.SplitPairRule_animationBackgroundColor,
+ 0)
+ typedArray.recycle()
+
+ val defaultAttrs = SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.buildSplitTypeFromValue(ratio))
+ .setLayoutDirection(
+ SplitAttributes.LayoutDirection.getLayoutDirectionFromValue(layoutDir)
+ )
+ .setAnimationBackgroundColor(animationBackgroundColor)
+ .build()
+
+ SplitPairRule.Builder(emptySet())
+ .setTag(tag)
+ .setMinWidthDp(minWidthDp)
+ .setMinHeightDp(minHeightDp)
+ .setMinSmallestWidthDp(minSmallestWidthDp)
+ .setMaxAspectRatioInPortrait(buildAspectRatioFromValue(maxAspectRatioInPortrait))
+ .setMaxAspectRatioInLandscape(buildAspectRatioFromValue(maxAspectRatioInLandscape))
+ .setFinishPrimaryWithSecondary(
+ getFinishBehaviorFromValue(finishPrimaryWithSecondary))
+ .setFinishSecondaryWithPrimary(
+ getFinishBehaviorFromValue(finishSecondaryWithPrimary))
+ .setClearTop(clearTop)
+ .setDefaultSplitAttributes(defaultAttrs)
+ .build()
}
- return SplitPairRule.Builder(emptySet())
- .setMinWidthDp(minWidthDp)
- .setMinSmallestWidthDp(minSmallestWidthDp)
- .setMaxAspectRatioInPortrait(buildAspectRatioFromValue(maxAspectRatioInPortrait))
- .setMaxAspectRatioInLandscape(buildAspectRatioFromValue(maxAspectRatioInLandscape))
- .setFinishPrimaryWithSecondary(finishPrimaryWithSecondary)
- .setFinishSecondaryWithPrimary(finishSecondaryWithPrimary)
- .setClearTop(clearTop)
- .setSplitRatio(ratio)
- .setLayoutDirection(layoutDir)
- .build()
- }
private fun parseSplitPlaceholderRule(
context: Context,
parser: XmlResourceParser
- ): SplitPlaceholderRule {
- val placeholderActivityIntentName: String?
- val stickyPlaceholder: Boolean
- val finishPrimaryWithPlaceholder: Int
- val ratio: Float
- val minWidthDp: Int
- val minSmallestWidthDp: Int
- val maxAspectRatioInPortrait: Float
- val maxAspectRatioInLandscape: Float
- val layoutDir: Int
+ ): SplitPlaceholderRule =
context.theme.obtainStyledAttributes(
parser,
R.styleable.SplitPlaceholderRule,
0,
0
- ).apply {
- placeholderActivityIntentName = getString(
+ ).let { typedArray ->
+ val tag = typedArray.getString(R.styleable.SplitPlaceholderRule_tag)
+ val placeholderActivityIntentName = typedArray.getString(
R.styleable.SplitPlaceholderRule_placeholderActivityName
)
- stickyPlaceholder = getBoolean(R.styleable.SplitPlaceholderRule_stickyPlaceholder,
- false)
- finishPrimaryWithPlaceholder =
- getInt(R.styleable.SplitPlaceholderRule_finishPrimaryWithPlaceholder, FINISH_ALWAYS)
- ratio = getFloat(R.styleable.SplitPlaceholderRule_splitRatio, 0.5f)
- minWidthDp = getInteger(
+ val stickyPlaceholder = typedArray.getBoolean(
+ R.styleable.SplitPlaceholderRule_stickyPlaceholder,
+ false
+ )
+ val finishPrimaryWithPlaceholder = typedArray.getInt(
+ R.styleable.SplitPlaceholderRule_finishPrimaryWithPlaceholder,
+ ALWAYS.value
+ )
+ if (finishPrimaryWithPlaceholder == NEVER.value) {
+ throw IllegalArgumentException(
+ "Never is not a valid configuration for Placeholder activities. " +
+ "Please use FINISH_ALWAYS or FINISH_ADJACENT instead or refer to the " +
+ "current API")
+ }
+ val ratio = typedArray.getFloat(R.styleable.SplitPlaceholderRule_splitRatio, 0.5f)
+ val minWidthDp = typedArray.getInteger(
R.styleable.SplitPlaceholderRule_splitMinWidthDp,
SplitRule.SPLIT_MIN_DIMENSION_DP_DEFAULT
)
- minSmallestWidthDp = getInteger(
+ val minHeightDp = typedArray.getInteger(
+ R.styleable.SplitPlaceholderRule_splitMinHeightDp,
+ SplitRule.SPLIT_MIN_DIMENSION_DP_DEFAULT
+ )
+ val minSmallestWidthDp = typedArray.getInteger(
R.styleable.SplitPlaceholderRule_splitMinSmallestWidthDp,
SplitRule.SPLIT_MIN_DIMENSION_DP_DEFAULT
)
- maxAspectRatioInPortrait = getFloat(
+ val maxAspectRatioInPortrait = typedArray.getFloat(
R.styleable.SplitPlaceholderRule_splitMaxAspectRatioInPortrait,
SplitRule.SPLIT_MAX_ASPECT_RATIO_PORTRAIT_DEFAULT.value
)
- maxAspectRatioInLandscape = getFloat(
+ val maxAspectRatioInLandscape = typedArray.getFloat(
R.styleable.SplitPlaceholderRule_splitMaxAspectRatioInLandscape,
SplitRule.SPLIT_MAX_ASPECT_RATIO_LANDSCAPE_DEFAULT.value
)
- layoutDir = getInt(
+ val layoutDir = typedArray.getInt(
R.styleable.SplitPlaceholderRule_splitLayoutDirection,
- LayoutDirection.LOCALE
+ LOCALE.value
)
- }
- if (finishPrimaryWithPlaceholder == FINISH_NEVER) {
- throw IllegalArgumentException(
- "FINISH_NEVER is not a valid configuration for Placeholder activities. " +
- "Please use FINISH_ALWAYS or FINISH_ADJACENT instead or refer to the " +
- "current API")
- }
- val packageName = context.applicationContext.packageName
- val placeholderActivityClassName = buildClassName(
- packageName,
- placeholderActivityIntentName
- )
+ val animationBackgroundColor = typedArray.getColor(
+ R.styleable.SplitPlaceholderRule_animationBackgroundColor,
+ 0)
+ typedArray.recycle()
- return SplitPlaceholderRule.Builder(
- emptySet(),
- Intent().setComponent(placeholderActivityClassName)
- )
- .setMinWidthDp(minWidthDp)
- .setMinSmallestWidthDp(minSmallestWidthDp)
- .setMaxAspectRatioInPortrait(buildAspectRatioFromValue(maxAspectRatioInPortrait))
- .setMaxAspectRatioInLandscape(buildAspectRatioFromValue(maxAspectRatioInLandscape))
- .setSticky(stickyPlaceholder)
- .setFinishPrimaryWithPlaceholder(finishPrimaryWithPlaceholder)
- .setSplitRatio(ratio)
- .setLayoutDirection(layoutDir)
- .build()
- }
+ val defaultAttrs = SplitAttributes.Builder()
+ .setSplitType(SplitAttributes.SplitType.buildSplitTypeFromValue(ratio))
+ .setLayoutDirection(
+ SplitAttributes.LayoutDirection.getLayoutDirectionFromValue(layoutDir)
+ )
+ .setAnimationBackgroundColor(animationBackgroundColor)
+ .build()
+ val packageName = context.applicationContext.packageName
+ val placeholderActivityClassName = buildClassName(
+ packageName,
+ placeholderActivityIntentName
+ )
+
+ SplitPlaceholderRule.Builder(
+ emptySet(),
+ Intent().setComponent(placeholderActivityClassName)
+ )
+ .setTag(tag)
+ .setMinWidthDp(minWidthDp)
+ .setMinHeightDp(minHeightDp)
+ .setMinSmallestWidthDp(minSmallestWidthDp)
+ .setMaxAspectRatioInPortrait(buildAspectRatioFromValue(maxAspectRatioInPortrait))
+ .setMaxAspectRatioInLandscape(buildAspectRatioFromValue(maxAspectRatioInLandscape))
+ .setSticky(stickyPlaceholder)
+ .setFinishPrimaryWithPlaceholder(
+ getFinishBehaviorFromValue(finishPrimaryWithPlaceholder))
+ .setDefaultSplitAttributes(defaultAttrs)
+ .build()
+ }
private fun parseSplitPairFilter(
context: Context,
@@ -289,18 +325,23 @@
private fun parseActivityRule(
context: Context,
parser: XmlResourceParser
- ): ActivityRule {
- val alwaysExpand: Boolean
+ ): ActivityRule =
context.theme.obtainStyledAttributes(
parser,
R.styleable.ActivityRule,
0,
0
- ).apply {
- alwaysExpand = getBoolean(R.styleable.ActivityRule_alwaysExpand, false)
+ ).let { typedArray ->
+ val tag = typedArray.getString(R.styleable.ActivityRule_tag)
+ val alwaysExpand = typedArray.getBoolean(R.styleable.ActivityRule_alwaysExpand, false)
+ typedArray.recycle()
+
+ val builder = ActivityRule.Builder(emptySet()).setAlwaysExpand(alwaysExpand)
+ if (tag != null) {
+ builder.setTag(tag)
+ }
+ builder.build()
}
- return ActivityRule.Builder(emptySet()).setAlwaysExpand(alwaysExpand).build()
- }
private fun parseActivityFilter(
context: Context,
diff --git a/window/window/src/main/java/androidx/window/embedding/SplitAttributes.kt b/window/window/src/main/java/androidx/window/embedding/SplitAttributes.kt
new file mode 100644
index 0000000..d83ce52
--- /dev/null
+++ b/window/window/src/main/java/androidx/window/embedding/SplitAttributes.kt
@@ -0,0 +1,535 @@
+/*
+ * 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 androidx.window.embedding
+
+import android.annotation.SuppressLint
+import androidx.annotation.ColorInt
+import androidx.annotation.FloatRange
+import androidx.annotation.IntRange
+import androidx.window.core.SpecificationComputer.Companion.startSpecification
+import androidx.window.core.VerificationMode
+import androidx.window.embedding.SplitAttributes.LayoutDirection
+import androidx.window.embedding.SplitAttributes.LayoutDirection.Companion.LOCALE
+import androidx.window.embedding.SplitAttributes.SplitType
+import androidx.window.embedding.SplitAttributes.SplitType.Companion.splitEqually
+
+/**
+ * Attributes that describe how the parent window (typically the activity task
+ * window) is split between the primary and secondary activity containers,
+ * including:
+ * - Split type — Categorizes the split and specifies the sizes of the
+ * primary and secondary activity containers relative to the parent bounds
+ * - Layout direction — Specifies whether the parent window is split
+ * vertically or horizontally and in which direction the primary and
+ * secondary containers are respectively positioned (left to right, right to
+ * left, top to bottom, and so forth)
+ * - Animation background color — The color of the background during
+ * animation of the split involving this `SplitAttributes` object if the
+ * animation requires a background
+ *
+ * Attributes can be configured by:
+ * - Setting the default `SplitAttributes` using
+ * [SplitPairRule.Builder.setDefaultSplitAttributes] or
+ * [SplitPlaceholderRule.Builder.setDefaultSplitAttributes].
+ * - Setting `splitRatio`, `splitLayoutDirection`, and
+ * `animationBackgroundColor` attributes in `<SplitPairRule>` or
+ * `<SplitPlaceholderRule>` tags in an XML configuration file. The
+ * attributes are parsed as [SplitType], [LayoutDirection], and [ColorInt],
+ * respectively. Note that [SplitType.HingeSplitType] is not supported XML
+ * format.
+ * - Using
+ * [SplitAttributesCalculator.computeSplitAttributesForParams] to customize
+ * the `SplitAttributes` for a given device and window state.
+ *
+ * @see SplitAttributes.SplitType
+ * @see SplitAttributes.LayoutDirection
+ */
+class SplitAttributes internal constructor(
+
+ /**
+ * The split type attribute. Defaults to an equal split of the parent window
+ * for the primary and secondary containers.
+ */
+ val splitType: SplitType = splitEqually(),
+
+ /**
+ * The layout direction attribute for the parent window split. The default
+ * is based on locale.
+ */
+ val layoutDirection: LayoutDirection = LOCALE,
+
+ /**
+ * The [ColorInt] to use for the background color during the animation of
+ * the split involving this `SplitAttributes` object if the animation
+ * requires a background.
+ *
+ * The default is 0, which specifies the theme window background color.
+ */
+ @ColorInt
+ val animationBackgroundColor: Int = 0
+) {
+
+ /**
+ * The type of parent window split, which defines the proportion of the
+ * parent window occupied by the primary and secondary activity containers.
+ */
+ open class SplitType internal constructor(
+
+ /**
+ * The description of this `SplitType`.
+ */
+ internal val description: String,
+
+ /**
+ * An identifier for the split type.
+ *
+ * Used in the evaluation in the `equals()` method.
+ */
+ internal val value: Float,
+
+ ) {
+
+ /**
+ * A string representation of this split type.
+ *
+ * @return The string representation of the object.
+ */
+ override fun toString(): String = description
+
+ /**
+ * Determines whether this object is the same type of split as the
+ * compared object.
+ *
+ * @param other The object to compare to this object.
+ * @return True if the objects are the same split type, false otherwise.
+ */
+ override fun equals(other: Any?): Boolean {
+ if (other === this) return true
+ if (other !is SplitType) return false
+ return value == other.value &&
+ description == other.description
+ }
+
+ /**
+ * Returns a hash code for this split type.
+ *
+ * @return The hash code for this object.
+ */
+ override fun hashCode(): Int = description.hashCode() + 31 * value.hashCode()
+
+ /**
+ * A window split that's based on the ratio of the size of the primary
+ * container to the size of the parent window.
+ *
+ * @see SplitAttributes.SplitType.ratio
+ */
+ class RatioSplitType internal constructor(
+
+ /**
+ * The proportion of the parent window occupied by the primary
+ * container of the split.
+ */
+ @FloatRange(from = 0.0, to = 1.0, fromInclusive = false, toInclusive = false)
+ val ratio: Float
+
+ ) : SplitType("ratio:$ratio", ratio)
+
+ /**
+ * A window split in which the primary and secondary activity containers
+ * each occupy the entire parent window.
+ *
+ * The secondary container overlays the primary container.
+ *
+ * @see SplitAttributes.SplitType.ExpandContainersSplitType
+ */
+ class ExpandContainersSplitType internal constructor() : SplitType("expandContainer", 0.0f)
+
+ /**
+ * A parent window split that conforms to a hinge or separating fold in
+ * the device display.
+ *
+ * @see SplitAttributes.SplitType.splitByHinge
+ */
+ class HingeSplitType internal constructor(
+
+ /**
+ * The split type to use if a split based on the device hinge or
+ * separating fold cannot be determined.
+ */
+ val fallbackSplitType: SplitType
+
+ ) : SplitType("hinge, fallback=$fallbackSplitType", -1.0f)
+
+ /**
+ * Methods that create various split types.
+ */
+ companion object {
+
+ /**
+ * Creates a split type based on the proportion of the parent window
+ * occupied by the primary container of the split.
+ *
+ * Values in the non-inclusive range (0.0, 1.0) define the size of
+ * the primary container relative to the size of the parent window:
+ * - 0.5 — Primary container occupies half of the parent
+ * window; secondary container, the other half
+ * - > 0.5 — Primary container occupies a larger proportion
+ * of the parent window than the secondary container
+ * - < 0.5 — Primary container occupies a smaller
+ * proportion of the parent window than the secondary container
+ *
+ * @param ratio The proportion of the parent window occupied by the
+ * primary container of the split.
+ * @return An instance of [RatioSplitType] with the specified ratio.
+ */
+ @JvmStatic
+ fun ratio(
+ @FloatRange(from = 0.0, to = 1.0, fromInclusive = false, toInclusive = false)
+ ratio: Float
+ ): RatioSplitType {
+ val checkedRatio = ratio.startSpecification(
+ TAG,
+ VerificationMode.STRICT
+ ).require("Ratio must be in range (0.0, 1.0). " +
+ "Use SplitType.expandContainers() instead of 0 or 1.") {
+ ratio in 0.0..1.0 && ratio !in arrayOf(0.0f, 1.0f)
+ }.compute()!!
+ return RatioSplitType(checkedRatio)
+ }
+
+ private val EXPAND_CONTAINERS = ExpandContainersSplitType()
+
+ /**
+ * Creates a split type in which the primary and secondary activity
+ * containers each expand to fill the parent window; the secondary
+ * container overlays the primary container.
+ *
+ * Use this method with the function set in
+ * [SplitController.setSplitAttributesCalculator] to expand the activity containers in
+ * some device states. The following sample shows how to always fill the parent bounds
+ * if the device is in portrait orientation:
+ *
+ * @sample androidx.window.samples.embedding.expandContainersInPortrait
+ *
+ * @return An instance of [ExpandContainersSplitType].
+ */
+ @JvmStatic
+ fun expandContainers(): ExpandContainersSplitType = EXPAND_CONTAINERS
+
+ /**
+ * Creates a split type in which the primary and secondary
+ * containers occupy equal portions of the parent window.
+ *
+ * Serves as the default [SplitType].
+ *
+ * @return A `RatioSplitType` in which the activity containers
+ * occupy equal portions of the parent window.
+ */
+ @JvmStatic
+ fun splitEqually(): RatioSplitType = ratio(0.5f)
+
+ /**
+ * Creates a split type in which the split ratio conforms to the
+ * position of a hinge or separating fold in the device display.
+ *
+ * The split type is created only if:
+ * <ul>
+ * <li>The host task is not in multi-window mode (e.g.,
+ * split-screen mode or picture-in-picture mode)</li>
+ * <li>The device has a hinge or separating fold reported by
+ * [androidx.window.layout.FoldingFeature.isSeparating]</li>
+ * <li>The hinge or separating fold orientation matches how the
+ * parent bounds are split:
+ * <ul style="list-style-type: circle;">
+ * <li>The hinge or fold orientation is vertical, and
+ * the parent bounds are also split vertically
+ * (containers are side by side)</li>
+ * <li>The hinge or fold orientation is horizontal, and
+ * the parent bounds are also split horizontally
+ * (containers are top and bottom)</li>
+ * </ul>
+ * </li>
+ * </ul>
+ *
+ * Otherwise, the method falls back to `fallbackSplitType`.
+ *
+ * @param fallbackSplitType The split type to use if a split based
+ * on the device hinge or separating fold cannot be determined.
+ * Can be a [RatioSplitType] or [ExpandContainersSplitType].
+ * Defaults to [SplitType.splitEqually].
+ * @return An instance of [HingeSplitType] with a fallback split
+ * type.
+ */
+ @JvmStatic
+ fun splitByHinge(
+ fallbackSplitType: SplitType = splitEqually()
+ ): HingeSplitType {
+ val checkedType = fallbackSplitType.startSpecification(
+ TAG,
+ VerificationMode.STRICT
+ ).require(
+ "FallbackSplitType must be a RatioSplitType or ExpandContainerSplitType"
+ ) {
+ fallbackSplitType is RatioSplitType ||
+ fallbackSplitType is ExpandContainersSplitType
+ }.compute()!!
+ return HingeSplitType(checkedType)
+ }
+
+ /**
+ * Returns a `SplitType` with the given `value`.
+ */
+ @SuppressLint("Range") // value = 0.0 is covered.
+ @JvmStatic
+ internal fun buildSplitTypeFromValue(
+ @FloatRange(from = 0.0, to = 1.0, toInclusive = false) value: Float
+ ) = if (value == EXPAND_CONTAINERS.value) {
+ expandContainers()
+ } else {
+ ratio(value)
+ }
+ }
+ }
+
+ /**
+ * The layout direction of the primary and secondary activity containers.
+ */
+ class LayoutDirection private constructor(
+
+ /**
+ * The description of this `LayoutDirection`.
+ */
+ private val description: String,
+
+ /**
+ * The enum value defined in `splitLayoutDirection` attributes in
+ * `attrs.xml`.
+ */
+ internal val value: Int,
+
+ ) {
+
+ /**
+ * A string representation of this `LayoutDirection`.
+ *
+ * @return The string representation of the object.
+ */
+ override fun toString(): String = description
+
+ /**
+ * Non-public properties and methods.
+ */
+ companion object {
+ /**
+ * Specifies that the parent bounds are split vertically (side to
+ * side).
+ *
+ * The direction of the primary and secondary containers is deduced
+ * from the locale as either `LEFT_TO_RIGHT` or `RIGHT_TO_LEFT`.
+ *
+ * See also [layoutDirection].
+ */
+ @JvmField
+ val LOCALE = LayoutDirection("LOCALE", 0)
+ /**
+ * Specifies that the parent bounds are split vertically (side to
+ * side).
+ *
+ * Places the primary container in the left portion of the parent
+ * window, and the secondary container in the right portion.
+ *
+ * <img width="70%" height="70%" src="/images/guide/topics/large-screens/activity-embedding/reference-docs/a_to_a_b_ltr.png" alt="Activity A starts activity B to the right."/>
+ *
+ * See also [layoutDirection].
+ */
+ @JvmField
+ val LEFT_TO_RIGHT = LayoutDirection("LEFT_TO_RIGHT", 1)
+ /**
+ * Specifies that the parent bounds are split vertically (side to
+ * side).
+ *
+ * Places the primary container in the right portion of the parent
+ * window, and the secondary container in the left portion.
+ *
+ * <img width="70%" height="70%" src="/images/guide/topics/large-screens/activity-embedding/reference-docs/a_to_a_b_rtl.png" alt="Activity A starts activity B to the left."/>
+ *
+ * See also [layoutDirection].
+ */
+ @JvmField
+ val RIGHT_TO_LEFT = LayoutDirection("RIGHT_TO_LEFT", 2)
+ /**
+ * Specifies that the parent bounds are split horizontally (top and
+ * bottom).
+ *
+ * Places the primary container in the top portion of the parent
+ * window, and the secondary container in the bottom portion.
+ *
+ * <img width="70%" height="70%" src="/images/guide/topics/large-screens/activity-embedding/reference-docs/a_to_a_b_ttb.png" alt="Activity A starts activity B to the bottom."/>
+ *
+ * If the horizontal layout direction is not supported on the
+ * device, layout direction falls back to `LOCALE`.
+ *
+ * See also [layoutDirection].
+ */
+ @JvmField
+ val TOP_TO_BOTTOM = LayoutDirection("TOP_TO_BOTTOM", 3)
+ /**
+ * Specifies that the parent bounds are split horizontally (top and
+ * bottom).
+ *
+ * Places the primary container in the bottom portion of the parent
+ * window, and the secondary container in the top portion.
+ *
+ * <img width="70%" height="70%" src="/images/guide/topics/large-screens/activity-embedding/reference-docs/a_to_a_b_btt.png" alt="Activity A starts activity B to the top."/>
+ *
+ * If the horizontal layout direction is not supported on the
+ * device, layout direction falls back to `LOCALE`.
+ *
+ * See also [layoutDirection].
+ */
+ @JvmField
+ val BOTTOM_TO_TOP = LayoutDirection("BOTTOM_TO_TOP", 4)
+
+ /**
+ * Returns `LayoutDirection` with the given `value`.
+ */
+ @JvmStatic
+ internal fun getLayoutDirectionFromValue(
+ @IntRange(from = 0, to = 4) value: Int
+ ) = when (value) {
+ LEFT_TO_RIGHT.value -> LEFT_TO_RIGHT
+ RIGHT_TO_LEFT.value -> RIGHT_TO_LEFT
+ LOCALE.value -> LOCALE
+ TOP_TO_BOTTOM.value -> TOP_TO_BOTTOM
+ BOTTOM_TO_TOP.value -> BOTTOM_TO_TOP
+ else -> throw IllegalArgumentException("Undefined value:$value")
+ }
+ }
+ }
+
+ /**
+ * Non-public properties and methods.
+ */
+ companion object {
+ private val TAG = SplitAttributes::class.java.simpleName
+ }
+
+ /**
+ * Returns a hash code for this `SplitAttributes` object.
+ *
+ * @return The hash code for this object.
+ */
+ override fun hashCode(): Int {
+ var result = splitType.hashCode()
+ result = result * 31 + layoutDirection.hashCode()
+ result = result * 31 + animationBackgroundColor.hashCode()
+ return result
+ }
+
+ /**
+ * Determines whether this object has the same split attributes as the
+ * compared object.
+ *
+ * @param other The object to compare to this object.
+ * @return True if the objects have the same split attributes, false
+ * otherwise.
+ */
+ override fun equals(other: Any?): Boolean {
+ if (this === other) return true
+ if (other !is SplitAttributes) return false
+ return splitType == other.splitType &&
+ layoutDirection == other.layoutDirection &&
+ animationBackgroundColor == other.animationBackgroundColor
+ }
+
+ /**
+ * A string representation of this `SplitAttributes` object.
+ *
+ * @return The string representation of the object.
+ */
+ override fun toString(): String =
+ "${SplitAttributes::class.java.simpleName}:" +
+ "{splitType=$splitType, layoutDir=$layoutDirection," +
+ " animationBackgroundColor=${Integer.toHexString(animationBackgroundColor)}"
+
+ /**
+ * Builder for creating an instance of [SplitAttributes].
+ *
+ * The default split type is an equal split between primary and secondary
+ * containers. The default layout direction is based on locale. The default
+ * animation background color is 0, which specifies the theme window
+ * background color.
+ */
+ class Builder {
+ private var splitType: SplitType = splitEqually()
+ private var layoutDirection = LOCALE
+ @ColorInt
+ private var animationBackgroundColor = 0
+
+ /**
+ * Sets the split type attribute.
+ *
+ * The default is an equal split between primary and secondary
+ * containers.
+ *
+ * @param type The split type attribute.
+ * @return This `Builder`.
+ *
+ * @see SplitAttributes.SplitType
+ */
+ fun setSplitType(type: SplitType): Builder = apply { splitType = type }
+
+ /**
+ * Sets the split layout direction attribute.
+ *
+ * The default is based on locale.
+ *
+ * @param layoutDirection The layout direction attribute.
+ * @return This `Builder`.
+ *
+ * @see SplitAttributes.LayoutDirection
+ */
+ fun setLayoutDirection(layoutDirection: LayoutDirection): Builder =
+ apply { this.layoutDirection = layoutDirection }
+
+ /**
+ * Sets the [ColorInt] to use for the background color during animation
+ * of the split involving this `SplitAttributes` object if the animation
+ * requires a background.
+ *
+ * The default is 0, which specifies the theme window background color.
+ *
+ * @param color A packed color int of the form `AARRGGBB`, for the
+ * animation background color.
+ * @return This `Builder`.
+ *
+ * @see SplitAttributes.animationBackgroundColor
+ */
+ fun setAnimationBackgroundColor(@ColorInt color: Int): Builder =
+ apply { this.animationBackgroundColor = color }
+
+ /**
+ * Builds a `SplitAttributes` instance with the attributes specified by
+ * [setSplitType], [setLayoutDirection], and
+ * [setAnimationBackgroundColor].
+ *
+ * @return The new `SplitAttributes` instance.
+ */
+ fun build(): SplitAttributes = SplitAttributes(splitType, layoutDirection,
+ animationBackgroundColor)
+ }
+}
\ No newline at end of file
diff --git a/window/window/src/main/java/androidx/window/embedding/SplitAttributesCalculatorParams.kt b/window/window/src/main/java/androidx/window/embedding/SplitAttributesCalculatorParams.kt
new file mode 100644
index 0000000..40453be
--- /dev/null
+++ b/window/window/src/main/java/androidx/window/embedding/SplitAttributesCalculatorParams.kt
@@ -0,0 +1,71 @@
+/*
+ * 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 androidx.window.embedding
+
+import android.content.res.Configuration
+import androidx.annotation.RestrictTo
+import androidx.window.layout.WindowLayoutInfo
+import androidx.window.layout.WindowMetrics
+
+/**
+ * The parameter container used to report the current device and window state in
+ * [SplitController.setSplitAttributesCalculator] and references the corresponding [SplitRule] by
+ * [splitRuleTag] if [SplitPairRule.tag] is specified.
+ */
+class SplitAttributesCalculatorParams @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) constructor(
+ /** The parent container's [WindowMetrics] */
+ val parentWindowMetrics: WindowMetrics,
+ /** The parent container's [Configuration] */
+ val parentConfiguration: Configuration,
+ /** The parent container's [WindowLayoutInfo] */
+ val parentWindowLayoutInfo: WindowLayoutInfo,
+ /**
+ * The [SplitRule.defaultSplitAttributes]. It could be from [SplitRule] Builder APIs
+ * ([SplitPairRule.Builder.setDefaultSplitAttributes] or
+ * [SplitPlaceholderRule.Builder.setDefaultSplitAttributes]) or from the `splitRatio` and
+ * `splitLayoutDirection` attributes from static rule definitions.
+ */
+ val defaultSplitAttributes: SplitAttributes,
+ /**
+ * Whether the [parentWindowMetrics] satisfies the dimensions and aspect
+ * ratios requirements specified in the [SplitRule], which are:
+ * - [SplitRule.minWidthDp]
+ * - [SplitRule.minHeightDp]
+ * - [SplitRule.minSmallestWidthDp]
+ * - [SplitRule.maxAspectRatioInPortrait]
+ * - [SplitRule.maxAspectRatioInLandscape]
+ */
+ @get: JvmName("areDefaultConstraintsSatisfied")
+ val areDefaultConstraintsSatisfied: Boolean,
+ /**
+ * The [tag of `SplitRule`][SplitRule.tag] to apply this [SplitAttributes], which is `null`
+ * if the tag is not set.
+ *
+ * @see SplitPairRule.Builder.setTag
+ * @see SplitPlaceholderRule.Builder.setTag
+ */
+ val splitRuleTag: String?,
+) {
+ override fun toString(): String =
+ "${SplitAttributesCalculatorParams::class.java.simpleName}:{" +
+ "windowMetrics=$parentWindowMetrics" +
+ ", configuration=$parentConfiguration" +
+ ", windowLayoutInfo=$parentWindowLayoutInfo" +
+ ", defaultSplitAttributes=$defaultSplitAttributes" +
+ ", areDefaultConstraintsSatisfied=$areDefaultConstraintsSatisfied" +
+ ", tag=$splitRuleTag}"
+}
\ No newline at end of file
diff --git a/window/window/src/main/java/androidx/window/embedding/SplitController.kt b/window/window/src/main/java/androidx/window/embedding/SplitController.kt
index 4825dc0..a777f6f 100644
--- a/window/window/src/main/java/androidx/window/embedding/SplitController.kt
+++ b/window/window/src/main/java/androidx/window/embedding/SplitController.kt
@@ -18,26 +18,35 @@
import android.app.Activity
import android.content.Context
+import android.content.pm.PackageManager
+import android.os.Build
+import android.util.Log
+import androidx.annotation.DoNotInline
+import androidx.annotation.RequiresApi
import androidx.core.util.Consumer
+import androidx.window.WindowProperties
+import androidx.window.embedding.SplitController.Api31Impl.isSplitPropertyEnabled
+import androidx.window.layout.WindowMetrics
import java.util.concurrent.Executor
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
/**
- * A singleton controller class that gets information about the currently active activity
- * splits and provides interaction points to customize the splits and form new
- * splits.
- *
- * A split is a pair of containers that host activities in the same or different
- * processes, combined under the same parent window of the hosting task.
- *
- * A pair of activities can be put into a split by providing a static or runtime
- * split rule and then launching the activities in the same task using
- * [Activity.startActivity()][android.app.Activity.startActivity].
- */
-class SplitController private constructor(applicationContext: Context) {
+* A singleton controller class that gets information about the currently active activity
+* splits and provides interaction points to customize the splits and form new
+* splits.
+*
+* A split is a pair of containers that host activities in the same or different
+* processes, combined under the same parent window of the hosting task.
+*
+* A pair of activities can be put into a split by providing a static or runtime
+* split rule and then launching the activities in the same task using
+* [Activity.startActivity()][android.app.Activity.startActivity].
+*/
+class SplitController private constructor(private val applicationContext: Context) {
private val embeddingBackend: EmbeddingBackend = ExtensionEmbeddingBackend
.getInstance(applicationContext)
+ private var splitPropertyEnabled: Boolean = false
// TODO(b/258356512): Make this method a flow API
/**
@@ -85,15 +94,94 @@
* `isSplitSupported` always returns `true`, and if the split is collapsed,
* activities are launched on top, following the non-activity embedding
* model.
+ *
+ * Also the [androidx.window.WindowProperties.PROPERTY_ACTIVITY_EMBEDDING_SPLITS_ENABLED]
+ * must be enabled in AndroidManifest within <application> in order to get the correct
+ * state or `false` will be returned by default.
*/
fun isSplitSupported(): Boolean {
- return embeddingBackend.isSplitSupported()
+ if (!splitPropertyEnabled) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ splitPropertyEnabled = isSplitPropertyEnabled(applicationContext)
+ } else {
+ // The PackageManager#getProperty API is not supported before S, assuming
+ // the property is enabled to keep the same behavior on earlier platforms.
+ splitPropertyEnabled = true
+ }
+ }
+ return splitPropertyEnabled && embeddingBackend.isSplitSupported()
}
+ /**
+ * Sets or replaces the previously registered [SplitAttributes] calculator.
+ *
+ * **Note** that it's callers' responsibility to check if this API is supported by calling
+ * [isSplitAttributesCalculatorSupported] before using the this API. It is suggested to always
+ * set meaningful [SplitRule.defaultSplitAttributes] in case this API is not supported on some
+ * devices.
+ *
+ * Also, replacing the calculator will only update existing split pairs after a change
+ * in the window or device state, such as orientation changes or folding state changes.
+ *
+ * The [SplitAttributes] calculator is a function to compute the current [SplitAttributes] for
+ * the given [SplitRule] with the current device and window state. Then The calculator will be
+ * invoked if either:
+ * - An activity is started and matches a registered [SplitRule].
+ * - A parent configuration is updated and there's an existing split pair.
+ *
+ * By default, [SplitRule.defaultSplitAttributes] are applied if the parent container's
+ * [WindowMetrics] satisfies the [SplitRule]'s dimensions requirements, which are
+ * [SplitRule.minWidthDp], [SplitRule.minHeightDp] and [SplitRule.minSmallestWidthDp].
+ * The [SplitRule.defaultSplitAttributes] can be set by
+ * - [SplitRule] Builder APIs, which are
+ * [SplitPairRule.Builder.setDefaultSplitAttributes] and
+ * [SplitPlaceholderRule.Builder.setDefaultSplitAttributes].
+ * - Specifying with `splitRatio` and `splitLayoutDirection` attributes in `<SplitPairRule>` or
+ * `<SplitPlaceHolderRule>` tags in XML files.
+ *
+ * Developers may want to apply different [SplitAttributes] for different device or window
+ * states. For example, on foldable devices, developers may want to split the screen vertically
+ * if the device is in landscape, fill the screen if the device is in portrait and split
+ * the screen horizontally if the device is in
+ * [tabletop posture](https://developer.android.com/guide/topics/ui/foldables#postures).
+ * In this case, the [SplitAttributes] can be customized by the [SplitAttributes] calculator,
+ * which takes effects after calling this API. Developers can also clear the calculator
+ * by [clearSplitAttributesCalculator].
+ * Then, developers could implement the [SplitAttributes] calculator as the sample linked below
+ * shows.
+ *
+ * @sample androidx.window.samples.embedding.splitAttributesCalculatorSample
+ * @param calculator the function to calculate [SplitAttributes] based on the
+ * [SplitAttributesCalculatorParams]. It will replace the previously set if it exists.
+ * @throws UnsupportedOperationException if [isSplitAttributesCalculatorSupported] reports
+ * `false`
+ */
+ fun setSplitAttributesCalculator(
+ calculator: (SplitAttributesCalculatorParams) -> SplitAttributes
+ ) {
+ embeddingBackend.setSplitAttributesCalculator(calculator)
+ }
+
+ /**
+ * Clears the callback previously set by [setSplitAttributesCalculator].
+ * The caller **must** make sure [isSplitAttributesCalculatorSupported] before invoking.
+ *
+ * @throws UnsupportedOperationException if [isSplitAttributesCalculatorSupported] reports
+ * `false`
+ */
+ fun clearSplitAttributesCalculator() {
+ embeddingBackend.clearSplitAttributesCalculator()
+ }
+
+ /** Returns whether [setSplitAttributesCalculator] is supported or not. */
+ fun isSplitAttributesCalculatorSupported(): Boolean =
+ embeddingBackend.isSplitAttributesCalculatorSupported()
+
companion object {
@Volatile
private var globalInstance: SplitController? = null
private val globalLock = ReentrantLock()
+ private const val TAG = "SplitController"
internal const val sDebug = false
@@ -114,4 +202,35 @@
return globalInstance!!
}
}
+
+ @RequiresApi(31)
+ private object Api31Impl {
+ @DoNotInline
+ fun isSplitPropertyEnabled(applicationContext: Context): Boolean {
+ val property = try {
+ applicationContext.packageManager.getProperty(
+ WindowProperties.PROPERTY_ACTIVITY_EMBEDDING_SPLITS_ENABLED,
+ applicationContext.packageName
+ )
+ } catch (e: PackageManager.NameNotFoundException) {
+ Log.e(
+ TAG, WindowProperties.PROPERTY_ACTIVITY_EMBEDDING_SPLITS_ENABLED +
+ " must be set and enabled in AndroidManifest.xml to use splits APIs."
+ )
+ return false
+ } catch (e: Exception) {
+ // This can happen when it is a test environment that doesn't support getProperty.
+ Log.e(TAG, "PackageManager.getProperty is not supported", e)
+ return false
+ }
+ if (!property.isBoolean) {
+ Log.e(
+ TAG, WindowProperties.PROPERTY_ACTIVITY_EMBEDDING_SPLITS_ENABLED +
+ " must have a boolean value"
+ )
+ return false
+ }
+ return property.boolean
+ }
+ }
}
\ No newline at end of file
diff --git a/window/window/src/main/java/androidx/window/embedding/SplitInfo.kt b/window/window/src/main/java/androidx/window/embedding/SplitInfo.kt
index 3cabc9e..3bfea72 100644
--- a/window/window/src/main/java/androidx/window/embedding/SplitInfo.kt
+++ b/window/window/src/main/java/androidx/window/embedding/SplitInfo.kt
@@ -28,10 +28,8 @@
* The [ActivityStack] representing the secondary split container.
*/
val secondaryActivityStack: ActivityStack,
- /**
- * Ratio of the Task width that is given to the primary split container.
- */
- val splitRatio: Float
+ /** The [SplitAttributes] of this split pair. */
+ val splitAttributes: SplitAttributes
) {
operator fun contains(activity: Activity): Boolean {
return primaryActivityStack.contains(activity) ||
@@ -44,7 +42,7 @@
if (primaryActivityStack != other.primaryActivityStack) return false
if (secondaryActivityStack != other.secondaryActivityStack) return false
- if (splitRatio != other.splitRatio) return false
+ if (splitAttributes != other.splitAttributes) return false
return true
}
@@ -52,7 +50,7 @@
override fun hashCode(): Int {
var result = primaryActivityStack.hashCode()
result = 31 * result + secondaryActivityStack.hashCode()
- result = 31 * result + splitRatio.hashCode()
+ result = 31 * result + splitAttributes.hashCode()
return result
}
@@ -61,7 +59,7 @@
append("SplitInfo:{")
append("primaryActivityStack=$primaryActivityStack,")
append("secondaryActivityStack=$secondaryActivityStack,")
- append("splitRatio=$splitRatio}")
+ append("splitAttributes=$splitAttributes}")
}
}
}
\ No newline at end of file
diff --git a/window/window/src/main/java/androidx/window/embedding/SplitPairRule.kt b/window/window/src/main/java/androidx/window/embedding/SplitPairRule.kt
index 0b684a4..ad966ab 100644
--- a/window/window/src/main/java/androidx/window/embedding/SplitPairRule.kt
+++ b/window/window/src/main/java/androidx/window/embedding/SplitPairRule.kt
@@ -16,14 +16,14 @@
package androidx.window.embedding
-import android.util.LayoutDirection.LOCALE
-import androidx.annotation.FloatRange
import androidx.annotation.IntRange
+import androidx.window.embedding.SplitRule.FinishBehavior.Companion.ALWAYS
+import androidx.window.embedding.SplitRule.FinishBehavior.Companion.NEVER
/**
- * Split configuration rules for activity pairs. Define when activities that were launched on top of
- * each other should be shown side-by-side, and the visual properties of such splits. Can be set
- * either via [RuleController.setRules] or via [RuleController.addRule]. The rules are always
+ * Split configuration rules for activity pairs. Define when activities that were launched on top
+ * should be placed adjacent to the one below, and the visual properties of such splits. Can be set
+ * either by [RuleController.setRules] or [RuleController.addRule]. The rules are always
* applied only to activities that will be started after the rules were set.
*/
class SplitPairRule : SplitRule {
@@ -37,18 +37,16 @@
/**
* Determines what happens with the primary container when all activities are finished in the
* associated secondary container.
- * @see SplitRule.SplitFinishBehavior
+ * @see SplitRule.FinishBehavior
*/
- @SplitFinishBehavior
- val finishPrimaryWithSecondary: Int
+ val finishPrimaryWithSecondary: FinishBehavior
/**
* Determines what happens with the secondary container when all activities are finished in the
* associated primary container.
- * @see SplitRule.SplitFinishBehavior
+ * @see SplitRule.FinishBehavior
*/
- @SplitFinishBehavior
- val finishSecondaryWithPrimary: Int
+ val finishSecondaryWithPrimary: FinishBehavior
/**
* If there is an existing split with the same primary container, indicates whether the
@@ -58,18 +56,19 @@
val clearTop: Boolean
internal constructor(
+ tag: String? = null,
filters: Set<SplitPairFilter>,
- @SplitFinishBehavior finishPrimaryWithSecondary: Int = FINISH_NEVER,
- @SplitFinishBehavior finishSecondaryWithPrimary: Int = FINISH_ALWAYS,
+ finishPrimaryWithSecondary: FinishBehavior = NEVER,
+ finishSecondaryWithPrimary: FinishBehavior = ALWAYS,
clearTop: Boolean = false,
@IntRange(from = 0) minWidthDp: Int = SPLIT_MIN_DIMENSION_DP_DEFAULT,
+ @IntRange(from = 0) minHeightDp: Int = SPLIT_MIN_DIMENSION_DP_DEFAULT,
@IntRange(from = 0) minSmallestWidthDp: Int = SPLIT_MIN_DIMENSION_DP_DEFAULT,
maxAspectRatioInPortrait: EmbeddingAspectRatio = SPLIT_MAX_ASPECT_RATIO_PORTRAIT_DEFAULT,
maxAspectRatioInLandscape: EmbeddingAspectRatio = SPLIT_MAX_ASPECT_RATIO_LANDSCAPE_DEFAULT,
- @FloatRange(from = 0.0, to = 1.0) splitRatio: Float = SPLIT_RATIO_DEFAULT,
- @LayoutDirection layoutDirection: Int = LOCALE
- ) : super(minWidthDp, minSmallestWidthDp, maxAspectRatioInPortrait, maxAspectRatioInLandscape,
- splitRatio, layoutDirection) {
+ defaultSplitAttributes: SplitAttributes,
+ ) : super(tag, minWidthDp, minHeightDp, minSmallestWidthDp, maxAspectRatioInPortrait,
+ maxAspectRatioInLandscape, defaultSplitAttributes) {
this.filters = filters.toSet()
this.clearTop = clearTop
this.finishPrimaryWithSecondary = finishPrimaryWithSecondary
@@ -82,23 +81,21 @@
* @param filters See [SplitPairRule.filters].
*/
class Builder(
- private val filters: Set<SplitPairFilter>,
+ private val filters: Set<SplitPairFilter>
) {
+ private var tag: String? = null
@IntRange(from = 0)
private var minWidthDp = SPLIT_MIN_DIMENSION_DP_DEFAULT
@IntRange(from = 0)
+ private var minHeightDp = SPLIT_MIN_DIMENSION_DP_DEFAULT
+ @IntRange(from = 0)
private var minSmallestWidthDp = SPLIT_MIN_DIMENSION_DP_DEFAULT
private var maxAspectRatioInPortrait = SPLIT_MAX_ASPECT_RATIO_PORTRAIT_DEFAULT
private var maxAspectRatioInLandscape = SPLIT_MAX_ASPECT_RATIO_LANDSCAPE_DEFAULT
- @SplitFinishBehavior
- private var finishPrimaryWithSecondary = FINISH_NEVER
- @SplitFinishBehavior
- private var finishSecondaryWithPrimary = FINISH_ALWAYS
+ private var finishPrimaryWithSecondary = NEVER
+ private var finishSecondaryWithPrimary = ALWAYS
private var clearTop = false
- @FloatRange(from = 0.0, to = 1.0)
- private var splitRatio = SPLIT_RATIO_DEFAULT
- @LayoutDirection
- private var layoutDirection = LOCALE
+ private var defaultSplitAttributes = SplitAttributes.Builder().build()
/**
* @see SplitPairRule.minWidthDp
@@ -107,6 +104,12 @@
apply { this.minWidthDp = minWidthDp }
/**
+ * @see SplitPairRule.minHeightDp
+ */
+ fun setMinHeightDp(@IntRange(from = 0) minHeightDp: Int): Builder =
+ apply { this.minHeightDp = minHeightDp }
+
+ /**
* @see SplitPairRule.minSmallestWidthDp
*/
fun setMinSmallestWidthDp(@IntRange(from = 0) minSmallestWidthDp: Int): Builder =
@@ -128,7 +131,7 @@
* @see SplitPairRule.finishPrimaryWithSecondary
*/
fun setFinishPrimaryWithSecondary(
- @SplitFinishBehavior finishPrimaryWithSecondary: Int
+ finishPrimaryWithSecondary: FinishBehavior
): Builder =
apply { this.finishPrimaryWithSecondary = finishPrimaryWithSecondary }
@@ -136,7 +139,7 @@
* @see SplitPairRule.finishSecondaryWithPrimary
*/
fun setFinishSecondaryWithPrimary(
- @SplitFinishBehavior finishSecondaryWithPrimary: Int
+ finishSecondaryWithPrimary: FinishBehavior
): Builder =
apply { this.finishSecondaryWithPrimary = finishSecondaryWithPrimary }
@@ -147,21 +150,27 @@
fun setClearTop(clearTop: Boolean): Builder =
apply { this.clearTop = clearTop }
- /**
- * @see SplitPairRule.splitRatio
- */
- fun setSplitRatio(@FloatRange(from = 0.0, to = 1.0) splitRatio: Float): Builder =
- apply { this.splitRatio = splitRatio }
+ /** @see SplitPairRule.defaultSplitAttributes */
+ fun setDefaultSplitAttributes(defaultSplitAttributes: SplitAttributes): Builder =
+ apply { this.defaultSplitAttributes = defaultSplitAttributes }
- /**
- * @see SplitPairRule.layoutDirection
- */
- fun setLayoutDirection(@LayoutDirection layoutDirection: Int): Builder =
- apply { this.layoutDirection = layoutDirection }
+ /** @see SplitPairRule.tag */
+ fun setTag(tag: String?): Builder =
+ apply { this.tag = tag }
- fun build() = SplitPairRule(filters, finishPrimaryWithSecondary, finishSecondaryWithPrimary,
- clearTop, minWidthDp, minSmallestWidthDp, maxAspectRatioInPortrait,
- maxAspectRatioInLandscape, splitRatio, layoutDirection)
+ fun build() = SplitPairRule(
+ tag,
+ filters,
+ finishPrimaryWithSecondary,
+ finishSecondaryWithPrimary,
+ clearTop,
+ minWidthDp,
+ minHeightDp,
+ minSmallestWidthDp,
+ maxAspectRatioInPortrait,
+ maxAspectRatioInLandscape,
+ defaultSplitAttributes,
+ )
}
/**
@@ -173,15 +182,16 @@
newSet.addAll(filters)
newSet.add(filter)
return Builder(newSet.toSet())
+ .setTag(tag)
.setMinWidthDp(minWidthDp)
+ .setMinHeightDp(minHeightDp)
.setMinSmallestWidthDp(minSmallestWidthDp)
.setMaxAspectRatioInPortrait(maxAspectRatioInPortrait)
.setMaxAspectRatioInLandscape(maxAspectRatioInLandscape)
.setFinishPrimaryWithSecondary(finishPrimaryWithSecondary)
.setFinishSecondaryWithPrimary(finishSecondaryWithPrimary)
.setClearTop(clearTop)
- .setSplitRatio(splitRatio)
- .setLayoutDirection(layoutDirection)
+ .setDefaultSplitAttributes(defaultSplitAttributes)
.build()
}
@@ -209,9 +219,10 @@
override fun toString(): String =
"${SplitPairRule::class.java.simpleName}{" +
- " splitRatio=$splitRatio" +
- ", layoutDirection=$layoutDirection" +
+ "tag=$tag" +
+ ", defaultSplitAttributes=$defaultSplitAttributes" +
", minWidthDp=$minWidthDp" +
+ ", minHeightDp=$minHeightDp" +
", minSmallestWidthDp=$minSmallestWidthDp" +
", maxAspectRatioInPortrait=$maxAspectRatioInPortrait" +
", maxAspectRatioInLandscape=$maxAspectRatioInLandscape" +
diff --git a/window/window/src/main/java/androidx/window/embedding/SplitPlaceholderRule.kt b/window/window/src/main/java/androidx/window/embedding/SplitPlaceholderRule.kt
index fe5f896..05de87a 100644
--- a/window/window/src/main/java/androidx/window/embedding/SplitPlaceholderRule.kt
+++ b/window/window/src/main/java/androidx/window/embedding/SplitPlaceholderRule.kt
@@ -17,11 +17,10 @@
package androidx.window.embedding
import android.content.Intent
-import android.util.LayoutDirection.LOCALE
-import androidx.annotation.FloatRange
-import androidx.annotation.IntDef
import androidx.annotation.IntRange
import androidx.core.util.Preconditions.checkArgument
+import androidx.window.embedding.SplitRule.FinishBehavior.Companion.ALWAYS
+import androidx.window.embedding.SplitRule.FinishBehavior.Companion.NEVER
/**
* Configuration rules for split placeholders.
@@ -59,37 +58,30 @@
val isSticky: Boolean
/**
- * Defines whether a container should be finished together when the associated placeholder
- * activity is being finished based on current presentation mode.
- */
- @Target(AnnotationTarget.PROPERTY, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.TYPE)
- @Retention(AnnotationRetention.SOURCE)
- @IntDef(FINISH_ALWAYS, FINISH_ADJACENT)
- internal annotation class SplitPlaceholderFinishBehavior
-
- /**
* Determines what happens with the primary container when all activities are finished in the
* associated placeholder container.
- * @see SplitPlaceholderFinishBehavior
+ *
+ * **Note** that it is not valid to set [SplitRule.FinishBehavior.NEVER]
+ * @see SplitRule.FinishBehavior
*/
- @SplitPlaceholderFinishBehavior
- val finishPrimaryWithPlaceholder: Int
+ val finishPrimaryWithPlaceholder: FinishBehavior
internal constructor(
+ tag: String? = null,
filters: Set<ActivityFilter>,
placeholderIntent: Intent,
isSticky: Boolean,
- @SplitPlaceholderFinishBehavior finishPrimaryWithPlaceholder: Int = FINISH_ALWAYS,
+ finishPrimaryWithPlaceholder: FinishBehavior = ALWAYS,
@IntRange(from = 0) minWidthDp: Int = SPLIT_MIN_DIMENSION_DP_DEFAULT,
+ @IntRange(from = 0) minHeightDp: Int = SPLIT_MIN_DIMENSION_DP_DEFAULT,
@IntRange(from = 0) minSmallestWidthDp: Int = SPLIT_MIN_DIMENSION_DP_DEFAULT,
maxAspectRatioInPortrait: EmbeddingAspectRatio = SPLIT_MAX_ASPECT_RATIO_PORTRAIT_DEFAULT,
maxAspectRatioInLandscape: EmbeddingAspectRatio = SPLIT_MAX_ASPECT_RATIO_LANDSCAPE_DEFAULT,
- @FloatRange(from = 0.0, to = 1.0) splitRatio: Float = SPLIT_RATIO_DEFAULT,
- @LayoutDirection layoutDirection: Int = LOCALE
- ) : super(minWidthDp, minSmallestWidthDp, maxAspectRatioInPortrait, maxAspectRatioInLandscape,
- splitRatio, layoutDirection) {
- checkArgument(finishPrimaryWithPlaceholder != FINISH_NEVER,
- "FINISH_NEVER is not a valid configuration for SplitPlaceholderRule. " +
+ defaultSplitAttributes: SplitAttributes,
+ ) : super(tag, minWidthDp, minHeightDp, minSmallestWidthDp, maxAspectRatioInPortrait,
+ maxAspectRatioInLandscape, defaultSplitAttributes) {
+ checkArgument(finishPrimaryWithPlaceholder != NEVER,
+ "NEVER is not a valid configuration for SplitPlaceholderRule. " +
"Please use FINISH_ALWAYS or FINISH_ADJACENT instead or refer to the current API.")
this.filters = filters.toSet()
this.placeholderIntent = placeholderIntent
@@ -99,27 +91,25 @@
/**
* Builder for [SplitPlaceholderRule].
- *
* @param filters See [SplitPlaceholderRule.filters].
* @param placeholderIntent See [SplitPlaceholderRule.placeholderIntent].
*/
class Builder(
private val filters: Set<ActivityFilter>,
- private val placeholderIntent: Intent,
+ private val placeholderIntent: Intent
) {
+ private var tag: String? = null
@IntRange(from = 0)
private var minWidthDp = SPLIT_MIN_DIMENSION_DP_DEFAULT
@IntRange(from = 0)
+ private var minHeightDp = SPLIT_MIN_DIMENSION_DP_DEFAULT
+ @IntRange(from = 0)
private var minSmallestWidthDp = SPLIT_MIN_DIMENSION_DP_DEFAULT
private var maxAspectRatioInPortrait = SPLIT_MAX_ASPECT_RATIO_PORTRAIT_DEFAULT
private var maxAspectRatioInLandscape = SPLIT_MAX_ASPECT_RATIO_LANDSCAPE_DEFAULT
- @SplitPlaceholderFinishBehavior
- private var finishPrimaryWithPlaceholder = FINISH_ALWAYS
+ private var finishPrimaryWithPlaceholder = ALWAYS
private var isSticky = false
- @FloatRange(from = 0.0, to = 1.0)
- private var splitRatio = SPLIT_RATIO_DEFAULT
- @LayoutDirection
- private var layoutDirection = LOCALE
+ private var defaultSplitAttributes = SplitAttributes.Builder().build()
/**
* @see SplitPlaceholderRule.minWidthDp
@@ -128,6 +118,12 @@
apply { this.minWidthDp = minWidthDp }
/**
+ * @see SplitPlaceholderRule.minHeightDp
+ */
+ fun setMinHeightDp(@IntRange(from = 0) minHeightDp: Int): Builder =
+ apply { this.minHeightDp = minHeightDp }
+
+ /**
* @see SplitPlaceholderRule.minSmallestWidthDp
*/
fun setMinSmallestWidthDp(@IntRange(from = 0) minSmallestWidthDp: Int): Builder =
@@ -148,9 +144,7 @@
/**
* @see SplitPlaceholderRule.finishPrimaryWithPlaceholder
*/
- fun setFinishPrimaryWithPlaceholder(
- @SplitPlaceholderFinishBehavior finishPrimaryWithPlaceholder: Int
- ): Builder =
+ fun setFinishPrimaryWithPlaceholder(finishPrimaryWithPlaceholder: FinishBehavior): Builder =
apply {
this.finishPrimaryWithPlaceholder = finishPrimaryWithPlaceholder
}
@@ -161,21 +155,27 @@
fun setSticky(isSticky: Boolean): Builder =
apply { this.isSticky = isSticky }
- /**
- * @see SplitPlaceholderRule.splitRatio
- */
- fun setSplitRatio(@FloatRange(from = 0.0, to = 1.0) splitRatio: Float): Builder =
- apply { this.splitRatio = splitRatio }
+ /** @see SplitPlaceholderRule.defaultSplitAttributes */
+ fun setDefaultSplitAttributes(defaultSplitAttributes: SplitAttributes): Builder =
+ apply { this.defaultSplitAttributes = defaultSplitAttributes }
- /**
- * @see SplitPlaceholderRule.layoutDirection
- */
- fun setLayoutDirection(@LayoutDirection layoutDirection: Int): Builder =
- apply { this.layoutDirection = layoutDirection }
+ /** @see SplitPlaceholderRule.tag */
+ fun setTag(tag: String?): Builder =
+ apply { this.tag = tag }
- fun build() = SplitPlaceholderRule(filters, placeholderIntent, isSticky,
- finishPrimaryWithPlaceholder, minWidthDp, minSmallestWidthDp, maxAspectRatioInPortrait,
- maxAspectRatioInLandscape, splitRatio, layoutDirection)
+ fun build() = SplitPlaceholderRule(
+ tag,
+ filters,
+ placeholderIntent,
+ isSticky,
+ finishPrimaryWithPlaceholder,
+ minWidthDp,
+ minHeightDp,
+ minSmallestWidthDp,
+ maxAspectRatioInPortrait,
+ maxAspectRatioInLandscape,
+ defaultSplitAttributes,
+ )
}
/**
@@ -187,14 +187,15 @@
newSet.addAll(filters)
newSet.add(filter)
return Builder(newSet.toSet(), placeholderIntent)
+ .setTag(tag)
.setMinWidthDp(minWidthDp)
+ .setMinHeightDp(minHeightDp)
.setMinSmallestWidthDp(minSmallestWidthDp)
.setMaxAspectRatioInPortrait(maxAspectRatioInPortrait)
.setMaxAspectRatioInLandscape(maxAspectRatioInLandscape)
.setSticky(isSticky)
.setFinishPrimaryWithPlaceholder(finishPrimaryWithPlaceholder)
- .setSplitRatio(splitRatio)
- .setLayoutDirection(layoutDirection)
+ .setDefaultSplitAttributes(defaultSplitAttributes)
.build()
}
@@ -221,16 +222,17 @@
}
override fun toString(): String =
- "SplitPlaceholderRule{" +
- " splitRatio=$splitRatio" +
- ", layoutDirection=$layoutDirection" +
- ", minWidthDp=$minWidthDp" +
- ", minSmallestWidthDp=$minSmallestWidthDp" +
- ", maxAspectRatioInPortrait=$maxAspectRatioInPortrait" +
- ", maxAspectRatioInLandscape=$maxAspectRatioInLandscape" +
- ", placeholderIntent=$placeholderIntent" +
- ", isSticky=$isSticky" +
- ", finishPrimaryWithPlaceholder=$finishPrimaryWithPlaceholder" +
- ", filters=$filters" +
- "}"
+ "SplitPlaceholderRule{" +
+ "tag=$tag" +
+ ", defaultSplitAttributes=$defaultSplitAttributes" +
+ ", minWidthDp=$minWidthDp" +
+ ", minHeightDp=$minHeightDp" +
+ ", minSmallestWidthDp=$minSmallestWidthDp" +
+ ", maxAspectRatioInPortrait=$maxAspectRatioInPortrait" +
+ ", maxAspectRatioInLandscape=$maxAspectRatioInLandscape" +
+ ", placeholderIntent=$placeholderIntent" +
+ ", isSticky=$isSticky" +
+ ", finishPrimaryWithPlaceholder=$finishPrimaryWithPlaceholder" +
+ ", filters=$filters" +
+ "}"
}
\ No newline at end of file
diff --git a/window/window/src/main/java/androidx/window/embedding/SplitRule.kt b/window/window/src/main/java/androidx/window/embedding/SplitRule.kt
index c4f7905..7cdfefe 100644
--- a/window/window/src/main/java/androidx/window/embedding/SplitRule.kt
+++ b/window/window/src/main/java/androidx/window/embedding/SplitRule.kt
@@ -19,19 +19,19 @@
import android.content.Context
import android.graphics.Rect
import android.os.Build
-import android.util.LayoutDirection.LOCALE
-import android.util.LayoutDirection.LTR
-import android.util.LayoutDirection.RTL
import android.view.WindowMetrics
import androidx.annotation.DoNotInline
-import androidx.annotation.FloatRange
-import androidx.annotation.IntDef
import androidx.annotation.IntRange
+import androidx.annotation.OptIn
import androidx.annotation.RequiresApi
+import androidx.core.os.BuildCompat
import androidx.core.util.Preconditions
import androidx.window.embedding.EmbeddingAspectRatio.Companion.alwaysAllow
import androidx.window.embedding.EmbeddingAspectRatio.Companion.ratio
+import androidx.window.embedding.SplitRule.Companion.SPLIT_MAX_ASPECT_RATIO_LANDSCAPE_DEFAULT
+import androidx.window.embedding.SplitRule.Companion.SPLIT_MAX_ASPECT_RATIO_PORTRAIT_DEFAULT
import androidx.window.embedding.SplitRule.Companion.SPLIT_MIN_DIMENSION_DP_DEFAULT
+import androidx.window.embedding.SplitRule.FinishBehavior.Companion.ADJACENT
import kotlin.math.min
/**
@@ -40,29 +40,58 @@
* via [RuleController.addRule]. The rules are always applied only to activities that will be
* started after the rules were set.
*
+ * Note that regardless of whether the minimal requirements ([minWidthDp], [minHeightDp] and
+ * [minSmallestWidthDp]) are met or not, the callback set in
+ * [SplitController.setSplitAttributesCalculator] will still be called for the rule if the
+ * calculator is registered via [SplitController.setSplitAttributesCalculator].
+ * Whether this [SplitRule]'s minimum requirements are satisfied is dispatched in
+ * [SplitAttributesCalculatorParams.areDefaultConstraintsSatisfied] instead.
+ * The width and height could be verified in the [SplitAttributes] calculator callback
+ * as the sample linked below shows.
+ *
+ * It is useful if this [SplitRule] is supported to split the parent container in different
+ * directions with different device states.
+ *
+ * @sample androidx.window.samples.embedding.splitWithOrientations
* @see androidx.window.embedding.SplitPairRule
* @see androidx.window.embedding.SplitPlaceholderRule
*/
open class SplitRule internal constructor(
+ tag: String? = null,
/**
- * The smallest value of width of the parent window when the split should be used, in DP.
+ * The smallest value of width of the parent task window when the split should be used, in DP.
* When the window size is smaller than requested here, activities in the secondary container
* will be stacked on top of the activities in the primary one, completely overlapping them.
*
- * The default is [SPLIT_MIN_DIMENSION_DP_DEFAULT] if the app doesn't set.
- * [SPLIT_MIN_DIMENSION_ALWAYS_ALLOW] means to always allow split.
+ * Uses `0` to always allow split regardless of the parent task width.
+ * The default is [SPLIT_MIN_DIMENSION_DP_DEFAULT].
*/
@IntRange(from = 0)
val minWidthDp: Int = SPLIT_MIN_DIMENSION_DP_DEFAULT,
/**
- * The smallest value of the smallest possible width of the parent window in any rotation
- * when the split should be used, in DP. When the window size is smaller than requested
- * here, activities in the secondary container will be stacked on top of the activities in
- * the primary one, completely overlapping them.
+ * The smallest value of height of the parent task window when the split should be used, in DP.
+ * When the window size is smaller than requested here, activities in the secondary container
+ * will be stacked on top of the activities in the primary one, completely overlapping them.
+ * It is useful if it's necessary to split the parent window horizontally for this [SplitRule].
*
- * The default is [SPLIT_MIN_DIMENSION_DP_DEFAULT] if the app doesn't set.
- * [SPLIT_MIN_DIMENSION_ALWAYS_ALLOW] means to always allow split.
+ * Uses `0` to always allow split regardless of the parent task height.
+ * The default is [SPLIT_MIN_DIMENSION_DP_DEFAULT].
+ *
+ * @see SplitAttributes.LayoutDirection.TOP_TO_BOTTOM
+ * @see SplitAttributes.LayoutDirection.BOTTOM_TO_TOP
+ */
+ @IntRange(from = 0)
+ val minHeightDp: Int = SPLIT_MIN_DIMENSION_DP_DEFAULT,
+
+ /**
+ * The smallest value of the smallest possible width of the parent task window in any rotation
+ * when the split should be used, in DP. When the window size is smaller than requested here,
+ * activities in the secondary container will be stacked on top of the activities in the primary
+ * one, completely overlapping them.
+ *
+ * Uses `0` to always allow split regardless of the parent task smallest width.
+ * The default is [SPLIT_MIN_DIMENSION_DP_DEFAULT].
*/
@IntRange(from = 0)
val minSmallestWidthDp: Int = SPLIT_MIN_DIMENSION_DP_DEFAULT,
@@ -75,8 +104,8 @@
*
* This value is only used when the parent window is in portrait (height >= width).
*
- * The default is [SPLIT_MAX_ASPECT_RATIO_PORTRAIT_DEFAULT] if the app doesn't set, which is the
- * recommend value to only allow split when the parent window is not too stretched in portrait.
+ * The default is [SPLIT_MAX_ASPECT_RATIO_PORTRAIT_DEFAULT], which is the recommend value to
+ * only allow split when the parent window is not too stretched in portrait.
*
* @see EmbeddingAspectRatio.ratio
* @see EmbeddingAspectRatio.alwaysAllow
@@ -92,8 +121,8 @@
*
* This value is only used when the parent window is in landscape (width > height).
*
- * The default is [SPLIT_MAX_ASPECT_RATIO_LANDSCAPE_DEFAULT] if the app doesn't set, which is
- * the recommend value to always allow split when the parent window is in landscape.
+ * The default is [SPLIT_MAX_ASPECT_RATIO_LANDSCAPE_DEFAULT], which is the recommend value to
+ * always allow split when the parent window is in landscape.
*
* @see EmbeddingAspectRatio.ratio
* @see EmbeddingAspectRatio.alwaysAllow
@@ -102,78 +131,23 @@
val maxAspectRatioInLandscape: EmbeddingAspectRatio = SPLIT_MAX_ASPECT_RATIO_LANDSCAPE_DEFAULT,
/**
- * Defines what part of the width should be given to the primary activity.
- *
- * The default is `0.5` if the app doesn't set, which is to split with equal width.
+ * The default [SplitAttributes] to apply on the activity containers pair when the host task
+ * bounds satisfy [minWidthDp], [minHeightDp] and [minSmallestWidthDp] requirements.
*/
- @FloatRange(from = 0.0, to = 1.0)
- val splitRatio: Float = SPLIT_RATIO_DEFAULT,
-
- /**
- * The layout direction for the split. The value must be one of [LTR], [RTL] or [LOCALE].
- * - [LTR]: It splits the task bounds vertically, and put the primary container on the left
- * portion, and the secondary container on the right portion.
- * - [RTL]: It splits the task bounds vertically, and put the primary container on the right
- * portion, and the secondary container on the left portion.
- * - [LOCALE]: It splits the task bounds vertically, and the direction is deduced from the
- * default language script of locale. The direction can be either [LTR] or [RTL].
- */
- @LayoutDirection
- val layoutDirection: Int = LOCALE
-) : EmbeddingRule() {
+ val defaultSplitAttributes: SplitAttributes,
+) : EmbeddingRule(tag) {
init {
Preconditions.checkArgumentNonnegative(minWidthDp, "minWidthDp must be non-negative")
+ Preconditions.checkArgumentNonnegative(minHeightDp, "minHeightDp must be non-negative")
Preconditions.checkArgumentNonnegative(
minSmallestWidthDp,
"minSmallestWidthDp must be non-negative"
)
- Preconditions.checkArgument(splitRatio in 0.0..1.0, "splitRatio must be in 0.0..1.0 range")
}
- @IntDef(LTR, RTL, LOCALE)
- @Retention(AnnotationRetention.SOURCE)
- internal annotation class LayoutDirection
-
- /**
- * Determines what happens with the associated container when all activities are finished in
- * one of the containers in a split.
- *
- * For example, given that [SplitPairRule.finishPrimaryWithSecondary] is [FINISH_ADJACENT] and
- * secondary container finishes. The primary associated container is finished if it's
- * side-by-side with secondary container. The primary associated container is not finished
- * if it occupies entire task bounds.
- *
- * @see SplitPairRule.finishPrimaryWithSecondary
- * @see SplitPairRule.finishSecondaryWithPrimary
- * @see SplitPlaceholderRule.finishPrimaryWithPlaceholder
- */
companion object {
/**
- * Never finish the associated container.
- * @see SplitRule.Companion
- */
- const val FINISH_NEVER = 0
- /**
- * Always finish the associated container independent of the current presentation mode.
- * @see SplitRule.Companion
- */
- const val FINISH_ALWAYS = 1
- /**
- * Only finish the associated container when displayed side-by-side/adjacent to the one
- * being finished. Does not finish the associated one when containers are stacked on top of
- * each other.
- * @see SplitRule.Companion
- */
- const val FINISH_ADJACENT = 2
-
- /**
- * The default split ratio if it is not set by apps.
- * @see SplitRule.splitRatio
- */
- internal const val SPLIT_RATIO_DEFAULT = 0.5f
-
- /**
* When the min dimension is set to this value, it means to always allow split.
* @see SplitRule.minWidthDp
* @see SplitRule.minSmallestWidthDp
@@ -183,8 +157,6 @@
/**
* The default min dimension in DP for allowing split if it is not set by apps. The value
* reflects [androidx.window.core.layout.WindowWidthSizeClass.MEDIUM].
- * @see SplitRule.minWidthDp
- * @see SplitRule.minSmallestWidthDp
*/
const val SPLIT_MIN_DIMENSION_DP_DEFAULT = 600
@@ -204,25 +176,73 @@
}
/**
- * Defines whether an associated container should be finished together with the one that's
- * already being finished based on their current presentation mode.
+ * Determines what happens with the associated container when all activities are finished in
+ * one of the containers in a split.
+ *
+ * For example, given that [SplitPairRule.finishPrimaryWithSecondary] is [ADJACENT] and
+ * secondary container finishes. The primary associated container is finished if it's
+ * adjacent to the secondary container. The primary associated container is not finished
+ * if it occupies entire task bounds.
+ *
+ * @see SplitPairRule.finishPrimaryWithSecondary
+ * @see SplitPairRule.finishSecondaryWithPrimary
+ * @see SplitPlaceholderRule.finishPrimaryWithPlaceholder
*/
- @Retention(AnnotationRetention.SOURCE)
- @IntDef(FINISH_NEVER, FINISH_ALWAYS, FINISH_ADJACENT)
- internal annotation class SplitFinishBehavior
+ class FinishBehavior private constructor(
+ /** The description of this [FinishBehavior] */
+ private val description: String,
+ /** The enum value defined in `splitLayoutDirection` attributes in `attrs.xml` */
+ internal val value: Int,
+ ) {
+ override fun toString(): String = description
+
+ companion object {
+ /** Never finish the associated container. */
+ @JvmField
+ val NEVER = FinishBehavior("NEVER", 0)
+ /**
+ * Always finish the associated container independent of the current presentation mode.
+ */
+ @JvmField
+ val ALWAYS = FinishBehavior("ALWAYS", 1)
+ /**
+ * Only finish the associated container when displayed adjacent to the one being
+ * finished. Does not finish the associated one when containers are stacked on top of
+ * each other.
+ */
+ @JvmField
+ val ADJACENT = FinishBehavior("ADJACENT", 2)
+
+ @JvmStatic
+ internal fun getFinishBehaviorFromValue(
+ @IntRange(from = 0, to = 2) value: Int
+ ): FinishBehavior =
+ when (value) {
+ NEVER.value -> NEVER
+ ALWAYS.value -> ALWAYS
+ ADJACENT.value -> ADJACENT
+ else -> throw IllegalArgumentException("Unknown finish behavior:$value")
+ }
+ }
+ }
/**
* Verifies if the provided parent bounds satisfy the dimensions and aspect ratio requirements
* to apply the rule.
*/
+ // TODO(b/265089843) remove after Build.VERSION_CODES.U released.
+ @OptIn(markerClass = [BuildCompat.PrereleaseSdkCheck::class])
internal fun checkParentMetrics(context: Context, parentMetrics: WindowMetrics): Boolean {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {
return false
}
val bounds = Api30Impl.getBounds(parentMetrics)
- // TODO(b/257000820): Application displayMetrics should only be used as a fallback. Replace
- // with Task density after we include it in WindowMetrics.
- val density = context.resources.displayMetrics.density
+ // TODO(b/265089843) replace with Build.VERSION.SDK_INT >= Build.VERSION_CODES.U
+ val density = if (BuildCompat.isAtLeastU()) {
+ Api34Impl.getDensity(parentMetrics)
+ } else {
+ context.resources.displayMetrics.density
+ }
return checkParentBounds(density, bounds)
}
@@ -236,9 +256,12 @@
return false
}
val minWidthPx = convertDpToPx(density, minWidthDp)
+ val minHeightPx = convertDpToPx(density, minHeightDp)
val minSmallestWidthPx = convertDpToPx(density, minSmallestWidthDp)
// Always allow split if the min dimensions are 0.
val validMinWidth = minWidthDp == SPLIT_MIN_DIMENSION_ALWAYS_ALLOW || width >= minWidthPx
+ val validMinHeight = minHeightDp == SPLIT_MIN_DIMENSION_ALWAYS_ALLOW ||
+ height >= minHeightPx
val validSmallestMinWidth = minSmallestWidthDp == SPLIT_MIN_DIMENSION_ALWAYS_ALLOW ||
min(width, height) >= minSmallestWidthPx
val validAspectRatio = if (height >= width) {
@@ -250,7 +273,7 @@
maxAspectRatioInLandscape == alwaysAllow() ||
width * 1f / height <= maxAspectRatioInLandscape.value
}
- return validMinWidth && validSmallestMinWidth && validAspectRatio
+ return validMinWidth && validMinHeight && validSmallestMinWidth && validAspectRatio
}
/**
@@ -268,35 +291,45 @@
}
}
+ @RequiresApi(34)
+ internal object Api34Impl {
+ @DoNotInline
+ fun getDensity(windowMetrics: WindowMetrics): Float {
+ return windowMetrics.density
+ }
+ }
+
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is SplitRule) return false
+ if (!super.equals(other)) return false
if (minWidthDp != other.minWidthDp) return false
+ if (minHeightDp != other.minHeightDp) return false
if (minSmallestWidthDp != other.minSmallestWidthDp) return false
if (maxAspectRatioInPortrait != other.maxAspectRatioInPortrait) return false
if (maxAspectRatioInLandscape != other.maxAspectRatioInLandscape) return false
- if (splitRatio != other.splitRatio) return false
- if (layoutDirection != other.layoutDirection) return false
-
+ if (defaultSplitAttributes != other.defaultSplitAttributes) return false
return true
}
override fun hashCode(): Int {
- var result = minWidthDp
+ var result = super.hashCode()
+ result = 31 * result + minWidthDp
+ result = 31 * result + minHeightDp
result = 31 * result + minSmallestWidthDp
result = 31 * result + maxAspectRatioInPortrait.hashCode()
result = 31 * result + maxAspectRatioInLandscape.hashCode()
- result = 31 * result + splitRatio.hashCode()
- result = 31 * result + layoutDirection
+ result = 31 * result + defaultSplitAttributes.hashCode()
return result
}
override fun toString(): String =
"${SplitRule::class.java.simpleName}{" +
- " splitRatio=$splitRatio" +
- ", layoutDirection=$layoutDirection" +
+ " tag=$tag" +
+ ", defaultSplitAttributes=$defaultSplitAttributes" +
", minWidthDp=$minWidthDp" +
+ ", minHeightDp=$minHeightDp" +
", minSmallestWidthDp=$minSmallestWidthDp" +
", maxAspectRatioInPortrait=$maxAspectRatioInPortrait" +
", maxAspectRatioInLandscape=$maxAspectRatioInLandscape" +
diff --git a/window/window/src/main/java/androidx/window/layout/ContextCompatHelper.kt b/window/window/src/main/java/androidx/window/layout/ContextCompatHelper.kt
new file mode 100644
index 0000000..2bc997d
--- /dev/null
+++ b/window/window/src/main/java/androidx/window/layout/ContextCompatHelper.kt
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2021 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 androidx.window.layout.util
+
+import android.app.Activity
+import android.content.Context
+import android.graphics.Rect
+import android.os.Build
+import android.view.WindowManager
+import androidx.annotation.DoNotInline
+import androidx.annotation.RequiresApi
+import androidx.annotation.UiContext
+import androidx.core.view.WindowInsetsCompat
+import androidx.window.layout.WindowMetrics
+
+@RequiresApi(Build.VERSION_CODES.N)
+internal object ContextCompatHelperApi24 {
+ fun isInMultiWindowMode(activity: Activity): Boolean {
+ return activity.isInMultiWindowMode
+ }
+}
+
+@RequiresApi(Build.VERSION_CODES.R)
+internal object ContextCompatHelperApi30 {
+
+ fun currentWindowMetrics(@UiContext context: Context): WindowMetrics {
+ val wm = context.getSystemService(WindowManager::class.java)
+ val insets = WindowInsetsCompat.toWindowInsetsCompat(wm.currentWindowMetrics.windowInsets)
+ return WindowMetrics(wm.currentWindowMetrics.bounds, insets)
+ }
+
+ fun currentWindowBounds(@UiContext context: Context): Rect {
+ val wm = context.getSystemService(WindowManager::class.java)
+ return wm.currentWindowMetrics.bounds
+ }
+
+ fun currentWindowInsets(@UiContext context: Context): WindowInsetsCompat {
+ val wm = context.getSystemService(WindowManager::class.java)
+ return WindowInsetsCompat.toWindowInsetsCompat(wm.currentWindowMetrics.windowInsets)
+ }
+
+ fun maximumWindowBounds(@UiContext context: Context): Rect {
+ val wm = context.getSystemService(WindowManager::class.java)
+ return wm.maximumWindowMetrics.bounds
+ }
+
+ /**
+ * Computes the [WindowInsetsCompat] for platforms above [Build.VERSION_CODES.R], inclusive.
+ * @DoNotInline required for implementation-specific class method to prevent it from being
+ * inlined.
+ *
+ * @see androidx.window.layout.WindowMetrics.getWindowInsets
+ */
+ @DoNotInline
+ fun currentWindowInsets(activity: Activity): WindowInsetsCompat {
+ val platformInsets = activity.windowManager.currentWindowMetrics.windowInsets
+ return WindowInsetsCompat.toWindowInsetsCompat(platformInsets)
+ }
+}
\ No newline at end of file
diff --git a/window/window/src/main/java/androidx/window/layout/WindowInfoTracker.kt b/window/window/src/main/java/androidx/window/layout/WindowInfoTracker.kt
index 3ae9ec8..242217a 100644
--- a/window/window/src/main/java/androidx/window/layout/WindowInfoTracker.kt
+++ b/window/window/src/main/java/androidx/window/layout/WindowInfoTracker.kt
@@ -18,9 +18,11 @@
import android.app.Activity
import android.content.Context
+import android.inputmethodservice.InputMethodService
import android.util.Log
import androidx.annotation.RestrictTo
import androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP
+import androidx.annotation.UiContext
import androidx.window.core.ConsumerAdapter
import androidx.window.layout.adapter.WindowBackend
import androidx.window.layout.adapter.extensions.ExtensionWindowLayoutInfoBackend
@@ -37,10 +39,48 @@
* A [Flow] of [WindowLayoutInfo] that contains all the available features. A [WindowLayoutInfo]
* contains a [List] of [DisplayFeature] that intersect the associated [android.view.Window].
*
+ * This method exports the same content as
+ * [WindowLayoutInfo.windowLayoutInfo(activity: Activity)], but also supports non-Activity
+ * windows to receive [WindowLayoutInfo] updates. A [WindowLayoutInfo] value should be published
+ * when [DisplayFeature] have changed, but the behavior is ultimately decided by the hardware
+ * implementation. It is recommended to test the following scenarios:
+ *
+ * * Values are emitted immediately after subscribing to this function.
+ * * There is a long delay between subscribing and receiving the first value.
+ * * Never receiving a value after subscription.
+ *
+ * A derived class may throw NotImplementedError if this method is not overridden.
+ * Obtaining a [WindowInfoTracker] through [WindowInfoTracker.getOrCreate] guarantees having a
+ * default implementation for this method.
+ *
+ * @param context a [UiContext] such as an [Activity], an [InputMethodService], or an instance
+ * created via [Context.createWindowContext] that listens to configuration changes.
+ * @see WindowLayoutInfo
+ * @see DisplayFeature
+ *
+ * @throws NotImplementedError when [Context] is not an [UiContext] or this method has no
+ * supporting implementation.
+ */
+ fun windowLayoutInfo(@UiContext context: Context): Flow<WindowLayoutInfo> {
+ val windowLayoutInfoFlow: Flow<WindowLayoutInfo>? = windowLayoutInfo((context as Activity))
+ return windowLayoutInfoFlow
+ ?: throw NotImplementedError(
+ message = "Must override windowLayoutInfo(context) and provide an implementation.")
+ }
+
+ /**
+ * A [Flow] of [WindowLayoutInfo] that contains all the available features. A [WindowLayoutInfo]
+ * contains a [List] of [DisplayFeature] that intersect the associated [android.view.Window].
+ *
* The first [WindowLayoutInfo] will not be emitted until [Activity.onStart] has been called.
- * which values you receive and when is device dependent. It is recommended to test scenarios
- * where there is a long delay between subscribing and receiving the first value or never
- * receiving a value, since it may differ between hardware implementations.
+ * which values you receive and when is device dependent.
+ *
+ * It is recommended to test the following scenarios since behaviors may differ between hardware
+ * implementations:
+ *
+ * * Values are emitted immediately after subscribing to this function.
+ * * There is a long delay between subscribing and receiving the first value.
+ * * Never receiving a value after subscription.
*
* Since the information is associated to the [Activity] you should not retain the [Flow] across
* [Activity] recreations. Doing so can result in unpredictable behavior such as a memory leak
diff --git a/window/window/src/main/java/androidx/window/layout/WindowInfoTrackerImpl.kt b/window/window/src/main/java/androidx/window/layout/WindowInfoTrackerImpl.kt
index 16efaad..0796437 100644
--- a/window/window/src/main/java/androidx/window/layout/WindowInfoTrackerImpl.kt
+++ b/window/window/src/main/java/androidx/window/layout/WindowInfoTrackerImpl.kt
@@ -18,6 +18,7 @@
import android.app.Activity
import android.content.Context
+import androidx.annotation.UiContext
import androidx.core.util.Consumer
import androidx.window.layout.adapter.WindowBackend
import kotlinx.coroutines.channels.awaitClose
@@ -26,7 +27,7 @@
/**
* An implementation of [WindowInfoTracker] that provides the [WindowLayoutInfo] and
- * [WindowMetrics] for the given [Activity].
+ * [WindowMetrics] for the given [Activity] or [UiContext].
*
* @param windowMetricsCalculator a helper to calculate the [WindowMetrics] for the [Activity].
* @param windowBackend a helper to provide the [WindowLayoutInfo].
@@ -37,9 +38,21 @@
) : WindowInfoTracker {
/**
- * A [Flow] of window layout changes in the current visual [Context].
- *
- * @see Activity.onAttachedToWindow
+ * A [Flow] of window layout changes in the current visual [UiContext]. A context has to be
+ * either an [Activity] or created with [Context#createWindowContext].
+ */
+ override fun windowLayoutInfo(@UiContext context: Context): Flow<WindowLayoutInfo> {
+ return callbackFlow {
+ val listener = Consumer { info: WindowLayoutInfo -> trySend(info) }
+ windowBackend.registerLayoutChangeCallback(context, Runnable::run, listener)
+ awaitClose {
+ windowBackend.unregisterLayoutChangeCallback(listener)
+ }
+ }
+ }
+
+ /**
+ * A [Flow] of window layout changes in the current visual [Activity].
*/
override fun windowLayoutInfo(activity: Activity): Flow<WindowLayoutInfo> {
return callbackFlow {
diff --git a/window/window/src/main/java/androidx/window/layout/WindowMetrics.kt b/window/window/src/main/java/androidx/window/layout/WindowMetrics.kt
index bbf6d69..449c566 100644
--- a/window/window/src/main/java/androidx/window/layout/WindowMetrics.kt
+++ b/window/window/src/main/java/androidx/window/layout/WindowMetrics.kt
@@ -19,7 +19,6 @@
import android.os.Build.VERSION_CODES
import androidx.annotation.RequiresApi
import androidx.annotation.RestrictTo
-import androidx.annotation.RestrictTo.Scope.TESTS
import androidx.core.view.WindowInsetsCompat
import androidx.window.core.Bounds
import androidx.window.core.ExperimentalWindowApi
@@ -42,7 +41,7 @@
* An internal constructor for [WindowMetrics]
* @suppress
*/
- @RestrictTo(TESTS)
+ @RestrictTo(RestrictTo.Scope.TESTS)
constructor(
bounds: Rect,
insets: WindowInsetsCompat = WindowInsetsCompat.Builder().build()
diff --git a/window/window/src/main/java/androidx/window/layout/WindowMetricsCalculator.kt b/window/window/src/main/java/androidx/window/layout/WindowMetricsCalculator.kt
index 0de1501..f7181bb 100644
--- a/window/window/src/main/java/androidx/window/layout/WindowMetricsCalculator.kt
+++ b/window/window/src/main/java/androidx/window/layout/WindowMetricsCalculator.kt
@@ -16,14 +16,20 @@
package androidx.window.layout
+import android.view.WindowMetrics as AndroidWindowMetrics
import android.app.Activity
+import android.content.Context
+import android.inputmethodservice.InputMethodService
import android.os.Build
import android.view.Display
+import androidx.annotation.RequiresApi
import androidx.annotation.RestrictTo
+import androidx.annotation.UiContext
+import androidx.core.view.WindowInsetsCompat
import androidx.window.core.ExperimentalWindowApi
/**
- * An interface to calculate the [WindowMetrics] for an [Activity].
+ * An interface to calculate the [WindowMetrics] for an [Activity] or a [UiContext].
*/
interface WindowMetricsCalculator {
@@ -65,6 +71,24 @@
fun computeCurrentWindowMetrics(activity: Activity): WindowMetrics
/**
+ * Computes the size and position of the area the window would occupy with
+ * [MATCH_PARENT][android.view.WindowManager.LayoutParams.MATCH_PARENT] width and height
+ * and any combination of flags that would allow the window to extend behind display cutouts.
+ *
+ * On [Build.VERSION_CODES.Q] and older, a [UiContext] is either an [Activity] or an
+ * [InputMethodService]. On [Build.VERSION_CODES.R] and newer, a [UiContext] can also be one
+ * created via the [Context.createWindowContext] APIs.
+ *
+ * @see [computeCurrentWindowMetrics]
+ * @throws NotImplementedError if not implemented. The default implementation from [getOrCreate]
+ * is guaranteed to implement this method.
+ */
+ fun computeCurrentWindowMetrics(@UiContext context: Context): WindowMetrics {
+ throw NotImplementedError("Must override computeCurrentWindowMetrics(context) and" +
+ " provide an implementation.")
+ }
+
+ /**
* Computes the maximum size and position of the area the window can expect with
* [MATCH_PARENT][android.view.WindowManager.LayoutParams.MATCH_PARENT] width and height
* and any combination of flags that would allow the window to extend behind display cutouts.
@@ -76,6 +100,27 @@
*/
fun computeMaximumWindowMetrics(activity: Activity): WindowMetrics
+ /**
+ * Computes the maximum size and position of the area the window can expect with
+ * [MATCH_PARENT][android.view.WindowManager.LayoutParams.MATCH_PARENT] width and height
+ * and any combination of flags that would allow the window to extend behind display cutouts.
+ *
+ * The value returned from this method will always match [Display.getRealSize] on
+ * [Android 10][Build.VERSION_CODES.Q] and below.
+ *
+ * On [Build.VERSION_CODES.Q] and older, a [UiContext] is either an [Activity] or an
+ * [InputMethodService]. On [Build.VERSION_CODES.R] and newer, a [UiContext] can also be one
+ * created via the [Context.createWindowContext] APIs.
+ *
+ * @see [computeMaximumWindowMetrics]
+ * @throws NotImplementedError if not implemented. The default implementation from [getOrCreate]
+ * is guaranteed to implement this method.
+ */
+ fun computeMaximumWindowMetrics(@UiContext context: Context): WindowMetrics {
+ throw NotImplementedError("Must override computeMaximumWindowMetrics(context) and" +
+ " provide an implementation.")
+ }
+
companion object {
private var decorator: (WindowMetricsCalculator) -> WindowMetricsCalculator =
@@ -99,6 +144,18 @@
fun reset() {
decorator = { it }
}
+
+ /**
+ * Converts [Android API WindowMetrics][AndroidWindowMetrics] to
+ * [Jetpack version WindowMetrics][WindowMetrics]
+ */
+ @Suppress("ClassVerificationFailure")
+ @RequiresApi(Build.VERSION_CODES.R)
+ internal fun translateWindowMetrics(windowMetrics: AndroidWindowMetrics): WindowMetrics =
+ WindowMetrics(
+ windowMetrics.bounds,
+ WindowInsetsCompat.toWindowInsetsCompat(windowMetrics.windowInsets)
+ )
}
}
diff --git a/window/window/src/main/java/androidx/window/layout/WindowMetricsCalculatorCompat.kt b/window/window/src/main/java/androidx/window/layout/WindowMetricsCalculatorCompat.kt
index 4fa733a..72e8ffa 100644
--- a/window/window/src/main/java/androidx/window/layout/WindowMetricsCalculatorCompat.kt
+++ b/window/window/src/main/java/androidx/window/layout/WindowMetricsCalculatorCompat.kt
@@ -21,19 +21,24 @@
import android.content.res.Configuration
import android.graphics.Point
import android.graphics.Rect
+import android.inputmethodservice.InputMethodService
import android.os.Build
import android.os.Build.VERSION_CODES
import android.util.Log
import android.view.Display
import android.view.DisplayCutout
+import android.view.WindowManager
import androidx.annotation.RequiresApi
+import androidx.annotation.UiContext
import androidx.annotation.VisibleForTesting
import androidx.core.view.WindowInsetsCompat
import androidx.window.core.Bounds
import androidx.window.layout.util.ActivityCompatHelperApi24.isInMultiWindowMode
-import androidx.window.layout.util.ActivityCompatHelperApi30.currentWindowBounds
-import androidx.window.layout.util.ActivityCompatHelperApi30.currentWindowInsets
-import androidx.window.layout.util.ActivityCompatHelperApi30.maximumWindowBounds
+import androidx.window.layout.util.ContextCompatHelperApi30.currentWindowBounds
+import androidx.window.layout.util.ContextCompatHelperApi30.currentWindowInsets
+import androidx.window.layout.util.ContextCompatHelperApi30.currentWindowMetrics
+import androidx.window.layout.util.ContextCompatHelperApi30.maximumWindowBounds
+import androidx.window.layout.util.ContextUtils.unwrapUiContext
import androidx.window.layout.util.DisplayCompatHelperApi17.getRealSize
import androidx.window.layout.util.DisplayCompatHelperApi28.safeInsetBottom
import androidx.window.layout.util.DisplayCompatHelperApi28.safeInsetLeft
@@ -49,6 +54,42 @@
private val TAG: String = WindowMetricsCalculatorCompat::class.java.simpleName
/**
+ * Computes the current [WindowMetrics] for a given [Context]. The context can be either
+ * an [Activity], a Context created with [Context#createWindowContext], or an
+ * [InputMethodService].
+ * @see WindowMetricsCalculator.computeCurrentWindowMetrics
+ */
+ override fun computeCurrentWindowMetrics(@UiContext context: Context): WindowMetrics {
+ // TODO(b/259148796): Make WindowMetricsCalculatorCompat more testable
+ if (Build.VERSION.SDK_INT >= VERSION_CODES.R) {
+ return currentWindowMetrics(context)
+ } else {
+ when (unwrapUiContext(context)) {
+ is Activity -> {
+ return computeCurrentWindowMetrics(context as Activity)
+ }
+ is InputMethodService -> {
+ val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
+
+ // On older SDK levels, the app and IME could show up on different displays.
+ // However, there isn't a way for us to figure this out from the application
+ // layer. But, this should be good enough for now given the small likelihood of
+ // IMEs showing up on non-primary displays on these SDK levels.
+ @Suppress("DEPRECATION")
+ val displaySize = getRealSizeForDisplay(wm.defaultDisplay)
+
+ // IME occupies the whole display bounds.
+ val imeBounds = Rect(0, 0, displaySize.x, displaySize.y)
+ return WindowMetrics(imeBounds)
+ }
+ else -> {
+ throw IllegalArgumentException("$context is not a UiContext")
+ }
+ }
+ }
+ }
+
+ /**
* Computes the current [WindowMetrics] for a given [Activity]
* @see WindowMetricsCalculator.computeCurrentWindowMetrics
*/
@@ -78,19 +119,30 @@
* @see WindowMetricsCalculator.computeMaximumWindowMetrics
*/
override fun computeMaximumWindowMetrics(activity: Activity): WindowMetrics {
+ return computeMaximumWindowMetrics(activity as Context)
+ }
+
+ /**
+ * Computes the maximum [WindowMetrics] for a given [UiContext]
+ * @See WindowMetricsCalculator.computeMaximumWindowMetrics
+ */
+ override fun computeMaximumWindowMetrics(@UiContext context: Context): WindowMetrics {
+ // TODO(b/259148796): Make WindowMetricsCalculatorCompat more testable
val bounds = if (Build.VERSION.SDK_INT >= VERSION_CODES.R) {
- maximumWindowBounds(activity)
+ maximumWindowBounds(context)
} else {
+ val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
// [WindowManager#getDefaultDisplay] is deprecated but we have this for
- // compatibility with older versions
+ // compatibility with older versions, as we can't reliably get the display associated
+ // with a Context through public APIs either.
@Suppress("DEPRECATION")
- val display = activity.windowManager.defaultDisplay
+ val display = wm.defaultDisplay
val displaySize = getRealSizeForDisplay(display)
Rect(0, 0, displaySize.x, displaySize.y)
}
// TODO (b/233899790): compute insets for other platform versions below R
val windowInsetsCompat = if (Build.VERSION.SDK_INT >= VERSION_CODES.R) {
- computeWindowInsetsCompat(activity)
+ computeWindowInsetsCompat(context)
} else {
WindowInsetsCompat.Builder().build()
}
@@ -408,13 +460,13 @@
)
/**
- * Computes the current [WindowInsetsCompat] for a given [Activity].
+ * Computes the current [WindowInsetsCompat] for a given [Context].
*/
@RequiresApi(VERSION_CODES.R)
- internal fun computeWindowInsetsCompat(activity: Activity): WindowInsetsCompat {
+ internal fun computeWindowInsetsCompat(@UiContext context: Context): WindowInsetsCompat {
val build = Build.VERSION.SDK_INT
val windowInsetsCompat = if (build >= VERSION_CODES.R) {
- currentWindowInsets(activity)
+ currentWindowInsets(context)
} else {
throw Exception("Incompatible SDK version")
}
diff --git a/window/window/src/main/java/androidx/window/layout/adapter/WindowBackend.kt b/window/window/src/main/java/androidx/window/layout/adapter/WindowBackend.kt
index d799f4a..3524cb1 100644
--- a/window/window/src/main/java/androidx/window/layout/adapter/WindowBackend.kt
+++ b/window/window/src/main/java/androidx/window/layout/adapter/WindowBackend.kt
@@ -16,27 +16,32 @@
package androidx.window.layout.adapter
import android.app.Activity
+import android.content.Context
import androidx.core.util.Consumer
import androidx.window.layout.WindowLayoutInfo
import java.util.concurrent.Executor
+import androidx.annotation.UiContext
/**
* Backing interface for [androidx.window.layout.WindowInfoTracker] instances that serve as the
* default information supplier.
*/
internal interface WindowBackend {
+
/**
- * Registers a callback for layout changes of the window for the supplied [Activity].
+ * Registers a callback for layout changes of the window for the supplied [UiContext].
* Must be called only after the it is attached to the window.
+ * The supplied [UiContext] should correspond to a window or an area on the screen. It must be
+ * either an [Activity] or a [UiContext] created with [Context#createWindowContext].
*/
fun registerLayoutChangeCallback(
- activity: Activity,
+ @UiContext context: Context,
executor: Executor,
callback: Consumer<WindowLayoutInfo>
)
/**
- * Unregisters a callback for window layout changes of the [Activity] window.
+ * Unregisters a callback for window layout changes.
*/
fun unregisterLayoutChangeCallback(callback: Consumer<WindowLayoutInfo>)
}
\ No newline at end of file
diff --git a/window/window/src/main/java/androidx/window/layout/adapter/extensions/ExtensionWindowLayoutInfoBackend.kt b/window/window/src/main/java/androidx/window/layout/adapter/extensions/ExtensionWindowLayoutInfoBackend.kt
index 2c304b4..64e60f8 100644
--- a/window/window/src/main/java/androidx/window/layout/adapter/extensions/ExtensionWindowLayoutInfoBackend.kt
+++ b/window/window/src/main/java/androidx/window/layout/adapter/extensions/ExtensionWindowLayoutInfoBackend.kt
@@ -16,12 +16,17 @@
package androidx.window.layout.adapter.extensions
+import androidx.window.extensions.core.util.function.Consumer as OEMConsumer
import androidx.window.extensions.layout.WindowLayoutInfo as OEMWindowLayoutInfo
import android.app.Activity
+import android.content.Context
import androidx.annotation.GuardedBy
+import androidx.annotation.UiContext
import androidx.annotation.VisibleForTesting
import androidx.core.util.Consumer
import androidx.window.core.ConsumerAdapter
+import androidx.window.core.ExtensionsUtil
+import androidx.window.extensions.WindowExtensions
import androidx.window.extensions.layout.WindowLayoutComponent
import androidx.window.layout.WindowLayoutInfo
import androidx.window.layout.adapter.WindowBackend
@@ -32,8 +37,9 @@
/**
* A wrapper around [WindowLayoutComponent] that ensures
- * [WindowLayoutComponent.addWindowLayoutInfoListener] is called at most once per activity while
- * there are active listeners.
+ * [WindowLayoutComponent.addWindowLayoutInfoListener] is called at most once per context while
+ * there are active listeners. Context has to be an [Activity] or a [UiContext] created with
+ * [Context#createWindowContext] or InputMethodService.
*/
internal class ExtensionWindowLayoutInfoBackend(
private val component: WindowLayoutComponent,
@@ -42,72 +48,117 @@
private val extensionWindowBackendLock = ReentrantLock()
@GuardedBy("lock")
- private val activityToListeners = mutableMapOf<Activity, MulticastConsumer>()
+ private val contextToListeners = mutableMapOf<Context, MulticastConsumer>()
+
@GuardedBy("lock")
- private val listenerToActivity = mutableMapOf<Consumer<WindowLayoutInfo>, Activity>()
+ private val listenerToContext = mutableMapOf<Consumer<WindowLayoutInfo>, Context>()
+
@GuardedBy("lock")
private val consumerToToken = mutableMapOf<MulticastConsumer, ConsumerAdapter.Subscription>()
/**
+ * The mapping from [MulticastConsumer] to Extensions Core version [Consumer]. This is used
+ * to translate [MulticastConsumer] to Extensions APIs after
+ * [WindowExtensions.VENDOR_API_LEVEL_2].
+ *
+ * @see WindowLayoutComponent.addWindowLayoutInfoListener
+ * @see WindowLayoutComponent.removeWindowLayoutInfoListener
+ */
+ @GuardedBy("lock")
+ private val consumerToOemConsumer =
+ mutableMapOf<MulticastConsumer, OEMConsumer<OEMWindowLayoutInfo>>()
+
+ /**
* Registers a listener to consume new values of [WindowLayoutInfo]. If there was a listener
- * registered for a given [Activity] then the new listener will receive a replay of the last
+ * registered for a given [Context] then the new listener will receive a replay of the last
* known value.
- * @param activity the host of a [android.view.Window]
+ * @param context the host of a [android.view.Window] or an area on the screen. Has to be an
+ * [Activity] or a [UiContext] created with [Context#createWindowContext] or InputMethodService.
* @param executor an executor from the parent interface
* @param callback the listener that will receive new values
*/
+ @OptIn(androidx.window.core.ExperimentalWindowApi::class)
override fun registerLayoutChangeCallback(
- activity: Activity,
+ @UiContext context: Context,
executor: Executor,
callback: Consumer<WindowLayoutInfo>
) {
extensionWindowBackendLock.withLock {
- activityToListeners[activity]?.let { listener ->
+ contextToListeners[context]?.let { listener ->
listener.addListener(callback)
- listenerToActivity[callback] = activity
+ listenerToContext[callback] = context
} ?: run {
- val consumer = MulticastConsumer(activity)
- activityToListeners[activity] = consumer
- listenerToActivity[callback] = activity
+ val consumer = MulticastConsumer(context)
+ contextToListeners[context] = consumer
+ listenerToContext[callback] = context
consumer.addListener(callback)
- val disposableToken = consumerAdapter.createSubscription(
- component,
- OEMWindowLayoutInfo::class,
- "addWindowLayoutInfoListener",
- "removeWindowLayoutInfoListener",
- activity
- ) { value ->
- consumer.accept(value)
+ if (ExtensionsUtil.safeVendorApiLevel < WindowExtensions.VENDOR_API_LEVEL_2) {
+ val consumeWindowLayoutInfo: (OEMWindowLayoutInfo) -> Unit = { value ->
+ consumer.accept(value)
+ }
+ // The registrations above maintain 1-many mapping of Context-Listeners across
+ // different subscription implementations.
+ val disposableToken = if (context is Activity) {
+ consumerAdapter.createSubscription(
+ component,
+ OEMWindowLayoutInfo::class,
+ "addWindowLayoutInfoListener",
+ "removeWindowLayoutInfoListener",
+ context,
+ consumeWindowLayoutInfo
+ )
+ } else {
+ // Prior to WM Extensions v2 addWindowLayoutInfoListener only
+ // supports Activities. Return empty WindowLayoutInfo if the
+ // provided Context is not an Activity.
+ consumer.accept(OEMWindowLayoutInfo(emptyList()))
+ return@registerLayoutChangeCallback
+ }
+ consumerToToken[consumer] = disposableToken
+ } else {
+ val oemConsumer = OEMConsumer<OEMWindowLayoutInfo> { info ->
+ consumer.accept(info)
+ }
+ consumerToOemConsumer[consumer] = oemConsumer
+ component.addWindowLayoutInfoListener(context,
+ oemConsumer)
}
- consumerToToken[consumer] = disposableToken
}
}
}
/**
- * Unregisters a listener, if this is the last listener for an [Activity] then the listener is
+ * Unregisters a listener, if this is the last listener for a [UiContext] then the listener is
* removed from the [WindowLayoutComponent]. Calling with the same listener multiple times in a
- * row does not have an effect. @param callback a listener that may have been registered
+ * row does not have an effect.
+ * @param callback a listener that may have been registered
*/
override fun unregisterLayoutChangeCallback(callback: Consumer<WindowLayoutInfo>) {
extensionWindowBackendLock.withLock {
- val activity = listenerToActivity[callback] ?: return
- val multicastListener = activityToListeners[activity] ?: return
+ val context = listenerToContext[callback] ?: return
+ val multicastListener = contextToListeners[context] ?: return
multicastListener.removeListener(callback)
- listenerToActivity.remove(callback)
+ listenerToContext.remove(callback)
if (multicastListener.isEmpty()) {
- consumerToToken.remove(multicastListener)?.dispose()
- activityToListeners.remove(activity)
+ contextToListeners.remove(context)
+ if (ExtensionsUtil.safeVendorApiLevel < WindowExtensions.VENDOR_API_LEVEL_2) {
+ consumerToToken.remove(multicastListener)?.dispose()
+ } else {
+ val oemConsumer = consumerToOemConsumer.remove(multicastListener)
+ if (oemConsumer != null) {
+ component.removeWindowLayoutInfoListener(oemConsumer)
+ }
+ }
}
}
}
/**
- * Returns {@code true} there is any registered listener information, {@code false} otherwise.
+ * Returns {@code true} if all the collections are empty, {@code false} otherwise
*/
@VisibleForTesting
fun hasRegisteredListeners(): Boolean {
- return !(activityToListeners.isEmpty() && listenerToActivity.isEmpty() &&
+ return !(contextToListeners.isEmpty() && listenerToContext.isEmpty() &&
consumerToToken.isEmpty())
}
@@ -117,7 +168,7 @@
* value whenever a new consumer registers.
*/
private class MulticastConsumer(
- private val activity: Activity
+ private val context: Context
) : Consumer<OEMWindowLayoutInfo> {
private val multicastConsumerLock = ReentrantLock()
@GuardedBy("lock")
@@ -127,7 +178,7 @@
override fun accept(value: OEMWindowLayoutInfo) {
multicastConsumerLock.withLock {
- lastKnownValue = translate(activity, value)
+ lastKnownValue = translate(context, value)
registeredListeners.forEach { consumer -> consumer.accept(lastKnownValue) }
}
}
diff --git a/window/window/src/main/java/androidx/window/layout/adapter/extensions/ExtensionsWindowLayoutInfoAdapter.kt b/window/window/src/main/java/androidx/window/layout/adapter/extensions/ExtensionsWindowLayoutInfoAdapter.kt
index 2ba93ca..ed9f74d 100644
--- a/window/window/src/main/java/androidx/window/layout/adapter/extensions/ExtensionsWindowLayoutInfoAdapter.kt
+++ b/window/window/src/main/java/androidx/window/layout/adapter/extensions/ExtensionsWindowLayoutInfoAdapter.kt
@@ -19,6 +19,9 @@
import androidx.window.extensions.layout.FoldingFeature as OEMFoldingFeature
import androidx.window.extensions.layout.WindowLayoutInfo as OEMWindowLayoutInfo
import android.app.Activity
+import android.content.Context
+import android.os.Build
+import androidx.annotation.UiContext
import androidx.window.core.Bounds
import androidx.window.layout.FoldingFeature
import androidx.window.layout.FoldingFeature.State.Companion.FLAT
@@ -27,11 +30,15 @@
import androidx.window.layout.HardwareFoldingFeature.Type.Companion.FOLD
import androidx.window.layout.HardwareFoldingFeature.Type.Companion.HINGE
import androidx.window.layout.WindowLayoutInfo
+import androidx.window.layout.WindowMetrics
import androidx.window.layout.WindowMetricsCalculatorCompat.computeCurrentWindowMetrics
internal object ExtensionsWindowLayoutInfoAdapter {
- internal fun translate(activity: Activity, oemFeature: OEMFoldingFeature): FoldingFeature? {
+ internal fun translate(
+ windowMetrics: WindowMetrics,
+ oemFeature: OEMFoldingFeature,
+ ): FoldingFeature? {
val type = when (oemFeature.type) {
OEMFoldingFeature.TYPE_FOLD -> FOLD
OEMFoldingFeature.TYPE_HINGE -> HINGE
@@ -43,17 +50,36 @@
else -> return null
}
val bounds = Bounds(oemFeature.bounds)
- return if (validBounds(activity, bounds)) {
+ return if (validBounds(windowMetrics, bounds)) {
HardwareFoldingFeature(Bounds(oemFeature.bounds), type, state)
} else {
null
}
}
- internal fun translate(activity: Activity, info: OEMWindowLayoutInfo): WindowLayoutInfo {
+ internal fun translate(
+ @UiContext context: Context,
+ info: OEMWindowLayoutInfo,
+ ): WindowLayoutInfo {
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ translate(computeCurrentWindowMetrics(context), info)
+ } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && (context is Activity)) {
+ translate(computeCurrentWindowMetrics(context), info)
+ } else {
+ throw UnsupportedOperationException(
+ "Display Features are only supported after Q. Display features for non-Activity " +
+ "contexts are not expected to be reported on devices running Q."
+ )
+ }
+ }
+
+ internal fun translate(
+ windowMetrics: WindowMetrics,
+ info: OEMWindowLayoutInfo
+ ): WindowLayoutInfo {
val features = info.displayFeatures.mapNotNull { feature ->
when (feature) {
- is OEMFoldingFeature -> translate(activity, feature)
+ is OEMFoldingFeature -> translate(windowMetrics, feature)
else -> null
}
}
@@ -61,19 +87,17 @@
}
/**
- * Validate the bounds for a [FoldingFeature] within a given [Activity]. Check the following
- * <ul>
- * <li>Bounds are not 0</li>
- * <li>Bounds are either full width or full height</li>
- * <li>Bounds do not take up the entire window</li>
- * </ul>
- *
- * @param activity housing the [FoldingFeature].
+ * Checks the bounds for a [FoldingFeature] within a given [WindowMetrics]. Validates the
+ * following:
+ * - [Bounds] are not `0`
+ * - [Bounds] are either full width or full height
+ * - [Bounds] do not take up the entire [windowMetrics]
+ * @param windowMetrics Extracted from a [UiContext] housing the [FoldingFeature].
* @param bounds the bounds of a [FoldingFeature]
- * @return true if the bounds are valid for the [Activity], false otherwise.
+ * @return true if the bounds are valid for the [WindowMetrics], false otherwise.
*/
- private fun validBounds(activity: Activity, bounds: Bounds): Boolean {
- val windowBounds = computeCurrentWindowMetrics(activity).bounds
+ private fun validBounds(windowMetrics: WindowMetrics, bounds: Bounds): Boolean {
+ val windowBounds = windowMetrics.bounds
if (bounds.isZero) {
return false
}
diff --git a/window/window/src/main/java/androidx/window/layout/adapter/sidecar/SidecarWindowBackend.kt b/window/window/src/main/java/androidx/window/layout/adapter/sidecar/SidecarWindowBackend.kt
index fa9f015..79fd244 100644
--- a/window/window/src/main/java/androidx/window/layout/adapter/sidecar/SidecarWindowBackend.kt
+++ b/window/window/src/main/java/androidx/window/layout/adapter/sidecar/SidecarWindowBackend.kt
@@ -20,6 +20,7 @@
import android.content.Context
import android.util.Log
import androidx.annotation.GuardedBy
+import androidx.annotation.UiContext
import androidx.annotation.VisibleForTesting
import androidx.core.util.Consumer
import androidx.window.core.Version
@@ -54,37 +55,43 @@
}
override fun registerLayoutChangeCallback(
- activity: Activity,
+ @UiContext context: Context,
executor: Executor,
callback: Consumer<WindowLayoutInfo>
) {
- globalLock.withLock {
- val windowExtension = windowExtension
- if (windowExtension == null) {
- if (DEBUG) {
- Log.v(TAG, "Extension not loaded, skipping callback registration.")
+ val activity = context as? Activity
+ activity?.let {
+ globalLock.withLock {
+ val windowExtension = windowExtension
+ if (windowExtension == null) {
+ if (DEBUG) {
+ Log.v(TAG, "Extension not loaded, skipping callback registration.")
+ }
+ callback.accept(WindowLayoutInfo(emptyList()))
+ return
}
- callback.accept(WindowLayoutInfo(emptyList()))
- return
- }
- // Check if the activity was already registered, in case we need to report tracking of
- // a new activity to the extension.
- val isActivityRegistered = isActivityRegistered(activity)
- val callbackWrapper = WindowLayoutChangeCallbackWrapper(activity, executor, callback)
- windowLayoutChangeCallbacks.add(callbackWrapper)
- if (!isActivityRegistered) {
- windowExtension.onWindowLayoutChangeListenerAdded(activity)
- } else {
- // Latest info for the previously registered callback for activity
- // and send it to the new activity
- val lastInfo = windowLayoutChangeCallbacks.firstOrNull {
- activity == it.activity
- }?.lastInfo
- if (lastInfo != null) {
- callbackWrapper.accept(lastInfo)
+ // Check if the activity was already registered, in case we need to report tracking
+ // of a new activity to the extension.
+ val isActivityRegistered = isActivityRegistered(activity)
+ val callbackWrapper =
+ WindowLayoutChangeCallbackWrapper(activity, executor, callback)
+ windowLayoutChangeCallbacks.add(callbackWrapper)
+ if (!isActivityRegistered) {
+ windowExtension.onWindowLayoutChangeListenerAdded(activity)
+ } else {
+ // Latest info for the previously registered callback for activity
+ // and send it to the new activity
+ val lastInfo = windowLayoutChangeCallbacks.firstOrNull {
+ activity == it.activity
+ }?.lastInfo
+ if (lastInfo != null) {
+ callbackWrapper.accept(lastInfo)
+ }
}
}
+ } ?: run {
+ callback.accept(WindowLayoutInfo(emptyList()))
}
}
diff --git a/window/window-samples/src/main/java/androidx/window/sample/demos/DemoItem.kt b/window/window/src/main/java/androidx/window/layout/util/ActivityCompatHelperApi24.kt
similarity index 68%
copy from window/window-samples/src/main/java/androidx/window/sample/demos/DemoItem.kt
copy to window/window/src/main/java/androidx/window/layout/util/ActivityCompatHelperApi24.kt
index fb08562..a4117f0 100644
--- a/window/window-samples/src/main/java/androidx/window/sample/demos/DemoItem.kt
+++ b/window/window/src/main/java/androidx/window/layout/util/ActivityCompatHelperApi24.kt
@@ -13,8 +13,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package androidx.window.sample.demos
+
+package androidx.window.layout.util
import android.app.Activity
+import android.os.Build
+import androidx.annotation.RequiresApi
-class DemoItem(val description: String, val buttonTitle: String, val clazz: Class<out Activity>)
\ No newline at end of file
+@RequiresApi(Build.VERSION_CODES.N)
+internal object ActivityCompatHelperApi24 {
+ fun isInMultiWindowMode(activity: Activity): Boolean {
+ return activity.isInMultiWindowMode
+ }
+}
diff --git a/window/window/src/main/java/androidx/window/layout/util/ActivityCompatHelper.kt b/window/window/src/main/java/androidx/window/layout/util/ContextCompatHelper.kt
similarity index 61%
rename from window/window/src/main/java/androidx/window/layout/util/ActivityCompatHelper.kt
rename to window/window/src/main/java/androidx/window/layout/util/ContextCompatHelper.kt
index aafd1f9..eaafa91 100644
--- a/window/window/src/main/java/androidx/window/layout/util/ActivityCompatHelper.kt
+++ b/window/window/src/main/java/androidx/window/layout/util/ContextCompatHelper.kt
@@ -1,5 +1,5 @@
/*
- * Copyright 2021 The Android Open Source Project
+ * 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.
@@ -16,28 +16,26 @@
package androidx.window.layout.util
-import android.app.Activity
+import android.content.Context
import android.graphics.Rect
import android.os.Build
+import android.view.WindowManager
import androidx.annotation.DoNotInline
import androidx.annotation.RequiresApi
+import androidx.annotation.UiContext
import androidx.core.view.WindowInsetsCompat
-@RequiresApi(Build.VERSION_CODES.N)
-internal object ActivityCompatHelperApi24 {
- fun isInMultiWindowMode(activity: Activity): Boolean {
- return activity.isInMultiWindowMode
- }
-}
-
@RequiresApi(Build.VERSION_CODES.R)
-internal object ActivityCompatHelperApi30 {
- fun currentWindowBounds(activity: Activity): Rect {
- return activity.windowManager.currentWindowMetrics.bounds
+internal object ContextCompatHelper {
+
+ fun currentWindowBounds(@UiContext context: Context): Rect {
+ val wm = context.getSystemService(WindowManager::class.java)
+ return wm.currentWindowMetrics.bounds
}
- fun maximumWindowBounds(activity: Activity): Rect {
- return activity.windowManager.maximumWindowMetrics.bounds
+ fun maximumWindowBounds(@UiContext context: Context): Rect {
+ val wm = context.getSystemService(WindowManager::class.java)
+ return wm.maximumWindowMetrics.bounds
}
/**
@@ -48,8 +46,9 @@
* @see androidx.window.layout.WindowMetrics.getWindowInsets
*/
@DoNotInline
- fun currentWindowInsets(activity: Activity): WindowInsetsCompat {
- val platformInsets = activity.windowManager.currentWindowMetrics.windowInsets
+ fun currentWindowInsets(@UiContext context: Context): WindowInsetsCompat {
+ val wm = context.getSystemService(WindowManager::class.java)
+ val platformInsets = wm.currentWindowMetrics.windowInsets
return WindowInsetsCompat.toWindowInsetsCompat(platformInsets)
}
}
\ No newline at end of file
diff --git a/window/window/src/main/java/androidx/window/layout/util/ContextUtils.kt b/window/window/src/main/java/androidx/window/layout/util/ContextUtils.kt
new file mode 100644
index 0000000..070bdf4
--- /dev/null
+++ b/window/window/src/main/java/androidx/window/layout/util/ContextUtils.kt
@@ -0,0 +1,54 @@
+/*
+ * 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 androidx.window.layout.util
+
+import android.app.Activity
+import android.content.Context
+import android.content.ContextWrapper
+import android.inputmethodservice.InputMethodService
+import androidx.annotation.UiContext
+
+internal object ContextUtils {
+ /**
+ * Given a [UiContext], check if it is a [ContextWrapper]. If so, we need to unwrap it and
+ * return the actual [UiContext] within.
+ */
+ @UiContext
+ internal fun unwrapUiContext(@UiContext context: Context): Context {
+ var iterator = context
+
+ while (iterator is ContextWrapper) {
+ if (iterator is Activity) {
+ // Activities are always ContextWrappers
+ return iterator
+ } else if (iterator is InputMethodService) {
+ // InputMethodService are always ContextWrappers
+ return iterator
+ } else if (iterator.baseContext == null) {
+ return iterator
+ }
+
+ iterator = iterator.baseContext
+ }
+
+ // TODO(b/259148796): This code path is not needed for APIs R and above. However, that is
+ // not clear and also not enforced anywhere. Once we move to version-based implementations,
+ // this ambiguity will no longer exist. Again for clarity, on APIs before R, UiContexts are
+ // Activities or InputMethodServices, so we should never reach this point.
+ throw IllegalArgumentException("Context $context is not a UiContext")
+ }
+}
diff --git a/window/window/src/main/res/values/attrs.xml b/window/window/src/main/res/values/attrs.xml
index 96527f8..8ee9802 100644
--- a/window/window/src/main/res/values/attrs.xml
+++ b/window/window/src/main/res/values/attrs.xml
@@ -14,134 +14,221 @@
See the License for the specific language governing permissions and
limitations under the License.
-->
-<resources>
- <!-- Defines what part of the width should be given to the primary activity. Defaults to an
- equal width split. -->
+<resources xmlns:xs="http://schemas.android.com/apk/res/android">
+ <!-- An attribute for Activity Embedding rules.
+ Defines what part of the Task bounds should be given to the primary container in split.
+ Values in range `(0.0, 1.0)` define the size of the primary container of the split relative
+ to the corresponding parent Task bounds.
+ The default is `0.5`, which is to split with equal width. -->
<attr name="splitRatio" format="float" />
- <!-- The smallest value of width of the parent window when the split should be used. -->
- <attr name="splitMinWidthDp" format="integer" />
- <!-- The smallest value of the smallest-width (sw) of the parent window in any rotation when
- the split should be used. -->
- <attr name="splitMinSmallestWidthDp" format="integer" />
- <!-- The largest value of the aspect ratio, expressed as (height / width) in decimal form, of
- the parent window bounds in portrait when the split should be used.
- `0` or `alwaysAllow` means to always allow split in portrait.
- `-1` or `alwaysDisallow` means to always disallow split in portrait.
- Any other values less than 1 are invalid. -->
- <attr name="splitMaxAspectRatioInPortrait" format="float">
- <!-- Special value to always allow split in portrait. -->
- <enum name="alwaysAllow" value="0" />
- <!-- Special value to always disallow split in portrait. -->
- <enum name="alwaysDisallow" value="-1" />
- </attr>
- <!-- The largest value of the aspect ratio, expressed as (width / height) in decimal form, of
- the parent window bounds in landscape when the split should be used.
- `0` or `alwaysAllow` means to always allow split in landscape.
- `-1` or `alwaysDisallow` means to always disallow split in landscape.
- Any other values less than 1 are invalid. -->
- <attr name="splitMaxAspectRatioInLandscape" format="float">
- <!-- Special value to always allow split in landscape. -->
- <enum name="alwaysAllow" value="0" />
- <!-- Special value to always disallow split in landscape. -->
- <enum name="alwaysDisallow" value="-1" />
- </attr>
- <!-- The layout direction for the split. The value must be one of "ltr", "rtl" or "locale". -->
+ <!-- An attribute for Activity Embedding rules.
+ Defines the layout direction for the Activity Embedding split. -->
<attr name="splitLayoutDirection" format="enum">
- <!-- It splits the task bounds vertically, and the direction is deduced from the default
- language script of locale, which can be either "ltr" or "rtl". -->
- <enum name="locale" value="3" />
- <!-- It splits the task bounds vertically, and put the primary container on the left
- portion, and the secondary container on the right portion. -->
- <enum name="ltr" value="0" />
- <!-- It splits the task bounds vertically, and put the primary container on the right
- portion, and the secondary container on the left portion. -->
- <enum name="rtl" value="1" />
+ <!-- A layout direction that splits the task bounds vertically, and the direction is deduced
+ from the language script of locale. The direction can be either `rtl` or `ltr` -->
+ <enum name="locale" value="0" />
+ <!-- The primary container is placed on the left, and the secondary is on the right hand
+ side. -->
+ <enum name="ltr" value="1" />
+ <!-- The primary container is placed on the right, and the secondary is on the left hand
+ side. -->
+ <enum name="rtl" value="2" />
+ <!-- The primary container is placed on top, and the secondary is at the bottom. -->
+ <enum name="topToBottom" value="3" />
+ <!-- The primary container is placed on bottom, and the secondary is at the top. -->
+ <enum name="bottomToTop" value="4" />
</attr>
+ <!-- An attribute for Activity Embedding rules.
+ An optional but unique string to identify a `SplitPairRule`, `SplitPlaceholderRule` or
+ `ActivityRule`. The suggested usage is to set the tag to be able to differentiate between
+ different rules in the callbacks.
+ For example, it can be used to compute the right `SplitAttributes` for the given split rule
+ in `SplitAttributesCalculator.computeSplitAttributesForParams`. -->
+ <attr name="tag" format="string" />
+ <!-- An attribute for Activity Embedding rules.
+ Background color of Activity Embedding window animation if the animation requires a
+ background.
+ The default is to use the theme's windowBackground. -->
+ <attr name="animationBackgroundColor" format="color" />
+
+ <!-- An attribute for Activity Embedding rules.
+ The smallest value of width of the parent Task bounds when the split should be used, in DP.
+ Uses `0` to always allow split regardless of the parent Task width.
+ The default is `600`. -->
+ <attr name="splitMinWidthDp" format="integer" />
+ <!-- An attribute for Activity Embedding rules.
+ The smallest value of height of the parent Task bounds when the split should be used, in
+ DP.
+ Uses `0` to always allow split regardless of the parent Task height.
+ The default is `600`. -->
+ <attr name="splitMinHeightDp" format="integer" />
+ <!-- An attribute for Activity Embedding rules.
+ The smallest value of the smallest possible width of the parent Task bounds in any rotation
+ when the split should be used, in DP.
+ Uses `0` to always allow split regardless of the parent Task smallest width.
+ The default is `600`. -->
+ <attr name="splitMinSmallestWidthDp" format="integer" />
+ <!-- An attribute for Activity Embedding rules.
+ The largest value of the aspect ratio, expressed as (height / width) in decimal form, of
+ the parent Task bounds in portrait when the split should be used.
+ Uses `0` or `alwaysAllow` to always allow split in portrait.
+ Uses `-1` or `alwaysDisallow` to always disallow split in portrait.
+ Any other values less than `1` are invalid.
+ The default is `1.4`. -->
+ <attr name="splitMaxAspectRatioInPortrait" format="float">
+ <!-- Special value to always allow split in portrait regardless of the aspect ratio. -->
+ <enum name="alwaysAllow" value="0" />
+ <!-- Special value to always disallow split in portrait regardless of the aspect ratio. -->
+ <enum name="alwaysDisallow" value="-1" />
+ </attr>
+ <!-- An attribute for Activity Embedding rules.
+ The largest value of the aspect ratio, expressed as (width / height) in decimal form, of
+ the parent Task bounds in landscape when the split should be used.
+ Uses `0` or `alwaysAllow` to always allow split in landscape.
+ Uses `-1` or `alwaysDisallow` to always disallow split in landscape.
+ Any other values less than `1` are invalid.
+ The default is `alwaysAllow`. -->
+ <attr name="splitMaxAspectRatioInLandscape" format="float">
+ <!-- Special value to always allow split in landscape regardless of the aspect ratio. -->
+ <enum name="alwaysAllow" value="0" />
+ <!-- Special value to always disallow split in landscape regardless of the aspect ratio. -->
+ <enum name="alwaysDisallow" value="-1" />
+ </attr>
+ <!-- An attribute for Activity Embedding rules.
+ Determines what happens with the primary container when all activities are finished in
+ the associated secondary container.
+ The default is `never`. -->
<attr name="finishPrimaryWithSecondary" format="enum">
+ <!-- Never finish the primary container. -->
<enum name="never" value="0" />
+ <!-- Always finish the primary container. -->
<enum name="always" value="1" />
+ <!-- Only finish the primary container when the primary container is displayed adjacent to
+ the secondary container.
+ Does not finish the primary one when the secondary container is stacked on top of
+ the primary. -->
<enum name="adjacent" value="2" />
</attr>
- <attr name="finishPrimaryWithPlaceholder" format="enum">
- <enum name="always" value="1" />
- <enum name="adjacent" value="2" />
- </attr>
+
+ <!-- An attribute for Activity Embedding rules.
+ Determines what happens with the secondary container when all activities are finished
+ in the associated primary container.
+ The default is `always`. -->
<attr name="finishSecondaryWithPrimary" format="enum">
+ <!-- Never finish the secondary container. -->
<enum name="never" value="0" />
+ <!-- Always finish the secondary container. -->
<enum name="always" value="1" />
+ <!-- Only finish the secondary container when the primary container is displayed adjacent to
+ the secondary container.
+ Does not finish the secondary one when the secondary container is stacked on top of
+ the primary. -->
+ <enum name="adjacent" value="2" />
+ </attr>
+ <!-- An attribute for Activity Embedding rules.
+ Determines what happens with the primary container when the associated placeholder
+ activity is being finished.
+ The default is `always`. -->
+ <attr name="finishPrimaryWithPlaceholder" format="enum">
+ <!-- Always finish the primary container. -->
+ <enum name="always" value="1" />
+ <!-- Only finish the primary container when the primary container is displayed adjacent to
+ the placeholder container.
+ Does not finish the primary one when the placeholder container is stacked on top of
+ the primary. -->
<enum name="adjacent" value="2" />
</attr>
- <!-- Split configuration rules for activity pairs. Must contain at least one SplitPairFilter.
- See androidx.window.embedding.SplitPairRule for complete documentation. -->
+ <!-- Attributes that are read when parsing a <SplitPairRule> tag, which defines the split
+ configuration rules for activity pairs.
+ Must contain at least one `SplitPairFilter`. -->
<declare-styleable name="SplitPairRule">
- <!-- When all activities are finished in the secondary container, the activity in the
- primary container that created the split should also be finished. Defaults to "never". -->
- <attr name="finishPrimaryWithSecondary" />
- <!-- When all activities are finished in the primary container, the activities in the
- secondary container in the split should also be finished. Defaults to "always". -->
- <attr name="finishSecondaryWithPrimary" />
- <!-- If there is an existing split with the same primary container, indicates whether the
- existing secondary container on top and all activities in it should be destroyed when a new
- split is created using this rule. Otherwise the new secondary will appear on top. Defaults
- to "false". -->
+ <!-- An attribute for Activity Embedding rules.
+ If there is an existing split with the same primary container, indicates whether the
+ existing secondary container on top and all activities in it should be destroyed when a
+ new split is created using this rule. Otherwise the new secondary will appear on top.
+ The default is 'false'. -->
<attr name="clearTop" format="boolean" />
+ <attr name="finishPrimaryWithSecondary" />
+ <attr name="finishSecondaryWithPrimary" />
<attr name="splitRatio"/>
<attr name="splitMinWidthDp"/>
+ <attr name="splitMinHeightDp"/>
<attr name="splitMinSmallestWidthDp"/>
<attr name="splitMaxAspectRatioInPortrait" />
<attr name="splitMaxAspectRatioInLandscape" />
<attr name="splitLayoutDirection"/>
+ <attr name="tag"/>
+ <attr name="animationBackgroundColor"/>
</declare-styleable>
- <!-- Configuration rules for split placeholders. Must contain at least one ActivityFilter for
- the primary activity for which the rule should be applied.
- See androidx.window.embedding.SplitPlaceholderRule for complete documentation. -->
+ <!-- Attributes that are read when parsing a <SplitPlaceholderRule> tag, which defines the split
+ configuration rules for split placeholders.
+ Must contain at least one `ActivityFilter` for the primary activity for which the rule
+ should be applied. -->
<declare-styleable name="SplitPlaceholderRule">
- <!-- Component name of the placeholder activity in the split. Must be non-empty. -->
+ <!-- An attribute for Activity Embedding rules.
+ Component name of the placeholder activity to launch in the split.
+ Must be non-empty. -->
<attr name="placeholderActivityName" format="string" />
- <!-- Determines whether the placeholder will show on top in a smaller window size after
- it first appeared in a split with sufficient minimum width. -->
+ <!-- An attribute for Activity Embedding rules.
+ Determines whether the placeholder will show on top if Task window constraints are not
+ satisfied after it first appeared in a split with sufficient Task window constraints.
+ The default is `false`. -->
<attr name="stickyPlaceholder" format="boolean" />
- <!-- When all activities are finished in the secondary container, the activity in the
- primary container that created the split should also be finished. Defaults to "always". -->
- <attr name="finishPrimaryWithPlaceholder" />
+ <attr name="finishPrimaryWithPlaceholder"/>
<attr name="splitRatio"/>
<attr name="splitMinWidthDp"/>
+ <attr name="splitMinHeightDp"/>
<attr name="splitMinSmallestWidthDp"/>
<attr name="splitMaxAspectRatioInPortrait" />
<attr name="splitMaxAspectRatioInLandscape" />
<attr name="splitLayoutDirection"/>
+ <attr name="tag"/>
+ <attr name="animationBackgroundColor"/>
</declare-styleable>
- <!-- Filter used to find if a pair of activities should be put in a split. -->
+ <!-- Attributes that are read when parsing an <ActivityRule> tag, which defines the layout
+ configuration rules for individual activities. It takes precedence over `SplitPairRule`.
+ Must contain at least one `ActivityFilter`. -->
+ <declare-styleable name="ActivityRule">
+ <!-- An attribute for Activity Embedding rules.
+ Whether the activity should always be expanded on launch.
+ The default is `false`. -->
+ <attr name="alwaysExpand" format="boolean" />
+ <attr name="tag"/>
+ </declare-styleable>
+
+ <!-- Attributes that are read when parsing an <SplitPairFilter> tag, which defines the filter
+ for `SplitPairRule`. -->
<declare-styleable name="SplitPairFilter">
- <!-- Component name of the primary activity in the split. Must be non-empty. Can contain a
- wildcard at the end or instead of package name and/or class name. -->
+ <!-- An attribute for Activity Embedding rules.
+ Component name of the primary activity in the split. Must be non-empty. Can contain a
+ wildcard at the end or instead of package name and/or class name. -->
<attr name="primaryActivityName" format="string" />
- <!-- Component name of the secondary activity in the split. Must be non-empty. Can contain a
- wildcard at the end or instead of package name and/or class name. -->
+ <!-- An attribute for Activity Embedding rules.
+ Component name of the secondary activity in the split. Must be non-empty. Can contain a
+ wildcard at the end or instead of package name and/or class name. -->
<attr name="secondaryActivityName" format="string" />
- <!-- Action used for secondary activity launch. May be empty. Must not contain wildcards.
- -->
+ <!-- An attribute for Activity Embedding rules.
+ Action used for the secondary activity launch. May be empty. Must not contain
+ wildcards.
+ When it is set, the filter only matches if the secondary activity is launched with an
+ intent with the given action. -->
<attr name="secondaryActivityAction" format="string" />
</declare-styleable>
- <!-- Layout configuration rules for individual activities. Takes precedence over
- SplitPairRule. Must contain at least one ActivityFilter.
- See androidx.window.layout.ActivityRule for complete documentation. -->
- <declare-styleable name="ActivityRule">
- <!-- Whether the activity should always be expanded on launch. -->
- <attr name="alwaysExpand" format="boolean" />
- </declare-styleable>
-
- <!-- Filter for ActivityRule. -->
+ <!-- Attributes that are read when parsing an <ActivityFilter> tag, which defines the filter
+ Filter for `ActivityRule` and `SplitPlaceholderRule`. -->
<declare-styleable name="ActivityFilter">
- <!-- Component name of the primary activity in the split. Must be non-empty. Can contain a
- single wildcard at the end. -->
+ <!-- An attribute for Activity Embedding rules.
+ Component name of the launched activity. Must be non-empty. Can contain a single
+ wildcard at the end. -->
<attr name="activityName" format="string" />
- <!-- Action used for activity launch. May be empty. Must not contain wildcards.
- -->
+ <!-- An attribute for Activity Embedding rules.
+ Action used for the activity launch. May be empty. Must not contain wildcards.
+ When it is set, the filter only matches if the activity is launched with an intent with
+ the given action. -->
<attr name="activityAction" format="string" />
</declare-styleable>
</resources>
\ No newline at end of file
diff --git a/window/window/src/main/res/values/public.xml b/window/window/src/main/res/values/public.xml
new file mode 100644
index 0000000..70d9306
--- /dev/null
+++ b/window/window/src/main/res/values/public.xml
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?><!--
+ Copyright 2023 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.
+ -->
+<resources>
+ <public name="splitRatio" type="attr" />
+ <public name="splitLayoutDirection" type="attr" />
+ <public name="tag" type="attr" />
+ <public name="animationBackgroundColor" type="attr" />
+
+ <public name="splitMinWidthDp" type="attr" />
+ <public name="splitMinHeightDp" type="attr" />
+ <public name="splitMinSmallestWidthDp" type="attr" />
+ <public name="splitMaxAspectRatioInPortrait" type="attr" />
+ <public name="splitMaxAspectRatioInLandscape" type="attr" />
+
+ <public name="finishPrimaryWithSecondary" type="attr" />
+ <public name="finishSecondaryWithPrimary" type="attr" />
+ <public name="finishPrimaryWithPlaceholder" type="attr" />
+
+ <public name="clearTop" type="attr" />
+ <public name="placeholderActivityName" type="attr" />
+ <public name="stickyPlaceholder" type="attr" />
+ <public name="alwaysExpand" type="attr" />
+ <public name="primaryActivityName" type="attr" />
+ <public name="secondaryActivityName" type="attr" />
+ <public name="secondaryActivityAction" type="attr" />
+ <public name="activityName" type="attr" />
+ <public name="activityAction" type="attr" />
+</resources>
\ No newline at end of file
diff --git a/window/window/src/test/java/androidx/window/area/WindowAreaStatusUnitTest.kt b/window/window/src/test/java/androidx/window/area/WindowAreaStatusUnitTest.kt
new file mode 100644
index 0000000..04d3702
--- /dev/null
+++ b/window/window/src/test/java/androidx/window/area/WindowAreaStatusUnitTest.kt
@@ -0,0 +1,49 @@
+/*
+ * Copyright 2021 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 androidx.window.area
+
+import androidx.window.core.ExperimentalWindowApi
+import androidx.window.extensions.area.WindowAreaComponent
+import org.junit.Test
+
+/**
+ * Unit tests for [WindowAreaStatus] that run on the JVM.
+ */
+@OptIn(ExperimentalWindowApi::class)
+class WindowAreaStatusUnitTest {
+
+ @Test
+ fun testWindowAreaStatusTranslateValueAvailable() {
+ val expected = WindowAreaStatus.AVAILABLE
+ val translateValue = WindowAreaStatus.translate(WindowAreaComponent.STATUS_AVAILABLE)
+ assert(expected == translateValue)
+ }
+
+ @Test
+ fun testWindowAreaStatusTranslateValueUnavailable() {
+ val expected = WindowAreaStatus.UNAVAILABLE
+ val translateValue = WindowAreaStatus.translate(WindowAreaComponent.STATUS_UNAVAILABLE)
+ assert(expected == translateValue)
+ }
+
+ @Test
+ fun testWindowAreaStatusTranslateValueUnsupported() {
+ val expected = WindowAreaStatus.UNSUPPORTED
+ val translateValue = WindowAreaStatus.translate(WindowAreaComponent.STATUS_UNSUPPORTED)
+ assert(expected == translateValue)
+ }
+}
\ No newline at end of file
diff --git a/window/window/src/test/java/androidx/window/core/ConsumerAdapterTest.kt b/window/window/src/test/java/androidx/window/core/ConsumerAdapterTest.kt
index 57709d2..cc18d1e 100644
--- a/window/window/src/test/java/androidx/window/core/ConsumerAdapterTest.kt
+++ b/window/window/src/test/java/androidx/window/core/ConsumerAdapterTest.kt
@@ -18,6 +18,8 @@
import android.annotation.SuppressLint
import android.app.Activity
+import android.content.Context
+import android.os.Build
import org.mockito.kotlin.mock
import java.util.function.Consumer
import org.junit.Assert.assertEquals
@@ -38,7 +40,12 @@
}
@Suppress("UNUSED_PARAMETER")
- fun addConsumer(a: Activity, c: Consumer<String>) {
+ fun addConsumer(context: Context, c: Consumer<String>) {
+ consumers.add(c)
+ }
+
+ @Suppress("UNUSED_PARAMETER")
+ fun addConsumer(activity: Activity, c: Consumer<String>) {
consumers.add(c)
}
@@ -85,6 +92,29 @@
}
@Test
+ fun testSubscribeByReflectionForContext() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
+ // java.util.function.Consumer#accept is supported after N.
+ return
+ }
+ val values = mutableListOf<String>()
+ val context = mock<Context>()
+ adapter.createSubscription(
+ listenerInterface,
+ String::class,
+ "addConsumer",
+ "removeConsumer",
+ context
+ ) { s: String ->
+ values.add(s)
+ }
+
+ assertEquals(1, listenerInterface.consumers.size)
+ listenerInterface.consumers.first().accept(value)
+ assertEquals(listOf(value), values)
+ }
+
+ @Test
fun testDisposeSubscribe() {
val values = mutableListOf<String>()
val subscription = adapter.createSubscription(
@@ -102,6 +132,24 @@
}
@Test
+ fun testDisposeSubscribeForContext() {
+ val values = mutableListOf<String>()
+ val context = mock<Context>()
+ val subscription = adapter.createSubscription(
+ listenerInterface,
+ String::class,
+ "addConsumer",
+ "removeConsumer",
+ context
+ ) { s: String ->
+ values.add(s)
+ }
+ subscription.dispose()
+
+ assertTrue(listenerInterface.consumers.isEmpty())
+ }
+
+ @Test
fun testToStringAdd() {
val values = mutableListOf<String>()
val consumer: (String) -> Unit = { s: String -> values.add(s) }
diff --git a/window/window/src/test/java/androidx/window/embedding/EmbeddingCompatTest.kt b/window/window/src/test/java/androidx/window/embedding/EmbeddingCompatTest.kt
index 9e42ae6..aa9e3f1 100644
--- a/window/window/src/test/java/androidx/window/embedding/EmbeddingCompatTest.kt
+++ b/window/window/src/test/java/androidx/window/embedding/EmbeddingCompatTest.kt
@@ -16,9 +16,14 @@
package androidx.window.embedding
+import java.util.function.Consumer as JavaConsumer
+import androidx.window.extensions.embedding.SplitInfo as OEMSplitInfo
import android.app.Activity
import androidx.window.core.ConsumerAdapter
+import androidx.window.core.ExtensionsUtil
import androidx.window.core.PredicateAdapter
+import androidx.window.extensions.WindowExtensions.VENDOR_API_LEVEL_2
+import androidx.window.extensions.core.util.function.Consumer
import androidx.window.extensions.embedding.ActivityEmbeddingComponent
import org.junit.Test
import org.mockito.kotlin.any
@@ -28,6 +33,7 @@
class EmbeddingCompatTest {
private val component = mock<ActivityEmbeddingComponent>()
+ private val vendorApiLevel = ExtensionsUtil.safeVendorApiLevel
private val embeddingCompat = EmbeddingCompat(
component,
EMBEDDING_ADAPTER,
@@ -35,6 +41,7 @@
mock()
)
+ @Suppress("Deprecation")
@Test
fun setSplitInfoCallback_callsActualMethod() {
val callback = object : EmbeddingInterfaceCompat.EmbeddingCallbackInterface {
@@ -43,7 +50,11 @@
}
embeddingCompat.setEmbeddingCallback(callback)
- verify(component).setSplitInfoCallback(any())
+ if (vendorApiLevel < VENDOR_API_LEVEL_2) {
+ verify(component).setSplitInfoCallback(any<JavaConsumer<List<OEMSplitInfo>>>())
+ } else {
+ verify(component).setSplitInfoCallback(any<Consumer<List<OEMSplitInfo>>>())
+ }
}
@Test
diff --git a/window/window/src/test/java/androidx/window/embedding/SplitAttributesTest.kt b/window/window/src/test/java/androidx/window/embedding/SplitAttributesTest.kt
new file mode 100644
index 0000000..96571cc
--- /dev/null
+++ b/window/window/src/test/java/androidx/window/embedding/SplitAttributesTest.kt
@@ -0,0 +1,148 @@
+/*
+ * 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 androidx.window.embedding
+
+import android.graphics.Color
+import androidx.window.core.WindowStrictModeException
+import androidx.window.embedding.SplitAttributes.LayoutDirection.Companion.BOTTOM_TO_TOP
+import androidx.window.embedding.SplitAttributes.LayoutDirection.Companion.LEFT_TO_RIGHT
+import androidx.window.embedding.SplitAttributes.LayoutDirection.Companion.LOCALE
+import androidx.window.embedding.SplitAttributes.LayoutDirection.Companion.RIGHT_TO_LEFT
+import androidx.window.embedding.SplitAttributes.LayoutDirection.Companion.TOP_TO_BOTTOM
+import androidx.window.embedding.SplitAttributes.SplitType
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotEquals
+import org.junit.Assert.assertThrows
+import org.junit.Test
+
+/** Test class to verify [SplitAttributes] */
+class SplitAttributesTest {
+ @Test
+ fun testSplitAttributesEquals() {
+ val attrs1 = SplitAttributes.Builder()
+ .setSplitType(SplitType.splitEqually())
+ .setLayoutDirection(LOCALE)
+ .setAnimationBackgroundColor(0)
+ .build()
+ val attrs2 = SplitAttributes.Builder()
+ .setSplitType(SplitType.splitByHinge())
+ .setLayoutDirection(LOCALE)
+ .setAnimationBackgroundColor(0)
+ .build()
+ val attrs3 = SplitAttributes.Builder()
+ .setSplitType(SplitType.splitByHinge())
+ .setLayoutDirection(TOP_TO_BOTTOM)
+ .setAnimationBackgroundColor(0)
+ .build()
+ val attrs4 = SplitAttributes.Builder()
+ .setSplitType(SplitType.splitByHinge())
+ .setLayoutDirection(TOP_TO_BOTTOM)
+ .setAnimationBackgroundColor(Color.GREEN)
+ .build()
+ val attrs5 = SplitAttributes.Builder()
+ .setSplitType(SplitType.splitByHinge())
+ .setLayoutDirection(TOP_TO_BOTTOM)
+ .setAnimationBackgroundColor(Color.GREEN)
+ .build()
+
+ assertNotEquals(attrs1, attrs2)
+ assertNotEquals(attrs1.hashCode(), attrs2.hashCode())
+
+ assertNotEquals(attrs2, attrs3)
+ assertNotEquals(attrs2.hashCode(), attrs3.hashCode())
+
+ assertNotEquals(attrs3, attrs1)
+ assertNotEquals(attrs3.hashCode(), attrs1.hashCode())
+
+ assertNotEquals(attrs3, attrs4)
+ assertNotEquals(attrs3.hashCode(), attrs4.hashCode())
+
+ assertEquals(attrs4, attrs5)
+ assertEquals(attrs4.hashCode(), attrs5.hashCode())
+ }
+
+ @Test
+ fun testTypesEquals() {
+ val splitTypes = arrayOf(
+ SplitType.splitEqually(),
+ SplitType.expandContainers(),
+ SplitType.splitByHinge(),
+ SplitType.splitByHinge(SplitType.expandContainers())
+ )
+
+ for ((i, type1) in splitTypes.withIndex()) {
+ if (type1 is SplitType.RatioSplitType) {
+ assertEquals(
+ "Two SplitTypes must regarded as equal if their ratios are the same.",
+ type1, SplitType.ratio(type1.value)
+ )
+ assertEquals(type1.hashCode(), SplitType.ratio(type1.value).hashCode())
+ }
+ for ((j, type2) in splitTypes.withIndex()) {
+ if (i == j) {
+ assertEquals(type1, type2)
+ assertEquals(type1.hashCode(), type2.hashCode())
+ } else {
+ assertNotEquals(type1, type2)
+ assertNotEquals(type1.hashCode(), type2.hashCode())
+ }
+ }
+ }
+ }
+
+ @Test
+ fun testSplitRatioRatio() {
+ assertThrows(WindowStrictModeException::class.java) {
+ SplitType.ratio(-0.01f)
+ }
+ assertThrows(WindowStrictModeException::class.java) {
+ SplitType.ratio(0.0f)
+ }
+ SplitType.ratio(0.001f)
+ SplitType.ratio(0.5f)
+ SplitType.ratio(0.999f)
+ assertThrows(WindowStrictModeException::class.java) {
+ SplitType.ratio(1.0f)
+ }
+ assertThrows(WindowStrictModeException::class.java) {
+ SplitType.ratio(1.1f)
+ }
+ }
+
+ @Test
+ fun testLayoutDirectionEquals() {
+ val layoutDirectionList = arrayOf(
+ LOCALE,
+ LEFT_TO_RIGHT,
+ RIGHT_TO_LEFT,
+ TOP_TO_BOTTOM,
+ BOTTOM_TO_TOP,
+ )
+
+ for ((i, layoutDirection1) in layoutDirectionList.withIndex()) {
+ for ((j, layoutDirection2) in layoutDirectionList.withIndex()) {
+ if (i == j) {
+ assertEquals(layoutDirection1, layoutDirection2)
+ assertEquals(layoutDirection1.hashCode(), layoutDirection2.hashCode())
+ } else {
+ assertNotEquals(layoutDirection1, layoutDirection2)
+ assertNotEquals(layoutDirection1.hashCode(), layoutDirection2.hashCode())
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/window/window/src/test/java/androidx/window/embedding/SplitInfoTest.kt b/window/window/src/test/java/androidx/window/embedding/SplitInfoTest.kt
index 8f15b16..06c6bbc 100644
--- a/window/window/src/test/java/androidx/window/embedding/SplitInfoTest.kt
+++ b/window/window/src/test/java/androidx/window/embedding/SplitInfoTest.kt
@@ -29,7 +29,8 @@
val activity = mock<Activity>()
val firstStack = ActivityStack(listOf(activity))
val secondStack = ActivityStack(emptyList())
- val info = SplitInfo(firstStack, secondStack, 0.5f)
+ val attributes = SplitAttributes()
+ val info = SplitInfo(firstStack, secondStack, attributes)
assertTrue(info.contains(activity))
}
@@ -39,7 +40,8 @@
val activity = mock<Activity>()
val firstStack = ActivityStack(emptyList())
val secondStack = ActivityStack(listOf(activity))
- val info = SplitInfo(firstStack, secondStack, 0.5f)
+ val attributes = SplitAttributes()
+ val info = SplitInfo(firstStack, secondStack, attributes)
assertTrue(info.contains(activity))
}
@@ -49,8 +51,9 @@
val activity = mock<Activity>()
val firstStack = ActivityStack(emptyList())
val secondStack = ActivityStack(listOf(activity))
- val firstInfo = SplitInfo(firstStack, secondStack, 0.5f)
- val secondInfo = SplitInfo(firstStack, secondStack, 0.5f)
+ val attributes = SplitAttributes()
+ val firstInfo = SplitInfo(firstStack, secondStack, attributes)
+ val secondInfo = SplitInfo(firstStack, secondStack, attributes)
assertEquals(firstInfo, secondInfo)
assertEquals(firstInfo.hashCode(), secondInfo.hashCode())
diff --git a/window/window/src/test/java/androidx/window/layout/adapter/sidecar/SidecarWindowBackendUnitTest.kt b/window/window/src/test/java/androidx/window/layout/adapter/sidecar/SidecarWindowBackendUnitTest.kt
index a5d698f..f286aa1 100644
--- a/window/window/src/test/java/androidx/window/layout/adapter/sidecar/SidecarWindowBackendUnitTest.kt
+++ b/window/window/src/test/java/androidx/window/layout/adapter/sidecar/SidecarWindowBackendUnitTest.kt
@@ -73,6 +73,18 @@
}
@Test
+ public fun testRegisterLayoutChangeCallback_withContext() {
+ val backend = SidecarWindowBackend.getInstance(context)
+ backend.windowExtension = mock()
+
+ // Check registering the layout change callback
+ val consumer = mock<Consumer<WindowLayoutInfo>>()
+ val context = mock<Context>()
+ backend.registerLayoutChangeCallback(context, { obj: Runnable -> obj.run() }, consumer)
+ verify(consumer).accept(any())
+ }
+
+ @Test
public fun testRegisterLayoutChangeCallback_noExtension() {
val backend = SidecarWindowBackend.getInstance(context)
backend.windowExtension = null
diff --git a/window/window/src/testUtil/java/androidx/window/layout/TestWindowMetricsCalculator.kt b/window/window/src/testUtil/java/androidx/window/layout/TestWindowMetricsCalculator.kt
index 9ec07b1..5206e1e 100644
--- a/window/window/src/testUtil/java/androidx/window/layout/TestWindowMetricsCalculator.kt
+++ b/window/window/src/testUtil/java/androidx/window/layout/TestWindowMetricsCalculator.kt
@@ -16,7 +16,9 @@
package androidx.window.layout
import android.app.Activity
+import android.content.Context
import android.graphics.Rect
+import androidx.annotation.UiContext
/**
* Implementation of [WindowMetricsCalculator] for testing.
@@ -24,44 +26,62 @@
* @see WindowMetricsCalculator
*/
internal class TestWindowMetricsCalculator : WindowMetricsCalculator {
- private var globalOverriddenBounds: Rect? = null
- private val overriddenBounds = mutableMapOf<Activity, Rect?>()
- private val overriddenMaximumBounds = mutableMapOf<Activity, Rect?>()
+ private var overrideBounds: Rect? = null
+ private var overrideMaxBounds: Rect? = null
+ private val currentBounds = mutableMapOf<Context, Rect>()
+ private val maxBounds = mutableMapOf<Context, Rect>()
/**
- * Overrides the bounds returned from this helper for the given context. Passing `null` [bounds]
- * has the effect of clearing the bounds override.
+ * Sets the bounds returned from this helper for the given context.
*
- * Note: A global override set as a result of [.setCurrentBounds] takes precedence
- * over the value set with this method.
+ * Note: An override set via [setOverrideBounds] takes precedence over the values set with
+ * this method.
*/
- fun setCurrentBoundsForActivity(activity: Activity, bounds: Rect?) {
- overriddenBounds[activity] = bounds
+ fun setBounds(@UiContext context: Context, currentBounds: Rect, maxBounds: Rect) {
+ this.currentBounds[context] = currentBounds
+ this.maxBounds[context] = maxBounds
}
/**
- * Overrides the max bounds returned from this helper for the given context. Passing `null`
- * [bounds] has the effect of clearing the bounds override.
+ * Clears the bounds that were set via [setBounds] for the given context.
*/
- fun setMaximumBoundsForActivity(activity: Activity, bounds: Rect?) {
- overriddenMaximumBounds[activity] = bounds
+ fun clearBounds(@UiContext context: Context) {
+ currentBounds.remove(context)
+ maxBounds.remove(context)
}
/**
- * Overrides the bounds returned from this helper for all supplied contexts. Passing null
- * [bounds] has the effect of clearing the global override.
+ * Overrides the bounds returned from this helper for all supplied contexts.
*/
- fun setCurrentBounds(bounds: Rect?) {
- globalOverriddenBounds = bounds
+ fun setOverrideBounds(currentBounds: Rect, maxBounds: Rect) {
+ overrideBounds = currentBounds
+ overrideMaxBounds = maxBounds
+ }
+
+ /**
+ * Clears the overrides that were set in [setOverrideBounds].
+ */
+ fun clearOverrideBounds() {
+ overrideBounds = null
+ overrideMaxBounds = null
}
override fun computeCurrentWindowMetrics(activity: Activity): WindowMetrics {
- val bounds = globalOverriddenBounds ?: overriddenBounds[activity] ?: Rect()
+ return computeCurrentWindowMetrics(activity as Context)
+ }
+
+ override fun computeCurrentWindowMetrics(@UiContext context: Context): WindowMetrics {
+ val bounds = overrideBounds ?: currentBounds[context] ?: Rect()
return WindowMetrics(bounds)
}
override fun computeMaximumWindowMetrics(activity: Activity): WindowMetrics {
- return WindowMetrics(overriddenMaximumBounds[activity] ?: Rect())
+ return computeMaximumWindowMetrics(activity as Context)
+ }
+
+ override fun computeMaximumWindowMetrics(@UiContext context: Context): WindowMetrics {
+ val bounds = overrideMaxBounds ?: maxBounds[context] ?: Rect()
+ return WindowMetrics(bounds)
}
/**
@@ -69,8 +89,9 @@
* [.setCurrentBoundsForActivity].
*/
fun reset() {
- globalOverriddenBounds = null
- overriddenBounds.clear()
- overriddenMaximumBounds.clear()
+ overrideBounds = null
+ overrideMaxBounds = null
+ currentBounds.clear()
+ maxBounds.clear()
}
}