cls);
+
+ class Helper {
+ public static String getAction(Class
cls) {
+ ProvidesInterface info = cls.getDeclaredAnnotation(ProvidesInterface.class);
+ if (info == null) {
+ throw new RuntimeException(cls + " doesn't provide an interface");
+ }
+ if (TextUtils.isEmpty(info.action())) {
+ throw new RuntimeException(cls + " doesn't provide an action");
+ }
+ return info.action();
+ }
+ }
+
+}
diff --git a/SystemUIShared/src/com/android/systemui/shared/plugins/PluginManagerImpl.java b/SystemUIShared/src/com/android/systemui/shared/plugins/PluginManagerImpl.java
new file mode 100644
index 0000000000..843914b272
--- /dev/null
+++ b/SystemUIShared/src/com/android/systemui/shared/plugins/PluginManagerImpl.java
@@ -0,0 +1,491 @@
+/*
+ * Copyright (C) 2016 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 com.android.systemui.shared.plugins;
+
+import android.app.LoadedApk;
+import android.app.Notification;
+import android.app.Notification.Action;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.content.res.Resources;
+import android.net.Uri;
+import android.os.Build;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.SystemProperties;
+import android.text.TextUtils;
+import android.util.ArrayMap;
+import android.util.ArraySet;
+import android.util.Log;
+import android.widget.Toast;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
+import com.android.systemui.plugins.Plugin;
+import com.android.systemui.plugins.PluginListener;
+import com.android.systemui.plugins.annotations.ProvidesInterface;
+import com.android.systemui.shared.plugins.PluginInstanceManager.PluginInfo;
+
+import dalvik.system.PathClassLoader;
+
+import java.io.File;
+import java.io.FileDescriptor;
+import java.io.PrintWriter;
+import java.lang.Thread.UncaughtExceptionHandler;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+/**
+ * @see Plugin
+ */
+public class PluginManagerImpl extends BroadcastReceiver implements PluginManager {
+
+ private static final String TAG = PluginManagerImpl.class.getSimpleName();
+ static final String DISABLE_PLUGIN = "com.android.systemui.action.DISABLE_PLUGIN";
+
+ private static PluginManager sInstance;
+
+ private final ArrayMap, PluginInstanceManager> mPluginMap
+ = new ArrayMap<>();
+ private final Map mClassLoaders = new ArrayMap<>();
+ private final ArraySet mOneShotPackages = new ArraySet<>();
+ private final ArraySet mWhitelistedPlugins = new ArraySet<>();
+ private final Context mContext;
+ private final PluginInstanceManagerFactory mFactory;
+ private final boolean isDebuggable;
+ private final PluginPrefs mPluginPrefs;
+ private final PluginEnabler mPluginEnabler;
+ private final PluginInitializer mPluginInitializer;
+ private ClassLoaderFilter mParentClassLoader;
+ private boolean mListening;
+ private boolean mHasOneShot;
+ private Looper mLooper;
+
+ public PluginManagerImpl(Context context, PluginInitializer initializer) {
+ this(context, new PluginInstanceManagerFactory(), Build.IS_DEBUGGABLE,
+ (UncaughtExceptionHandler) invoke(sGetUncaughtExceptionPreHandler, null), initializer);
+ }
+
+ @VisibleForTesting
+ PluginManagerImpl(Context context, PluginInstanceManagerFactory factory, boolean debuggable,
+ UncaughtExceptionHandler defaultHandler, final PluginInitializer initializer) {
+ mContext = context;
+ mFactory = factory;
+ mLooper = initializer.getBgLooper();
+ isDebuggable = debuggable;
+ mWhitelistedPlugins.addAll(Arrays.asList(initializer.getWhitelistedPlugins(mContext)));
+ mPluginPrefs = new PluginPrefs(mContext);
+ mPluginEnabler = initializer.getPluginEnabler(mContext);
+ mPluginInitializer = initializer;
+
+ PluginExceptionHandler uncaughtExceptionHandler = new PluginExceptionHandler(
+ defaultHandler);
+ invoke(sSetUncaughtExceptionPreHandler, null, uncaughtExceptionHandler);
+
+ new Handler(mLooper).post(new Runnable() {
+ @Override
+ public void run() {
+ initializer.onPluginManagerInit();
+ }
+ });
+ }
+
+ public String[] getWhitelistedPlugins() {
+ return mWhitelistedPlugins.toArray(new String[0]);
+ }
+
+ public PluginEnabler getPluginEnabler() {
+ return mPluginEnabler;
+ }
+
+ // TODO(mankoff): This appears to be only called from tests. Remove?
+ public T getOneShotPlugin(Class cls) {
+ ProvidesInterface info = cls.getDeclaredAnnotation(ProvidesInterface.class);
+ if (info == null) {
+ throw new RuntimeException(cls + " doesn't provide an interface");
+ }
+ if (TextUtils.isEmpty(info.action())) {
+ throw new RuntimeException(cls + " doesn't provide an action");
+ }
+ return getOneShotPlugin(info.action(), cls);
+ }
+
+ public T getOneShotPlugin(String action, Class> cls) {
+ if (Looper.myLooper() != Looper.getMainLooper()) {
+ throw new RuntimeException("Must be called from UI thread");
+ }
+ // Passing null causes compiler to complain about incompatible (generic) types.
+ PluginListener dummy = null;
+ PluginInstanceManager p = mFactory.createPluginInstanceManager(mContext, action, dummy,
+ false, mLooper, cls, this);
+ mPluginPrefs.addAction(action);
+ PluginInfo info = p.getPlugin();
+ if (info != null) {
+ mOneShotPackages.add(info.mPackage);
+ mHasOneShot = true;
+ startListening();
+ return info.mPlugin;
+ }
+ return null;
+ }
+
+ public void addPluginListener(PluginListener listener, Class> cls) {
+ addPluginListener(listener, cls, false);
+ }
+
+ public void addPluginListener(PluginListener listener, Class> cls,
+ boolean allowMultiple) {
+ addPluginListener(PluginManager.Helper.getAction(cls), listener, cls, allowMultiple);
+ }
+
+ public void addPluginListener(String action, PluginListener listener,
+ Class> cls) {
+ addPluginListener(action, listener, cls, false);
+ }
+
+ public void addPluginListener(String action, PluginListener listener,
+ Class cls, boolean allowMultiple) {
+ mPluginPrefs.addAction(action);
+ PluginInstanceManager p = mFactory.createPluginInstanceManager(mContext, action, listener,
+ allowMultiple, mLooper, cls, this);
+ p.loadAll();
+ synchronized (this) {
+ mPluginMap.put(listener, p);
+ }
+ startListening();
+ }
+
+ public void removePluginListener(PluginListener> listener) {
+ synchronized (this) {
+ if (!mPluginMap.containsKey(listener)) {
+ return;
+ }
+ mPluginMap.remove(listener).destroy();
+ if (mPluginMap.size() == 0) {
+ stopListening();
+ }
+ }
+ }
+
+ private void startListening() {
+ if (mListening) return;
+ mListening = true;
+ IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
+ filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
+ filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
+ filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
+ filter.addAction(PLUGIN_CHANGED);
+ filter.addAction(DISABLE_PLUGIN);
+ filter.addDataScheme("package");
+ mContext.registerReceiver(this, filter);
+ filter = new IntentFilter(Intent.ACTION_USER_UNLOCKED);
+ mContext.registerReceiver(this, filter);
+ }
+
+ private void stopListening() {
+ // Never stop listening if a one-shot is present.
+ if (!mListening || mHasOneShot) return;
+ mListening = false;
+ mContext.unregisterReceiver(this);
+ }
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ if (Intent.ACTION_USER_UNLOCKED.equals(intent.getAction())) {
+ synchronized (this) {
+ for (PluginInstanceManager manager : mPluginMap.values()) {
+ manager.loadAll();
+ }
+ }
+ } else if (DISABLE_PLUGIN.equals(intent.getAction())) {
+ Uri uri = intent.getData();
+ ComponentName component = ComponentName.unflattenFromString(
+ uri.toString().substring(10));
+ if (isPluginWhitelisted(component)) {
+ // Don't disable whitelisted plugins as they are a part of the OS.
+ return;
+ }
+ getPluginEnabler().setDisabled(component, PluginEnabler.DISABLED_INVALID_VERSION);
+ mContext.getSystemService(NotificationManager.class).cancel(component.getClassName(),
+ SystemMessage.NOTE_PLUGIN);
+ } else {
+ Uri data = intent.getData();
+ String pkg = data.getEncodedSchemeSpecificPart();
+ ComponentName componentName = ComponentName.unflattenFromString(pkg);
+ if (mOneShotPackages.contains(pkg)) {
+ int icon = Resources.getSystem().getIdentifier(
+ "stat_sys_warning", "drawable", "android");
+ int color = Resources.getSystem().getIdentifier(
+ "system_notification_accent_color", "color", "android");
+ String label = pkg;
+ try {
+ PackageManager pm = mContext.getPackageManager();
+ label = pm.getApplicationInfo(pkg, 0).loadLabel(pm).toString();
+ } catch (NameNotFoundException e) {
+ }
+ // Localization not required as this will never ever appear in a user build.
+ final Notification.Builder nb =
+ new Notification.Builder(mContext, NOTIFICATION_CHANNEL_ID)
+ .setSmallIcon(icon)
+ .setWhen(0)
+ .setShowWhen(false)
+ .setPriority(Notification.PRIORITY_MAX)
+ .setVisibility(Notification.VISIBILITY_PUBLIC)
+ .setColor(mContext.getColor(color))
+ .setContentTitle("Plugin \"" + label + "\" has updated")
+ .setContentText("Restart SysUI for changes to take effect.");
+ Intent i = new Intent("com.android.systemui.action.RESTART").setData(
+ Uri.parse("package://" + pkg));
+ PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, i, 0);
+ nb.addAction(new Action.Builder(null, "Restart SysUI", pi).build());
+ mContext.getSystemService(NotificationManager.class)
+ .notify(SystemMessage.NOTE_PLUGIN, nb.build());
+ }
+ if (clearClassLoader(pkg)) {
+ if (Build.IS_ENG) {
+ Toast.makeText(mContext, "Reloading " + pkg, Toast.LENGTH_LONG).show();
+ } else {
+ Log.v(TAG, "Reloading " + pkg);
+ }
+ }
+ if (Intent.ACTION_PACKAGE_REPLACED.equals(intent.getAction())
+ && componentName != null) {
+ @PluginEnabler.DisableReason int disableReason =
+ getPluginEnabler().getDisableReason(componentName);
+ if (disableReason == PluginEnabler.DISABLED_FROM_EXPLICIT_CRASH
+ || disableReason == PluginEnabler.DISABLED_FROM_SYSTEM_CRASH
+ || disableReason == PluginEnabler.DISABLED_INVALID_VERSION) {
+ Log.i(TAG, "Re-enabling previously disabled plugin that has been "
+ + "updated: " + componentName.flattenToShortString());
+ getPluginEnabler().setEnabled(componentName);
+ }
+ }
+ synchronized (this) {
+ if (!Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
+ for (PluginInstanceManager manager : mPluginMap.values()) {
+ manager.onPackageChange(pkg);
+ }
+ } else {
+ for (PluginInstanceManager manager : mPluginMap.values()) {
+ manager.onPackageRemoved(pkg);
+ }
+ }
+ }
+ }
+ }
+
+ /** Returns class loader specific for the given plugin. */
+ public ClassLoader getClassLoader(ApplicationInfo appInfo) {
+ if (!isDebuggable && !isPluginPackageWhitelisted(appInfo.packageName)) {
+ Log.w(TAG, "Cannot get class loader for non-whitelisted plugin. Src:"
+ + appInfo.sourceDir + ", pkg: " + appInfo.packageName);
+ return null;
+ }
+ if (mClassLoaders.containsKey(appInfo.packageName)) {
+ return mClassLoaders.get(appInfo.packageName);
+ }
+
+ List zipPaths = new ArrayList<>();
+ List libPaths = new ArrayList<>();
+ LoadedApk.makePaths(null, true, appInfo, zipPaths, libPaths);
+ ClassLoader classLoader = new PathClassLoader(
+ TextUtils.join(File.pathSeparator, zipPaths),
+ TextUtils.join(File.pathSeparator, libPaths),
+ getParentClassLoader());
+ mClassLoaders.put(appInfo.packageName, classLoader);
+ return classLoader;
+ }
+
+ private boolean clearClassLoader(String pkg) {
+ return mClassLoaders.remove(pkg) != null;
+ }
+
+ ClassLoader getParentClassLoader() {
+ if (mParentClassLoader == null) {
+ // Lazily load this so it doesn't have any effect on devices without plugins.
+ mParentClassLoader = new ClassLoaderFilter(getClass().getClassLoader(),
+ "com.android.systemui.plugin");
+ }
+ return mParentClassLoader;
+ }
+
+ public boolean dependsOn(Plugin p, Class cls) {
+ synchronized (this) {
+ for (int i = 0; i < mPluginMap.size(); i++) {
+ if (mPluginMap.valueAt(i).dependsOn(p, cls)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public void handleWtfs() {
+ mPluginInitializer.handleWtfs();
+ }
+
+ public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
+ synchronized (this) {
+ pw.println(String.format(" plugin map (%d):", mPluginMap.size()));
+ for (PluginListener listener : mPluginMap.keySet()) {
+ pw.println(String.format(" %s -> %s",
+ listener, mPluginMap.get(listener)));
+ }
+ }
+ }
+
+ @VisibleForTesting
+ public static class PluginInstanceManagerFactory {
+ public PluginInstanceManager createPluginInstanceManager(Context context,
+ String action, PluginListener listener, boolean allowMultiple, Looper looper,
+ Class> cls, PluginManagerImpl manager) {
+ return new PluginInstanceManager(context, action, listener, allowMultiple, looper,
+ new VersionInfo().addClass(cls), manager);
+ }
+ }
+
+ private boolean isPluginPackageWhitelisted(String packageName) {
+ for (String componentNameOrPackage : mWhitelistedPlugins) {
+ ComponentName componentName = ComponentName.unflattenFromString(componentNameOrPackage);
+ if (componentName != null) {
+ if (componentName.getPackageName().equals(packageName)) {
+ return true;
+ }
+ } else if (componentNameOrPackage.equals(packageName)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private boolean isPluginWhitelisted(ComponentName pluginName) {
+ for (String componentNameOrPackage : mWhitelistedPlugins) {
+ ComponentName componentName = ComponentName.unflattenFromString(componentNameOrPackage);
+ if (componentName != null) {
+ if (componentName.equals(pluginName)) {
+ return true;
+ }
+ } else if (componentNameOrPackage.equals(pluginName.getPackageName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // This allows plugins to include any libraries or copied code they want by only including
+ // classes from the plugin library.
+ private static class ClassLoaderFilter extends ClassLoader {
+ private final String mPackage;
+ private final ClassLoader mBase;
+
+ public ClassLoaderFilter(ClassLoader base, String pkg) {
+ super(ClassLoader.getSystemClassLoader());
+ mBase = base;
+ mPackage = pkg;
+ }
+
+ @Override
+ protected Class> loadClass(String name, boolean resolve) throws ClassNotFoundException {
+ if (!name.startsWith(mPackage)) super.loadClass(name, resolve);
+ return mBase.loadClass(name);
+ }
+ }
+
+ private class PluginExceptionHandler implements UncaughtExceptionHandler {
+ private final UncaughtExceptionHandler mHandler;
+
+ private PluginExceptionHandler(UncaughtExceptionHandler handler) {
+ mHandler = handler;
+ }
+
+ @Override
+ public void uncaughtException(Thread thread, Throwable throwable) {
+ if (SystemProperties.getBoolean("plugin.debugging", false)) {
+ mHandler.uncaughtException(thread, throwable);
+ return;
+ }
+ // Search for and disable plugins that may have been involved in this crash.
+ boolean disabledAny = checkStack(throwable);
+ if (!disabledAny) {
+ // We couldn't find any plugins involved in this crash, just to be safe
+ // disable all the plugins, so we can be sure that SysUI is running as
+ // best as possible.
+ synchronized (this) {
+ for (PluginInstanceManager manager : mPluginMap.values()) {
+ disabledAny |= manager.disableAll();
+ }
+ }
+ }
+ if (disabledAny) {
+ throwable = new CrashWhilePluginActiveException(throwable);
+ }
+
+ // Run the normal exception handler so we can crash and cleanup our state.
+ mHandler.uncaughtException(thread, throwable);
+ }
+
+ private boolean checkStack(Throwable throwable) {
+ if (throwable == null) return false;
+ boolean disabledAny = false;
+ synchronized (this) {
+ for (StackTraceElement element : throwable.getStackTrace()) {
+ for (PluginInstanceManager manager : mPluginMap.values()) {
+ disabledAny |= manager.checkAndDisable(element.getClassName());
+ }
+ }
+ }
+ return disabledAny | checkStack(throwable.getCause());
+ }
+ }
+
+ public static class CrashWhilePluginActiveException extends RuntimeException {
+ public CrashWhilePluginActiveException(Throwable throwable) {
+ super(throwable);
+ }
+ }
+
+ private static Method sGetUncaughtExceptionPreHandler;
+ private static Method sSetUncaughtExceptionPreHandler;
+
+ static {
+ try {
+ Method getDeclaredMethod = Class.class.getDeclaredMethod("getDeclaredMethod", String.class, Class[].class);
+ sGetUncaughtExceptionPreHandler = (Method) getDeclaredMethod.invoke(Thread.class, "getUncaughtExceptionPreHandler", new Class[]{});
+ sSetUncaughtExceptionPreHandler = (Method) getDeclaredMethod.invoke(Thread.class, "setUncaughtExceptionPreHandler", new Class[]{UncaughtExceptionHandler.class});
+ } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private static Object invoke(Method method, Object obj, Object... args) {
+ try {
+ return method.invoke(obj, args);
+ } catch (IllegalAccessException | InvocationTargetException e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
+}
diff --git a/SystemUIShared/src/com/android/systemui/shared/plugins/PluginPrefs.java b/SystemUIShared/src/com/android/systemui/shared/plugins/PluginPrefs.java
new file mode 100644
index 0000000000..6baad466ab
--- /dev/null
+++ b/SystemUIShared/src/com/android/systemui/shared/plugins/PluginPrefs.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2016 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 com.android.systemui.shared.plugins;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.util.ArraySet;
+
+import java.util.Set;
+
+/**
+ * Storage for all plugin actions in SharedPreferences.
+ *
+ * This allows the list of actions that the Tuner needs to search for to be generated
+ * instead of hard coded.
+ */
+public class PluginPrefs {
+
+ private static final String PREFS = "plugin_prefs";
+
+ private static final String PLUGIN_ACTIONS = "actions";
+ private static final String HAS_PLUGINS = "plugins";
+
+ private final Set mPluginActions;
+ private final SharedPreferences mSharedPrefs;
+
+ public PluginPrefs(Context context) {
+ mSharedPrefs = context.getSharedPreferences(PREFS, 0);
+ mPluginActions = new ArraySet<>(mSharedPrefs.getStringSet(PLUGIN_ACTIONS, null));
+ }
+
+ public Set getPluginList() {
+ return new ArraySet<>(mPluginActions);
+ }
+
+ public synchronized void addAction(String action) {
+ if (mPluginActions.add(action)){
+ mSharedPrefs.edit().putStringSet(PLUGIN_ACTIONS, mPluginActions).apply();
+ }
+ }
+
+ public static boolean hasPlugins(Context context) {
+ return context.getSharedPreferences(PREFS, 0).getBoolean(HAS_PLUGINS, false);
+ }
+
+ public static void setHasPlugins(Context context) {
+ context.getSharedPreferences(PREFS, 0).edit().putBoolean(HAS_PLUGINS, true).apply();
+ }
+}
diff --git a/SystemUIShared/src/com/android/systemui/shared/plugins/VersionInfo.java b/SystemUIShared/src/com/android/systemui/shared/plugins/VersionInfo.java
new file mode 100644
index 0000000000..bb845cd879
--- /dev/null
+++ b/SystemUIShared/src/com/android/systemui/shared/plugins/VersionInfo.java
@@ -0,0 +1,148 @@
+/*
+ * 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.
+ */
+
+package com.android.systemui.shared.plugins;
+
+import android.util.ArrayMap;
+
+import com.android.systemui.plugins.annotations.Dependencies;
+import com.android.systemui.plugins.annotations.DependsOn;
+import com.android.systemui.plugins.annotations.ProvidesInterface;
+import com.android.systemui.plugins.annotations.Requirements;
+import com.android.systemui.plugins.annotations.Requires;
+
+import java.util.function.BiConsumer;
+
+public class VersionInfo {
+
+ private final ArrayMap, Version> mVersions = new ArrayMap<>();
+ private Class> mDefault;
+
+ public boolean hasVersionInfo() {
+ return !mVersions.isEmpty();
+ }
+
+ public int getDefaultVersion() {
+ return mVersions.get(mDefault).mVersion;
+ }
+
+ public VersionInfo addClass(Class> cls) {
+ if (mDefault == null) {
+ // The legacy default version is from the first class we add.
+ mDefault = cls;
+ }
+ addClass(cls, false);
+ return this;
+ }
+
+ private void addClass(Class> cls, boolean required) {
+ if (mVersions.containsKey(cls)) return;
+ ProvidesInterface provider = cls.getDeclaredAnnotation(ProvidesInterface.class);
+ if (provider != null) {
+ mVersions.put(cls, new Version(provider.version(), true));
+ }
+ Requires requires = cls.getDeclaredAnnotation(Requires.class);
+ if (requires != null) {
+ mVersions.put(requires.target(), new Version(requires.version(), required));
+ }
+ Requirements requirements = cls.getDeclaredAnnotation(Requirements.class);
+ if (requirements != null) {
+ for (Requires r : requirements.value()) {
+ mVersions.put(r.target(), new Version(r.version(), required));
+ }
+ }
+ DependsOn depends = cls.getDeclaredAnnotation(DependsOn.class);
+ if (depends != null) {
+ addClass(depends.target(), true);
+ }
+ Dependencies dependencies = cls.getDeclaredAnnotation(Dependencies.class);
+ if (dependencies != null) {
+ for (DependsOn d : dependencies.value()) {
+ addClass(d.target(), true);
+ }
+ }
+ }
+
+ public void checkVersion(VersionInfo plugin) throws InvalidVersionException {
+ final ArrayMap, Version> versions = new ArrayMap<>(mVersions);
+ plugin.mVersions.forEach(new BiConsumer, Version>() {
+ @Override
+ public void accept(Class> aClass, Version version) {
+ Version v = versions.remove(aClass);
+ if (v == null) {
+ v = VersionInfo.this.createVersion(aClass);
+ }
+ if (v == null) {
+ throw new InvalidVersionException(aClass.getSimpleName()
+ + " does not provide an interface", false);
+ }
+ if (v.mVersion != version.mVersion) {
+ throw new InvalidVersionException(aClass, v.mVersion < version.mVersion,
+ v.mVersion,
+ version.mVersion);
+ }
+ }
+ });
+ versions.forEach(new BiConsumer, Version>() {
+ @Override
+ public void accept(Class> aClass, Version version) {
+ if (version.mRequired) {
+ throw new InvalidVersionException("Missing required dependency "
+ + aClass.getSimpleName(), false);
+ }
+ }
+ });
+ }
+
+ private Version createVersion(Class> cls) {
+ ProvidesInterface provider = cls.getDeclaredAnnotation(ProvidesInterface.class);
+ if (provider != null) {
+ return new Version(provider.version(), false);
+ }
+ return null;
+ }
+
+ public boolean hasClass(Class cls) {
+ return mVersions.containsKey(cls);
+ }
+
+ public static class InvalidVersionException extends RuntimeException {
+ private final boolean mTooNew;
+
+ public InvalidVersionException(String str, boolean tooNew) {
+ super(str);
+ mTooNew = tooNew;
+ }
+
+ public InvalidVersionException(Class> cls, boolean tooNew, int expected, int actual) {
+ super(cls.getSimpleName() + " expected version " + expected + " but had " + actual);
+ mTooNew = tooNew;
+ }
+
+ public boolean isTooNew() {
+ return mTooNew;
+ }
+ }
+
+ private static class Version {
+
+ private final int mVersion;
+ private final boolean mRequired;
+
+ public Version(int version, boolean required) {
+ mVersion = version;
+ mRequired = required;
+ }
+ }
+}
diff --git a/SystemUIShared/src/com/android/systemui/shared/recents/IOverviewProxy.aidl b/SystemUIShared/src/com/android/systemui/shared/recents/IOverviewProxy.aidl
new file mode 100644
index 0000000000..114472b15f
--- /dev/null
+++ b/SystemUIShared/src/com/android/systemui/shared/recents/IOverviewProxy.aidl
@@ -0,0 +1,78 @@
+/*
+ * 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.
+ */
+
+package com.android.systemui.shared.recents;
+
+import android.graphics.Rect;
+import android.graphics.Region;
+import android.os.Bundle;
+import android.view.MotionEvent;
+import com.android.systemui.shared.recents.ISystemUiProxy;
+
+oneway interface IOverviewProxy {
+
+ void onActiveNavBarRegionChanges(in Region activeRegion) = 11;
+
+ void onInitialize(in Bundle params) = 12;
+
+ /**
+ * Sent when overview button is pressed to toggle show/hide of overview.
+ */
+ void onOverviewToggle() = 6;
+
+ /**
+ * Sent when overview is to be shown.
+ */
+ void onOverviewShown(boolean triggeredFromAltTab) = 7;
+
+ /**
+ * Sent when overview is to be hidden.
+ */
+ void onOverviewHidden(boolean triggeredFromAltTab, boolean triggeredFromHomeKey) = 8;
+
+ /**
+ * Sent when there was an action on one of the onboarding tips view.
+ * TODO: Move this implementation to SystemUI completely
+ */
+ void onTip(int actionType, int viewType) = 10;
+
+ /**
+ * Sent when device assistant changes its default assistant whether it is available or not.
+ */
+ void onAssistantAvailable(boolean available) = 13;
+
+ /**
+ * Sent when the assistant changes how visible it is to the user.
+ */
+ void onAssistantVisibilityChanged(float visibility) = 14;
+
+ /**
+ * Sent when back is triggered.
+ * TODO: Move this implementation to SystemUI completely
+ */
+ void onBackAction(boolean completed, int downX, int downY, boolean isButton,
+ boolean gestureSwipeLeft) = 15;
+
+ /**
+ * Sent when some system ui state changes.
+ */
+ void onSystemUiStateChanged(int stateFlags) = 16;
+
+ /**
+ * Sent when the split screen is resized
+ */
+ void onSplitScreenSecondaryBoundsChanged(in Rect bounds, in Rect insets) = 17;
+}
diff --git a/SystemUIShared/src/com/android/systemui/shared/recents/IPinnedStackAnimationListener.aidl b/SystemUIShared/src/com/android/systemui/shared/recents/IPinnedStackAnimationListener.aidl
new file mode 100644
index 0000000000..97aa512ea7
--- /dev/null
+++ b/SystemUIShared/src/com/android/systemui/shared/recents/IPinnedStackAnimationListener.aidl
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.shared.recents;
+
+/**
+ * Listener interface that Launcher attaches to SystemUI to get
+ * pinned stack animation callbacks.
+ */
+oneway interface IPinnedStackAnimationListener {
+ /**
+ * Notifies the pinned stack animation is started.
+ */
+ void onPinnedStackAnimationStarted();
+}
diff --git a/SystemUIShared/src/com/android/systemui/shared/recents/ISystemUiProxy.aidl b/SystemUIShared/src/com/android/systemui/shared/recents/ISystemUiProxy.aidl
new file mode 100644
index 0000000000..655008b774
--- /dev/null
+++ b/SystemUIShared/src/com/android/systemui/shared/recents/ISystemUiProxy.aidl
@@ -0,0 +1,159 @@
+/*
+ * 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.
+ */
+
+package com.android.systemui.shared.recents;
+
+import android.graphics.Bitmap;
+import android.graphics.Insets;
+import android.graphics.Rect;
+import android.os.Bundle;
+import android.view.MotionEvent;
+
+import com.android.systemui.shared.recents.IPinnedStackAnimationListener;
+import com.android.systemui.shared.recents.model.Task;
+
+/**
+ * Temporary callbacks into SystemUI.
+ * Next id = 27
+ */
+interface ISystemUiProxy {
+
+ /**
+ * Proxies SurfaceControl.screenshotToBuffer().
+ * @Removed
+ * GraphicBufferCompat screenshot(in Rect sourceCrop, int width, int height, int minLayer,
+ * int maxLayer, boolean useIdentityTransform, int rotation) = 0;
+ */
+
+ /**
+ * Begins screen pinning on the provided {@param taskId}.
+ */
+ void startScreenPinning(int taskId) = 1;
+
+ /**
+ * Notifies SystemUI that split screen has been invoked.
+ */
+ void onSplitScreenInvoked() = 5;
+
+ /**
+ * Notifies SystemUI that Overview is shown.
+ */
+ void onOverviewShown(boolean fromHome) = 6;
+
+ /**
+ * Get the secondary split screen app's rectangle when not minimized.
+ */
+ Rect getNonMinimizedSplitScreenSecondaryBounds() = 7;
+
+ /**
+ * Control the {@param alpha} of the back button in the navigation bar and {@param animate} if
+ * needed from current value
+ * @deprecated
+ */
+ void setBackButtonAlpha(float alpha, boolean animate) = 8;
+
+ /**
+ * Control the {@param alpha} of the option nav bar button (back-button in 2 button mode
+ * and home bar in no-button mode) and {@param animate} if needed from current value
+ */
+ void setNavBarButtonAlpha(float alpha, boolean animate) = 19;
+
+ /**
+ * Proxies motion events from the homescreen UI to the status bar. Only called when
+ * swipe down is detected on WORKSPACE. The sender guarantees the following order of events on
+ * the tracking pointer.
+ *
+ * Normal gesture: DOWN, MOVE/POINTER_DOWN/POINTER_UP)*, UP or CANCLE
+ */
+ void onStatusBarMotionEvent(in MotionEvent event) = 9;
+
+ /**
+ * Proxies the assistant gesture's progress started from navigation bar.
+ */
+ void onAssistantProgress(float progress) = 12;
+
+ /**
+ * Proxies the assistant gesture fling velocity (in pixels per millisecond) upon completion.
+ * Velocity is 0 for drag gestures.
+ */
+ void onAssistantGestureCompletion(float velocity) = 18;
+
+ /**
+ * Start the assistant.
+ */
+ void startAssistant(in Bundle bundle) = 13;
+
+ /**
+ * Creates a new gesture monitor
+ */
+ Bundle monitorGestureInput(String name, int displayId) = 14;
+
+ /**
+ * Notifies that the accessibility button in the system's navigation area has been clicked
+ */
+ void notifyAccessibilityButtonClicked(int displayId) = 15;
+
+ /**
+ * Notifies that the accessibility button in the system's navigation area has been long clicked
+ */
+ void notifyAccessibilityButtonLongClicked() = 16;
+
+ /**
+ * Ends the system screen pinning.
+ */
+ void stopScreenPinning() = 17;
+
+ /**
+ * Sets the shelf height and visibility.
+ */
+ void setShelfHeight(boolean visible, int shelfHeight) = 20;
+
+ /**
+ * Handle the provided image as if it was a screenshot.
+ *
+ * Deprecated, use handleImageBundleAsScreenshot with image bundle and UserTask
+ * @deprecated
+ */
+ void handleImageAsScreenshot(in Bitmap screenImage, in Rect locationInScreen,
+ in Insets visibleInsets, int taskId) = 21;
+
+ /**
+ * Sets the split-screen divider minimized state
+ */
+ void setSplitScreenMinimized(boolean minimized) = 22;
+
+ /*
+ * Notifies that the swipe-to-home (recents animation) is finished.
+ */
+ void notifySwipeToHomeFinished() = 23;
+
+ /**
+ * Sets listener to get pinned stack animation callbacks.
+ */
+ void setPinnedStackAnimationListener(IPinnedStackAnimationListener listener) = 24;
+
+ /**
+ * Notifies that quickstep will switch to a new task
+ * @param rotation indicates which Surface.Rotation the gesture was started in
+ */
+ void onQuickSwitchToNewTask(int rotation) = 25;
+
+ /**
+ * Handle the provided image as if it was a screenshot.
+ */
+ void handleImageBundleAsScreenshot(in Bundle screenImageBundle, in Rect locationInScreen,
+ in Insets visibleInsets, in Task.TaskKey task) = 26;
+}
diff --git a/SystemUIShared/src/com/android/systemui/shared/recents/model/Task.aidl b/SystemUIShared/src/com/android/systemui/shared/recents/model/Task.aidl
new file mode 100644
index 0000000000..e7cad2acc6
--- /dev/null
+++ b/SystemUIShared/src/com/android/systemui/shared/recents/model/Task.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.shared.recents.model;
+
+parcelable Task.TaskKey;
\ No newline at end of file
diff --git a/SystemUIShared/src/com/android/systemui/shared/recents/model/Task.java b/SystemUIShared/src/com/android/systemui/shared/recents/model/Task.java
new file mode 100644
index 0000000000..186379af4b
--- /dev/null
+++ b/SystemUIShared/src/com/android/systemui/shared/recents/model/Task.java
@@ -0,0 +1,436 @@
+/*
+ * Copyright (C) 2014 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 com.android.systemui.shared.recents.model;
+
+import static android.view.Display.DEFAULT_DISPLAY;
+
+import android.app.ActivityManager;
+import android.app.ActivityManager.TaskDescription;
+import android.app.TaskInfo;
+import android.content.ComponentName;
+import android.content.Intent;
+import android.content.pm.ActivityInfo;
+import android.graphics.Color;
+import android.graphics.drawable.Drawable;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.view.ViewDebug;
+
+import com.android.systemui.shared.recents.utilities.Utilities;
+
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.Objects;
+
+/**
+ * A task in the recent tasks list.
+ */
+public class Task {
+
+ public static final String TAG = "Task";
+
+ /* Task callbacks */
+ @Deprecated
+ public interface TaskCallbacks {
+ /* Notifies when a task has been bound */
+ void onTaskDataLoaded(Task task, ThumbnailData thumbnailData);
+ /* Notifies when a task has been unbound */
+ void onTaskDataUnloaded();
+ /* Notifies when a task's windowing mode has changed. */
+ void onTaskWindowingModeChanged();
+ }
+
+ /**
+ * The Task Key represents the unique primary key for the task
+ */
+ public static class TaskKey implements Parcelable {
+ @ViewDebug.ExportedProperty(category="recents")
+ public final int id;
+ @ViewDebug.ExportedProperty(category="recents")
+ public int windowingMode;
+ @ViewDebug.ExportedProperty(category="recents")
+ public final Intent baseIntent;
+ @ViewDebug.ExportedProperty(category="recents")
+ public final int userId;
+ @ViewDebug.ExportedProperty(category="recents")
+ public long lastActiveTime;
+
+ /**
+ * The id of the task was running from which display.
+ */
+ @ViewDebug.ExportedProperty(category = "recents")
+ public final int displayId;
+
+ // The source component name which started this task
+ public final ComponentName sourceComponent;
+
+ private int mHashCode;
+
+ public TaskKey(TaskInfo t) {
+ ComponentName sourceComponent = t.origActivity != null
+ // Activity alias if there is one
+ ? t.origActivity
+ // The real activity if there is no alias (or the target if there is one)
+ : t.realActivity;
+ this.id = t.taskId;
+ this.windowingMode = t.configuration.windowConfiguration.getWindowingMode();
+ this.baseIntent = t.baseIntent;
+ this.sourceComponent = sourceComponent;
+ this.userId = t.userId;
+ this.lastActiveTime = t.lastActiveTime;
+ this.displayId = t.displayId;
+ updateHashCode();
+ }
+
+ public TaskKey(int id, int windowingMode, Intent intent,
+ ComponentName sourceComponent, int userId, long lastActiveTime) {
+ this.id = id;
+ this.windowingMode = windowingMode;
+ this.baseIntent = intent;
+ this.sourceComponent = sourceComponent;
+ this.userId = userId;
+ this.lastActiveTime = lastActiveTime;
+ this.displayId = DEFAULT_DISPLAY;
+ updateHashCode();
+ }
+
+ public TaskKey(int id, int windowingMode, Intent intent,
+ ComponentName sourceComponent, int userId, long lastActiveTime, int displayId) {
+ this.id = id;
+ this.windowingMode = windowingMode;
+ this.baseIntent = intent;
+ this.sourceComponent = sourceComponent;
+ this.userId = userId;
+ this.lastActiveTime = lastActiveTime;
+ this.displayId = displayId;
+ updateHashCode();
+ }
+
+ public void setWindowingMode(int windowingMode) {
+ this.windowingMode = windowingMode;
+ updateHashCode();
+ }
+
+ public ComponentName getComponent() {
+ return this.baseIntent.getComponent();
+ }
+
+ public String getPackageName() {
+ if (this.baseIntent.getComponent() != null) {
+ return this.baseIntent.getComponent().getPackageName();
+ }
+ return this.baseIntent.getPackage();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (!(o instanceof TaskKey)) {
+ return false;
+ }
+ TaskKey otherKey = (TaskKey) o;
+ return id == otherKey.id
+ && windowingMode == otherKey.windowingMode
+ && userId == otherKey.userId;
+ }
+
+ @Override
+ public int hashCode() {
+ return mHashCode;
+ }
+
+ @Override
+ public String toString() {
+ return "id=" + id + " windowingMode=" + windowingMode + " user=" + userId
+ + " lastActiveTime=" + lastActiveTime;
+ }
+
+ private void updateHashCode() {
+ mHashCode = Objects.hash(id, windowingMode, userId);
+ }
+
+ public static final Parcelable.Creator CREATOR =
+ new Parcelable.Creator() {
+ @Override
+ public TaskKey createFromParcel(Parcel source) {
+ return TaskKey.readFromParcel(source);
+ }
+
+ @Override
+ public TaskKey[] newArray(int size) {
+ return new TaskKey[size];
+ }
+ };
+
+ @Override
+ public final void writeToParcel(Parcel parcel, int flags) {
+ parcel.writeInt(id);
+ parcel.writeInt(windowingMode);
+ parcel.writeTypedObject(baseIntent, flags);
+ parcel.writeInt(userId);
+ parcel.writeLong(lastActiveTime);
+ parcel.writeInt(displayId);
+ parcel.writeTypedObject(sourceComponent, flags);
+ }
+
+ private static TaskKey readFromParcel(Parcel parcel) {
+ int id = parcel.readInt();
+ int windowingMode = parcel.readInt();
+ Intent baseIntent = parcel.readTypedObject(Intent.CREATOR);
+ int userId = parcel.readInt();
+ long lastActiveTime = parcel.readLong();
+ int displayId = parcel.readInt();
+ ComponentName sourceComponent = parcel.readTypedObject(ComponentName.CREATOR);
+
+ return new TaskKey(id, windowingMode, baseIntent, sourceComponent, userId,
+ lastActiveTime, displayId);
+ }
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+ }
+
+ @ViewDebug.ExportedProperty(deepExport=true, prefix="key_")
+ public TaskKey key;
+
+ /**
+ * The temporary sort index in the stack, used when ordering the stack.
+ */
+ @Deprecated
+ public int temporarySortIndexInStack;
+
+ /**
+ * The icon is the task description icon (if provided), which falls back to the activity icon,
+ * which can then fall back to the application icon.
+ */
+ public Drawable icon;
+ public ThumbnailData thumbnail;
+ @ViewDebug.ExportedProperty(category="recents")
+ @Deprecated
+ public String title;
+ @ViewDebug.ExportedProperty(category="recents")
+ public String titleDescription;
+ @ViewDebug.ExportedProperty(category="recents")
+ public int colorPrimary;
+ @ViewDebug.ExportedProperty(category="recents")
+ public int colorBackground;
+ @ViewDebug.ExportedProperty(category="recents")
+ @Deprecated
+ public boolean useLightOnPrimaryColor;
+
+ /**
+ * The task description for this task, only used to reload task icons.
+ */
+ public TaskDescription taskDescription;
+
+ /**
+ * The state isLaunchTarget will be set for the correct task upon launching Recents.
+ */
+ @ViewDebug.ExportedProperty(category="recents")
+ @Deprecated
+ public boolean isLaunchTarget;
+ @ViewDebug.ExportedProperty(category="recents")
+ @Deprecated
+ public boolean isStackTask;
+ @ViewDebug.ExportedProperty(category="recents")
+ @Deprecated
+ public boolean isSystemApp;
+ @ViewDebug.ExportedProperty(category="recents")
+ public boolean isDockable;
+
+ /**
+ * Resize mode. See {@link ActivityInfo#resizeMode}.
+ */
+ @ViewDebug.ExportedProperty(category="recents")
+ @Deprecated
+ public int resizeMode;
+
+ @ViewDebug.ExportedProperty(category="recents")
+ public ComponentName topActivity;
+
+ @ViewDebug.ExportedProperty(category="recents")
+ public boolean isLocked;
+
+ @Deprecated
+ private ArrayList mCallbacks = new ArrayList<>();
+
+ public Task() {
+ // Do nothing
+ }
+
+ /**
+ * Creates a task object from the provided task info
+ */
+ public static Task from(TaskKey taskKey, TaskInfo taskInfo, boolean isLocked) {
+ ActivityManager.TaskDescription td = taskInfo.taskDescription;
+ return new Task(taskKey,
+ td != null ? td.getPrimaryColor() : 0,
+ td != null ? td.getBackgroundColor() : 0,
+ taskInfo.supportsSplitScreenMultiWindow, isLocked, td, taskInfo.topActivity);
+ }
+
+ public Task(TaskKey key) {
+ this.key = key;
+ this.taskDescription = new TaskDescription();
+ }
+
+ public Task(TaskKey key, int colorPrimary, int colorBackground,
+ boolean isDockable, boolean isLocked, TaskDescription taskDescription,
+ ComponentName topActivity) {
+ this.key = key;
+ this.colorPrimary = colorPrimary;
+ this.colorBackground = colorBackground;
+ this.taskDescription = taskDescription;
+ this.isDockable = isDockable;
+ this.isLocked = isLocked;
+ this.topActivity = topActivity;
+ }
+
+ @Deprecated
+ public Task(TaskKey key, Drawable icon, ThumbnailData thumbnail, String title,
+ String titleDescription, int colorPrimary, int colorBackground, boolean isLaunchTarget,
+ boolean isStackTask, boolean isSystemApp, boolean isDockable,
+ TaskDescription taskDescription, int resizeMode, ComponentName topActivity,
+ boolean isLocked) {
+ this.key = key;
+ this.icon = icon;
+ this.thumbnail = thumbnail;
+ this.title = title;
+ this.titleDescription = titleDescription;
+ this.colorPrimary = colorPrimary;
+ this.colorBackground = colorBackground;
+ this.useLightOnPrimaryColor = Utilities.computeContrastBetweenColors(this.colorPrimary,
+ Color.WHITE) > 3f;
+ this.taskDescription = taskDescription;
+ this.isLaunchTarget = isLaunchTarget;
+ this.isStackTask = isStackTask;
+ this.isSystemApp = isSystemApp;
+ this.isDockable = isDockable;
+ this.resizeMode = resizeMode;
+ this.topActivity = topActivity;
+ this.isLocked = isLocked;
+ }
+
+ /**
+ * Copies the metadata from another task, but retains the current callbacks.
+ */
+ @Deprecated
+ public void copyFrom(Task o) {
+ this.key = o.key;
+ this.icon = o.icon;
+ this.thumbnail = o.thumbnail;
+ this.title = o.title;
+ this.titleDescription = o.titleDescription;
+ this.colorPrimary = o.colorPrimary;
+ this.colorBackground = o.colorBackground;
+ this.useLightOnPrimaryColor = o.useLightOnPrimaryColor;
+ this.taskDescription = o.taskDescription;
+ this.isLaunchTarget = o.isLaunchTarget;
+ this.isStackTask = o.isStackTask;
+ this.isSystemApp = o.isSystemApp;
+ this.isDockable = o.isDockable;
+ this.resizeMode = o.resizeMode;
+ this.isLocked = o.isLocked;
+ this.topActivity = o.topActivity;
+ }
+
+ /**
+ * Add a callback.
+ */
+ @Deprecated
+ public void addCallback(TaskCallbacks cb) {
+ if (!mCallbacks.contains(cb)) {
+ mCallbacks.add(cb);
+ }
+ }
+
+ /**
+ * Remove a callback.
+ */
+ @Deprecated
+ public void removeCallback(TaskCallbacks cb) {
+ mCallbacks.remove(cb);
+ }
+
+ /** Updates the task's windowing mode. */
+ @Deprecated
+ public void setWindowingMode(int windowingMode) {
+ key.setWindowingMode(windowingMode);
+ int callbackCount = mCallbacks.size();
+ for (int i = 0; i < callbackCount; i++) {
+ mCallbacks.get(i).onTaskWindowingModeChanged();
+ }
+ }
+
+ /** Notifies the callback listeners that this task has been loaded */
+ @Deprecated
+ public void notifyTaskDataLoaded(ThumbnailData thumbnailData, Drawable applicationIcon) {
+ this.icon = applicationIcon;
+ this.thumbnail = thumbnailData;
+ int callbackCount = mCallbacks.size();
+ for (int i = 0; i < callbackCount; i++) {
+ mCallbacks.get(i).onTaskDataLoaded(this, thumbnailData);
+ }
+ }
+
+ /** Notifies the callback listeners that this task has been unloaded */
+ @Deprecated
+ public void notifyTaskDataUnloaded(Drawable defaultApplicationIcon) {
+ icon = defaultApplicationIcon;
+ thumbnail = null;
+ for (int i = mCallbacks.size() - 1; i >= 0; i--) {
+ mCallbacks.get(i).onTaskDataUnloaded();
+ }
+ }
+
+ /**
+ * Returns the top activity component.
+ */
+ public ComponentName getTopComponent() {
+ return topActivity != null
+ ? topActivity
+ : key.baseIntent.getComponent();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ // Check that the id matches
+ Task t = (Task) o;
+ return key.equals(t.key);
+ }
+
+ @Override
+ public String toString() {
+ return "[" + key.toString() + "] " + title;
+ }
+
+ public void dump(String prefix, PrintWriter writer) {
+ writer.print(prefix); writer.print(key);
+ if (!isDockable) {
+ writer.print(" dockable=N");
+ }
+ if (isLaunchTarget) {
+ writer.print(" launchTarget=Y");
+ }
+ if (isLocked) {
+ writer.print(" locked=Y");
+ }
+ writer.print(" "); writer.print(title);
+ writer.println();
+ }
+}
diff --git a/SystemUIShared/src/com/android/systemui/shared/recents/model/ThumbnailData.java b/SystemUIShared/src/com/android/systemui/shared/recents/model/ThumbnailData.java
new file mode 100644
index 0000000000..1e505801c2
--- /dev/null
+++ b/SystemUIShared/src/com/android/systemui/shared/recents/model/ThumbnailData.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2016 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 com.android.systemui.shared.recents.model;
+
+import static android.app.WindowConfiguration.ROTATION_UNDEFINED;
+import static android.content.res.Configuration.ORIENTATION_UNDEFINED;
+import static android.graphics.Bitmap.Config.ARGB_8888;
+
+import static com.android.systemui.shared.system.WindowManagerWrapper.WINDOWING_MODE_UNDEFINED;
+
+import android.app.ActivityManager.TaskSnapshot;
+import android.graphics.Bitmap;
+import android.graphics.Color;
+import android.graphics.GraphicBuffer;
+import android.graphics.Point;
+import android.graphics.Rect;
+import android.hardware.HardwareBuffer;
+import android.util.Log;
+
+/**
+ * Data for a single thumbnail.
+ */
+public class ThumbnailData {
+
+ public final Bitmap thumbnail;
+ public int orientation;
+ public int rotation;
+ public Rect insets;
+ public boolean reducedResolution;
+ public boolean isRealSnapshot;
+ public boolean isTranslucent;
+ public int windowingMode;
+ public int systemUiVisibility;
+ public float scale;
+ public long snapshotId;
+
+ public ThumbnailData() {
+ thumbnail = null;
+ orientation = ORIENTATION_UNDEFINED;
+ rotation = ROTATION_UNDEFINED;
+ insets = new Rect();
+ reducedResolution = false;
+ scale = 1f;
+ isRealSnapshot = true;
+ isTranslucent = false;
+ windowingMode = WINDOWING_MODE_UNDEFINED;
+ systemUiVisibility = 0;
+ snapshotId = 0;
+ }
+
+ public ThumbnailData(TaskSnapshot snapshot) {
+ final GraphicBuffer buffer = snapshot.getSnapshot();
+ if (buffer == null || (buffer.getUsage() & HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE) == 0) {
+ // TODO(b/157562905): Workaround for a crash when we get a snapshot without this state
+ Log.e("ThumbnailData", "Unexpected snapshot without USAGE_GPU_SAMPLED_IMAGE: "
+ + buffer);
+ Point taskSize = snapshot.getTaskSize();
+ thumbnail = Bitmap.createBitmap(taskSize.x, taskSize.y, ARGB_8888);
+ thumbnail.eraseColor(Color.BLACK);
+ } else {
+ thumbnail = Bitmap.wrapHardwareBuffer(buffer, snapshot.getColorSpace());
+ }
+ insets = new Rect(snapshot.getContentInsets());
+ orientation = snapshot.getOrientation();
+ rotation = snapshot.getRotation();
+ reducedResolution = snapshot.isLowResolution();
+ // TODO(b/149579527): Pass task size instead of computing scale.
+ // Assume width and height were scaled the same; compute scale only for width
+ scale = (float) thumbnail.getWidth() / snapshot.getTaskSize().x;
+ isRealSnapshot = snapshot.isRealSnapshot();
+ isTranslucent = snapshot.isTranslucent();
+ windowingMode = snapshot.getWindowingMode();
+ systemUiVisibility = snapshot.getSystemUiVisibility();
+ snapshotId = snapshot.getId();
+ }
+}
diff --git a/SystemUIShared/src/com/android/systemui/shared/recents/utilities/AppTrace.java b/SystemUIShared/src/com/android/systemui/shared/recents/utilities/AppTrace.java
new file mode 100644
index 0000000000..0241c593b8
--- /dev/null
+++ b/SystemUIShared/src/com/android/systemui/shared/recents/utilities/AppTrace.java
@@ -0,0 +1,73 @@
+/*
+ * 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.
+ */
+package com.android.systemui.shared.recents.utilities;
+
+import static android.os.Trace.TRACE_TAG_APP;
+
+/**
+ * Helper class for internal trace functions.
+ */
+public class AppTrace {
+
+ /**
+ * Begins a new async trace section with the given {@param key} and {@param cookie}.
+ */
+ public static void start(String key, int cookie) {
+ android.os.Trace.asyncTraceBegin(TRACE_TAG_APP, key, cookie);
+ }
+
+ /**
+ * Begins a new async trace section with the given {@param key}.
+ */
+ public static void start(String key) {
+ android.os.Trace.asyncTraceBegin(TRACE_TAG_APP, key, 0);
+ }
+
+ /**
+ * Ends an existing async trace section with the given {@param key}.
+ */
+ public static void end(String key) {
+ android.os.Trace.asyncTraceEnd(TRACE_TAG_APP, key, 0);
+ }
+
+ /**
+ * Ends an existing async trace section with the given {@param key} and {@param cookie}.
+ */
+ public static void end(String key, int cookie) {
+ android.os.Trace.asyncTraceEnd(TRACE_TAG_APP, key, cookie);
+ }
+
+ /**
+ * Begins a new trace section with the given {@param key}. Can be nested.
+ */
+ public static void beginSection(String key) {
+ android.os.Trace.beginSection(key);
+ }
+
+ /**
+ * Ends an existing trace section started in the last {@link #beginSection(String)}.
+ */
+ public static void endSection() {
+ android.os.Trace.endSection();
+ }
+
+ /**
+ * Traces a counter value.
+ */
+ public static void count(String name, int count) {
+ android.os.Trace.traceCounter(TRACE_TAG_APP, name, count);
+ }
+}
diff --git a/SystemUIShared/src/com/android/systemui/shared/recents/utilities/BitmapUtil.java b/SystemUIShared/src/com/android/systemui/shared/recents/utilities/BitmapUtil.java
new file mode 100644
index 0000000000..b79fcbd439
--- /dev/null
+++ b/SystemUIShared/src/com/android/systemui/shared/recents/utilities/BitmapUtil.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.shared.recents.utilities;
+
+import android.graphics.Bitmap;
+import android.graphics.ColorSpace;
+import android.graphics.ParcelableColorSpace;
+import android.hardware.HardwareBuffer;
+import android.os.Bundle;
+
+import java.util.Objects;
+
+/**
+ * Utils for working with Bitmaps.
+ */
+public final class BitmapUtil {
+ private static final String KEY_BUFFER = "bitmap_util_buffer";
+ private static final String KEY_COLOR_SPACE = "bitmap_util_color_space";
+
+ private BitmapUtil(){ }
+
+ /**
+ * Creates a Bundle that represents the given Bitmap.
+ * The Bundle will contain a wrapped version of the Bitmaps HardwareBuffer, so will avoid
+ * copies when passing across processes, only pass to processes you trust.
+ *
+ *
Returns a new Bundle rather than modifying an exiting one to avoid key collisions, the
+ * returned Bundle should be treated as a standalone object.
+ *
+ * @param bitmap to convert to bundle
+ * @return a Bundle representing the bitmap, should only be parsed by
+ * {@link #bundleToHardwareBitmap(Bundle)}
+ */
+ public static Bundle hardwareBitmapToBundle(Bitmap bitmap) {
+ if (bitmap.getConfig() != Bitmap.Config.HARDWARE) {
+ throw new IllegalArgumentException(
+ "Passed bitmap must have hardware config, found: " + bitmap.getConfig());
+ }
+
+ // Bitmap assumes SRGB for null color space
+ ParcelableColorSpace colorSpace =
+ bitmap.getColorSpace() == null
+ ? new ParcelableColorSpace(ColorSpace.get(ColorSpace.Named.SRGB))
+ : new ParcelableColorSpace(bitmap.getColorSpace());
+
+ Bundle bundle = new Bundle();
+ bundle.putParcelable(KEY_BUFFER, bitmap.getHardwareBuffer());
+ bundle.putParcelable(KEY_COLOR_SPACE, colorSpace);
+
+ return bundle;
+ }
+
+ /**
+ * Extracts the Bitmap added to a Bundle with {@link #hardwareBitmapToBundle(Bitmap)} .}
+ *
+ *
This Bitmap contains the HardwareBuffer from the original caller, be careful passing this
+ * Bitmap on to any other source.
+ *
+ * @param bundle containing the bitmap
+ * @return a hardware Bitmap
+ */
+ public static Bitmap bundleToHardwareBitmap(Bundle bundle) {
+ if (!bundle.containsKey(KEY_BUFFER) || !bundle.containsKey(KEY_COLOR_SPACE)) {
+ throw new IllegalArgumentException("Bundle does not contain a hardware bitmap");
+ }
+
+ HardwareBuffer buffer = bundle.getParcelable(KEY_BUFFER);
+ ParcelableColorSpace colorSpace = bundle.getParcelable(KEY_COLOR_SPACE);
+
+ return Bitmap.wrapHardwareBuffer(Objects.requireNonNull(buffer), colorSpace);
+ }
+}
diff --git a/SystemUIShared/src/com/android/systemui/shared/recents/utilities/RectFEvaluator.java b/SystemUIShared/src/com/android/systemui/shared/recents/utilities/RectFEvaluator.java
new file mode 100644
index 0000000000..51c1b5aa13
--- /dev/null
+++ b/SystemUIShared/src/com/android/systemui/shared/recents/utilities/RectFEvaluator.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2016 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 com.android.systemui.shared.recents.utilities;
+
+import android.animation.TypeEvaluator;
+import android.graphics.RectF;
+
+/**
+ * This evaluator can be used to perform type interpolation between RectF values.
+ */
+public class RectFEvaluator implements TypeEvaluator {
+
+ private final RectF mRect = new RectF();
+
+ /**
+ * This function returns the result of linearly interpolating the start and
+ * end Rect values, with fraction representing the proportion
+ * between the start and end values. The calculation is a simple parametric
+ * calculation on each of the separate components in the Rect objects
+ * (left, top, right, and bottom).
+ *
+ * The object returned will be the reuseRect passed into the constructor.
+ *
+ * @param fraction The fraction from the starting to the ending values
+ * @param startValue The start Rect
+ * @param endValue The end Rect
+ * @return A linear interpolation between the start and end values, given the
+ * fraction parameter.
+ */
+ @Override
+ public RectF evaluate(float fraction, RectF startValue, RectF endValue) {
+ float left = startValue.left + ((endValue.left - startValue.left) * fraction);
+ float top = startValue.top + ((endValue.top - startValue.top) * fraction);
+ float right = startValue.right + ((endValue.right - startValue.right) * fraction);
+ float bottom = startValue.bottom + ((endValue.bottom - startValue.bottom) * fraction);
+ mRect.set(left, top, right, bottom);
+ return mRect;
+ }
+}
diff --git a/SystemUIShared/src/com/android/systemui/shared/recents/utilities/Utilities.java b/SystemUIShared/src/com/android/systemui/shared/recents/utilities/Utilities.java
new file mode 100644
index 0000000000..7dffc26139
--- /dev/null
+++ b/SystemUIShared/src/com/android/systemui/shared/recents/utilities/Utilities.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2018 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 com.android.systemui.shared.recents.utilities;
+
+import android.graphics.Color;
+import android.os.Handler;
+import android.os.Message;
+
+/* Common code */
+public class Utilities {
+
+ /**
+ * Posts a runnable on a handler at the front of the queue ignoring any sync barriers.
+ */
+ public static void postAtFrontOfQueueAsynchronously(Handler h, Runnable r) {
+ Message msg = h.obtainMessage().setCallback(r);
+ h.sendMessageAtFrontOfQueue(msg);
+ }
+
+ /** Calculates the constrast between two colors, using the algorithm provided by the WCAG v2. */
+ public static float computeContrastBetweenColors(int bg, int fg) {
+ float bgR = Color.red(bg) / 255f;
+ float bgG = Color.green(bg) / 255f;
+ float bgB = Color.blue(bg) / 255f;
+ bgR = (bgR < 0.03928f) ? bgR / 12.92f : (float) Math.pow((bgR + 0.055f) / 1.055f, 2.4f);
+ bgG = (bgG < 0.03928f) ? bgG / 12.92f : (float) Math.pow((bgG + 0.055f) / 1.055f, 2.4f);
+ bgB = (bgB < 0.03928f) ? bgB / 12.92f : (float) Math.pow((bgB + 0.055f) / 1.055f, 2.4f);
+ float bgL = 0.2126f * bgR + 0.7152f * bgG + 0.0722f * bgB;
+
+ float fgR = Color.red(fg) / 255f;
+ float fgG = Color.green(fg) / 255f;
+ float fgB = Color.blue(fg) / 255f;
+ fgR = (fgR < 0.03928f) ? fgR / 12.92f : (float) Math.pow((fgR + 0.055f) / 1.055f, 2.4f);
+ fgG = (fgG < 0.03928f) ? fgG / 12.92f : (float) Math.pow((fgG + 0.055f) / 1.055f, 2.4f);
+ fgB = (fgB < 0.03928f) ? fgB / 12.92f : (float) Math.pow((fgB + 0.055f) / 1.055f, 2.4f);
+ float fgL = 0.2126f * fgR + 0.7152f * fgG + 0.0722f * fgB;
+
+ return Math.abs((fgL + 0.05f) / (bgL + 0.05f));
+ }
+
+ /**
+ * @return the clamped {@param value} between the provided {@param min} and {@param max}.
+ */
+ public static float clamp(float value, float min, float max) {
+ return Math.max(min, Math.min(max, value));
+ }
+}
diff --git a/SystemUIShared/src/com/android/systemui/shared/recents/view/AppTransitionAnimationSpecCompat.java b/SystemUIShared/src/com/android/systemui/shared/recents/view/AppTransitionAnimationSpecCompat.java
new file mode 100644
index 0000000000..ebdc884285
--- /dev/null
+++ b/SystemUIShared/src/com/android/systemui/shared/recents/view/AppTransitionAnimationSpecCompat.java
@@ -0,0 +1,41 @@
+/*
+ * 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.
+ */
+package com.android.systemui.shared.recents.view;
+
+import android.graphics.Bitmap;
+import android.graphics.Rect;
+import android.view.AppTransitionAnimationSpec;
+
+/**
+ * Wraps the internal app transition animation spec.
+ */
+public class AppTransitionAnimationSpecCompat {
+
+ private int mTaskId;
+ private Bitmap mBuffer;
+ private Rect mRect;
+
+ public AppTransitionAnimationSpecCompat(int taskId, Bitmap buffer, Rect rect) {
+ mTaskId = taskId;
+ mBuffer = buffer;
+ mRect = rect;
+ }
+
+ public AppTransitionAnimationSpec toAppTransitionAnimationSpec() {
+ return new AppTransitionAnimationSpec(mTaskId,
+ mBuffer != null ? mBuffer.createGraphicBufferHandle() : null, mRect);
+ }
+}
diff --git a/SystemUIShared/src/com/android/systemui/shared/recents/view/AppTransitionAnimationSpecsFuture.java b/SystemUIShared/src/com/android/systemui/shared/recents/view/AppTransitionAnimationSpecsFuture.java
new file mode 100644
index 0000000000..c227feec75
--- /dev/null
+++ b/SystemUIShared/src/com/android/systemui/shared/recents/view/AppTransitionAnimationSpecsFuture.java
@@ -0,0 +1,93 @@
+/*
+ * 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.
+ */
+package com.android.systemui.shared.recents.view;
+
+import android.os.Handler;
+import android.os.Looper;
+import android.os.RemoteException;
+import android.view.AppTransitionAnimationSpec;
+import android.view.IAppTransitionAnimationSpecsFuture;
+
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.FutureTask;
+
+/**
+ * To be implemented by a particular animation to asynchronously provide the animation specs for a
+ * particular transition.
+ */
+public abstract class AppTransitionAnimationSpecsFuture {
+
+ private final Handler mHandler;
+ private FutureTask> mComposeTask = new FutureTask<>(
+ new Callable>() {
+ @Override
+ public List call() throws Exception {
+ return composeSpecs();
+ }
+ });
+
+ private final IAppTransitionAnimationSpecsFuture mFuture =
+ new IAppTransitionAnimationSpecsFuture.Stub() {
+ @Override
+ public AppTransitionAnimationSpec[] get() throws RemoteException {
+ try {
+ if (!mComposeTask.isDone()) {
+ mHandler.post(mComposeTask);
+ }
+ List specs = mComposeTask.get();
+ // Clear reference to the compose task this future holds onto the reference to it's
+ // implementation (which can leak references to the bitmap it creates for the
+ // transition)
+ mComposeTask = null;
+ if (specs == null) {
+ return null;
+ }
+
+ AppTransitionAnimationSpec[] arr = new AppTransitionAnimationSpec[specs.size()];
+ for (int i = 0; i < specs.size(); i++) {
+ arr[i] = specs.get(i).toAppTransitionAnimationSpec();
+ }
+ return arr;
+ } catch (Exception e) {
+ return null;
+ }
+ }
+ };
+
+ public AppTransitionAnimationSpecsFuture(Handler handler) {
+ mHandler = handler;
+ }
+
+ /**
+ * Returns the future to handle the call from window manager.
+ */
+ public final IAppTransitionAnimationSpecsFuture getFuture() {
+ return mFuture;
+ }
+
+ /**
+ * Called ahead of the future callback to compose the specs to be returned in the future.
+ */
+ public final void composeSpecsSynchronous() {
+ if (Looper.myLooper() != mHandler.getLooper()) {
+ throw new RuntimeException("composeSpecsSynchronous() called from wrong looper");
+ }
+ mComposeTask.run();
+ }
+
+ public abstract List composeSpecs();
+}
diff --git a/SystemUIShared/src/com/android/systemui/shared/recents/view/RecentsTransition.java b/SystemUIShared/src/com/android/systemui/shared/recents/view/RecentsTransition.java
new file mode 100644
index 0000000000..e253360a53
--- /dev/null
+++ b/SystemUIShared/src/com/android/systemui/shared/recents/view/RecentsTransition.java
@@ -0,0 +1,115 @@
+/*
+ * 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.
+ */
+package com.android.systemui.shared.recents.view;
+
+import android.app.ActivityOptions;
+import android.app.ActivityOptions.OnAnimationStartedListener;
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.GraphicBuffer;
+import android.graphics.Picture;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.IRemoteCallback;
+import android.os.RemoteException;
+import android.view.View;
+
+import java.util.function.Consumer;
+
+/**
+ * A helper class to create transitions to/from an App to Recents.
+ */
+public class RecentsTransition {
+
+ /**
+ * Creates a new transition aspect scaled transition activity options.
+ */
+ public static ActivityOptions createAspectScaleAnimation(Context context, Handler handler,
+ boolean scaleUp, AppTransitionAnimationSpecsFuture animationSpecsFuture,
+ final Runnable animationStartCallback) {
+ final OnAnimationStartedListener animStartedListener = new OnAnimationStartedListener() {
+ private boolean mHandled;
+
+ @Override
+ public void onAnimationStarted() {
+ // OnAnimationStartedListener can be called numerous times, so debounce here to
+ // prevent multiple callbacks
+ if (mHandled) {
+ return;
+ }
+ mHandled = true;
+
+ if (animationStartCallback != null) {
+ animationStartCallback.run();
+ }
+ }
+ };
+ final ActivityOptions opts = ActivityOptions.makeMultiThumbFutureAspectScaleAnimation(
+ context, handler,
+ animationSpecsFuture != null ? animationSpecsFuture.getFuture() : null,
+ animStartedListener, scaleUp);
+ return opts;
+ }
+
+ /**
+ * Wraps a animation-start callback in a binder that can be called from window manager.
+ */
+ public static IRemoteCallback wrapStartedListener(final Handler handler,
+ final Runnable animationStartCallback) {
+ if (animationStartCallback == null) {
+ return null;
+ }
+ return new IRemoteCallback.Stub() {
+ @Override
+ public void sendResult(Bundle data) throws RemoteException {
+ handler.post(animationStartCallback);
+ }
+ };
+ }
+
+ /**
+ * @return a {@link GraphicBuffer} with the {@param view} drawn into it. Result can be null if
+ * we were unable to allocate a hardware bitmap.
+ */
+ public static Bitmap drawViewIntoHardwareBitmap(int width, int height, final View view,
+ final float scale, final int eraseColor) {
+ return createHardwareBitmap(width, height, new Consumer