From 39579786f32a39a24e29bf1e71df621f6994aa45 Mon Sep 17 00:00:00 2001 From: Suphon Thanakornpakapong Date: Thu, 3 Jun 2021 10:55:06 +0700 Subject: [PATCH] Build SystemUIShared from source --- SystemUIShared/.gitignore | 13 + SystemUIShared/AndroidManifest.xml | 22 + SystemUIShared/build.gradle | 41 ++ .../com/android/systemui/plugins/Plugin.java | 129 +++++ .../systemui/plugins/PluginFragment.java | 45 ++ .../systemui/plugins/PluginListener.java | 38 ++ .../plugins/annotations/Dependencies.java | 27 + .../plugins/annotations/DependsOn.java | 32 + .../annotations/ProvidesInterface.java | 30 + .../plugins/annotations/Requirements.java | 27 + .../plugins/annotations/Requires.java | 33 ++ .../shared/plugins/PluginEnabler.java | 53 ++ .../shared/plugins/PluginInitializer.java | 40 ++ .../shared/plugins/PluginInstanceManager.java | 462 +++++++++++++++ .../shared/plugins/PluginManager.java | 60 ++ .../shared/plugins/PluginManagerImpl.java | 491 ++++++++++++++++ .../systemui/shared/plugins/PluginPrefs.java | 61 ++ .../systemui/shared/plugins/VersionInfo.java | 148 +++++ .../shared/recents/IOverviewProxy.aidl | 78 +++ .../IPinnedStackAnimationListener.aidl | 28 + .../shared/recents/ISystemUiProxy.aidl | 159 +++++ .../systemui/shared/recents/model/Task.aidl | 19 + .../systemui/shared/recents/model/Task.java | 436 ++++++++++++++ .../shared/recents/model/ThumbnailData.java | 90 +++ .../shared/recents/utilities/AppTrace.java | 73 +++ .../shared/recents/utilities/BitmapUtil.java | 86 +++ .../recents/utilities/RectFEvaluator.java | 52 ++ .../shared/recents/utilities/Utilities.java | 61 ++ .../AppTransitionAnimationSpecCompat.java | 41 ++ .../AppTransitionAnimationSpecsFuture.java | 93 +++ .../recents/view/RecentsTransition.java | 115 ++++ .../shared/system/ActivityCompat.java | 72 +++ .../shared/system/ActivityManagerWrapper.java | 546 ++++++++++++++++++ .../shared/system/ActivityOptionsCompat.java | 89 +++ .../shared/system/AssistDataReceiver.java | 28 + .../shared/system/BackgroundExecutor.java | 61 ++ .../systemui/shared/system/BlurUtils.java | 37 ++ .../shared/system/ChoreographerCompat.java | 37 ++ .../shared/system/ConfigurationCompat.java | 28 + .../systemui/shared/system/ContextCompat.java | 34 ++ .../system/DevicePolicyManagerWrapper.java | 43 ++ .../system/DockedStackListenerCompat.java | 63 ++ .../shared/system/InputChannelCompat.java | 124 ++++ .../system/InputConsumerController.java | 196 +++++++ .../shared/system/InputMonitorCompat.java | 66 +++ .../shared/system/KeyguardManagerCompat.java | 32 + .../shared/system/LatencyTrackerCompat.java | 34 ++ .../shared/system/LauncherEventUtil.java | 29 + .../shared/system/MetricsLoggerCompat.java | 50 ++ .../shared/system/PackageManagerWrapper.java | 87 +++ .../system/PinnedStackListenerForwarder.java | 124 ++++ .../shared/system/QuickStepContract.java | 247 ++++++++ .../RecentsAnimationControllerCompat.java | 124 ++++ .../system/RecentsAnimationListener.java | 41 ++ .../system/RemoteAnimationAdapterCompat.java | 75 +++ .../RemoteAnimationDefinitionCompat.java | 40 ++ .../system/RemoteAnimationRunnerCompat.java | 23 + .../system/RemoteAnimationTargetCompat.java | 91 +++ .../shared/system/RotationWatcher.java | 69 +++ .../shared/system/SurfaceControlCompat.java | 47 ++ .../system/SurfaceViewRequestReceiver.java | 100 ++++ .../system/SurfaceViewRequestUtils.java | 63 ++ ...SyncRtSurfaceTransactionApplierCompat.java | 384 ++++++++++++ .../SystemGestureExclusionListenerCompat.java | 105 ++++ .../shared/system/TaskDescriptionCompat.java | 49 ++ .../shared/system/TaskInfoCompat.java | 48 ++ .../system/TaskStackChangeListener.java | 120 ++++ .../system/TaskStackChangeListeners.java | 464 +++++++++++++++ .../shared/system/ThreadedRendererCompat.java | 33 ++ .../systemui/shared/system/TonalCompat.java | 53 ++ .../shared/system/TransactionCompat.java | 125 ++++ .../system/UniversalSmartspaceUtils.java | 44 ++ .../shared/system/ViewRootImplCompat.java | 63 ++ .../shared/system/WallpaperEngineCompat.java | 56 ++ .../shared/system/WallpaperManagerCompat.java | 51 ++ .../shared/system/WindowCallbacksCompat.java | 109 ++++ .../shared/system/WindowManagerWrapper.java | 228 ++++++++ .../shared/tracing/FrameProtoTracer.java | 190 ++++++ .../shared/tracing/ProtoTraceable.java | 26 + build.gradle | 2 +- settings.gradle | 3 +- 81 files changed, 7934 insertions(+), 2 deletions(-) create mode 100644 SystemUIShared/.gitignore create mode 100644 SystemUIShared/AndroidManifest.xml create mode 100644 SystemUIShared/build.gradle create mode 100644 SystemUIShared/src/com/android/systemui/plugins/Plugin.java create mode 100644 SystemUIShared/src/com/android/systemui/plugins/PluginFragment.java create mode 100644 SystemUIShared/src/com/android/systemui/plugins/PluginListener.java create mode 100644 SystemUIShared/src/com/android/systemui/plugins/annotations/Dependencies.java create mode 100644 SystemUIShared/src/com/android/systemui/plugins/annotations/DependsOn.java create mode 100644 SystemUIShared/src/com/android/systemui/plugins/annotations/ProvidesInterface.java create mode 100644 SystemUIShared/src/com/android/systemui/plugins/annotations/Requirements.java create mode 100644 SystemUIShared/src/com/android/systemui/plugins/annotations/Requires.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/plugins/PluginEnabler.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/plugins/PluginInitializer.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/plugins/PluginInstanceManager.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/plugins/PluginManager.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/plugins/PluginManagerImpl.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/plugins/PluginPrefs.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/plugins/VersionInfo.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/recents/IOverviewProxy.aidl create mode 100644 SystemUIShared/src/com/android/systemui/shared/recents/IPinnedStackAnimationListener.aidl create mode 100644 SystemUIShared/src/com/android/systemui/shared/recents/ISystemUiProxy.aidl create mode 100644 SystemUIShared/src/com/android/systemui/shared/recents/model/Task.aidl create mode 100644 SystemUIShared/src/com/android/systemui/shared/recents/model/Task.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/recents/model/ThumbnailData.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/recents/utilities/AppTrace.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/recents/utilities/BitmapUtil.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/recents/utilities/RectFEvaluator.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/recents/utilities/Utilities.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/recents/view/AppTransitionAnimationSpecCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/recents/view/AppTransitionAnimationSpecsFuture.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/recents/view/RecentsTransition.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/ActivityCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/ActivityManagerWrapper.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/ActivityOptionsCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/AssistDataReceiver.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/BackgroundExecutor.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/BlurUtils.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/ChoreographerCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/ConfigurationCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/ContextCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/DevicePolicyManagerWrapper.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/DockedStackListenerCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/InputChannelCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/InputConsumerController.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/InputMonitorCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/KeyguardManagerCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/LatencyTrackerCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/LauncherEventUtil.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/MetricsLoggerCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/PackageManagerWrapper.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/PinnedStackListenerForwarder.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/QuickStepContract.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/RecentsAnimationControllerCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/RecentsAnimationListener.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationAdapterCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationDefinitionCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationRunnerCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationTargetCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/RotationWatcher.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/SurfaceControlCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/SurfaceViewRequestReceiver.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/SurfaceViewRequestUtils.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/SyncRtSurfaceTransactionApplierCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/SystemGestureExclusionListenerCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/TaskDescriptionCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/TaskInfoCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/TaskStackChangeListener.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/TaskStackChangeListeners.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/ThreadedRendererCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/TonalCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/TransactionCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/UniversalSmartspaceUtils.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/ViewRootImplCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/WallpaperEngineCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/WallpaperManagerCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/WindowCallbacksCompat.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/system/WindowManagerWrapper.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/tracing/FrameProtoTracer.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/tracing/ProtoTraceable.java diff --git a/SystemUIShared/.gitignore b/SystemUIShared/.gitignore new file mode 100644 index 0000000000..6213826ab5 --- /dev/null +++ b/SystemUIShared/.gitignore @@ -0,0 +1,13 @@ +*.iml +.project +.classpath +.project.properties +gen/ +bin/ +.idea/ +.gradle/ +local.properties +gradle/ +build/ +gradlew* +.DS_Store diff --git a/SystemUIShared/AndroidManifest.xml b/SystemUIShared/AndroidManifest.xml new file mode 100644 index 0000000000..aaadea6ec3 --- /dev/null +++ b/SystemUIShared/AndroidManifest.xml @@ -0,0 +1,22 @@ + + + + + + + diff --git a/SystemUIShared/build.gradle b/SystemUIShared/build.gradle new file mode 100644 index 0000000000..e97e0aa84d --- /dev/null +++ b/SystemUIShared/build.gradle @@ -0,0 +1,41 @@ +apply plugin: 'com.android.library' + +android { + compileSdkVersion COMPILE_SDK + buildToolsVersion BUILD_TOOLS_VERSION + + defaultConfig { + minSdkVersion 28 + targetSdkVersion 28 + versionCode 1 + versionName "1.0" + } + + sourceSets { + main { + java.srcDirs = ['src'] + aidl.srcDirs = ['src'] + manifest.srcFile 'AndroidManifest.xml' + res.srcDirs = ['res'] + } + } + + lintOptions { + abortOnError false + } + + tasks.withType(JavaCompile) { + options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation" + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + addFrameworkJar('framework.jar') +} + +dependencies { + +} diff --git a/SystemUIShared/src/com/android/systemui/plugins/Plugin.java b/SystemUIShared/src/com/android/systemui/plugins/Plugin.java new file mode 100644 index 0000000000..bb93367c37 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/plugins/Plugin.java @@ -0,0 +1,129 @@ +/* + * 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.plugins; + +import com.android.systemui.plugins.annotations.Requires; + +import android.content.Context; + +/** + * Plugins are separate APKs that + * are expected to implement interfaces provided by SystemUI. Their + * code is dynamically loaded into the SysUI process which can allow + * for multiple prototypes to be created and run on a single android + * build. + * + * PluginLifecycle: + *
+ *
+ * plugin.onCreate(Context sysuiContext, Context pluginContext);
+ * --- This is always called before any other calls
+ *
+ * pluginListener.onPluginConnected(Plugin p);
+ * --- This lets the plugin hook know that a plugin is now connected.
+ *
+ * ** Any other calls back and forth between sysui/plugin **
+ *
+ * pluginListener.onPluginDisconnected(Plugin p);
+ * --- Lets the plugin hook know that it should stop interacting with
+ *     this plugin and drop all references to it.
+ *
+ * plugin.onDestroy();
+ * --- Finally the plugin can perform any cleanup to ensure that its not
+ *     leaking into the SysUI process.
+ *
+ * Any time a plugin APK is updated the plugin is destroyed and recreated
+ * to load the new code/resources.
+ *
+ * 
+ * + * Creating plugin hooks: + * + * To create a plugin hook, first create an interface in + * frameworks/base/packages/SystemUI/plugin that extends Plugin. + * Include in it any hooks you want to be able to call into from + * sysui and create callback interfaces for anything you need to + * pass through into the plugin. + * + * Then to attach to any plugins simply add a plugin listener and + * onPluginConnected will get called whenever new plugins are installed, + * updated, or enabled. Like this example from SystemUIApplication: + * + *
+ * {@literal
+ * PluginManager.getInstance(this).addPluginListener(OverlayPlugin.COMPONENT,
+ *        new PluginListener() {
+ *        @Override
+ *        public void onPluginConnected(OverlayPlugin plugin) {
+ *            StatusBar phoneStatusBar = getComponent(StatusBar.class);
+ *            if (phoneStatusBar != null) {
+ *                plugin.setup(phoneStatusBar.getStatusBarWindow(),
+ *                phoneStatusBar.getNavigationBarView());
+ *            }
+ *        }
+ * }, OverlayPlugin.VERSION, true /* Allow multiple plugins *\/);
+ * }
+ * 
+ * Note the VERSION included here. Any time incompatible changes in the + * interface are made, this version should be changed to ensure old plugins + * aren't accidentally loaded. Since the plugin library is provided by + * SystemUI, default implementations can be added for new methods to avoid + * version changes when possible. + * + * Implementing a Plugin: + * + * See the ExamplePlugin for an example Android.mk on how to compile + * a plugin. Note that SystemUILib is not static for plugins, its classes + * are provided by SystemUI. + * + * Plugin security is based around a signature permission, so plugins must + * hold the following permission in their manifest. + * + *
+ * {@literal
+ * 
+ * }
+ * 
+ * + * A plugin is found through a querying for services, so to let SysUI know + * about it, create a service with a name that points at your implementation + * of the plugin interface with the action accompanying it: + * + *
+ * {@literal
+ * 
+ *    
+ *        
+ *    
+ * 
+ * }
+ * 
+ */ +public interface Plugin { + + /** + * @deprecated + * @see Requires + */ + default int getVersion() { + // Default of -1 indicates the plugin supports the new Requires model. + return -1; + } + + default void onCreate(Context sysuiContext, Context pluginContext) { + } + + default void onDestroy() { + } +} diff --git a/SystemUIShared/src/com/android/systemui/plugins/PluginFragment.java b/SystemUIShared/src/com/android/systemui/plugins/PluginFragment.java new file mode 100644 index 0000000000..1bfa567b66 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/plugins/PluginFragment.java @@ -0,0 +1,45 @@ +/* + * 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.plugins; + +import android.app.Fragment; +import android.content.Context; +import android.os.Bundle; +import android.view.LayoutInflater; + +public abstract class PluginFragment extends Fragment implements Plugin { + + private Context mPluginContext; + + @Override + public void onCreate(Context sysuiContext, Context pluginContext) { + mPluginContext = pluginContext; + } + + @Override + public LayoutInflater onGetLayoutInflater(Bundle savedInstanceState) { + return super.onGetLayoutInflater(savedInstanceState).cloneInContext(getContext()); + } + + @Override + public void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + } + + @Override + public Context getContext() { + return mPluginContext; + } +} diff --git a/SystemUIShared/src/com/android/systemui/plugins/PluginListener.java b/SystemUIShared/src/com/android/systemui/plugins/PluginListener.java new file mode 100644 index 0000000000..b488d2a84b --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/plugins/PluginListener.java @@ -0,0 +1,38 @@ +/* + * 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.plugins; + +import android.content.Context; + +/** + * Interface for listening to plugins being connected. + */ +public interface PluginListener { + /** + * Called when the plugin has been loaded and is ready to be used. + * This may be called multiple times if multiple plugins are allowed. + * It may also be called in the future if the plugin package changes + * and needs to be reloaded. + */ + void onPluginConnected(T plugin, Context pluginContext); + + /** + * Called when a plugin has been uninstalled/updated and should be removed + * from use. + */ + default void onPluginDisconnected(T plugin) { + // Optional. + } +} diff --git a/SystemUIShared/src/com/android/systemui/plugins/annotations/Dependencies.java b/SystemUIShared/src/com/android/systemui/plugins/annotations/Dependencies.java new file mode 100644 index 0000000000..dbbf047519 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/plugins/annotations/Dependencies.java @@ -0,0 +1,27 @@ +/* + * 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.plugins.annotations; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Used for repeated @DependsOn internally, not for plugin + * use. + */ +@Retention(RetentionPolicy.RUNTIME) +public @interface Dependencies { + DependsOn[] value(); +} diff --git a/SystemUIShared/src/com/android/systemui/plugins/annotations/DependsOn.java b/SystemUIShared/src/com/android/systemui/plugins/annotations/DependsOn.java new file mode 100644 index 0000000000..b81d673063 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/plugins/annotations/DependsOn.java @@ -0,0 +1,32 @@ +/* + * 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.plugins.annotations; + +import java.lang.annotation.Repeatable; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Used to indicate that an interface in the plugin library needs another + * interface to function properly. When this is added, it will be enforced + * that all plugins that @Requires the annotated interface also @Requires + * the specified class as well. + */ +@Retention(RetentionPolicy.RUNTIME) +@Repeatable(value = Dependencies.class) +public @interface DependsOn { + Class target(); + +} diff --git a/SystemUIShared/src/com/android/systemui/plugins/annotations/ProvidesInterface.java b/SystemUIShared/src/com/android/systemui/plugins/annotations/ProvidesInterface.java new file mode 100644 index 0000000000..d0e14b8657 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/plugins/annotations/ProvidesInterface.java @@ -0,0 +1,30 @@ +/* + * 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.plugins.annotations; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Should be added to all interfaces in plugin lib to specify their + * current version and optionally their action to implement the plugin. + */ +@Retention(RetentionPolicy.RUNTIME) +public @interface ProvidesInterface { + int version(); + + String action() default ""; + +} diff --git a/SystemUIShared/src/com/android/systemui/plugins/annotations/Requirements.java b/SystemUIShared/src/com/android/systemui/plugins/annotations/Requirements.java new file mode 100644 index 0000000000..9cfa279b9c --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/plugins/annotations/Requirements.java @@ -0,0 +1,27 @@ +/* + * 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.plugins.annotations; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Used for repeated @Requires internally, not for plugin + * use. + */ +@Retention(RetentionPolicy.RUNTIME) +public @interface Requirements { + Requires[] value(); +} diff --git a/SystemUIShared/src/com/android/systemui/plugins/annotations/Requires.java b/SystemUIShared/src/com/android/systemui/plugins/annotations/Requires.java new file mode 100644 index 0000000000..e1b1303b8c --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/plugins/annotations/Requires.java @@ -0,0 +1,33 @@ +/* + * 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.plugins.annotations; + +import java.lang.annotation.Repeatable; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Used to annotate which interfaces a given plugin depends on. + * + * At minimum all plugins should have at least one @Requires annotation + * for the plugin interface that they are implementing. They will also + * need an @Requires for each class that the plugin interface @DependsOn. + */ +@Retention(RetentionPolicy.RUNTIME) +@Repeatable(value = Requirements.class) +public @interface Requires { + Class target(); + int version(); +} diff --git a/SystemUIShared/src/com/android/systemui/shared/plugins/PluginEnabler.java b/SystemUIShared/src/com/android/systemui/shared/plugins/PluginEnabler.java new file mode 100644 index 0000000000..01b012d1fc --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/plugins/PluginEnabler.java @@ -0,0 +1,53 @@ +/* + * 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.plugins; + +import android.annotation.IntDef; +import android.content.ComponentName; + +/** + * Enables and disables plugins. + */ +public interface PluginEnabler { + + int ENABLED = 0; + int DISABLED_MANUALLY = 1; + int DISABLED_INVALID_VERSION = 1; + int DISABLED_FROM_EXPLICIT_CRASH = 2; + int DISABLED_FROM_SYSTEM_CRASH = 3; + + @IntDef({ENABLED, DISABLED_MANUALLY, DISABLED_INVALID_VERSION, DISABLED_FROM_EXPLICIT_CRASH, + DISABLED_FROM_SYSTEM_CRASH}) + @interface DisableReason { + } + + /** Enables plugin via the PackageManager. */ + void setEnabled(ComponentName component); + + /** Disables a plugin via the PackageManager and records the reason for disabling. */ + void setDisabled(ComponentName component, @DisableReason int reason); + + /** Returns true if the plugin is enabled in the PackageManager. */ + boolean isEnabled(ComponentName component); + + /** + * Returns the reason that a plugin is disabled, (if it is). + * + * It should return {@link #ENABLED} if the plugin is turned on. + * It should return {@link #DISABLED_MANUALLY} if the plugin is off but the reason is unknown. + */ + @DisableReason + int getDisableReason(ComponentName componentName); +} diff --git a/SystemUIShared/src/com/android/systemui/shared/plugins/PluginInitializer.java b/SystemUIShared/src/com/android/systemui/shared/plugins/PluginInitializer.java new file mode 100644 index 0000000000..c3815e4cee --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/plugins/PluginInitializer.java @@ -0,0 +1,40 @@ +/* + * 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.plugins; + +import android.content.Context; +import android.os.Looper; + +/** + * Provides necessary components for initializing {@link PluginManagerImpl}. + */ +public interface PluginInitializer { + + Looper getBgLooper(); + + /** + * Called from the bg looper during initialization of {@link PluginManagerImpl}. + */ + void onPluginManagerInit(); + + String[] getWhitelistedPlugins(Context context); + + PluginEnabler getPluginEnabler(Context context); + + /** + * Called from {@link PluginManagerImpl#handleWtfs()}. + */ + void handleWtfs(); +} diff --git a/SystemUIShared/src/com/android/systemui/shared/plugins/PluginInstanceManager.java b/SystemUIShared/src/com/android/systemui/shared/plugins/PluginInstanceManager.java new file mode 100644 index 0000000000..c8607df8fe --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/plugins/PluginInstanceManager.java @@ -0,0 +1,462 @@ +/* + * 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.Notification; +import android.app.Notification.Action; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.ComponentName; +import android.content.Context; +import android.content.ContextWrapper; +import android.content.Intent; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.content.pm.PackageManager.NameNotFoundException; +import android.content.pm.ResolveInfo; +import android.content.res.Resources; +import android.net.Uri; +import android.os.Build; +import android.os.Handler; +import android.os.Looper; +import android.os.Message; +import android.util.ArraySet; +import android.util.Log; +import android.view.LayoutInflater; + +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.PluginFragment; +import com.android.systemui.plugins.PluginListener; +import com.android.systemui.shared.plugins.VersionInfo.InvalidVersionException; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class PluginInstanceManager { + + private static final boolean DEBUG = false; + + private static final String TAG = "PluginInstanceManager"; + public static final String PLUGIN_PERMISSION = "com.android.systemui.permission.PLUGIN"; + + private final Context mContext; + private final PluginListener mListener; + private final String mAction; + private final boolean mAllowMultiple; + private final VersionInfo mVersion; + + @VisibleForTesting + final MainHandler mMainHandler; + @VisibleForTesting + final PluginHandler mPluginHandler; + private final boolean isDebuggable; + private final PackageManager mPm; + private final PluginManagerImpl mManager; + private final ArraySet mWhitelistedPlugins = new ArraySet<>(); + + PluginInstanceManager(Context context, String action, PluginListener listener, + boolean allowMultiple, Looper looper, VersionInfo version, PluginManagerImpl manager) { + this(context, context.getPackageManager(), action, listener, allowMultiple, looper, version, + manager, Build.IS_DEBUGGABLE, manager.getWhitelistedPlugins()); + } + + @VisibleForTesting + PluginInstanceManager(Context context, PackageManager pm, String action, + PluginListener listener, boolean allowMultiple, Looper looper, VersionInfo version, + PluginManagerImpl manager, boolean debuggable, String[] pluginWhitelist) { + mMainHandler = new MainHandler(Looper.getMainLooper()); + mPluginHandler = new PluginHandler(looper); + mManager = manager; + mContext = context; + mPm = pm; + mAction = action; + mListener = listener; + mAllowMultiple = allowMultiple; + mVersion = version; + mWhitelistedPlugins.addAll(Arrays.asList(pluginWhitelist)); + isDebuggable = debuggable; + } + + public PluginInfo getPlugin() { + if (Looper.myLooper() != Looper.getMainLooper()) { + throw new RuntimeException("Must be called from UI thread"); + } + mPluginHandler.handleQueryPlugins(null /* All packages */); + if (mPluginHandler.mPlugins.size() > 0) { + mMainHandler.removeMessages(MainHandler.PLUGIN_CONNECTED); + PluginInfo info = mPluginHandler.mPlugins.get(0); + PluginPrefs.setHasPlugins(mContext); + info.mPlugin.onCreate(mContext, info.mPluginContext); + return info; + } + return null; + } + + public void loadAll() { + if (DEBUG) Log.d(TAG, "startListening"); + mPluginHandler.sendEmptyMessage(PluginHandler.QUERY_ALL); + } + + public void destroy() { + if (DEBUG) Log.d(TAG, "stopListening"); + ArrayList plugins = new ArrayList(mPluginHandler.mPlugins); + for (PluginInfo plugin : plugins) { + mMainHandler.obtainMessage(MainHandler.PLUGIN_DISCONNECTED, + plugin.mPlugin).sendToTarget(); + } + } + + public void onPackageRemoved(String pkg) { + mPluginHandler.obtainMessage(PluginHandler.REMOVE_PKG, pkg).sendToTarget(); + } + + public void onPackageChange(String pkg) { + mPluginHandler.obtainMessage(PluginHandler.REMOVE_PKG, pkg).sendToTarget(); + mPluginHandler.obtainMessage(PluginHandler.QUERY_PKG, pkg).sendToTarget(); + } + + public boolean checkAndDisable(String className) { + boolean disableAny = false; + ArrayList plugins = new ArrayList(mPluginHandler.mPlugins); + for (PluginInfo info : plugins) { + if (className.startsWith(info.mPackage)) { + disableAny |= disable(info, PluginEnabler.DISABLED_FROM_EXPLICIT_CRASH); + } + } + return disableAny; + } + + public boolean disableAll() { + ArrayList plugins = new ArrayList(mPluginHandler.mPlugins); + boolean disabledAny = false; + for (int i = 0; i < plugins.size(); i++) { + disabledAny |= disable(plugins.get(i), PluginEnabler.DISABLED_FROM_SYSTEM_CRASH); + } + return disabledAny; + } + + private boolean isPluginWhitelisted(ComponentName pluginName) { + for (String componentNameOrPackage : mWhitelistedPlugins) { + ComponentName componentName = ComponentName.unflattenFromString(componentNameOrPackage); + if (componentName == null) { + if (componentNameOrPackage.equals(pluginName.getPackageName())) { + return true; + } + } else { + if (componentName.equals(pluginName)) { + return true; + } + } + } + return false; + } + + private boolean disable(PluginInfo info, @PluginEnabler.DisableReason int reason) { + // Live by the sword, die by the sword. + // Misbehaving plugins get disabled and won't come back until uninstall/reinstall. + + ComponentName pluginComponent = new ComponentName(info.mPackage, info.mClass); + // If a plugin is detected in the stack of a crash then this will be called for that + // plugin, if the plugin causing a crash cannot be identified, they are all disabled + // assuming one of them must be bad. + if (isPluginWhitelisted(pluginComponent)) { + // Don't disable whitelisted plugins as they are a part of the OS. + return false; + } + Log.w(TAG, "Disabling plugin " + pluginComponent.flattenToShortString()); + mManager.getPluginEnabler().setDisabled(pluginComponent, reason); + + return true; + } + + public boolean dependsOn(Plugin p, Class cls) { + ArrayList plugins = new ArrayList(mPluginHandler.mPlugins); + for (PluginInfo info : plugins) { + if (info.mPlugin.getClass().getName().equals(p.getClass().getName())) { + return info.mVersion != null && info.mVersion.hasClass(cls); + } + } + return false; + } + + @Override + public String toString() { + return String.format("%s@%s (action=%s)", + getClass().getSimpleName(), hashCode(), mAction); + } + + private class MainHandler extends Handler { + private static final int PLUGIN_CONNECTED = 1; + private static final int PLUGIN_DISCONNECTED = 2; + + public MainHandler(Looper looper) { + super(looper); + } + + @Override + public void handleMessage(Message msg) { + switch (msg.what) { + case PLUGIN_CONNECTED: + if (DEBUG) Log.d(TAG, "onPluginConnected"); + PluginPrefs.setHasPlugins(mContext); + PluginInfo info = (PluginInfo) msg.obj; + mManager.handleWtfs(); + if (!(msg.obj instanceof PluginFragment)) { + // Only call onDestroy for plugins that aren't fragments, as fragments + // will get the onCreate as part of the fragment lifecycle. + info.mPlugin.onCreate(mContext, info.mPluginContext); + } + mListener.onPluginConnected(info.mPlugin, info.mPluginContext); + break; + case PLUGIN_DISCONNECTED: + if (DEBUG) Log.d(TAG, "onPluginDisconnected"); + mListener.onPluginDisconnected((T) msg.obj); + if (!(msg.obj instanceof PluginFragment)) { + // Only call onDestroy for plugins that aren't fragments, as fragments + // will get the onDestroy as part of the fragment lifecycle. + ((T) msg.obj).onDestroy(); + } + break; + default: + super.handleMessage(msg); + break; + } + } + } + + private class PluginHandler extends Handler { + private static final int QUERY_ALL = 1; + private static final int QUERY_PKG = 2; + private static final int REMOVE_PKG = 3; + + private final ArrayList> mPlugins = new ArrayList<>(); + + public PluginHandler(Looper looper) { + super(looper); + } + + @Override + public void handleMessage(Message msg) { + switch (msg.what) { + case QUERY_ALL: + if (DEBUG) Log.d(TAG, "queryAll " + mAction); + for (int i = mPlugins.size() - 1; i >= 0; i--) { + PluginInfo pluginInfo = mPlugins.get(i); + mMainHandler.obtainMessage( + MainHandler.PLUGIN_DISCONNECTED, pluginInfo.mPlugin).sendToTarget(); + } + mPlugins.clear(); + handleQueryPlugins(null); + break; + case REMOVE_PKG: + String pkg = (String) msg.obj; + for (int i = mPlugins.size() - 1; i >= 0; i--) { + final PluginInfo plugin = mPlugins.get(i); + if (plugin.mPackage.equals(pkg)) { + mMainHandler.obtainMessage(MainHandler.PLUGIN_DISCONNECTED, + plugin.mPlugin).sendToTarget(); + mPlugins.remove(i); + } + } + break; + case QUERY_PKG: + String p = (String) msg.obj; + if (DEBUG) Log.d(TAG, "queryPkg " + p + " " + mAction); + if (mAllowMultiple || (mPlugins.size() == 0)) { + handleQueryPlugins(p); + } else { + if (DEBUG) Log.d(TAG, "Too many of " + mAction); + } + break; + default: + super.handleMessage(msg); + } + } + + private void handleQueryPlugins(String pkgName) { + // This isn't actually a service and shouldn't ever be started, but is + // a convenient PM based way to manage our plugins. + Intent intent = new Intent(mAction); + if (pkgName != null) { + intent.setPackage(pkgName); + } + List result = mPm.queryIntentServices(intent, 0); + if (DEBUG) Log.d(TAG, "Found " + result.size() + " plugins"); + if (result.size() > 1 && !mAllowMultiple) { + // TODO: Show warning. + Log.w(TAG, "Multiple plugins found for " + mAction); + if (DEBUG) { + for (ResolveInfo info : result) { + ComponentName name = new ComponentName(info.serviceInfo.packageName, + info.serviceInfo.name); + Log.w(TAG, " " + name); + } + } + return; + } + for (ResolveInfo info : result) { + ComponentName name = new ComponentName(info.serviceInfo.packageName, + info.serviceInfo.name); + PluginInfo t = handleLoadPlugin(name); + if (t == null) continue; + + // add plugin before sending PLUGIN_CONNECTED message + mPlugins.add(t); + mMainHandler.obtainMessage(mMainHandler.PLUGIN_CONNECTED, t).sendToTarget(); + } + } + + protected PluginInfo handleLoadPlugin(ComponentName component) { + // This was already checked, but do it again here to make extra extra sure, we don't + // use these on production builds. + if (!isDebuggable && !isPluginWhitelisted(component)) { + // Never ever ever allow these on production builds, they are only for prototyping. + Log.w(TAG, "Plugin cannot be loaded on production build: " + component); + return null; + } + if (!mManager.getPluginEnabler().isEnabled(component)) { + if (DEBUG) Log.d(TAG, "Plugin is not enabled, aborting load: " + component); + return null; + } + String pkg = component.getPackageName(); + String cls = component.getClassName(); + try { + ApplicationInfo info = mPm.getApplicationInfo(pkg, 0); + // TODO: This probably isn't needed given that we don't have IGNORE_SECURITY on + if (mPm.checkPermission(PLUGIN_PERMISSION, pkg) + != PackageManager.PERMISSION_GRANTED) { + Log.d(TAG, "Plugin doesn't have permission: " + pkg); + return null; + } + // Create our own ClassLoader so we can use our own code as the parent. + ClassLoader classLoader = mManager.getClassLoader(info); + Context pluginContext = new PluginContextWrapper( + mContext.createApplicationContext(info, 0), classLoader); + Class pluginClass = Class.forName(cls, true, classLoader); + // TODO: Only create the plugin before version check if we need it for + // legacy version check. + T plugin = (T) pluginClass.newInstance(); + try { + VersionInfo version = checkVersion(pluginClass, plugin, mVersion); + if (DEBUG) Log.d(TAG, "createPlugin"); + return new PluginInfo(pkg, cls, plugin, pluginContext, version); + } catch (InvalidVersionException e) { + final int icon = Resources.getSystem().getIdentifier( + "stat_sys_warning", "drawable", "android"); + final int color = Resources.getSystem().getIdentifier( + "system_notification_accent_color", "color", "android"); + final Notification.Builder nb = new Notification.Builder(mContext, + PluginManager.NOTIFICATION_CHANNEL_ID) + .setStyle(new Notification.BigTextStyle()) + .setSmallIcon(icon) + .setWhen(0) + .setShowWhen(false) + .setVisibility(Notification.VISIBILITY_PUBLIC) + .setColor(mContext.getColor(color)); + String label = cls; + try { + label = mPm.getServiceInfo(component, 0).loadLabel(mPm).toString(); + } catch (NameNotFoundException e2) { + } + if (!e.isTooNew()) { + // Localization not required as this will never ever appear in a user build. + nb.setContentTitle("Plugin \"" + label + "\" is too old") + .setContentText("Contact plugin developer to get an updated" + + " version.\n" + e.getMessage()); + } else { + // Localization not required as this will never ever appear in a user build. + nb.setContentTitle("Plugin \"" + label + "\" is too new") + .setContentText("Check to see if an OTA is available.\n" + + e.getMessage()); + } + Intent i = new Intent(PluginManagerImpl.DISABLE_PLUGIN).setData( + Uri.parse("package://" + component.flattenToString())); + PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, i, 0); + nb.addAction(new Action.Builder(null, "Disable plugin", pi).build()); + mContext.getSystemService(NotificationManager.class) + .notify(SystemMessage.NOTE_PLUGIN, nb.build()); + // TODO: Warn user. + Log.w(TAG, "Plugin has invalid interface version " + plugin.getVersion() + + ", expected " + mVersion); + return null; + } + } catch (Throwable e) { + Log.w(TAG, "Couldn't load plugin: " + pkg, e); + return null; + } + } + + private VersionInfo checkVersion(Class pluginClass, T plugin, VersionInfo version) + throws InvalidVersionException { + VersionInfo pv = new VersionInfo().addClass(pluginClass); + if (pv.hasVersionInfo()) { + version.checkVersion(pv); + } else { + int fallbackVersion = plugin.getVersion(); + if (fallbackVersion != version.getDefaultVersion()) { + throw new InvalidVersionException("Invalid legacy version", false); + } + return null; + } + return pv; + } + } + + public static class PluginContextWrapper extends ContextWrapper { + private final ClassLoader mClassLoader; + private LayoutInflater mInflater; + + public PluginContextWrapper(Context base, ClassLoader classLoader) { + super(base); + mClassLoader = classLoader; + } + + @Override + public ClassLoader getClassLoader() { + return mClassLoader; + } + + @Override + public Object getSystemService(String name) { + if (LAYOUT_INFLATER_SERVICE.equals(name)) { + if (mInflater == null) { + mInflater = LayoutInflater.from(getBaseContext()).cloneInContext(this); + } + return mInflater; + } + return getBaseContext().getSystemService(name); + } + } + + static class PluginInfo { + private final Context mPluginContext; + private final VersionInfo mVersion; + private String mClass; + T mPlugin; + String mPackage; + + public PluginInfo(String pkg, String cls, T plugin, Context pluginContext, + VersionInfo info) { + mPlugin = plugin; + mClass = cls; + mPackage = pkg; + mPluginContext = pluginContext; + mVersion = info; + } + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/plugins/PluginManager.java b/SystemUIShared/src/com/android/systemui/shared/plugins/PluginManager.java new file mode 100644 index 0000000000..3f907a8aa3 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/plugins/PluginManager.java @@ -0,0 +1,60 @@ +/* + * 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.text.TextUtils; + +import com.android.systemui.plugins.Plugin; +import com.android.systemui.plugins.PluginListener; +import com.android.systemui.plugins.annotations.ProvidesInterface; + +public interface PluginManager { + + String PLUGIN_CHANGED = "com.android.systemui.action.PLUGIN_CHANGED"; + + // must be one of the channels created in NotificationChannels.java + String NOTIFICATION_CHANNEL_ID = "ALR"; + + String[] getWhitelistedPlugins(); + + T getOneShotPlugin(Class cls); + T getOneShotPlugin(String action, Class cls); + + void addPluginListener(PluginListener listener, Class cls); + void addPluginListener(PluginListener listener, Class cls, + boolean allowMultiple); + void addPluginListener(String action, PluginListener listener, + Class cls); + void addPluginListener(String action, PluginListener listener, + Class cls, boolean allowMultiple); + + void removePluginListener(PluginListener listener); + + boolean dependsOn(Plugin p, Class 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() { + @Override + public void accept(Canvas c) { + c.scale(scale, scale); + if (eraseColor != 0) { + c.drawColor(eraseColor); + } + if (view != null) { + view.draw(c); + } + } + }); + } + + /** + * @return a hardware {@link Bitmap} after being drawn with the {@param consumer}. Result can be + * null if we were unable to allocate a hardware bitmap. + */ + public static Bitmap createHardwareBitmap(int width, int height, Consumer consumer) { + final Picture picture = new Picture(); + final Canvas canvas = picture.beginRecording(width, height); + consumer.accept(canvas); + picture.endRecording(); + return Bitmap.createBitmap(picture); + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/ActivityCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/ActivityCompat.java new file mode 100644 index 0000000000..0c7e56e071 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/ActivityCompat.java @@ -0,0 +1,72 @@ +/* + * 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.system; + +import android.app.Activity; +import android.view.View; +import android.view.ViewHierarchyEncoder; + +import java.io.ByteArrayOutputStream; + +public class ActivityCompat { + private final Activity mWrapped; + + public ActivityCompat(Activity activity) { + mWrapped = activity; + } + + /** + * @see Activity#registerRemoteAnimations + */ + public void registerRemoteAnimations(RemoteAnimationDefinitionCompat definition) { + mWrapped.registerRemoteAnimations(definition.getWrapped()); + } + + /** + * @see Activity#unregisterRemoteAnimations + */ + public void unregisterRemoteAnimations() { + mWrapped.unregisterRemoteAnimations(); + } + + /** + * @see android.view.ViewDebug#dumpv2(View, ByteArrayOutputStream) + */ + public boolean encodeViewHierarchy(ByteArrayOutputStream out) { + View view = null; + if (mWrapped.getWindow() != null && + mWrapped.getWindow().peekDecorView() != null && + mWrapped.getWindow().peekDecorView().getViewRootImpl() != null) { + view = mWrapped.getWindow().peekDecorView().getViewRootImpl().getView(); + } + if (view == null) { + return false; + } + + final ViewHierarchyEncoder encoder = new ViewHierarchyEncoder(out); + int[] location = view.getLocationOnScreen(); + encoder.addProperty("window:left", location[0]); + encoder.addProperty("window:top", location[1]); + view.encode(encoder); + encoder.endStream(); + return true; + } + + public int getDisplayId() { + return mWrapped.getDisplayId(); + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/ActivityManagerWrapper.java b/SystemUIShared/src/com/android/systemui/shared/system/ActivityManagerWrapper.java new file mode 100644 index 0000000000..cffc10f65f --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/ActivityManagerWrapper.java @@ -0,0 +1,546 @@ +/* + * Copyright (C) 2015 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.system; + +import static android.app.ActivityManager.LOCK_TASK_MODE_LOCKED; +import static android.app.ActivityManager.LOCK_TASK_MODE_NONE; +import static android.app.ActivityManager.LOCK_TASK_MODE_PINNED; +import static android.app.ActivityManager.RECENT_IGNORE_UNAVAILABLE; +import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED; +import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY; +import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY; +import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED; + +import android.annotation.NonNull; +import android.app.Activity; +import android.app.ActivityManager; +import android.app.ActivityManager.RecentTaskInfo; +import android.app.ActivityManager.RunningTaskInfo; +import android.app.ActivityManager.TaskSnapshot; +import android.app.ActivityOptions; +import android.app.ActivityTaskManager; +import android.app.AppGlobals; +import android.app.IAssistDataReceiver; +import android.app.WindowConfiguration; +import android.content.ContentResolver; +import android.content.Context; +import android.content.Intent; +import android.content.pm.ActivityInfo; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.content.pm.UserInfo; +import android.graphics.Bitmap; +import android.graphics.Rect; +import android.os.Bundle; +import android.os.Handler; +import android.os.IBinder; +import android.os.Looper; +import android.os.RemoteException; +import android.os.ServiceManager; +import android.os.SystemClock; +import android.os.UserHandle; +import android.provider.Settings; +import android.util.Log; +import android.view.IRecentsAnimationController; +import android.view.IRecentsAnimationRunner; +import android.view.RemoteAnimationTarget; + +import com.android.internal.app.IVoiceInteractionManagerService; +import com.android.systemui.shared.recents.model.Task; +import com.android.systemui.shared.recents.model.Task.TaskKey; +import com.android.systemui.shared.recents.model.ThumbnailData; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Future; +import java.util.function.Consumer; + +public class ActivityManagerWrapper { + + private static final String TAG = "ActivityManagerWrapper"; + + private static final ActivityManagerWrapper sInstance = new ActivityManagerWrapper(); + + // Should match the values in PhoneWindowManager + public static final String CLOSE_SYSTEM_WINDOWS_REASON_RECENTS = "recentapps"; + public static final String CLOSE_SYSTEM_WINDOWS_REASON_HOME_KEY = "homekey"; + + // Should match the value in AssistManager + private static final String INVOCATION_TIME_MS_KEY = "invocation_time_ms"; + + private final PackageManager mPackageManager; + private final BackgroundExecutor mBackgroundExecutor; + private final TaskStackChangeListeners mTaskStackChangeListeners; + + private ActivityManagerWrapper() { + final Context context = AppGlobals.getInitialApplication(); + mPackageManager = context.getPackageManager(); + mBackgroundExecutor = BackgroundExecutor.get(); + mTaskStackChangeListeners = new TaskStackChangeListeners(Looper.getMainLooper()); + } + + public static ActivityManagerWrapper getInstance() { + return sInstance; + } + + /** + * @return the current user's id. + */ + public int getCurrentUserId() { + UserInfo ui; + try { + ui = ActivityManager.getService().getCurrentUser(); + return ui != null ? ui.id : 0; + } catch (RemoteException e) { + throw e.rethrowFromSystemServer(); + } + } + + /** + * @return the top running task (can be {@code null}). + */ + public ActivityManager.RunningTaskInfo getRunningTask() { + return getRunningTask(false /* filterVisibleRecents */); + } + + /** + * @return the top running task filtering only for tasks that can be visible in the recent tasks + * list (can be {@code null}). + */ + public ActivityManager.RunningTaskInfo getRunningTask(boolean filterOnlyVisibleRecents) { + // Note: The set of running tasks from the system is ordered by recency + try { + List tasks = + ActivityTaskManager.getService().getFilteredTasks(1, filterOnlyVisibleRecents); + if (tasks.isEmpty()) { + return null; + } + return tasks.get(0); + } catch (RemoteException e) { + return null; + } + } + + /** + * @return a list of the recents tasks. + */ + public List getRecentTasks(int numTasks, int userId) { + try { + return ActivityTaskManager.getService().getRecentTasks(numTasks, + RECENT_IGNORE_UNAVAILABLE, userId).getList(); + } catch (RemoteException e) { + Log.e(TAG, "Failed to get recent tasks", e); + return new ArrayList<>(); + } + } + + /** + * @return the task snapshot for the given {@param taskId}. + */ + public @NonNull ThumbnailData getTaskThumbnail(int taskId, boolean isLowResolution) { + ActivityManager.TaskSnapshot snapshot = null; + try { + snapshot = ActivityTaskManager.getService().getTaskSnapshot(taskId, isLowResolution); + } catch (RemoteException e) { + Log.w(TAG, "Failed to retrieve task snapshot", e); + } + if (snapshot != null) { + return new ThumbnailData(snapshot); + } else { + return new ThumbnailData(); + } + } + + /** + * Removes the outdated snapshot of home task. + */ + public void invalidateHomeTaskSnapshot(final Activity homeActivity) { + mBackgroundExecutor.submit(new Runnable() { + @Override + public void run() { + try { + ActivityTaskManager.getService().invalidateHomeTaskSnapshot( + homeActivity.getActivityToken()); + } catch (RemoteException e) { + Log.w(TAG, "Failed to invalidate home snapshot", e); + } + } + }); + } + + /** + * @return the activity label, badging if necessary. + */ + public String getBadgedActivityLabel(ActivityInfo info, int userId) { + return getBadgedLabel(info.loadLabel(mPackageManager).toString(), userId); + } + + /** + * @return the application label, badging if necessary. + */ + public String getBadgedApplicationLabel(ApplicationInfo appInfo, int userId) { + return getBadgedLabel(appInfo.loadLabel(mPackageManager).toString(), userId); + } + + /** + * @return the content description for a given task, badging it if necessary. The content + * description joins the app and activity labels. + */ + public String getBadgedContentDescription(ActivityInfo info, int userId, + ActivityManager.TaskDescription td) { + String activityLabel; + if (td != null && td.getLabel() != null) { + activityLabel = td.getLabel(); + } else { + activityLabel = info.loadLabel(mPackageManager).toString(); + } + String applicationLabel = info.applicationInfo.loadLabel(mPackageManager).toString(); + String badgedApplicationLabel = getBadgedLabel(applicationLabel, userId); + return applicationLabel.equals(activityLabel) + ? badgedApplicationLabel + : badgedApplicationLabel + " " + activityLabel; + } + + /** + * @return the given label for a user, badging if necessary. + */ + private String getBadgedLabel(String label, int userId) { + if (userId != UserHandle.myUserId()) { + label = mPackageManager.getUserBadgedLabel(label, new UserHandle(userId)).toString(); + } + return label; + } + + /** + * Starts the recents activity. The caller should manage the thread on which this is called. + */ + public void startRecentsActivity(Intent intent, final AssistDataReceiver assistDataReceiver, + final RecentsAnimationListener animationHandler, final Consumer resultCallback, + Handler resultCallbackHandler) { + try { + IAssistDataReceiver receiver = null; + if (assistDataReceiver != null) { + receiver = new IAssistDataReceiver.Stub() { + public void onHandleAssistData(Bundle resultData) { + assistDataReceiver.onHandleAssistData(resultData); + } + public void onHandleAssistScreenshot(Bitmap screenshot) { + assistDataReceiver.onHandleAssistScreenshot(screenshot); + } + }; + } + IRecentsAnimationRunner runner = null; + if (animationHandler != null) { + runner = new IRecentsAnimationRunner.Stub() { + @Override + public void onAnimationStart(IRecentsAnimationController controller, + RemoteAnimationTarget[] apps, RemoteAnimationTarget[] wallpapers, + Rect homeContentInsets, Rect minimizedHomeBounds) { + final RecentsAnimationControllerCompat controllerCompat = + new RecentsAnimationControllerCompat(controller); + final RemoteAnimationTargetCompat[] appsCompat = + RemoteAnimationTargetCompat.wrap(apps); + final RemoteAnimationTargetCompat[] wallpapersCompat = + RemoteAnimationTargetCompat.wrap(wallpapers); + animationHandler.onAnimationStart(controllerCompat, appsCompat, + wallpapersCompat, homeContentInsets, minimizedHomeBounds); + } + + @Override + public void onAnimationCanceled(TaskSnapshot taskSnapshot) { + animationHandler.onAnimationCanceled( + taskSnapshot != null ? new ThumbnailData(taskSnapshot) : null); + } + + @Override + public void onTaskAppeared(RemoteAnimationTarget app) { + animationHandler.onTaskAppeared(new RemoteAnimationTargetCompat(app)); + } + }; + } + ActivityTaskManager.getService().startRecentsActivity(intent, receiver, runner); + if (resultCallback != null) { + resultCallbackHandler.post(new Runnable() { + @Override + public void run() { + resultCallback.accept(true); + } + }); + } + } catch (Exception e) { + if (resultCallback != null) { + resultCallbackHandler.post(new Runnable() { + @Override + public void run() { + resultCallback.accept(false); + } + }); + } + } + } + + /** + * Cancels the remote recents animation started from {@link #startRecentsActivity}. + */ + public void cancelRecentsAnimation(boolean restoreHomeStackPosition) { + try { + ActivityTaskManager.getService().cancelRecentsAnimation(restoreHomeStackPosition); + } catch (RemoteException e) { + Log.e(TAG, "Failed to cancel recents animation", e); + } + } + + /** + * Starts a task from Recents. + * + * @see {@link #startActivityFromRecentsAsync(TaskKey, ActivityOptions, int, int, Consumer, Handler)} + */ + public void startActivityFromRecentsAsync(Task.TaskKey taskKey, ActivityOptions options, + Consumer resultCallback, Handler resultCallbackHandler) { + startActivityFromRecentsAsync(taskKey, options, WINDOWING_MODE_UNDEFINED, + ACTIVITY_TYPE_UNDEFINED, resultCallback, resultCallbackHandler); + } + + /** + * Starts a task from Recents. + * + * @param resultCallback The result success callback + * @param resultCallbackHandler The handler to receive the result callback + */ + public void startActivityFromRecentsAsync(final Task.TaskKey taskKey, ActivityOptions options, + int windowingMode, int activityType, final Consumer resultCallback, + final Handler resultCallbackHandler) { + if (taskKey.windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) { + // We show non-visible docked tasks in Recents, but we always want to launch + // them in the fullscreen stack. + if (options == null) { + options = ActivityOptions.makeBasic(); + } + options.setLaunchWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_SECONDARY); + } else if (windowingMode != WINDOWING_MODE_UNDEFINED + || activityType != ACTIVITY_TYPE_UNDEFINED) { + if (options == null) { + options = ActivityOptions.makeBasic(); + } + options.setLaunchWindowingMode(windowingMode); + options.setLaunchActivityType(activityType); + } + final ActivityOptions finalOptions = options; + + + boolean result = false; + try { + result = startActivityFromRecents(taskKey.id, finalOptions); + } catch (Exception e) { + // Fall through + } + final boolean finalResult = result; + if (resultCallback != null) { + resultCallbackHandler.post(new Runnable() { + @Override + public void run() { + resultCallback.accept(finalResult); + } + }); + } + } + + /** + * Starts a task from Recents synchronously. + */ + public boolean startActivityFromRecents(int taskId, ActivityOptions options) { + try { + Bundle optsBundle = options == null ? null : options.toBundle(); + ActivityTaskManager.getService().startActivityFromRecents(taskId, optsBundle); + return true; + } catch (Exception e) { + return false; + } + } + + /** + * Moves an already resumed task to the side of the screen to initiate split screen. + */ + public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode, + Rect initialBounds) { + try { + return ActivityTaskManager.getService().setTaskWindowingModeSplitScreenPrimary(taskId, + true /* onTop */); + } catch (RemoteException e) { + return false; + } + } + + /** + * Registers a task stack listener with the system. + * This should be called on the main thread. + */ + public void registerTaskStackListener(TaskStackChangeListener listener) { + synchronized (mTaskStackChangeListeners) { + mTaskStackChangeListeners.addListener(ActivityManager.getService(), listener); + } + } + + /** + * Unregisters a task stack listener with the system. + * This should be called on the main thread. + */ + public void unregisterTaskStackListener(TaskStackChangeListener listener) { + synchronized (mTaskStackChangeListeners) { + mTaskStackChangeListeners.removeListener(listener); + } + } + + /** + * Requests that the system close any open system windows (including other SystemUI). + */ + public Future closeSystemWindows(final String reason) { + return mBackgroundExecutor.submit(new Runnable() { + @Override + public void run() { + try { + ActivityManager.getService().closeSystemDialogs(reason); + } catch (RemoteException e) { + Log.w(TAG, "Failed to close system windows", e); + } + } + }); + } + + /** + * Removes a task by id. + */ + public void removeTask(final int taskId) { + mBackgroundExecutor.submit(new Runnable() { + @Override + public void run() { + try { + ActivityTaskManager.getService().removeTask(taskId); + } catch (RemoteException e) { + Log.w(TAG, "Failed to remove task=" + taskId, e); + } + } + }); + } + + /** + * Removes all the recent tasks. + */ + public void removeAllRecentTasks() { + mBackgroundExecutor.submit(new Runnable() { + @Override + public void run() { + try { + ActivityTaskManager.getService().removeAllVisibleRecentTasks(); + } catch (RemoteException e) { + Log.w(TAG, "Failed to remove all tasks", e); + } + } + }); + } + + /** + * Cancels the current window transtion to/from Recents for the given task id. + */ + public void cancelWindowTransition(int taskId) { + try { + ActivityTaskManager.getService().cancelTaskWindowTransition(taskId); + } catch (RemoteException e) { + Log.w(TAG, "Failed to cancel window transition for task=" + taskId, e); + } + } + + /** + * @return whether screen pinning is active. + */ + public boolean isScreenPinningActive() { + try { + return ActivityTaskManager.getService().getLockTaskModeState() == LOCK_TASK_MODE_PINNED; + } catch (RemoteException e) { + return false; + } + } + + /** + * @return whether screen pinning is enabled. + */ + public boolean isScreenPinningEnabled() { + final ContentResolver cr = AppGlobals.getInitialApplication().getContentResolver(); + return Settings.System.getInt(cr, Settings.System.LOCK_TO_APP_ENABLED, 0) != 0; + } + + /** + * @return whether there is currently a locked task (ie. in screen pinning). + */ + public boolean isLockToAppActive() { + try { + return ActivityTaskManager.getService().getLockTaskModeState() != LOCK_TASK_MODE_NONE; + } catch (RemoteException e) { + return false; + } + } + + /** + * @return whether lock task mode is active in kiosk-mode (not screen pinning). + */ + public boolean isLockTaskKioskModeActive() { + try { + return ActivityTaskManager.getService().getLockTaskModeState() == LOCK_TASK_MODE_LOCKED; + } catch (RemoteException e) { + return false; + } + } + + /** + * Shows a voice session identified by {@code token} + * @return true if the session was shown, false otherwise + */ + public boolean showVoiceSession(IBinder token, Bundle args, int flags) { + IVoiceInteractionManagerService service = IVoiceInteractionManagerService.Stub.asInterface( + ServiceManager.getService(Context.VOICE_INTERACTION_MANAGER_SERVICE)); + if (service == null) { + return false; + } + args.putLong(INVOCATION_TIME_MS_KEY, SystemClock.elapsedRealtime()); + + try { + return service.showSessionFromSession(token, args, flags); + } catch (RemoteException e) { + return false; + } + } + + /** + * Returns true if the system supports freeform multi-window. + */ + public boolean supportsFreeformMultiWindow(Context context) { + final boolean freeformDevOption = Settings.Global.getInt(context.getContentResolver(), + Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0; + return ActivityTaskManager.supportsMultiWindow(context) + && (context.getPackageManager().hasSystemFeature( + PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT) + || freeformDevOption); + } + + /** + * Returns true if the running task represents the home task + */ + public static boolean isHomeTask(RunningTaskInfo info) { + return info.configuration.windowConfiguration.getActivityType() + == WindowConfiguration.ACTIVITY_TYPE_HOME; + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/ActivityOptionsCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/ActivityOptionsCompat.java new file mode 100644 index 0000000000..345a649a03 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/ActivityOptionsCompat.java @@ -0,0 +1,89 @@ +/* + * 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.system; + +import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT; +import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT; +import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM; +import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY; +import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY; + +import android.app.ActivityOptions; +import android.content.Context; +import android.os.Handler; + +/** + * Wrapper around internal ActivityOptions creation. + */ +public abstract class ActivityOptionsCompat { + + /** + * @return ActivityOptions for starting a task in split screen as the primary window. + */ + public static ActivityOptions makeSplitScreenOptions(boolean dockTopLeft) { + return makeSplitScreenOptions(dockTopLeft, true); + } + + /** + * @return ActivityOptions for starting a task in split screen. + */ + public static ActivityOptions makeSplitScreenOptions(boolean dockTopLeft, boolean isPrimary) { + final ActivityOptions options = ActivityOptions.makeBasic(); + options.setLaunchWindowingMode(isPrimary + ? WINDOWING_MODE_SPLIT_SCREEN_PRIMARY + : WINDOWING_MODE_SPLIT_SCREEN_SECONDARY); + options.setSplitScreenCreateMode(dockTopLeft + ? SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT + : SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT); + return options; + } + + /** + * @return ActivityOptions for starting a task in freeform. + */ + public static ActivityOptions makeFreeformOptions() { + final ActivityOptions options = ActivityOptions.makeBasic(); + options.setLaunchWindowingMode(WINDOWING_MODE_FREEFORM); + return options; + } + + public static ActivityOptions makeRemoteAnimation( + RemoteAnimationAdapterCompat remoteAnimationAdapter) { + return ActivityOptions.makeRemoteAnimation(remoteAnimationAdapter.getWrapped()); + } + + public static ActivityOptions makeCustomAnimation(Context context, int enterResId, + int exitResId, final Runnable callback, final Handler callbackHandler) { + return ActivityOptions.makeCustomAnimation(context, enterResId, exitResId, callbackHandler, + new ActivityOptions.OnAnimationStartedListener() { + @Override + public void onAnimationStarted() { + if (callback != null) { + callbackHandler.post(callback); + } + } + }, null /* finishedListener */); + } + + /** + * Sets the flag to freeze the recents task list reordering as a part of launching the activity. + */ + public static ActivityOptions setFreezeRecentTasksList(ActivityOptions opts) { + opts.setFreezeRecentTasksReordering(); + return opts; + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/AssistDataReceiver.java b/SystemUIShared/src/com/android/systemui/shared/system/AssistDataReceiver.java new file mode 100644 index 0000000000..7cd6c512b6 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/AssistDataReceiver.java @@ -0,0 +1,28 @@ +/* + * 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.system; + +import android.graphics.Bitmap; +import android.os.Bundle; + +/** + * Abstract class for assist data receivers. + */ +public abstract class AssistDataReceiver { + public void onHandleAssistData(Bundle resultData) {} + public void onHandleAssistScreenshot(Bitmap screenshot) {} +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/BackgroundExecutor.java b/SystemUIShared/src/com/android/systemui/shared/system/BackgroundExecutor.java new file mode 100644 index 0000000000..0bd89a78cf --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/BackgroundExecutor.java @@ -0,0 +1,61 @@ +/* + * 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.system; + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +/** + * Offloads work from other threads by running it in a background thread. + */ +public class BackgroundExecutor { + + private static final BackgroundExecutor sInstance = new BackgroundExecutor(); + + private final ExecutorService mExecutorService = Executors.newFixedThreadPool(2); + + /** + * @return the static instance of the background executor. + */ + public static BackgroundExecutor get() { + return sInstance; + } + + /** + * Runs the given {@param callable} on one of the background executor threads. + */ + public Future submit(Callable callable) { + return mExecutorService.submit(callable); + } + + /** + * Runs the given {@param runnable} on one of the background executor threads. + */ + public Future submit(Runnable runnable) { + return mExecutorService.submit(runnable); + } + + /** + * Runs the given {@param runnable} on one of the background executor threads. Return + * {@param result} when the future is resolved. + */ + public Future submit(Runnable runnable, T result) { + return mExecutorService.submit(runnable, result); + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/BlurUtils.java b/SystemUIShared/src/com/android/systemui/shared/system/BlurUtils.java new file mode 100644 index 0000000000..9f26d851f7 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/BlurUtils.java @@ -0,0 +1,37 @@ +/* + * 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.system; + +import android.app.ActivityManager; +import android.os.SystemProperties; + +public abstract class BlurUtils { + + private static boolean mBlurSupportedSysProp = SystemProperties + .getBoolean("ro.surface_flinger.supports_background_blur", false); + private static boolean mBlurDisabledSysProp = SystemProperties + .getBoolean("persist.sys.sf.disable_blurs", false); + + /** + * If this device can render blurs. + * + * @return {@code true} when supported. + */ + public static boolean supportsBlursOnWindows() { + return mBlurSupportedSysProp && !mBlurDisabledSysProp && ActivityManager.isHighEndGfx(); + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/ChoreographerCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/ChoreographerCompat.java new file mode 100644 index 0000000000..76b447e3fa --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/ChoreographerCompat.java @@ -0,0 +1,37 @@ +/* + * 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.system; + +import static android.view.Choreographer.CALLBACK_INPUT; + +import android.view.Choreographer; + +/** + * Wraps the internal choreographer. + */ +public class ChoreographerCompat { + + /** + * Posts an input callback to the choreographer. + */ + public static void postInputFrame(Choreographer choreographer, Runnable runnable) { + choreographer.postCallback(CALLBACK_INPUT, runnable, null); + } + + public static Choreographer getSfInstance() { + return Choreographer.getSfInstance(); + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/ConfigurationCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/ConfigurationCompat.java new file mode 100644 index 0000000000..d1c77a6e7c --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/ConfigurationCompat.java @@ -0,0 +1,28 @@ +/* + * 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.system; + +import android.content.res.Configuration; + +/** + * Wraps the Configuration to access the window configuration. + */ +public class ConfigurationCompat { + + public static int getWindowConfigurationRotation(Configuration c) { + return c.windowConfiguration.getRotation(); + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/ContextCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/ContextCompat.java new file mode 100644 index 0000000000..51fcb0a841 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/ContextCompat.java @@ -0,0 +1,34 @@ +/* + * 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.system; + +import android.content.Context; + +/** + * Wraps a context to expose some methods for launcher to call. + */ +public class ContextCompat { + private final Context mWrapped; + + public ContextCompat(Context context) { + mWrapped = context; + } + + public int getUserId() { + return mWrapped.getUserId(); + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/DevicePolicyManagerWrapper.java b/SystemUIShared/src/com/android/systemui/shared/system/DevicePolicyManagerWrapper.java new file mode 100644 index 0000000000..c6722aece9 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/DevicePolicyManagerWrapper.java @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2019 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.system; + +import android.app.AppGlobals; +import android.app.admin.DevicePolicyManager; + +/** + * Wrapper for {@link DevicePolicyManager}. + */ +public class DevicePolicyManagerWrapper { + private static final DevicePolicyManagerWrapper sInstance = new DevicePolicyManagerWrapper(); + + private static final DevicePolicyManager sDevicePolicyManager = + AppGlobals.getInitialApplication().getSystemService(DevicePolicyManager.class); + + private DevicePolicyManagerWrapper() { } + + public static DevicePolicyManagerWrapper getInstance() { + return sInstance; + } + + /** + * Returns whether the given package is allowed to run in Lock Task mode. + */ + public boolean isLockTaskPermitted(String pkg) { + return sDevicePolicyManager.isLockTaskPermitted(pkg); + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/DockedStackListenerCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/DockedStackListenerCompat.java new file mode 100644 index 0000000000..bb319e625b --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/DockedStackListenerCompat.java @@ -0,0 +1,63 @@ +/* + * 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.system; + +import android.view.IDockedStackListener; + +/** + * An interface to track docked stack changes. + */ +public class DockedStackListenerCompat { + + IDockedStackListener.Stub mListener = new IDockedStackListener.Stub() { + @Override + public void onDividerVisibilityChanged(boolean visible) {} + + @Override + public void onDockedStackExistsChanged(boolean exists) { + DockedStackListenerCompat.this.onDockedStackExistsChanged(exists); + } + + @Override + public void onDockedStackMinimizedChanged(boolean minimized, long animDuration, + boolean isHomeStackResizable) { + DockedStackListenerCompat.this.onDockedStackMinimizedChanged(minimized, animDuration, + isHomeStackResizable); + } + + @Override + public void onAdjustedForImeChanged(boolean adjustedForIme, long animDuration) {} + + @Override + public void onDockSideChanged(final int newDockSide) { + DockedStackListenerCompat.this.onDockSideChanged(newDockSide); + } + }; + + public void onDockedStackExistsChanged(boolean exists) { + // To be overridden + } + + public void onDockedStackMinimizedChanged(boolean minimized, long animDuration, + boolean isHomeStackResizable) { + // To be overridden + } + + public void onDockSideChanged(final int newDockSide) { + // To be overridden + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/InputChannelCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/InputChannelCompat.java new file mode 100644 index 0000000000..2b1fce8a4c --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/InputChannelCompat.java @@ -0,0 +1,124 @@ +/** + * Copyright (C) 2019 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.system; + +import android.os.Bundle; +import android.os.Looper; +import android.view.BatchedInputEventReceiver; +import android.view.Choreographer; +import android.view.InputChannel; +import android.view.InputEvent; +import android.view.InputEventSender; +import android.view.MotionEvent; + +/** + * @see android.view.InputChannel + */ +public class InputChannelCompat { + + /** + * Callback for receiving event callbacks + */ + public interface InputEventListener { + /** + * @param ev event to be handled + */ + void onInputEvent(InputEvent ev); + } + + /** + * Creates a dispatcher from the extras received as part on onInitialize + */ + public static InputEventReceiver fromBundle(Bundle params, String key, + Looper looper, Choreographer choreographer, InputEventListener listener) { + + InputChannel channel = params.getParcelable(key); + return new InputEventReceiver(channel, looper, choreographer, listener); + } + + /** + * Version of addBatch method which preserves time accuracy in nanoseconds instead of + * converting the time to milliseconds. + * @param src old MotionEvent where the target should be appended + * @param target new MotionEvent which should be added to the src + * @return true if the merge was successful + * + * @see MotionEvent#addBatch(MotionEvent) + */ + public static boolean mergeMotionEvent(MotionEvent src, MotionEvent target) { + return target.addBatch(src); + } + + /** + * @see BatchedInputEventReceiver + */ + public static class InputEventReceiver { + + private final BatchedInputEventReceiver mReceiver; + private final InputChannel mInputChannel; + + public InputEventReceiver(InputChannel inputChannel, Looper looper, + Choreographer choreographer, final InputEventListener listener) { + mInputChannel = inputChannel; + mReceiver = new BatchedInputEventReceiver(inputChannel, looper, choreographer) { + + @Override + public void onInputEvent(InputEvent event) { + listener.onInputEvent(event); + finishInputEvent(event, true /* handled */); + } + }; + } + + /** + * @see BatchedInputEventReceiver#dispose() + */ + public void dispose() { + mReceiver.dispose(); + mInputChannel.dispose(); + } + } + + /** + * @see InputEventSender + */ + public static class InputEventDispatcher { + + private final InputChannel mInputChannel; + private final InputEventSender mSender; + + public InputEventDispatcher(InputChannel inputChannel, Looper looper) { + mInputChannel = inputChannel; + mSender = new InputEventSender(inputChannel, looper) { }; + } + + /** + * @see InputEventSender#sendInputEvent(int, InputEvent) + */ + public void dispatch(InputEvent ev) { + mSender.sendInputEvent(ev.getSequenceNumber(), ev); + } + + /** + * @see InputEventSender#dispose() + */ + public void dispose() { + mSender.dispose(); + mInputChannel.dispose(); + } + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/InputConsumerController.java b/SystemUIShared/src/com/android/systemui/shared/system/InputConsumerController.java new file mode 100644 index 0000000000..27e4c85e1e --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/InputConsumerController.java @@ -0,0 +1,196 @@ +/* + * 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.system; + +import static android.view.Display.DEFAULT_DISPLAY; +import static android.view.WindowManager.INPUT_CONSUMER_PIP; +import static android.view.WindowManager.INPUT_CONSUMER_RECENTS_ANIMATION; + +import android.os.Binder; +import android.os.IBinder; +import android.os.Looper; +import android.os.RemoteException; +import android.util.Log; +import android.view.BatchedInputEventReceiver; +import android.view.Choreographer; +import android.view.IWindowManager; +import android.view.InputChannel; +import android.view.InputEvent; +import android.view.WindowManagerGlobal; + +import java.io.PrintWriter; + +/** + * Manages the input consumer that allows the SystemUI to directly receive input. + */ +public class InputConsumerController { + + private static final String TAG = InputConsumerController.class.getSimpleName(); + + /** + * Listener interface for callers to subscribe to input events. + */ + public interface InputListener { + /** Handles any input event. */ + boolean onInputEvent(InputEvent ev); + } + + /** + * Listener interface for callers to learn when this class is registered or unregistered with + * window manager + */ + public interface RegistrationListener { + void onRegistrationChanged(boolean isRegistered); + } + + /** + * Input handler used for the input consumer. Input events are batched and consumed with the + * SurfaceFlinger vsync. + */ + private final class InputEventReceiver extends BatchedInputEventReceiver { + + InputEventReceiver(InputChannel inputChannel, Looper looper, + Choreographer choreographer) { + super(inputChannel, looper, choreographer); + } + + @Override + public void onInputEvent(InputEvent event) { + boolean handled = true; + try { + if (mListener != null) { + handled = mListener.onInputEvent(event); + } + } finally { + finishInputEvent(event, handled); + } + } + } + + private final IWindowManager mWindowManager; + private final IBinder mToken; + private final String mName; + + private InputEventReceiver mInputEventReceiver; + private InputListener mListener; + private RegistrationListener mRegistrationListener; + + /** + * @param name the name corresponding to the input consumer that is defined in the system. + */ + public InputConsumerController(IWindowManager windowManager, String name) { + mWindowManager = windowManager; + mToken = new Binder(); + mName = name; + } + + /** + * @return A controller for the pip input consumer. + */ + public static InputConsumerController getPipInputConsumer() { + return new InputConsumerController(WindowManagerGlobal.getWindowManagerService(), + INPUT_CONSUMER_PIP); + } + + /** + * @return A controller for the recents animation input consumer. + */ + public static InputConsumerController getRecentsAnimationInputConsumer() { + return new InputConsumerController(WindowManagerGlobal.getWindowManagerService(), + INPUT_CONSUMER_RECENTS_ANIMATION); + } + + /** + * Sets the input listener. + */ + public void setInputListener(InputListener listener) { + mListener = listener; + } + + /** + * Sets the registration listener. + */ + public void setRegistrationListener(RegistrationListener listener) { + mRegistrationListener = listener; + if (mRegistrationListener != null) { + mRegistrationListener.onRegistrationChanged(mInputEventReceiver != null); + } + } + + /** + * Check if the InputConsumer is currently registered with WindowManager + * + * @return {@code true} if registered, {@code false} if not. + */ + public boolean isRegistered() { + return mInputEventReceiver != null; + } + + /** + * Registers the input consumer. + */ + public void registerInputConsumer() { + registerInputConsumer(false); + } + + /** + * Registers the input consumer. + * @param withSfVsync the flag set using sf vsync signal or no + */ + public void registerInputConsumer(boolean withSfVsync) { + if (mInputEventReceiver == null) { + final InputChannel inputChannel = new InputChannel(); + try { + // TODO(b/113087003): Support Picture-in-picture in multi-display. + mWindowManager.destroyInputConsumer(mName, DEFAULT_DISPLAY); + mWindowManager.createInputConsumer(mToken, mName, DEFAULT_DISPLAY, inputChannel); + } catch (RemoteException e) { + Log.e(TAG, "Failed to create input consumer", e); + } + mInputEventReceiver = new InputEventReceiver(inputChannel, Looper.myLooper(), + withSfVsync ? Choreographer.getSfInstance() : Choreographer.getInstance()); + if (mRegistrationListener != null) { + mRegistrationListener.onRegistrationChanged(true /* isRegistered */); + } + } + } + + /** + * Unregisters the input consumer. + */ + public void unregisterInputConsumer() { + if (mInputEventReceiver != null) { + try { + // TODO(b/113087003): Support Picture-in-picture in multi-display. + mWindowManager.destroyInputConsumer(mName, DEFAULT_DISPLAY); + } catch (RemoteException e) { + Log.e(TAG, "Failed to destroy input consumer", e); + } + mInputEventReceiver.dispose(); + mInputEventReceiver = null; + if (mRegistrationListener != null) { + mRegistrationListener.onRegistrationChanged(false /* isRegistered */); + } + } + } + + public void dump(PrintWriter pw, String prefix) { + final String innerPrefix = prefix + " "; + pw.println(prefix + TAG); + pw.println(innerPrefix + "registered=" + (mInputEventReceiver != null)); + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/InputMonitorCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/InputMonitorCompat.java new file mode 100644 index 0000000000..ddca7234c9 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/InputMonitorCompat.java @@ -0,0 +1,66 @@ +/** + * Copyright (C) 2019 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.system; + +import android.os.Bundle; +import android.os.Looper; +import android.view.Choreographer; +import android.view.InputMonitor; + +import com.android.systemui.shared.system.InputChannelCompat.InputEventListener; +import com.android.systemui.shared.system.InputChannelCompat.InputEventReceiver; + +/** + * @see android.view.InputMonitor + */ +public class InputMonitorCompat { + + private final InputMonitor mInputMonitor; + + private InputMonitorCompat(InputMonitor monitor) { + mInputMonitor = monitor; + } + + /** + * @see InputMonitor#pilferPointers() + */ + public void pilferPointers() { + mInputMonitor.pilferPointers(); + } + + /** + * @see InputMonitor#dispose() + */ + public void dispose() { + mInputMonitor.dispose(); + } + + /** + * @see InputMonitor#getInputChannel() + */ + public InputEventReceiver getInputReceiver(Looper looper, Choreographer choreographer, + InputEventListener listener) { + return new InputEventReceiver(mInputMonitor.getInputChannel(), looper, choreographer, + listener); + } + + /** + * Gets the input monitor stored in a bundle + */ + public static InputMonitorCompat fromBundle(Bundle bundle, String key) { + return new InputMonitorCompat((InputMonitor) bundle.getParcelable(key)); + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/KeyguardManagerCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/KeyguardManagerCompat.java new file mode 100644 index 0000000000..c42e7e3fd2 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/KeyguardManagerCompat.java @@ -0,0 +1,32 @@ +/* + * 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.system; + +import android.app.KeyguardManager; +import android.content.Context; + +public class KeyguardManagerCompat { + private final KeyguardManager mKeyguardManager; + + public KeyguardManagerCompat(Context context) { + mKeyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); + } + + public boolean isDeviceLocked(int userId) { + return mKeyguardManager.isDeviceLocked(userId); + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/LatencyTrackerCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/LatencyTrackerCompat.java new file mode 100644 index 0000000000..0d5933e5f5 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/LatencyTrackerCompat.java @@ -0,0 +1,34 @@ +/* + * 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.system; + +import android.content.Context; + +import com.android.internal.util.LatencyTracker; + +/** + * @see LatencyTracker + */ +public class LatencyTrackerCompat { + public static boolean isEnabled(Context context) { + return LatencyTracker.isEnabled(context); + } + + public static void logToggleRecents(int duration) { + LatencyTracker.logAction(LatencyTracker.ACTION_TOGGLE_RECENTS, duration); + } +} \ No newline at end of file diff --git a/SystemUIShared/src/com/android/systemui/shared/system/LauncherEventUtil.java b/SystemUIShared/src/com/android/systemui/shared/system/LauncherEventUtil.java new file mode 100644 index 0000000000..eed9580e22 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/LauncherEventUtil.java @@ -0,0 +1,29 @@ +/* + * 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.system; + +public class LauncherEventUtil { + + // Constants for the Action + public static final int VISIBLE = 0; + public static final int DISMISS = 1; + + // Constants for the Target (View) + public static final int RECENTS_SWIPE_UP_ONBOARDING_TIP = 0; + public static final int RECENTS_QUICK_SCRUB_ONBOARDING_TIP = 1; + +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/MetricsLoggerCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/MetricsLoggerCompat.java new file mode 100644 index 0000000000..952c8aee24 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/MetricsLoggerCompat.java @@ -0,0 +1,50 @@ +/* + * 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.system; + +import com.android.internal.logging.MetricsLogger; +import com.android.internal.logging.nano.MetricsProto.MetricsEvent; + +public class MetricsLoggerCompat { + + private final MetricsLogger mMetricsLogger; + public static final int OVERVIEW_ACTIVITY = MetricsEvent.OVERVIEW_ACTIVITY; + + public MetricsLoggerCompat() { + mMetricsLogger = new MetricsLogger(); + } + + public void action(int category) { + mMetricsLogger.action(category); + } + + public void action(int category, int value) { + mMetricsLogger.action(category, value); + } + + public void visible(int category) { + mMetricsLogger.visible(category); + } + + public void hidden(int category) { + mMetricsLogger.hidden(category); + } + + public void visibility(int category, boolean visible) { + mMetricsLogger.visibility(category, visible); + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/PackageManagerWrapper.java b/SystemUIShared/src/com/android/systemui/shared/system/PackageManagerWrapper.java new file mode 100644 index 0000000000..443c1e1280 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/PackageManagerWrapper.java @@ -0,0 +1,87 @@ +/* + * Copyright (C) 2015 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.system; + +import android.app.AppGlobals; +import android.content.ComponentName; +import android.content.Intent; +import android.content.pm.ActivityInfo; +import android.content.pm.IPackageManager; +import android.content.pm.PackageManager; +import android.content.pm.PackageManager.ResolveInfoFlags; +import android.content.pm.ResolveInfo; +import android.os.RemoteException; +import android.os.UserHandle; + +import java.util.List; + +public class PackageManagerWrapper { + + private static final PackageManagerWrapper sInstance = new PackageManagerWrapper(); + + private static final IPackageManager mIPackageManager = AppGlobals.getPackageManager(); + + public static final String ACTION_PREFERRED_ACTIVITY_CHANGED = + Intent.ACTION_PREFERRED_ACTIVITY_CHANGED; + + public static PackageManagerWrapper getInstance() { + return sInstance; + } + + private PackageManagerWrapper() {} + + /** + * @return the activity info for a given {@param componentName} and {@param userId}. + */ + public ActivityInfo getActivityInfo(ComponentName componentName, int userId) { + try { + return mIPackageManager.getActivityInfo(componentName, PackageManager.GET_META_DATA, + userId); + } catch (RemoteException e) { + e.printStackTrace(); + return null; + } + } + + /** + * Report the set of 'Home' activity candidates, plus (if any) which of them + * is the current "always use this one" setting. + */ + public ComponentName getHomeActivities(List allHomeCandidates) { + try { + return mIPackageManager.getHomeActivities(allHomeCandidates); + } catch (RemoteException e) { + e.printStackTrace(); + return null; + } + } + + /** + * Determine the best Activity to perform for a given Intent. + */ + public ResolveInfo resolveActivity(Intent intent, @ResolveInfoFlags int flags) { + final String resolvedType = + intent.resolveTypeIfNeeded(AppGlobals.getInitialApplication().getContentResolver()); + try { + return mIPackageManager.resolveIntent( + intent, resolvedType, flags, UserHandle.getCallingUserId()); + } catch (RemoteException e) { + e.printStackTrace(); + return null; + } + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/PinnedStackListenerForwarder.java b/SystemUIShared/src/com/android/systemui/shared/system/PinnedStackListenerForwarder.java new file mode 100644 index 0000000000..4794847d8b --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/PinnedStackListenerForwarder.java @@ -0,0 +1,124 @@ +/* + * Copyright (C) 2019 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.system; + +import android.content.ComponentName; +import android.content.pm.ParceledListSlice; +import android.view.DisplayInfo; +import android.view.IPinnedStackController; +import android.view.IPinnedStackListener; + +import java.util.ArrayList; +import java.util.List; + +/** + * PinnedStackListener that simply forwards all calls to each listener added via + * {@link #addListener}. This is necessary since calling + * {@link com.android.server.wm.WindowManagerService#registerPinnedStackListener} replaces any + * previously set listener. + */ +public class PinnedStackListenerForwarder extends IPinnedStackListener.Stub { + private List mListeners = new ArrayList<>(); + + /** Adds a listener to receive updates from the WindowManagerService. */ + public void addListener(PinnedStackListener listener) { + mListeners.add(listener); + } + + /** Removes a listener so it will no longer receive updates from the WindowManagerService. */ + public void removeListener(PinnedStackListener listener) { + mListeners.remove(listener); + } + + @Override + public void onListenerRegistered(IPinnedStackController controller) { + for (PinnedStackListener listener : mListeners) { + listener.onListenerRegistered(controller); + } + } + + @Override + public void onMovementBoundsChanged(boolean fromImeAdjustment) { + for (PinnedStackListener listener : mListeners) { + listener.onMovementBoundsChanged(fromImeAdjustment); + } + } + + @Override + public void onImeVisibilityChanged(boolean imeVisible, int imeHeight) { + for (PinnedStackListener listener : mListeners) { + listener.onImeVisibilityChanged(imeVisible, imeHeight); + } + } + + @Override + public void onActionsChanged(ParceledListSlice actions) { + for (PinnedStackListener listener : mListeners) { + listener.onActionsChanged(actions); + } + } + + @Override + public void onActivityHidden(ComponentName componentName) { + for (PinnedStackListener listener : mListeners) { + listener.onActivityHidden(componentName); + } + } + + @Override + public void onDisplayInfoChanged(DisplayInfo displayInfo) { + for (PinnedStackListener listener : mListeners) { + listener.onDisplayInfoChanged(displayInfo); + } + } + + @Override + public void onConfigurationChanged() { + for (PinnedStackListener listener : mListeners) { + listener.onConfigurationChanged(); + } + } + + @Override + public void onAspectRatioChanged(float aspectRatio) { + for (PinnedStackListener listener : mListeners) { + listener.onAspectRatioChanged(aspectRatio); + } + } + + /** + * A counterpart of {@link IPinnedStackListener} with empty implementations. + * Subclasses can ignore those methods they do not intend to take action upon. + */ + public static class PinnedStackListener { + public void onListenerRegistered(IPinnedStackController controller) {} + + public void onMovementBoundsChanged(boolean fromImeAdjustment) {} + + public void onImeVisibilityChanged(boolean imeVisible, int imeHeight) {} + + public void onActionsChanged(ParceledListSlice actions) {} + + public void onActivityHidden(ComponentName componentName) {} + + public void onDisplayInfoChanged(DisplayInfo displayInfo) {} + + public void onConfigurationChanged() {} + + public void onAspectRatioChanged(float aspectRatio) {} + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/QuickStepContract.java b/SystemUIShared/src/com/android/systemui/shared/system/QuickStepContract.java new file mode 100644 index 0000000000..5a78c90310 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/QuickStepContract.java @@ -0,0 +1,247 @@ +/* + * Copyright (C) 2019 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.system; + +import static android.view.WindowManagerPolicyConstants.NAV_BAR_MODE_2BUTTON; +import static android.view.WindowManagerPolicyConstants.NAV_BAR_MODE_3BUTTON; +import static android.view.WindowManagerPolicyConstants.NAV_BAR_MODE_GESTURAL; + +import android.annotation.IntDef; +import android.content.Context; +import android.content.res.Resources; +import android.view.ViewConfiguration; +import android.view.WindowManagerPolicyConstants; + +import com.android.internal.policy.ScreenDecorationsUtils; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.util.StringJoiner; + +/** + * Various shared constants between Launcher and SysUI as part of quickstep + */ +public class QuickStepContract { + + public static final String KEY_EXTRA_SYSUI_PROXY = "extra_sysui_proxy"; + public static final String KEY_EXTRA_INPUT_MONITOR = "extra_input_monitor"; + public static final String KEY_EXTRA_WINDOW_CORNER_RADIUS = "extra_window_corner_radius"; + public static final String KEY_EXTRA_SUPPORTS_WINDOW_CORNERS = "extra_supports_window_corners"; + + public static final String NAV_BAR_MODE_2BUTTON_OVERLAY = + WindowManagerPolicyConstants.NAV_BAR_MODE_2BUTTON_OVERLAY; + public static final String NAV_BAR_MODE_3BUTTON_OVERLAY = + WindowManagerPolicyConstants.NAV_BAR_MODE_3BUTTON_OVERLAY; + public static final String NAV_BAR_MODE_GESTURAL_OVERLAY = + WindowManagerPolicyConstants.NAV_BAR_MODE_GESTURAL_OVERLAY; + + // Overview is disabled, either because the device is in lock task mode, or because the device + // policy has disabled the feature + public static final int SYSUI_STATE_SCREEN_PINNING = 1 << 0; + // The navigation bar is hidden due to immersive mode + public static final int SYSUI_STATE_NAV_BAR_HIDDEN = 1 << 1; + // The notification panel is expanded and interactive (either locked or unlocked), and the + // quick settings is not expanded + public static final int SYSUI_STATE_NOTIFICATION_PANEL_EXPANDED = 1 << 2; + // The keyguard bouncer is showing + public static final int SYSUI_STATE_BOUNCER_SHOWING = 1 << 3; + // The navigation bar a11y button should be shown + public static final int SYSUI_STATE_A11Y_BUTTON_CLICKABLE = 1 << 4; + // The navigation bar a11y button shortcut is available + public static final int SYSUI_STATE_A11Y_BUTTON_LONG_CLICKABLE = 1 << 5; + // The keyguard is showing and not occluded + public static final int SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING = 1 << 6; + // The recents feature is disabled (either by SUW/SysUI/device policy) + public static final int SYSUI_STATE_OVERVIEW_DISABLED = 1 << 7; + // The home feature is disabled (either by SUW/SysUI/device policy) + public static final int SYSUI_STATE_HOME_DISABLED = 1 << 8; + // The keyguard is showing, but occluded + public static final int SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING_OCCLUDED = 1 << 9; + // The search feature is disabled (either by SUW/SysUI/device policy) + public static final int SYSUI_STATE_SEARCH_DISABLED = 1 << 10; + // The notification panel is expanded and interactive (either locked or unlocked), and quick + // settings is expanded. + public static final int SYSUI_STATE_QUICK_SETTINGS_EXPANDED = 1 << 11; + // Winscope tracing is enabled + public static final int SYSUI_STATE_TRACING_ENABLED = 1 << 12; + // The Assistant gesture should be constrained. It is up to the launcher implementation to + // decide how to constrain it + public static final int SYSUI_STATE_ASSIST_GESTURE_CONSTRAINED = 1 << 13; + // The bubble stack is expanded. This means that the home gesture should be ignored, since a + // swipe up is an attempt to close the bubble stack, but that the back gesture should remain + // enabled (since it's used to navigate back within the bubbled app, or to collapse the bubble + // stack. + public static final int SYSUI_STATE_BUBBLES_EXPANDED = 1 << 14; + // The global actions dialog is showing + public static final int SYSUI_STATE_GLOBAL_ACTIONS_SHOWING = 1 << 15; + + @Retention(RetentionPolicy.SOURCE) + @IntDef({SYSUI_STATE_SCREEN_PINNING, + SYSUI_STATE_NAV_BAR_HIDDEN, + SYSUI_STATE_NOTIFICATION_PANEL_EXPANDED, + SYSUI_STATE_QUICK_SETTINGS_EXPANDED, + SYSUI_STATE_BOUNCER_SHOWING, + SYSUI_STATE_A11Y_BUTTON_CLICKABLE, + SYSUI_STATE_A11Y_BUTTON_LONG_CLICKABLE, + SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING, + SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING_OCCLUDED, + SYSUI_STATE_OVERVIEW_DISABLED, + SYSUI_STATE_HOME_DISABLED, + SYSUI_STATE_SEARCH_DISABLED, + SYSUI_STATE_TRACING_ENABLED, + SYSUI_STATE_ASSIST_GESTURE_CONSTRAINED, + SYSUI_STATE_BUBBLES_EXPANDED, + SYSUI_STATE_GLOBAL_ACTIONS_SHOWING + }) + public @interface SystemUiStateFlags {} + + public static String getSystemUiStateString(int flags) { + StringJoiner str = new StringJoiner("|"); + str.add((flags & SYSUI_STATE_SCREEN_PINNING) != 0 ? "screen_pinned" : ""); + str.add((flags & SYSUI_STATE_OVERVIEW_DISABLED) != 0 ? "overview_disabled" : ""); + str.add((flags & SYSUI_STATE_HOME_DISABLED) != 0 ? "home_disabled" : ""); + str.add((flags & SYSUI_STATE_SEARCH_DISABLED) != 0 ? "search_disabled" : ""); + str.add((flags & SYSUI_STATE_NAV_BAR_HIDDEN) != 0 ? "navbar_hidden" : ""); + str.add((flags & SYSUI_STATE_NOTIFICATION_PANEL_EXPANDED) != 0 ? "notif_visible" : ""); + str.add((flags & SYSUI_STATE_QUICK_SETTINGS_EXPANDED) != 0 ? "qs_visible" : ""); + str.add((flags & SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING) != 0 ? "keygrd_visible" : ""); + str.add((flags & SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING_OCCLUDED) != 0 + ? "keygrd_occluded" : ""); + str.add((flags & SYSUI_STATE_BOUNCER_SHOWING) != 0 ? "bouncer_visible" : ""); + str.add((flags & SYSUI_STATE_GLOBAL_ACTIONS_SHOWING) != 0 ? "global_actions" : ""); + str.add((flags & SYSUI_STATE_A11Y_BUTTON_CLICKABLE) != 0 ? "a11y_click" : ""); + str.add((flags & SYSUI_STATE_A11Y_BUTTON_LONG_CLICKABLE) != 0 ? "a11y_long_click" : ""); + str.add((flags & SYSUI_STATE_TRACING_ENABLED) != 0 ? "tracing" : ""); + str.add((flags & SYSUI_STATE_ASSIST_GESTURE_CONSTRAINED) != 0 + ? "asst_gesture_constrain" : ""); + str.add((flags & SYSUI_STATE_BUBBLES_EXPANDED) != 0 ? "bubbles_expanded" : ""); + return str.toString(); + } + + /** + * Ratio of quickstep touch slop (when system takes over the touch) to view touch slop + */ + public static final float QUICKSTEP_TOUCH_SLOP_RATIO = 3; + + /** + * Touch slop for quickstep gesture + */ + public static final float getQuickStepTouchSlopPx(Context context) { + return QUICKSTEP_TOUCH_SLOP_RATIO * ViewConfiguration.get(context).getScaledTouchSlop(); + } + + /** + * Touch slopes and thresholds for quick step operations. Drag slop is the point where the + * home button press/long press over are ignored and will start to drag when exceeded and the + * touch slop is when the respected operation will occur when exceeded. Touch slop must be + * larger than the drag slop. + */ + public static int getQuickStepDragSlopPx() { + return convertDpToPixel(10); + } + + public static int getQuickStepTouchSlopPx() { + return convertDpToPixel(24); + } + + public static int getQuickScrubTouchSlopPx() { + return convertDpToPixel(24); + } + + private static int convertDpToPixel(float dp) { + return (int) (dp * Resources.getSystem().getDisplayMetrics().density); + } + + /** + * Returns whether the specified sysui state is such that the assistant gesture should be + * disabled. + */ + public static boolean isAssistantGestureDisabled(int sysuiStateFlags) { + // Disable when in quick settings, screen pinning, immersive, the bouncer is showing, + // or search is disabled + int disableFlags = SYSUI_STATE_SCREEN_PINNING + | SYSUI_STATE_NAV_BAR_HIDDEN + | SYSUI_STATE_BOUNCER_SHOWING + | SYSUI_STATE_SEARCH_DISABLED + | SYSUI_STATE_QUICK_SETTINGS_EXPANDED; + if ((sysuiStateFlags & disableFlags) != 0) { + return true; + } + + // Disable when notifications are showing (only if unlocked) + if ((sysuiStateFlags & SYSUI_STATE_NOTIFICATION_PANEL_EXPANDED) != 0 + && (sysuiStateFlags & SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING) == 0) { + return true; + } + + return false; + } + + /** + * Returns whether the specified sysui state is such that the back gesture should be + * disabled. + */ + public static boolean isBackGestureDisabled(int sysuiStateFlags) { + // Always allow when the bouncer/global actions is showing (even on top of the keyguard) + if ((sysuiStateFlags & SYSUI_STATE_BOUNCER_SHOWING) != 0 + || (sysuiStateFlags & SYSUI_STATE_GLOBAL_ACTIONS_SHOWING) != 0) { + return false; + } + // Disable when in immersive, or the notifications are interactive + int disableFlags = SYSUI_STATE_NAV_BAR_HIDDEN + | SYSUI_STATE_NOTIFICATION_PANEL_EXPANDED + | SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING; + return (sysuiStateFlags & disableFlags) != 0; + } + + /** + * @return whether this nav bar mode is edge to edge + */ + public static boolean isGesturalMode(int mode) { + return mode == NAV_BAR_MODE_GESTURAL; + } + + /** + * @return whether this nav bar mode is swipe up + */ + public static boolean isSwipeUpMode(int mode) { + return mode == NAV_BAR_MODE_2BUTTON; + } + + /** + * @return whether this nav bar mode is 3 button + */ + public static boolean isLegacyMode(int mode) { + return mode == NAV_BAR_MODE_3BUTTON; + } + + /** + * Corner radius that should be used on windows in order to cover the display. + * These values are expressed in pixels because they should not respect display or font + * scaling, this means that we don't have to reload them on config changes. + */ + public static float getWindowCornerRadius(Resources resources) { + return ScreenDecorationsUtils.getWindowCornerRadius(resources); + } + + /** + * If live rounded corners are supported on windows. + */ + public static boolean supportsRoundedCornersOnWindows(Resources resources) { + return ScreenDecorationsUtils.supportsRoundedCornersOnWindows(resources); + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/RecentsAnimationControllerCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/RecentsAnimationControllerCompat.java new file mode 100644 index 0000000000..76513c6ff3 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/RecentsAnimationControllerCompat.java @@ -0,0 +1,124 @@ +/* + * 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.system; + +import android.app.ActivityManager.TaskSnapshot; +import android.os.RemoteException; +import android.util.Log; +import android.view.IRecentsAnimationController; + +import com.android.systemui.shared.recents.model.ThumbnailData; + +public class RecentsAnimationControllerCompat { + + private static final String TAG = RecentsAnimationControllerCompat.class.getSimpleName(); + + private IRecentsAnimationController mAnimationController; + + public RecentsAnimationControllerCompat() { } + + public RecentsAnimationControllerCompat(IRecentsAnimationController animationController) { + mAnimationController = animationController; + } + + public ThumbnailData screenshotTask(int taskId) { + try { + TaskSnapshot snapshot = mAnimationController.screenshotTask(taskId); + return snapshot != null ? new ThumbnailData(snapshot) : new ThumbnailData(); + } catch (RemoteException e) { + Log.e(TAG, "Failed to screenshot task", e); + return new ThumbnailData(); + } + } + + public void setInputConsumerEnabled(boolean enabled) { + try { + mAnimationController.setInputConsumerEnabled(enabled); + } catch (RemoteException e) { + Log.e(TAG, "Failed to set input consumer enabled state", e); + } + } + + public void setAnimationTargetsBehindSystemBars(boolean behindSystemBars) { + try { + mAnimationController.setAnimationTargetsBehindSystemBars(behindSystemBars); + } catch (RemoteException e) { + Log.e(TAG, "Failed to set whether animation targets are behind system bars", e); + } + } + + public void hideCurrentInputMethod() { + try { + mAnimationController.hideCurrentInputMethod(); + } catch (RemoteException e) { + Log.e(TAG, "Failed to set hide input method", e); + } + } + + /** + * Finish the current recents animation. + * @param toHome Going to home or back to the previous app. + * @param sendUserLeaveHint determines whether userLeaveHint will be set true to the previous + * app. + */ + public void finish(boolean toHome, boolean sendUserLeaveHint) { + try { + mAnimationController.finish(toHome, sendUserLeaveHint); + } catch (RemoteException e) { + Log.e(TAG, "Failed to finish recents animation", e); + } + } + + public void setDeferCancelUntilNextTransition(boolean defer, boolean screenshot) { + try { + mAnimationController.setDeferCancelUntilNextTransition(defer, screenshot); + } catch (RemoteException e) { + Log.e(TAG, "Failed to set deferred cancel with screenshot", e); + } + } + + public void cleanupScreenshot() { + try { + mAnimationController.cleanupScreenshot(); + } catch (RemoteException e) { + Log.e(TAG, "Failed to clean up screenshot of recents animation", e); + } + } + + /** + * @see {{@link IRecentsAnimationController#setWillFinishToHome(boolean)}}. + */ + public void setWillFinishToHome(boolean willFinishToHome) { + try { + mAnimationController.setWillFinishToHome(willFinishToHome); + } catch (RemoteException e) { + Log.e(TAG, "Failed to set overview reached state", e); + } + } + + /** + * @see IRecentsAnimationController#removeTask + */ + public boolean removeTask(int taskId) { + try { + return mAnimationController.removeTask(taskId); + } catch (RemoteException e) { + Log.e(TAG, "Failed to remove remote animation target", e); + return false; + } + } +} \ No newline at end of file diff --git a/SystemUIShared/src/com/android/systemui/shared/system/RecentsAnimationListener.java b/SystemUIShared/src/com/android/systemui/shared/system/RecentsAnimationListener.java new file mode 100644 index 0000000000..c4cd192212 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/RecentsAnimationListener.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.system; + +import android.graphics.Rect; + +import com.android.systemui.shared.recents.model.ThumbnailData; + +public interface RecentsAnimationListener { + /** + * Called when the animation into Recents can start. This call is made on the binder thread. + */ + void onAnimationStart(RecentsAnimationControllerCompat controller, + RemoteAnimationTargetCompat[] apps, RemoteAnimationTargetCompat[] wallpapers, + Rect homeContentInsets, Rect minimizedHomeBounds); + + /** + * Called when the animation into Recents was canceled. This call is made on the binder thread. + */ + void onAnimationCanceled(ThumbnailData thumbnailData); + + /** + * Called when the task of an activity that has been started while the recents animation + * was running becomes ready for control. + */ + void onTaskAppeared(RemoteAnimationTargetCompat app); +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationAdapterCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationAdapterCompat.java new file mode 100644 index 0000000000..02e509eef2 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationAdapterCompat.java @@ -0,0 +1,75 @@ +/* + * 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.system; + +import android.os.RemoteException; +import android.util.Log; +import android.view.IRemoteAnimationFinishedCallback; +import android.view.IRemoteAnimationRunner; +import android.view.RemoteAnimationAdapter; +import android.view.RemoteAnimationTarget; + +/** + * @see RemoteAnimationAdapter + */ +public class RemoteAnimationAdapterCompat { + + private final RemoteAnimationAdapter mWrapped; + + public RemoteAnimationAdapterCompat(RemoteAnimationRunnerCompat runner, long duration, + long statusBarTransitionDelay) { + mWrapped = new RemoteAnimationAdapter(wrapRemoteAnimationRunner(runner), duration, + statusBarTransitionDelay); + } + + RemoteAnimationAdapter getWrapped() { + return mWrapped; + } + + private static IRemoteAnimationRunner.Stub wrapRemoteAnimationRunner( + final RemoteAnimationRunnerCompat remoteAnimationAdapter) { + return new IRemoteAnimationRunner.Stub() { + @Override + public void onAnimationStart(RemoteAnimationTarget[] apps, + RemoteAnimationTarget[] wallpapers, + final IRemoteAnimationFinishedCallback finishedCallback) { + final RemoteAnimationTargetCompat[] appsCompat = + RemoteAnimationTargetCompat.wrap(apps); + final RemoteAnimationTargetCompat[] wallpapersCompat = + RemoteAnimationTargetCompat.wrap(wallpapers); + final Runnable animationFinishedCallback = new Runnable() { + @Override + public void run() { + try { + finishedCallback.onAnimationFinished(); + } catch (RemoteException e) { + Log.e("ActivityOptionsCompat", "Failed to call app controlled animation" + + " finished callback", e); + } + } + }; + remoteAnimationAdapter.onAnimationStart(appsCompat, wallpapersCompat, + animationFinishedCallback); + } + + @Override + public void onAnimationCancelled() { + remoteAnimationAdapter.onAnimationCancelled(); + } + }; + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationDefinitionCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationDefinitionCompat.java new file mode 100644 index 0000000000..098698aa1c --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationDefinitionCompat.java @@ -0,0 +1,40 @@ +/* + * 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.system; + +import android.view.RemoteAnimationDefinition; + +/** + * @see RemoteAnimationDefinition + */ +public class RemoteAnimationDefinitionCompat { + + private final RemoteAnimationDefinition mWrapped = new RemoteAnimationDefinition(); + + public void addRemoteAnimation(int transition, RemoteAnimationAdapterCompat adapter) { + mWrapped.addRemoteAnimation(transition, adapter.getWrapped()); + } + + public void addRemoteAnimation(int transition, int activityTypeFilter, + RemoteAnimationAdapterCompat adapter) { + mWrapped.addRemoteAnimation(transition, activityTypeFilter, adapter.getWrapped()); + } + + RemoteAnimationDefinition getWrapped() { + return mWrapped; + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationRunnerCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationRunnerCompat.java new file mode 100644 index 0000000000..33372f6bd0 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationRunnerCompat.java @@ -0,0 +1,23 @@ +/* + * 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.system; + +public interface RemoteAnimationRunnerCompat { + void onAnimationStart(RemoteAnimationTargetCompat[] apps, + RemoteAnimationTargetCompat[] wallpapers, Runnable finishedCallback); + void onAnimationCancelled(); +} \ No newline at end of file diff --git a/SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationTargetCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationTargetCompat.java new file mode 100644 index 0000000000..aed7c21643 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationTargetCompat.java @@ -0,0 +1,91 @@ +/* + * 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.system; + +import android.app.WindowConfiguration; +import android.graphics.Point; +import android.graphics.Rect; +import android.view.RemoteAnimationTarget; +import android.view.SurfaceControl; + +/** + * @see RemoteAnimationTarget + */ +public class RemoteAnimationTargetCompat { + + public static final int MODE_OPENING = RemoteAnimationTarget.MODE_OPENING; + public static final int MODE_CLOSING = RemoteAnimationTarget.MODE_CLOSING; + public final int mode; + + public static final int ACTIVITY_TYPE_UNDEFINED = WindowConfiguration.ACTIVITY_TYPE_UNDEFINED; + public static final int ACTIVITY_TYPE_STANDARD = WindowConfiguration.ACTIVITY_TYPE_STANDARD; + public static final int ACTIVITY_TYPE_HOME = WindowConfiguration.ACTIVITY_TYPE_HOME; + public static final int ACTIVITY_TYPE_RECENTS = WindowConfiguration.ACTIVITY_TYPE_RECENTS; + public static final int ACTIVITY_TYPE_ASSISTANT = WindowConfiguration.ACTIVITY_TYPE_ASSISTANT; + public final int activityType; + + public final int taskId; + public final SurfaceControlCompat leash; + public final boolean isTranslucent; + public final Rect clipRect; + public final int prefixOrderIndex; + public final Point position; + public final Rect localBounds; + public final Rect sourceContainerBounds; + public final Rect screenSpaceBounds; + public final boolean isNotInRecents; + public final Rect contentInsets; + + private final SurfaceControl mStartLeash; + + public RemoteAnimationTargetCompat(RemoteAnimationTarget app) { + taskId = app.taskId; + mode = app.mode; + leash = new SurfaceControlCompat(app.leash); + isTranslucent = app.isTranslucent; + clipRect = app.clipRect; + position = app.position; + localBounds = app.localBounds; + sourceContainerBounds = app.sourceContainerBounds; + screenSpaceBounds = app.screenSpaceBounds; + prefixOrderIndex = app.prefixOrderIndex; + isNotInRecents = app.isNotInRecents; + contentInsets = app.contentInsets; + activityType = app.windowConfiguration.getActivityType(); + + mStartLeash = app.startLeash; + } + + public static RemoteAnimationTargetCompat[] wrap(RemoteAnimationTarget[] apps) { + final RemoteAnimationTargetCompat[] appsCompat = + new RemoteAnimationTargetCompat[apps != null ? apps.length : 0]; + for (int i = 0; i < apps.length; i++) { + appsCompat[i] = new RemoteAnimationTargetCompat(apps[i]); + } + return appsCompat; + } + + /** + * @see SurfaceControl#release() + */ + public void release() { + leash.mSurfaceControl.release(); + if (mStartLeash != null) { + mStartLeash.release(); + } + } +} \ No newline at end of file diff --git a/SystemUIShared/src/com/android/systemui/shared/system/RotationWatcher.java b/SystemUIShared/src/com/android/systemui/shared/system/RotationWatcher.java new file mode 100644 index 0000000000..7c8c23eba7 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/RotationWatcher.java @@ -0,0 +1,69 @@ +/* + * 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.system; + +import android.content.Context; +import android.os.RemoteException; +import android.util.Log; +import android.view.IRotationWatcher; +import android.view.WindowManagerGlobal; + +public abstract class RotationWatcher { + + private static final String TAG = "RotationWatcher"; + + private final Context mContext; + + private final IRotationWatcher mWatcher = new IRotationWatcher.Stub() { + + @Override + public void onRotationChanged(int rotation) { + RotationWatcher.this.onRotationChanged(rotation); + + } + }; + + private boolean mIsWatching = false; + + public RotationWatcher(Context context) { + mContext = context; + } + + protected abstract void onRotationChanged(int rotation); + + public void enable() { + if (!mIsWatching) { + try { + WindowManagerGlobal.getWindowManagerService().watchRotation(mWatcher, + mContext.getDisplayId()); + mIsWatching = true; + } catch (RemoteException e) { + Log.w(TAG, "Failed to set rotation watcher", e); + } + } + } + + public void disable() { + if (mIsWatching) { + try { + WindowManagerGlobal.getWindowManagerService().removeRotationWatcher(mWatcher); + mIsWatching = false; + } catch (RemoteException e) { + Log.w(TAG, "Failed to remove rotation watcher", e); + } + } + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/SurfaceControlCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/SurfaceControlCompat.java new file mode 100644 index 0000000000..acc691304c --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/SurfaceControlCompat.java @@ -0,0 +1,47 @@ +/* + * 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.system; + +import android.view.SurfaceControl; +import android.view.View; +import android.view.ViewRootImpl; + +/** + * TODO: Remove this class + */ +public class SurfaceControlCompat { + final SurfaceControl mSurfaceControl; + + public SurfaceControlCompat(SurfaceControl surfaceControl) { + mSurfaceControl = surfaceControl; + } + + public SurfaceControlCompat(View v) { + ViewRootImpl viewRootImpl = v.getViewRootImpl(); + mSurfaceControl = viewRootImpl != null + ? viewRootImpl.getSurfaceControl() + : null; + } + + public boolean isValid() { + return mSurfaceControl != null && mSurfaceControl.isValid(); + } + + public SurfaceControl getSurfaceControl() { + return mSurfaceControl; + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/SurfaceViewRequestReceiver.java b/SystemUIShared/src/com/android/systemui/shared/system/SurfaceViewRequestReceiver.java new file mode 100644 index 0000000000..30156a0cd6 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/SurfaceViewRequestReceiver.java @@ -0,0 +1,100 @@ +/* + * 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.system; + +import android.content.Context; +import android.graphics.PixelFormat; +import android.hardware.display.DisplayManager; +import android.os.Bundle; +import android.os.IBinder; +import android.util.Size; +import android.view.SurfaceControl; +import android.view.SurfaceControlViewHost; +import android.view.View; +import android.view.WindowManager; +import android.view.WindowlessWindowManager; + +/** + * A generic receiver that specifically handles SurfaceView request created by {@link + * com.android.systemui.shared.system.SurfaceViewRequestUtils}. + */ +public class SurfaceViewRequestReceiver { + + private final int mOpacity; + private SurfaceControlViewHost mSurfaceControlViewHost; + + public SurfaceViewRequestReceiver() { + this(PixelFormat.TRANSPARENT); + } + + public SurfaceViewRequestReceiver(int opacity) { + mOpacity = opacity; + } + + /** See {@link #onReceive(Context, Bundle, View, Size)}. */ + public void onReceive(Context context, Bundle bundle, View view) { + onReceive(context, bundle, view, null); + } + + /** + * Called whenever a surface view request is received. + * @param view the view rendering content, on the receiver end of the surface request. + * @param viewSize when {@param viewSize} is not specified, we will use the surface control size + * to attach the view to the window. + */ + public void onReceive(Context context, Bundle bundle, View view, Size viewSize) { + if (mSurfaceControlViewHost != null) { + mSurfaceControlViewHost.release(); + } + + SurfaceControl surfaceControl = SurfaceViewRequestUtils.getSurfaceControl(bundle); + if (surfaceControl != null) { + if (viewSize == null) { + viewSize = new Size(surfaceControl.getWidth(), surfaceControl.getHeight()); + } + + IBinder hostToken = SurfaceViewRequestUtils.getHostToken(bundle); + + WindowlessWindowManager windowlessWindowManager = + new WindowlessWindowManager(context.getResources().getConfiguration(), + surfaceControl, hostToken); + DisplayManager dm = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE); + mSurfaceControlViewHost = new SurfaceControlViewHost(context, + dm.getDisplay(SurfaceViewRequestUtils.getDisplayId(bundle)), + windowlessWindowManager); + WindowManager.LayoutParams layoutParams = + new WindowManager.LayoutParams( + viewSize.getWidth(), + viewSize.getHeight(), + WindowManager.LayoutParams.TYPE_APPLICATION, + WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, + mOpacity); + + // This aspect scales the view to fit in the surface and centers it + final float scale = Math.min(surfaceControl.getWidth() / (float) viewSize.getWidth(), + surfaceControl.getHeight() / (float) viewSize.getHeight()); + view.setScaleX(scale); + view.setScaleY(scale); + view.setPivotX(0); + view.setPivotY(0); + view.setTranslationX((surfaceControl.getWidth() - scale * viewSize.getWidth()) / 2); + view.setTranslationY((surfaceControl.getHeight() - scale * viewSize.getHeight()) / 2); + + mSurfaceControlViewHost.setView(view, layoutParams); + } + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/SurfaceViewRequestUtils.java b/SystemUIShared/src/com/android/systemui/shared/system/SurfaceViewRequestUtils.java new file mode 100644 index 0000000000..6742a4dc06 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/SurfaceViewRequestUtils.java @@ -0,0 +1,63 @@ +/* + * 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.system; + +import android.annotation.Nullable; +import android.os.Bundle; +import android.os.IBinder; +import android.view.SurfaceControl; +import android.view.SurfaceView; + +/** Util class that wraps a SurfaceView request into a bundle. */ +public class SurfaceViewRequestUtils { + private static final String KEY_HOST_TOKEN = "host_token"; + private static final String KEY_SURFACE_CONTROL = "surface_control"; + private static final String KEY_DISPLAY_ID = "display_id"; + + /** Creates a SurfaceView based bundle that stores the input host token and surface control. */ + public static Bundle createSurfaceBundle(SurfaceView surfaceView) { + Bundle bundle = new Bundle(); + bundle.putBinder(KEY_HOST_TOKEN, surfaceView.getHostToken()); + bundle.putParcelable(KEY_SURFACE_CONTROL, surfaceView.getSurfaceControl()); + bundle.putInt(KEY_DISPLAY_ID, surfaceView.getDisplay().getDisplayId()); + return bundle; + } + + /** + * Retrieves the SurfaceControl from a bundle created by + * {@link #createSurfaceBundle(SurfaceView)}. + */ + public static SurfaceControl getSurfaceControl(Bundle bundle) { + return bundle.getParcelable(KEY_SURFACE_CONTROL); + } + + /** + * Retrieves the input token from a bundle created by {@link #createSurfaceBundle(SurfaceView)}. + */ + public static @Nullable IBinder getHostToken(Bundle bundle) { + return bundle.getBinder(KEY_HOST_TOKEN); + } + + /** + * Retrieves the display id from a bundle created by {@link #createSurfaceBundle(SurfaceView)}. + */ + public static int getDisplayId(Bundle bundle) { + return bundle.getInt(KEY_DISPLAY_ID); + } + + private SurfaceViewRequestUtils() {} +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/SyncRtSurfaceTransactionApplierCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/SyncRtSurfaceTransactionApplierCompat.java new file mode 100644 index 0000000000..2985a61dec --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/SyncRtSurfaceTransactionApplierCompat.java @@ -0,0 +1,384 @@ +/* + * 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.system; + +import android.graphics.HardwareRenderer; +import android.graphics.Matrix; +import android.graphics.Rect; +import android.os.Handler; +import android.os.Handler.Callback; +import android.os.Message; +import android.os.Trace; +import android.view.SurfaceControl; +import android.view.SurfaceControl.Transaction; +import android.view.View; +import android.view.ViewRootImpl; + +import java.util.function.Consumer; + +/** + * Helper class to apply surface transactions in sync with RenderThread. + * + * NOTE: This is a modification of {@link android.view.SyncRtSurfaceTransactionApplier}, we can't + * currently reference that class from the shared lib as it is hidden. + */ +public class SyncRtSurfaceTransactionApplierCompat { + + public static final int FLAG_ALL = 0xffffffff; + public static final int FLAG_ALPHA = 1; + public static final int FLAG_MATRIX = 1 << 1; + public static final int FLAG_WINDOW_CROP = 1 << 2; + public static final int FLAG_LAYER = 1 << 3; + public static final int FLAG_CORNER_RADIUS = 1 << 4; + public static final int FLAG_BACKGROUND_BLUR_RADIUS = 1 << 5; + public static final int FLAG_VISIBILITY = 1 << 6; + public static final int FLAG_RELATIVE_LAYER = 1 << 7; + + private static final int MSG_UPDATE_SEQUENCE_NUMBER = 0; + + private final SurfaceControl mBarrierSurfaceControl; + private final ViewRootImpl mTargetViewRootImpl; + private final Handler mApplyHandler; + + private int mSequenceNumber = 0; + private int mPendingSequenceNumber = 0; + private Runnable mAfterApplyCallback; + + /** + * @param targetView The view in the surface that acts as synchronization anchor. + */ + public SyncRtSurfaceTransactionApplierCompat(View targetView) { + mTargetViewRootImpl = targetView != null ? targetView.getViewRootImpl() : null; + mBarrierSurfaceControl = mTargetViewRootImpl != null + ? mTargetViewRootImpl.getRenderSurfaceControl() : null; + + mApplyHandler = new Handler(new Callback() { + @Override + public boolean handleMessage(Message msg) { + if (msg.what == MSG_UPDATE_SEQUENCE_NUMBER) { + onApplyMessage(msg.arg1); + return true; + } + return false; + } + }); + } + + private void onApplyMessage(int seqNo) { + mSequenceNumber = seqNo; + if (mSequenceNumber == mPendingSequenceNumber && mAfterApplyCallback != null) { + Runnable r = mAfterApplyCallback; + mAfterApplyCallback = null; + r.run(); + } + } + + /** + * Schedules applying surface parameters on the next frame. + * + * @param params The surface parameters to apply. DO NOT MODIFY the list after passing into + * this method to avoid synchronization issues. + */ + public void scheduleApply(final SyncRtSurfaceTransactionApplierCompat.SurfaceParams... params) { + if (mTargetViewRootImpl == null || mTargetViewRootImpl.getView() == null) { + return; + } + + mPendingSequenceNumber++; + final int toApplySeqNo = mPendingSequenceNumber; + mTargetViewRootImpl.registerRtFrameCallback(new HardwareRenderer.FrameDrawingCallback() { + @Override + public void onFrameDraw(long frame) { + if (mBarrierSurfaceControl == null || !mBarrierSurfaceControl.isValid()) { + Message.obtain(mApplyHandler, MSG_UPDATE_SEQUENCE_NUMBER, toApplySeqNo, 0) + .sendToTarget(); + return; + } + Trace.traceBegin(Trace.TRACE_TAG_VIEW, "Sync transaction frameNumber=" + frame); + Transaction t = new Transaction(); + for (int i = params.length - 1; i >= 0; i--) { + SyncRtSurfaceTransactionApplierCompat.SurfaceParams surfaceParams = + params[i]; + t.deferTransactionUntil(surfaceParams.surface, mBarrierSurfaceControl, frame); + surfaceParams.applyTo(t); + } + t.apply(); + Trace.traceEnd(Trace.TRACE_TAG_VIEW); + Message.obtain(mApplyHandler, MSG_UPDATE_SEQUENCE_NUMBER, toApplySeqNo, 0) + .sendToTarget(); + } + }); + + // Make sure a frame gets scheduled. + mTargetViewRootImpl.getView().invalidate(); + } + + /** + * Calls the runnable when any pending apply calls have completed + */ + public void addAfterApplyCallback(final Runnable afterApplyCallback) { + if (mSequenceNumber == mPendingSequenceNumber) { + afterApplyCallback.run(); + } else { + if (mAfterApplyCallback == null) { + mAfterApplyCallback = afterApplyCallback; + } else { + final Runnable oldCallback = mAfterApplyCallback; + mAfterApplyCallback = new Runnable() { + @Override + public void run() { + afterApplyCallback.run(); + oldCallback.run(); + } + }; + } + } + } + + public static void applyParams(TransactionCompat t, + SyncRtSurfaceTransactionApplierCompat.SurfaceParams params) { + params.applyTo(t.mTransaction); + } + + /** + * Creates an instance of SyncRtSurfaceTransactionApplier, deferring until the target view is + * attached if necessary. + */ + public static void create(final View targetView, + final Consumer callback) { + if (targetView == null) { + // No target view, no applier + callback.accept(null); + } else if (targetView.getViewRootImpl() != null) { + // Already attached, we're good to go + callback.accept(new SyncRtSurfaceTransactionApplierCompat(targetView)); + } else { + // Haven't been attached before we can get the view root + targetView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() { + @Override + public void onViewAttachedToWindow(View v) { + targetView.removeOnAttachStateChangeListener(this); + callback.accept(new SyncRtSurfaceTransactionApplierCompat(targetView)); + } + + @Override + public void onViewDetachedFromWindow(View v) { + // Do nothing + } + }); + } + } + + public static class SurfaceParams { + public static class Builder { + final SurfaceControl surface; + int flags; + float alpha; + float cornerRadius; + int backgroundBlurRadius; + Matrix matrix; + Rect windowCrop; + int layer; + SurfaceControl relativeTo; + int relativeLayer; + boolean visible; + + /** + * @param surface The surface to modify. + */ + public Builder(SurfaceControlCompat surface) { + this(surface.mSurfaceControl); + } + + /** + * @param surface The surface to modify. + */ + public Builder(SurfaceControl surface) { + this.surface = surface; + } + + /** + * @param alpha The alpha value to apply to the surface. + * @return this Builder + */ + public Builder withAlpha(float alpha) { + this.alpha = alpha; + flags |= FLAG_ALPHA; + return this; + } + + /** + * @param matrix The matrix to apply to the surface. + * @return this Builder + */ + public Builder withMatrix(Matrix matrix) { + this.matrix = matrix; + flags |= FLAG_MATRIX; + return this; + } + + /** + * @param windowCrop The window crop to apply to the surface. + * @return this Builder + */ + public Builder withWindowCrop(Rect windowCrop) { + this.windowCrop = windowCrop; + flags |= FLAG_WINDOW_CROP; + return this; + } + + /** + * @param layer The layer to assign the surface. + * @return this Builder + */ + public Builder withLayer(int layer) { + this.layer = layer; + flags |= FLAG_LAYER; + return this; + } + + /** + * @param relativeTo The surface that's set relative layer to. + * @param relativeLayer The relative layer. + * @return this Builder + */ + public Builder withRelativeLayerTo(SurfaceControl relativeTo, int relativeLayer) { + this.relativeTo = relativeTo; + this.relativeLayer = relativeLayer; + flags |= FLAG_RELATIVE_LAYER; + return this; + } + + /** + * @param radius the Radius for rounded corners to apply to the surface. + * @return this Builder + */ + public Builder withCornerRadius(float radius) { + this.cornerRadius = radius; + flags |= FLAG_CORNER_RADIUS; + return this; + } + + /** + * @param radius the Radius for blur to apply to the background surfaces. + * @return this Builder + */ + public Builder withBackgroundBlur(int radius) { + this.backgroundBlurRadius = radius; + flags |= FLAG_BACKGROUND_BLUR_RADIUS; + return this; + } + + /** + * @param visible The visibility to apply to the surface. + * @return this Builder + */ + public Builder withVisibility(boolean visible) { + this.visible = visible; + flags |= FLAG_VISIBILITY; + return this; + } + + /** + * @return a new SurfaceParams instance + */ + public SurfaceParams build() { + return new SurfaceParams(surface, flags, alpha, matrix, windowCrop, layer, + relativeTo, relativeLayer, cornerRadius, backgroundBlurRadius, visible); + } + } + + /** + * Constructs surface parameters to be applied when the current view state gets pushed to + * RenderThread. + * + * @param surface The surface to modify. + * @param alpha Alpha to apply. + * @param matrix Matrix to apply. + * @param windowCrop Crop to apply, only applied if not {@code null} + */ + public SurfaceParams(SurfaceControlCompat surface, float alpha, Matrix matrix, + Rect windowCrop, int layer, SurfaceControl relativeTo, int relativeLayer, + float cornerRadius) { + this(surface.mSurfaceControl, + FLAG_ALL & ~(FLAG_VISIBILITY | FLAG_BACKGROUND_BLUR_RADIUS), alpha, + matrix, windowCrop, layer, relativeTo, relativeLayer, cornerRadius, + 0 /* backgroundBlurRadius */, true); + } + + private SurfaceParams(SurfaceControl surface, int flags, float alpha, Matrix matrix, + Rect windowCrop, int layer, SurfaceControl relativeTo, int relativeLayer, + float cornerRadius, int backgroundBlurRadius, boolean visible) { + this.flags = flags; + this.surface = surface; + this.alpha = alpha; + this.matrix = new Matrix(matrix); + this.windowCrop = windowCrop != null ? new Rect(windowCrop) : null; + this.layer = layer; + this.relativeTo = relativeTo; + this.relativeLayer = relativeLayer; + this.cornerRadius = cornerRadius; + this.backgroundBlurRadius = backgroundBlurRadius; + this.visible = visible; + } + + private final int flags; + private final float[] mTmpValues = new float[9]; + + public final SurfaceControl surface; + public final float alpha; + public final float cornerRadius; + public final int backgroundBlurRadius; + public final Matrix matrix; + public final Rect windowCrop; + public final int layer; + public final SurfaceControl relativeTo; + public final int relativeLayer; + public final boolean visible; + + public void applyTo(SurfaceControl.Transaction t) { + if ((flags & FLAG_MATRIX) != 0) { + t.setMatrix(surface, matrix, mTmpValues); + } + if ((flags & FLAG_WINDOW_CROP) != 0) { + t.setWindowCrop(surface, windowCrop); + } + if ((flags & FLAG_ALPHA) != 0) { + t.setAlpha(surface, alpha); + } + if ((flags & FLAG_LAYER) != 0) { + t.setLayer(surface, layer); + } + if ((flags & FLAG_CORNER_RADIUS) != 0) { + t.setCornerRadius(surface, cornerRadius); + } + if ((flags & FLAG_BACKGROUND_BLUR_RADIUS) != 0) { + t.setBackgroundBlurRadius(surface, backgroundBlurRadius); + } + if ((flags & FLAG_VISIBILITY) != 0) { + if (visible) { + t.show(surface); + } else { + t.hide(surface); + } + } + if ((flags & FLAG_RELATIVE_LAYER) != 0) { + t.setRelativeLayer(surface, relativeTo, relativeLayer); + } + } + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/SystemGestureExclusionListenerCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/SystemGestureExclusionListenerCompat.java new file mode 100644 index 0000000000..aeb0415c8c --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/SystemGestureExclusionListenerCompat.java @@ -0,0 +1,105 @@ +/** + * Copyright (C) 2019 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.system; + +import android.graphics.Region; +import android.os.RemoteException; +import android.util.Log; +import android.view.ISystemGestureExclusionListener; +import android.view.WindowManagerGlobal; + +/** + * Utility class to listen for exclusion rect changes. + */ +public abstract class SystemGestureExclusionListenerCompat { + + private static final String TAG = "SGEListenerCompat"; + + private final int mDisplayId; + + private ISystemGestureExclusionListener mGestureExclusionListener = + new ISystemGestureExclusionListener.Stub() { + @Override + public void onSystemGestureExclusionChanged(int displayId, + Region systemGestureExclusion, Region unrestrictedOrNull) { + if (displayId == mDisplayId) { + Region unrestricted = (unrestrictedOrNull == null) + ? systemGestureExclusion : unrestrictedOrNull; + onExclusionChanged(systemGestureExclusion, unrestricted); + } + } + }; + private boolean mRegistered; + + public SystemGestureExclusionListenerCompat(int displayId) { + mDisplayId = displayId; + } + + /** + * Called when the exclusion region has changed. + * + * TODO: remove, once all subclasses have migrated to + * {@link #onExclusionChanged(Region, Region)}. + */ + public abstract void onExclusionChanged(Region systemGestureExclusion); + + /** + * Called when the exclusion region has changed. + * + * @param systemGestureExclusion the system gesture exclusion to be applied + * @param systemGestureExclusionUnrestricted what would be the system gesture exclusion, if + * there were no restrictions being applied. For logging purposes only. + * + */ + public void onExclusionChanged(Region systemGestureExclusion, + Region systemGestureExclusionUnrestricted) { + // TODO: make abstract, once all subclasses have migrated away from + // onExclusionChanged(Region) + onExclusionChanged(systemGestureExclusion); + } + + /** + * Registers the listener for getting exclusion rect changes. + */ + public void register() { + if (!mRegistered) { + try { + WindowManagerGlobal.getWindowManagerService() + .registerSystemGestureExclusionListener( + mGestureExclusionListener, mDisplayId); + mRegistered = true; + } catch (RemoteException e) { + Log.e(TAG, "Failed to register window manager callbacks", e); + } + } + } + + /** + * Unregisters the receiver if previously registered + */ + public void unregister() { + if (mRegistered) { + try { + WindowManagerGlobal.getWindowManagerService() + .unregisterSystemGestureExclusionListener( + mGestureExclusionListener, mDisplayId); + mRegistered = false; + } catch (RemoteException e) { + Log.e(TAG, "Failed to unregister window manager callbacks", e); + } + } + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/TaskDescriptionCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/TaskDescriptionCompat.java new file mode 100644 index 0000000000..35952f55ec --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/TaskDescriptionCompat.java @@ -0,0 +1,49 @@ +/* + * 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.system; + +import android.app.ActivityManager; +import android.graphics.Bitmap; + +public class TaskDescriptionCompat { + + private ActivityManager.TaskDescription mTaskDescription; + + public TaskDescriptionCompat(ActivityManager.TaskDescription td) { + mTaskDescription = td; + } + + public int getPrimaryColor() { + return mTaskDescription != null + ? mTaskDescription.getPrimaryColor() + : 0; + } + + public int getBackgroundColor() { + return mTaskDescription != null + ? mTaskDescription.getBackgroundColor() + : 0; + } + + public static Bitmap getIcon(ActivityManager.TaskDescription desc, int userId) { + if (desc.getInMemoryIcon() != null) { + return desc.getInMemoryIcon(); + } + return ActivityManager.TaskDescription.loadTaskDescriptionIcon( + desc.getIconFilename(), userId); + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/TaskInfoCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/TaskInfoCompat.java new file mode 100644 index 0000000000..326c2aa371 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/TaskInfoCompat.java @@ -0,0 +1,48 @@ +/* + * 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.system; + +import android.app.ActivityManager; +import android.app.TaskInfo; +import android.content.ComponentName; + +public class TaskInfoCompat { + + public static int getUserId(TaskInfo info) { + return info.userId; + } + + public static int getActivityType(TaskInfo info) { + return info.configuration.windowConfiguration.getActivityType(); + } + + public static int getWindowingMode(TaskInfo info) { + return info.configuration.windowConfiguration.getWindowingMode(); + } + + public static boolean supportsSplitScreenMultiWindow(TaskInfo info) { + return info.supportsSplitScreenMultiWindow; + } + + public static ComponentName getTopActivity(TaskInfo info) { + return info.topActivity; + } + + public static ActivityManager.TaskDescription getTaskDescription(TaskInfo info) { + return info.taskDescription; + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/TaskStackChangeListener.java b/SystemUIShared/src/com/android/systemui/shared/system/TaskStackChangeListener.java new file mode 100644 index 0000000000..44372d76bb --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/TaskStackChangeListener.java @@ -0,0 +1,120 @@ +/* + * 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.system; + +import android.app.ActivityManager.RunningTaskInfo; +import android.app.ITaskStackListener; +import android.content.ComponentName; +import android.os.IBinder; + +import com.android.systemui.shared.recents.model.ThumbnailData; + +/** + * An interface to track task stack changes. Classes should implement this instead of + * {@link android.app.ITaskStackListener} to reduce IPC calls from system services. + */ +public abstract class TaskStackChangeListener { + + // Binder thread callbacks + public void onTaskStackChangedBackground() { } + + // Main thread callbacks + public void onTaskStackChanged() { } + public void onTaskSnapshotChanged(int taskId, ThumbnailData snapshot) { } + public void onActivityPinned(String packageName, int userId, int taskId, int stackId) { } + public void onActivityUnpinned() { } + public void onActivityRestartAttempt(RunningTaskInfo task, boolean homeTaskVisible, + boolean clearedTask, boolean wasVisible) { } + public void onActivityForcedResizable(String packageName, int taskId, int reason) { } + public void onActivityDismissingDockedStack() { } + public void onActivityLaunchOnSecondaryDisplayFailed() { } + + public void onActivityLaunchOnSecondaryDisplayFailed(RunningTaskInfo taskInfo) { + onActivityLaunchOnSecondaryDisplayFailed(); + } + + /** + * @see #onActivityLaunchOnSecondaryDisplayRerouted(RunningTaskInfo taskInfo) + */ + public void onActivityLaunchOnSecondaryDisplayRerouted() { } + + /** + * Called when an activity was requested to be launched on a secondary display but was rerouted + * to default display. + * + * @param taskInfo info about the Activity's task + */ + public void onActivityLaunchOnSecondaryDisplayRerouted(RunningTaskInfo taskInfo) { + onActivityLaunchOnSecondaryDisplayRerouted(); + } + + /** + * Called when contents are drawn for the first time on a display which can only contain one + * task. + * + * @param displayId the id of the display on which contents are drawn. + */ + public void onSingleTaskDisplayDrawn(int displayId) { } + + /** + * Called when the last task is removed from a display which can only contain one task. + * + * @param displayId the id of the display from which the window is removed. + */ + public void onSingleTaskDisplayEmpty(int displayId) {} + + public void onTaskProfileLocked(int taskId, int userId) { } + public void onTaskCreated(int taskId, ComponentName componentName) { } + public void onTaskRemoved(int taskId) { } + public void onTaskMovedToFront(int taskId) { } + + public void onTaskMovedToFront(RunningTaskInfo taskInfo) { + onTaskMovedToFront(taskInfo.taskId); + } + + /** + * Called when a task’s description is changed due to an activity calling + * ActivityManagerService.setTaskDescription + * + * @param taskInfo info about the task which changed, with {@link TaskInfo#taskDescription} + */ + public void onTaskDescriptionChanged(RunningTaskInfo taskInfo) { } + + public void onActivityRequestedOrientationChanged(int taskId, int requestedOrientation) { } + public void onSizeCompatModeActivityChanged(int displayId, IBinder activityToken) { } + + public void onBackPressedOnTaskRoot(RunningTaskInfo taskInfo) { } + + /** + * Called when a task is reparented to a stack on a different display. + * + * @param taskId id of the task which was moved to a different display. + * @param newDisplayId id of the new display. + */ + public void onTaskDisplayChanged(int taskId, int newDisplayId) { } + + /** + * Called when any additions or deletions to the recent tasks list have been made. + */ + public void onRecentTaskListUpdated() { } + + /** @see ITaskStackListener#onRecentTaskListFrozenChanged(boolean) */ + public void onRecentTaskListFrozenChanged(boolean frozen) { } + + /** @see ITaskStackListener#onActivityRotation(int)*/ + public void onActivityRotation(int displayId) { } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/TaskStackChangeListeners.java b/SystemUIShared/src/com/android/systemui/shared/system/TaskStackChangeListeners.java new file mode 100644 index 0000000000..f214648d89 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/TaskStackChangeListeners.java @@ -0,0 +1,464 @@ +/* + * 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.system; + +import android.app.ActivityManager.RunningTaskInfo; +import android.app.ActivityManager.TaskSnapshot; +import android.app.ActivityTaskManager; +import android.app.IActivityManager; +import android.app.TaskStackListener; +import android.content.ComponentName; +import android.os.Handler; +import android.os.IBinder; +import android.os.Looper; +import android.os.Message; +import android.os.RemoteException; +import android.os.Trace; +import android.util.Log; + +import com.android.internal.os.SomeArgs; +import com.android.systemui.shared.recents.model.ThumbnailData; + +import java.util.ArrayList; +import java.util.List; + +/** + * Tracks all the task stack listeners + */ +public class TaskStackChangeListeners extends TaskStackListener { + + private static final String TAG = TaskStackChangeListeners.class.getSimpleName(); + + /** + * List of {@link TaskStackChangeListener} registered from {@link #addListener}. + */ + private final List mTaskStackListeners = new ArrayList<>(); + private final List mTmpListeners = new ArrayList<>(); + + private final Handler mHandler; + private boolean mRegistered; + + public TaskStackChangeListeners(Looper looper) { + mHandler = new H(looper); + } + + public void addListener(IActivityManager am, TaskStackChangeListener listener) { + synchronized (mTaskStackListeners) { + mTaskStackListeners.add(listener); + } + if (!mRegistered) { + // Register mTaskStackListener to IActivityManager only once if needed. + try { + ActivityTaskManager.getService().registerTaskStackListener(this); + mRegistered = true; + } catch (Exception e) { + Log.w(TAG, "Failed to call registerTaskStackListener", e); + } + } + } + + public void removeListener(TaskStackChangeListener listener) { + boolean isEmpty; + synchronized (mTaskStackListeners) { + mTaskStackListeners.remove(listener); + isEmpty = mTaskStackListeners.isEmpty(); + } + if (isEmpty && mRegistered) { + // Unregister mTaskStackListener once we have no more listeners + try { + ActivityTaskManager.getService().unregisterTaskStackListener(this); + mRegistered = false; + } catch (Exception e) { + Log.w(TAG, "Failed to call unregisterTaskStackListener", e); + } + } + } + + @Override + public void onTaskStackChanged() throws RemoteException { + // Call the task changed callback for the non-ui thread listeners first. Copy to a set of + // temp listeners so that we don't lock on mTaskStackListeners while calling all the + // callbacks. This call is always on the same binder thread, so we can just synchronize + // on the copying of the listener list. + synchronized (mTaskStackListeners) { + mTmpListeners.addAll(mTaskStackListeners); + } + for (int i = mTmpListeners.size() - 1; i >= 0; i--) { + mTmpListeners.get(i).onTaskStackChangedBackground(); + } + mTmpListeners.clear(); + + mHandler.removeMessages(H.ON_TASK_STACK_CHANGED); + mHandler.sendEmptyMessage(H.ON_TASK_STACK_CHANGED); + } + + @Override + public void onActivityPinned(String packageName, int userId, int taskId, int stackId) + throws RemoteException { + mHandler.removeMessages(H.ON_ACTIVITY_PINNED); + mHandler.obtainMessage(H.ON_ACTIVITY_PINNED, + new PinnedActivityInfo(packageName, userId, taskId, stackId)).sendToTarget(); + } + + @Override + public void onActivityUnpinned() throws RemoteException { + mHandler.removeMessages(H.ON_ACTIVITY_UNPINNED); + mHandler.sendEmptyMessage(H.ON_ACTIVITY_UNPINNED); + } + + @Override + public void onActivityRestartAttempt(RunningTaskInfo task, boolean homeTaskVisible, + boolean clearedTask, boolean wasVisible) throws RemoteException { + final SomeArgs args = SomeArgs.obtain(); + args.arg1 = task; + args.argi1 = homeTaskVisible ? 1 : 0; + args.argi2 = clearedTask ? 1 : 0; + args.argi3 = wasVisible ? 1 : 0; + mHandler.removeMessages(H.ON_ACTIVITY_RESTART_ATTEMPT); + mHandler.obtainMessage(H.ON_ACTIVITY_RESTART_ATTEMPT, args).sendToTarget(); + } + + @Override + public void onActivityForcedResizable(String packageName, int taskId, int reason) + throws RemoteException { + mHandler.obtainMessage(H.ON_ACTIVITY_FORCED_RESIZABLE, taskId, reason, packageName) + .sendToTarget(); + } + + @Override + public void onActivityDismissingDockedStack() throws RemoteException { + mHandler.sendEmptyMessage(H.ON_ACTIVITY_DISMISSING_DOCKED_STACK); + } + + @Override + public void onActivityLaunchOnSecondaryDisplayFailed(RunningTaskInfo taskInfo, + int requestedDisplayId) throws RemoteException { + mHandler.obtainMessage(H.ON_ACTIVITY_LAUNCH_ON_SECONDARY_DISPLAY_FAILED, requestedDisplayId, + 0 /* unused */, + taskInfo).sendToTarget(); + } + + @Override + public void onActivityLaunchOnSecondaryDisplayRerouted(RunningTaskInfo taskInfo, + int requestedDisplayId) throws RemoteException { + mHandler.obtainMessage(H.ON_ACTIVITY_LAUNCH_ON_SECONDARY_DISPLAY_REROUTED, + requestedDisplayId, 0 /* unused */, taskInfo).sendToTarget(); + } + + @Override + public void onTaskProfileLocked(int taskId, int userId) throws RemoteException { + mHandler.obtainMessage(H.ON_TASK_PROFILE_LOCKED, taskId, userId).sendToTarget(); + } + + @Override + public void onTaskSnapshotChanged(int taskId, TaskSnapshot snapshot) throws RemoteException { + mHandler.obtainMessage(H.ON_TASK_SNAPSHOT_CHANGED, taskId, 0, snapshot).sendToTarget(); + } + + @Override + public void onTaskCreated(int taskId, ComponentName componentName) throws RemoteException { + mHandler.obtainMessage(H.ON_TASK_CREATED, taskId, 0, componentName).sendToTarget(); + } + + @Override + public void onTaskRemoved(int taskId) throws RemoteException { + mHandler.obtainMessage(H.ON_TASK_REMOVED, taskId, 0).sendToTarget(); + } + + @Override + public void onTaskMovedToFront(RunningTaskInfo taskInfo) + throws RemoteException { + mHandler.obtainMessage(H.ON_TASK_MOVED_TO_FRONT, taskInfo).sendToTarget(); + } + + @Override + public void onBackPressedOnTaskRoot(RunningTaskInfo taskInfo) throws RemoteException { + mHandler.obtainMessage(H.ON_BACK_PRESSED_ON_TASK_ROOT, taskInfo).sendToTarget(); + } + + @Override + public void onActivityRequestedOrientationChanged(int taskId, int requestedOrientation) + throws RemoteException { + mHandler.obtainMessage(H.ON_ACTIVITY_REQUESTED_ORIENTATION_CHANGE, taskId, + requestedOrientation).sendToTarget(); + } + + @Override + public void onSizeCompatModeActivityChanged(int displayId, IBinder activityToken) + throws RemoteException { + mHandler.obtainMessage(H.ON_SIZE_COMPAT_MODE_ACTIVITY_CHANGED, displayId, 0 /* unused */, + activityToken).sendToTarget(); + } + + @Override + public void onSingleTaskDisplayDrawn(int displayId) throws RemoteException { + mHandler.obtainMessage(H.ON_SINGLE_TASK_DISPLAY_DRAWN, displayId, + 0 /* unused */).sendToTarget(); + } + + @Override + public void onSingleTaskDisplayEmpty(int displayId) throws RemoteException { + mHandler.obtainMessage(H.ON_SINGLE_TASK_DISPLAY_EMPTY, displayId, + 0 /* unused */).sendToTarget(); + } + + @Override + public void onTaskDisplayChanged(int taskId, int newDisplayId) throws RemoteException { + mHandler.obtainMessage(H.ON_TASK_DISPLAY_CHANGED, taskId, newDisplayId).sendToTarget(); + } + + @Override + public void onRecentTaskListUpdated() throws RemoteException { + mHandler.obtainMessage(H.ON_TASK_LIST_UPDATED).sendToTarget(); + } + + @Override + public void onRecentTaskListFrozenChanged(boolean frozen) { + mHandler.obtainMessage(H.ON_TASK_LIST_FROZEN_UNFROZEN, frozen ? 1 : 0, 0 /* unused */) + .sendToTarget(); + } + + @Override + public void onTaskDescriptionChanged(RunningTaskInfo taskInfo) { + mHandler.obtainMessage(H.ON_TASK_DESCRIPTION_CHANGED, taskInfo).sendToTarget(); + } + + @Override + public void onActivityRotation(int displayId) { + mHandler.obtainMessage(H.ON_ACTIVITY_ROTATION, displayId, 0 /* unused */) + .sendToTarget(); + } + + private final class H extends Handler { + private static final int ON_TASK_STACK_CHANGED = 1; + private static final int ON_TASK_SNAPSHOT_CHANGED = 2; + private static final int ON_ACTIVITY_PINNED = 3; + private static final int ON_ACTIVITY_RESTART_ATTEMPT = 4; + private static final int ON_ACTIVITY_FORCED_RESIZABLE = 6; + private static final int ON_ACTIVITY_DISMISSING_DOCKED_STACK = 7; + private static final int ON_TASK_PROFILE_LOCKED = 8; + private static final int ON_ACTIVITY_UNPINNED = 10; + private static final int ON_ACTIVITY_LAUNCH_ON_SECONDARY_DISPLAY_FAILED = 11; + private static final int ON_TASK_CREATED = 12; + private static final int ON_TASK_REMOVED = 13; + private static final int ON_TASK_MOVED_TO_FRONT = 14; + private static final int ON_ACTIVITY_REQUESTED_ORIENTATION_CHANGE = 15; + private static final int ON_ACTIVITY_LAUNCH_ON_SECONDARY_DISPLAY_REROUTED = 16; + private static final int ON_SIZE_COMPAT_MODE_ACTIVITY_CHANGED = 17; + private static final int ON_BACK_PRESSED_ON_TASK_ROOT = 18; + private static final int ON_SINGLE_TASK_DISPLAY_DRAWN = 19; + private static final int ON_TASK_DISPLAY_CHANGED = 20; + private static final int ON_TASK_LIST_UPDATED = 21; + private static final int ON_SINGLE_TASK_DISPLAY_EMPTY = 22; + private static final int ON_TASK_LIST_FROZEN_UNFROZEN = 23; + private static final int ON_TASK_DESCRIPTION_CHANGED = 24; + private static final int ON_ACTIVITY_ROTATION = 25; + + + public H(Looper looper) { + super(looper); + } + + @Override + public void handleMessage(Message msg) { + synchronized (mTaskStackListeners) { + switch (msg.what) { + case ON_TASK_STACK_CHANGED: { + Trace.beginSection("onTaskStackChanged"); + for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) { + mTaskStackListeners.get(i).onTaskStackChanged(); + } + Trace.endSection(); + break; + } + case ON_TASK_SNAPSHOT_CHANGED: { + Trace.beginSection("onTaskSnapshotChanged"); + for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) { + mTaskStackListeners.get(i).onTaskSnapshotChanged(msg.arg1, + new ThumbnailData((TaskSnapshot) msg.obj)); + } + Trace.endSection(); + break; + } + case ON_ACTIVITY_PINNED: { + final PinnedActivityInfo info = (PinnedActivityInfo) msg.obj; + for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) { + mTaskStackListeners.get(i).onActivityPinned( + info.mPackageName, info.mUserId, info.mTaskId, info.mStackId); + } + break; + } + case ON_ACTIVITY_UNPINNED: { + for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) { + mTaskStackListeners.get(i).onActivityUnpinned(); + } + break; + } + case ON_ACTIVITY_RESTART_ATTEMPT: { + final SomeArgs args = (SomeArgs) msg.obj; + final RunningTaskInfo task = (RunningTaskInfo) args.arg1; + final boolean homeTaskVisible = args.argi1 != 0; + final boolean clearedTask = args.argi2 != 0; + final boolean wasVisible = args.argi3 != 0; + for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) { + mTaskStackListeners.get(i).onActivityRestartAttempt(task, + homeTaskVisible, clearedTask, wasVisible); + } + break; + } + case ON_ACTIVITY_FORCED_RESIZABLE: { + for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) { + mTaskStackListeners.get(i).onActivityForcedResizable( + (String) msg.obj, msg.arg1, msg.arg2); + } + break; + } + case ON_ACTIVITY_DISMISSING_DOCKED_STACK: { + for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) { + mTaskStackListeners.get(i).onActivityDismissingDockedStack(); + } + break; + } + case ON_ACTIVITY_LAUNCH_ON_SECONDARY_DISPLAY_FAILED: { + final RunningTaskInfo info = (RunningTaskInfo) msg.obj; + for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) { + mTaskStackListeners.get(i) + .onActivityLaunchOnSecondaryDisplayFailed(info); + } + break; + } + case ON_ACTIVITY_LAUNCH_ON_SECONDARY_DISPLAY_REROUTED: { + final RunningTaskInfo info = (RunningTaskInfo) msg.obj; + for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) { + mTaskStackListeners.get(i) + .onActivityLaunchOnSecondaryDisplayRerouted(info); + } + break; + } + case ON_TASK_PROFILE_LOCKED: { + for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) { + mTaskStackListeners.get(i).onTaskProfileLocked(msg.arg1, msg.arg2); + } + break; + } + case ON_TASK_CREATED: { + for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) { + mTaskStackListeners.get(i).onTaskCreated(msg.arg1, + (ComponentName) msg.obj); + } + break; + } + case ON_TASK_REMOVED: { + for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) { + mTaskStackListeners.get(i).onTaskRemoved(msg.arg1); + } + break; + } + case ON_TASK_MOVED_TO_FRONT: { + final RunningTaskInfo info = (RunningTaskInfo) msg.obj; + for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) { + mTaskStackListeners.get(i).onTaskMovedToFront(info); + } + break; + } + case ON_ACTIVITY_REQUESTED_ORIENTATION_CHANGE: { + for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) { + mTaskStackListeners.get(i) + .onActivityRequestedOrientationChanged(msg.arg1, msg.arg2); + } + break; + } + case ON_SIZE_COMPAT_MODE_ACTIVITY_CHANGED: { + for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) { + mTaskStackListeners.get(i).onSizeCompatModeActivityChanged( + msg.arg1, (IBinder) msg.obj); + } + break; + } + case ON_BACK_PRESSED_ON_TASK_ROOT: { + for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) { + mTaskStackListeners.get(i).onBackPressedOnTaskRoot( + (RunningTaskInfo) msg.obj); + } + break; + } + case ON_SINGLE_TASK_DISPLAY_DRAWN: { + for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) { + mTaskStackListeners.get(i).onSingleTaskDisplayDrawn(msg.arg1); + } + break; + } + case ON_SINGLE_TASK_DISPLAY_EMPTY: { + for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) { + mTaskStackListeners.get(i).onSingleTaskDisplayEmpty( + msg.arg1); + } + break; + } + case ON_TASK_DISPLAY_CHANGED: { + for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) { + mTaskStackListeners.get(i).onTaskDisplayChanged(msg.arg1, msg.arg2); + } + break; + } + case ON_TASK_LIST_UPDATED: { + for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) { + mTaskStackListeners.get(i).onRecentTaskListUpdated(); + } + break; + } + case ON_TASK_LIST_FROZEN_UNFROZEN: { + for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) { + mTaskStackListeners.get(i).onRecentTaskListFrozenChanged(msg.arg1 != 0); + } + break; + } + case ON_TASK_DESCRIPTION_CHANGED: { + final RunningTaskInfo info = (RunningTaskInfo) msg.obj; + for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) { + mTaskStackListeners.get(i).onTaskDescriptionChanged(info); + } + break; + } + case ON_ACTIVITY_ROTATION: { + for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) { + mTaskStackListeners.get(i).onActivityRotation(msg.arg1); + } + break; + } + } + } + if (msg.obj instanceof SomeArgs) { + ((SomeArgs) msg.obj).recycle(); + } + } + } + + private static class PinnedActivityInfo { + final String mPackageName; + final int mUserId; + final int mTaskId; + final int mStackId; + + PinnedActivityInfo(String packageName, int userId, int taskId, int stackId) { + mPackageName = packageName; + mUserId = userId; + mTaskId = taskId; + mStackId = stackId; + } + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/ThreadedRendererCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/ThreadedRendererCompat.java new file mode 100644 index 0000000000..bf88a29184 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/ThreadedRendererCompat.java @@ -0,0 +1,33 @@ +/* + * 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.system; + +import android.view.ThreadedRenderer; + +/** + * @see ThreadedRenderer + */ +public class ThreadedRendererCompat { + + public static int EGL_CONTEXT_PRIORITY_HIGH_IMG = 0x3101; + public static int EGL_CONTEXT_PRIORITY_MEDIUM_IMG = 0x3102; + public static int EGL_CONTEXT_PRIORITY_LOW_IMG = 0x3103; + + public static void setContextPriority(int priority) { + ThreadedRenderer.setContextPriority(priority); + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/TonalCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/TonalCompat.java new file mode 100644 index 0000000000..4a0f89b7dc --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/TonalCompat.java @@ -0,0 +1,53 @@ +/* + * 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.system; + +import android.app.WallpaperColors; +import android.content.Context; + +import com.android.internal.colorextraction.ColorExtractor.GradientColors; +import com.android.internal.colorextraction.types.Tonal; + +public class TonalCompat { + + private final Tonal mTonal; + + public TonalCompat(Context context) { + mTonal = new Tonal(context); + } + + public ExtractionInfo extractDarkColors(WallpaperColors colors) { + GradientColors darkColors = new GradientColors(); + mTonal.extractInto(colors, new GradientColors(), darkColors, new GradientColors()); + + ExtractionInfo result = new ExtractionInfo(); + result.mainColor = darkColors.getMainColor(); + result.secondaryColor = darkColors.getSecondaryColor(); + result.supportsDarkText = darkColors.supportsDarkText(); + if (colors != null) { + result.supportsDarkTheme = + (colors.getColorHints() & WallpaperColors.HINT_SUPPORTS_DARK_THEME) != 0; + } + return result; + } + + public static class ExtractionInfo { + public int mainColor; + public int secondaryColor; + public boolean supportsDarkText; + public boolean supportsDarkTheme; + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/TransactionCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/TransactionCompat.java new file mode 100644 index 0000000000..255fffdb32 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/TransactionCompat.java @@ -0,0 +1,125 @@ +/* + * 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.system; + +import android.graphics.Matrix; +import android.graphics.Rect; +import android.view.SurfaceControl; +import android.view.SurfaceControl.Transaction; + +public class TransactionCompat { + + final Transaction mTransaction; + + final float[] mTmpValues = new float[9]; + + public TransactionCompat() { + mTransaction = new Transaction(); + } + + public void apply() { + mTransaction.apply(); + } + + public TransactionCompat show(SurfaceControlCompat surfaceControl) { + mTransaction.show(surfaceControl.mSurfaceControl); + return this; + } + + public TransactionCompat hide(SurfaceControlCompat surfaceControl) { + mTransaction.hide(surfaceControl.mSurfaceControl); + return this; + } + + public TransactionCompat setPosition(SurfaceControlCompat surfaceControl, float x, float y) { + mTransaction.setPosition(surfaceControl.mSurfaceControl, x, y); + return this; + } + + public TransactionCompat setSize(SurfaceControlCompat surfaceControl, int w, int h) { + mTransaction.setBufferSize(surfaceControl.mSurfaceControl, w, h); + return this; + } + + public TransactionCompat setLayer(SurfaceControlCompat surfaceControl, int z) { + mTransaction.setLayer(surfaceControl.mSurfaceControl, z); + return this; + } + + public TransactionCompat setAlpha(SurfaceControlCompat surfaceControl, float alpha) { + mTransaction.setAlpha(surfaceControl.mSurfaceControl, alpha); + return this; + } + + public TransactionCompat setMatrix(SurfaceControlCompat surfaceControl, float dsdx, float dtdx, + float dtdy, float dsdy) { + mTransaction.setMatrix(surfaceControl.mSurfaceControl, dsdx, dtdx, dtdy, dsdy); + return this; + } + + public TransactionCompat setMatrix(SurfaceControlCompat surfaceControl, Matrix matrix) { + mTransaction.setMatrix(surfaceControl.mSurfaceControl, matrix, mTmpValues); + return this; + } + + public TransactionCompat setWindowCrop(SurfaceControlCompat surfaceControl, Rect crop) { + mTransaction.setWindowCrop(surfaceControl.mSurfaceControl, crop); + return this; + } + + public TransactionCompat setCornerRadius(SurfaceControlCompat surfaceControl, float radius) { + mTransaction.setCornerRadius(surfaceControl.mSurfaceControl, radius); + return this; + } + + public TransactionCompat setBackgroundBlurRadius(SurfaceControlCompat surfaceControl, + int radius) { + mTransaction.setBackgroundBlurRadius(surfaceControl.mSurfaceControl, radius); + return this; + } + + public TransactionCompat deferTransactionUntil(SurfaceControlCompat surfaceControl, + SurfaceControl barrier, long frameNumber) { + mTransaction.deferTransactionUntil(surfaceControl.mSurfaceControl, barrier, + frameNumber); + return this; + } + + @Deprecated + public TransactionCompat setEarlyWakeup() { + return this; + } + + public TransactionCompat setColor(SurfaceControlCompat surfaceControl, float[] color) { + mTransaction.setColor(surfaceControl.mSurfaceControl, color); + return this; + } + + public static void deferTransactionUntil(Transaction t, SurfaceControl surfaceControl, + SurfaceControl barrier, long frameNumber) { + t.deferTransactionUntil(surfaceControl, barrier, frameNumber); + } + + public static void setRelativeLayer(Transaction t, SurfaceControl surfaceControl, + SurfaceControl relativeTo, int z) { + t.setRelativeLayer(surfaceControl, relativeTo, z); + } + + @Deprecated + public static void setEarlyWakeup(Transaction t) { + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/UniversalSmartspaceUtils.java b/SystemUIShared/src/com/android/systemui/shared/system/UniversalSmartspaceUtils.java new file mode 100644 index 0000000000..359d36939b --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/UniversalSmartspaceUtils.java @@ -0,0 +1,44 @@ +/* + * 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.system; + +import android.content.Intent; +import android.os.Bundle; +import android.view.SurfaceView; + +/** Utility class that is shared between SysUI and Launcher for Universal Smartspace features. */ +public final class UniversalSmartspaceUtils { + public static final String ACTION_REQUEST_SMARTSPACE_VIEW = + "com.android.systemui.REQUEST_SMARTSPACE_VIEW"; + public static final String INTENT_BUNDLE_KEY = "bundle_key"; + + private static final String SYSUI_PACKAGE = "com.android.systemui"; + + /** Creates an intent to request that sysui draws the Smartspace to the SurfaceView. */ + public static Intent createRequestSmartspaceIntent(SurfaceView surfaceView) { + Intent intent = new Intent(ACTION_REQUEST_SMARTSPACE_VIEW); + + Bundle bundle = SurfaceViewRequestUtils.createSurfaceBundle(surfaceView); + return intent + .putExtra(INTENT_BUNDLE_KEY, bundle) + .setPackage(SYSUI_PACKAGE) + .addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY + | Intent.FLAG_RECEIVER_FOREGROUND); + } + + private UniversalSmartspaceUtils() {} +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/ViewRootImplCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/ViewRootImplCompat.java new file mode 100644 index 0000000000..73783ae7ec --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/ViewRootImplCompat.java @@ -0,0 +1,63 @@ +/* + * 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.system; + +import android.graphics.HardwareRenderer; +import android.view.SurfaceControl; +import android.view.View; +import android.view.ViewRootImpl; + +import java.util.function.LongConsumer; + +/** + * Helper class to expose some ViewRoomImpl methods + */ +public class ViewRootImplCompat { + + private final ViewRootImpl mViewRoot; + + public ViewRootImplCompat(View view) { + mViewRoot = view == null ? null : view.getViewRootImpl(); + } + + public SurfaceControl getRenderSurfaceControl() { + return mViewRoot == null ? null : mViewRoot.getRenderSurfaceControl(); + } + + public SurfaceControl getSurfaceControl() { + return mViewRoot == null ? null : mViewRoot.getSurfaceControl(); + } + + public boolean isValid() { + return mViewRoot != null; + } + + public View getView() { + return mViewRoot == null ? null : mViewRoot.getView(); + } + + public void registerRtFrameCallback(LongConsumer callback) { + if (mViewRoot != null) { + mViewRoot.registerRtFrameCallback( + new HardwareRenderer.FrameDrawingCallback() { + @Override + public void onFrameDraw(long l) { + callback.accept(l); + } + }); + } + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/WallpaperEngineCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/WallpaperEngineCompat.java new file mode 100644 index 0000000000..73dc60dbc7 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/WallpaperEngineCompat.java @@ -0,0 +1,56 @@ +/* + * 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.system; + +import android.graphics.Rect; +import android.service.wallpaper.IWallpaperEngine; +import android.util.Log; + +/** + * @see IWallpaperEngine + */ +public class WallpaperEngineCompat { + + private static final String TAG = "WallpaperEngineCompat"; + + /** + * Returns true if {@link IWallpaperEngine#scalePreview(Rect)} is available. + */ + public static boolean supportsScalePreview() { + try { + return IWallpaperEngine.class.getMethod("scalePreview", Rect.class) != null; + } catch (NoSuchMethodException | SecurityException e) { + return false; + } + } + + private final IWallpaperEngine mWrappedEngine; + + public WallpaperEngineCompat(IWallpaperEngine wrappedEngine) { + mWrappedEngine = wrappedEngine; + } + + /** + * @see IWallpaperEngine#scalePreview(Rect) + */ + public void scalePreview(Rect scaleToRect) { + try { + mWrappedEngine.scalePreview(scaleToRect); + } catch (Exception e) { + Log.i(TAG, "Couldn't call scalePreview method on WallpaperEngine", e); + } + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/WallpaperManagerCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/WallpaperManagerCompat.java new file mode 100644 index 0000000000..1f194eca81 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/WallpaperManagerCompat.java @@ -0,0 +1,51 @@ +/* + * 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.system; + +import android.app.WallpaperManager; +import android.content.Context; +import android.content.res.Resources; +import android.os.IBinder; + +/** + * @see WallpaperManager + */ +public class WallpaperManagerCompat { + private final WallpaperManager mWallpaperManager; + + public WallpaperManagerCompat(Context context) { + mWallpaperManager = context.getSystemService(WallpaperManager.class); + } + + /** + * @see WallpaperManager#setWallpaperZoomOut(IBinder, float) + */ + public void setWallpaperZoomOut(IBinder windowToken, float zoom) { + mWallpaperManager.setWallpaperZoomOut(windowToken, zoom); + } + + /** + * @return the max scale for the wallpaper when it's fully zoomed out + */ + public static float getWallpaperZoomOutMaxScale(Context context) { + return context.getResources() + .getFloat(Resources.getSystem().getIdentifier( + /* name= */ "config_wallpaperMaxScale", + /* defType= */ "dimen", + /* defPackage= */ "android")); + } +} \ No newline at end of file diff --git a/SystemUIShared/src/com/android/systemui/shared/system/WindowCallbacksCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/WindowCallbacksCompat.java new file mode 100644 index 0000000000..de2a3e4484 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/WindowCallbacksCompat.java @@ -0,0 +1,109 @@ +/* + * 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.system; + +import android.graphics.Canvas; +import android.graphics.Rect; +import android.graphics.RecordingCanvas; +import android.view.View; +import android.view.ViewRootImpl; +import android.view.WindowCallbacks; + +public class WindowCallbacksCompat { + + private final WindowCallbacks mWindowCallbacks = new WindowCallbacks() { + @Override + public void onWindowSizeIsChanging(Rect newBounds, boolean fullscreen, Rect systemInsets, + Rect stableInsets) { + WindowCallbacksCompat.this.onWindowSizeIsChanging(newBounds, fullscreen, systemInsets, + stableInsets); + } + + @Override + public void onWindowDragResizeStart(Rect initialBounds, boolean fullscreen, + Rect systemInsets, Rect stableInsets, int resizeMode) { + WindowCallbacksCompat.this.onWindowDragResizeStart(initialBounds, fullscreen, + systemInsets, stableInsets, resizeMode); + } + + @Override + public void onWindowDragResizeEnd() { + WindowCallbacksCompat.this.onWindowDragResizeEnd(); + } + + @Override + public boolean onContentDrawn(int offsetX, int offsetY, int sizeX, int sizeY) { + return WindowCallbacksCompat.this.onContentDrawn(offsetX, offsetY, sizeX, sizeY); + } + + @Override + public void onRequestDraw(boolean reportNextDraw) { + WindowCallbacksCompat.this.onRequestDraw(reportNextDraw); + } + + @Override + public void onPostDraw(RecordingCanvas canvas) { + WindowCallbacksCompat.this.onPostDraw(canvas); + } + }; + + private final View mView; + + public WindowCallbacksCompat(View view) { + mView = view; + } + + public void onWindowSizeIsChanging(Rect newBounds, boolean fullscreen, Rect systemInsets, + Rect stableInsets) { } + + public void onWindowDragResizeStart(Rect initialBounds, boolean fullscreen, Rect systemInsets, + Rect stableInsets, int resizeMode) { } + + public void onWindowDragResizeEnd() { } + + public boolean onContentDrawn(int offsetX, int offsetY, int sizeX, int sizeY) { + return false; + } + + public void onRequestDraw(boolean reportNextDraw) { + if (reportNextDraw) { + reportDrawFinish(); + } + } + + public void onPostDraw(Canvas canvas) { } + + public void reportDrawFinish() { + mView.getViewRootImpl().reportDrawFinish(); + } + + public boolean attach() { + ViewRootImpl root = mView.getViewRootImpl(); + if (root != null) { + root.addWindowCallbacks(mWindowCallbacks); + root.requestInvalidateRootRenderNode(); + return true; + } + return false; + } + + public void detach() { + ViewRootImpl root = mView.getViewRootImpl(); + if (root != null) { + root.removeWindowCallbacks(mWindowCallbacks); + } + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/WindowManagerWrapper.java b/SystemUIShared/src/com/android/systemui/shared/system/WindowManagerWrapper.java new file mode 100644 index 0000000000..d64bf77ad9 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/system/WindowManagerWrapper.java @@ -0,0 +1,228 @@ +/* + * 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.system; + +import static android.view.Display.DEFAULT_DISPLAY; +import static android.view.WindowManagerPolicyConstants.NAV_BAR_BOTTOM; +import static android.view.WindowManagerPolicyConstants.NAV_BAR_INVALID; +import static android.view.WindowManagerPolicyConstants.NAV_BAR_LEFT; +import static android.view.WindowManagerPolicyConstants.NAV_BAR_RIGHT; + +import android.app.WindowConfiguration; +import android.graphics.Rect; +import android.os.Handler; +import android.os.RemoteException; +import android.util.Log; +import android.view.SurfaceControl; +import android.view.WindowManager; +import android.view.WindowManagerGlobal; + +import com.android.systemui.shared.recents.view.AppTransitionAnimationSpecsFuture; +import com.android.systemui.shared.recents.view.RecentsTransition; +import com.android.systemui.shared.system.PinnedStackListenerForwarder.PinnedStackListener; + +public class WindowManagerWrapper { + + private static final String TAG = "WindowManagerWrapper"; + + public static final int TRANSIT_UNSET = WindowManager.TRANSIT_UNSET; + public static final int TRANSIT_NONE = WindowManager.TRANSIT_NONE; + public static final int TRANSIT_ACTIVITY_OPEN = WindowManager.TRANSIT_ACTIVITY_OPEN; + public static final int TRANSIT_ACTIVITY_CLOSE = WindowManager.TRANSIT_ACTIVITY_CLOSE; + public static final int TRANSIT_TASK_OPEN = WindowManager.TRANSIT_TASK_OPEN; + public static final int TRANSIT_TASK_CLOSE = WindowManager.TRANSIT_TASK_CLOSE; + public static final int TRANSIT_TASK_TO_FRONT = WindowManager.TRANSIT_TASK_TO_FRONT; + public static final int TRANSIT_TASK_TO_BACK = WindowManager.TRANSIT_TASK_TO_BACK; + public static final int TRANSIT_WALLPAPER_CLOSE = WindowManager.TRANSIT_WALLPAPER_CLOSE; + public static final int TRANSIT_WALLPAPER_OPEN = WindowManager.TRANSIT_WALLPAPER_OPEN; + public static final int TRANSIT_WALLPAPER_INTRA_OPEN = + WindowManager.TRANSIT_WALLPAPER_INTRA_OPEN; + public static final int TRANSIT_WALLPAPER_INTRA_CLOSE = + WindowManager.TRANSIT_WALLPAPER_INTRA_CLOSE; + public static final int TRANSIT_TASK_OPEN_BEHIND = WindowManager.TRANSIT_TASK_OPEN_BEHIND; + public static final int TRANSIT_ACTIVITY_RELAUNCH = WindowManager.TRANSIT_ACTIVITY_RELAUNCH; + public static final int TRANSIT_DOCK_TASK_FROM_RECENTS = + WindowManager.TRANSIT_DOCK_TASK_FROM_RECENTS; + public static final int TRANSIT_KEYGUARD_GOING_AWAY = WindowManager.TRANSIT_KEYGUARD_GOING_AWAY; + public static final int TRANSIT_KEYGUARD_GOING_AWAY_ON_WALLPAPER = + WindowManager.TRANSIT_KEYGUARD_GOING_AWAY_ON_WALLPAPER; + public static final int TRANSIT_KEYGUARD_OCCLUDE = WindowManager.TRANSIT_KEYGUARD_OCCLUDE; + public static final int TRANSIT_KEYGUARD_UNOCCLUDE = WindowManager.TRANSIT_KEYGUARD_UNOCCLUDE; + + public static final int NAV_BAR_POS_INVALID = NAV_BAR_INVALID; + public static final int NAV_BAR_POS_LEFT = NAV_BAR_LEFT; + public static final int NAV_BAR_POS_RIGHT = NAV_BAR_RIGHT; + public static final int NAV_BAR_POS_BOTTOM = NAV_BAR_BOTTOM; + + public static final int ACTIVITY_TYPE_STANDARD = WindowConfiguration.ACTIVITY_TYPE_STANDARD; + + public static final int WINDOWING_MODE_UNDEFINED = WindowConfiguration.WINDOWING_MODE_UNDEFINED; + public static final int WINDOWING_MODE_FULLSCREEN = + WindowConfiguration.WINDOWING_MODE_FULLSCREEN; + public static final int WINDOWING_MODE_MULTI_WINDOW = + WindowConfiguration.WINDOWING_MODE_MULTI_WINDOW; + public static final int WINDOWING_MODE_PINNED = WindowConfiguration.WINDOWING_MODE_PINNED; + public static final int WINDOWING_MODE_SPLIT_SCREEN_PRIMARY = + WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY; + public static final int WINDOWING_MODE_SPLIT_SCREEN_SECONDARY = + WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY; + public static final int WINDOWING_MODE_FREEFORM = WindowConfiguration.WINDOWING_MODE_FREEFORM; + + private static final WindowManagerWrapper sInstance = new WindowManagerWrapper(); + + /** + * Forwarder to which we can add multiple pinned stack listeners. Each listener will receive + * updates from the window manager service. + */ + private PinnedStackListenerForwarder mPinnedStackListenerForwarder = + new PinnedStackListenerForwarder(); + + public static WindowManagerWrapper getInstance() { + return sInstance; + } + + /** + * @return the stable insets for the primary display. + */ + public void getStableInsets(Rect outStableInsets) { + try { + WindowManagerGlobal.getWindowManagerService().getStableInsets(DEFAULT_DISPLAY, + outStableInsets); + } catch (RemoteException e) { + Log.e(TAG, "Failed to get stable insets", e); + } + } + + /** + * Overrides a pending app transition. + */ + public void overridePendingAppTransitionMultiThumbFuture( + AppTransitionAnimationSpecsFuture animationSpecFuture, Runnable animStartedCallback, + Handler animStartedCallbackHandler, boolean scaleUp, int displayId) { + try { + WindowManagerGlobal.getWindowManagerService() + .overridePendingAppTransitionMultiThumbFuture(animationSpecFuture.getFuture(), + RecentsTransition.wrapStartedListener(animStartedCallbackHandler, + animStartedCallback), scaleUp, displayId); + } catch (RemoteException e) { + Log.w(TAG, "Failed to override pending app transition (multi-thumbnail future): ", e); + } + } + + public void overridePendingAppTransitionRemote( + RemoteAnimationAdapterCompat remoteAnimationAdapter, int displayId) { + try { + WindowManagerGlobal.getWindowManagerService().overridePendingAppTransitionRemote( + remoteAnimationAdapter.getWrapped(), displayId); + } catch (RemoteException e) { + Log.w(TAG, "Failed to override pending app transition (remote): ", e); + } + } + + /** + * Enable or disable haptic feedback on the navigation bar buttons. + */ + public void setNavBarVirtualKeyHapticFeedbackEnabled(boolean enabled) { + try { + WindowManagerGlobal.getWindowManagerService() + .setNavBarVirtualKeyHapticFeedbackEnabled(enabled); + } catch (RemoteException e) { + Log.w(TAG, "Failed to enable or disable navigation bar button haptics: ", e); + } + } + + public void setRecentsVisibility(boolean visible) { + try { + WindowManagerGlobal.getWindowManagerService().setRecentsVisibility(visible); + } catch (RemoteException e) { + Log.w(TAG, "Failed to set recents visibility"); + } + } + + public void setPipVisibility(final boolean visible) { + try { + WindowManagerGlobal.getWindowManagerService().setPipVisibility(visible); + } catch (RemoteException e) { + Log.e(TAG, "Unable to reach window manager", e); + } + } + + /** + * @param displayId the id of display to check if there is a software navigation bar. + * + * @return whether there is a soft nav bar on specific display. + */ + public boolean hasSoftNavigationBar(int displayId) { + try { + return WindowManagerGlobal.getWindowManagerService().hasNavigationBar(displayId); + } catch (RemoteException e) { + return false; + } + } + + /** + * @return The side of the screen where navigation bar is positioned. + * @see #NAV_BAR_POS_RIGHT + * @see #NAV_BAR_POS_LEFT + * @see #NAV_BAR_POS_BOTTOM + * @see #NAV_BAR_POS_INVALID + */ + public int getNavBarPosition(int displayId) { + try { + return WindowManagerGlobal.getWindowManagerService().getNavBarPosition(displayId); + } catch (RemoteException e) { + Log.w(TAG, "Failed to get nav bar position"); + } + return NAV_BAR_POS_INVALID; + } + + /** + * Adds a pinned stack listener, which will receive updates from the window manager service + * along with any other pinned stack listeners that were added via this method. + */ + public void addPinnedStackListener(PinnedStackListener listener) throws RemoteException { + mPinnedStackListenerForwarder.addListener(listener); + WindowManagerGlobal.getWindowManagerService().registerPinnedStackListener( + DEFAULT_DISPLAY, mPinnedStackListenerForwarder); + } + + /** + * Removes a pinned stack listener. + */ + public void removePinnedStackListener(PinnedStackListener listener) { + mPinnedStackListenerForwarder.removeListener(listener); + } + + /** + * Mirrors a specified display. The SurfaceControl returned is the root of the mirrored + * hierarchy. + * + * @param displayId The id of the display to mirror + * @return The SurfaceControl for the root of the mirrored hierarchy. + */ + public SurfaceControl mirrorDisplay(final int displayId) { + try { + SurfaceControl outSurfaceControl = new SurfaceControl(); + WindowManagerGlobal.getWindowManagerService().mirrorDisplay(displayId, + outSurfaceControl); + return outSurfaceControl; + } catch (RemoteException e) { + Log.e(TAG, "Unable to reach window manager", e); + } + return null; + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/tracing/FrameProtoTracer.java b/SystemUIShared/src/com/android/systemui/shared/tracing/FrameProtoTracer.java new file mode 100644 index 0000000000..356e0ca719 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/tracing/FrameProtoTracer.java @@ -0,0 +1,190 @@ +/* + * Copyright (C) 2019 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.tracing; + +import android.os.Trace; +import android.util.Log; +import android.view.Choreographer; + +import com.android.internal.util.TraceBuffer; + +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; +import java.util.function.Consumer; + +/** + * A proto tracer implementation that can be updated directly (upon state change), or on the next + * scheduled frame. + * + * @param

The class type of the proto provider + * @param The proto class type of the encapsulating proto + * @param The proto class type of the individual proto entries in the buffer + * @param The proto class type of the entry root proto in the buffer + */ +public class FrameProtoTracer + implements Choreographer.FrameCallback { + + private static final String TAG = "FrameProtoTracer"; + private static final int BUFFER_CAPACITY = 1024 * 1024; + + private final Object mLock = new Object(); + private final TraceBuffer mBuffer; + private final File mTraceFile; + private final ProtoTraceParams mParams; + private final Choreographer mChoreographer; + private final Queue mPool = new LinkedList<>(); + private final ArrayList> mTraceables = new ArrayList<>(); + private final ArrayList> mTmpTraceables = new ArrayList<>(); + + private volatile boolean mEnabled; + private boolean mFrameScheduled; + + private final TraceBuffer.ProtoProvider mProvider = + new TraceBuffer.ProtoProvider() { + @Override + public int getItemSize(P proto) { + return mParams.getProtoSize(proto); + } + + @Override + public byte[] getBytes(P proto) { + return mParams.getProtoBytes(proto); + } + + @Override + public void write(S encapsulatingProto, Queue buffer, OutputStream os) + throws IOException { + os.write(mParams.serializeEncapsulatingProto(encapsulatingProto, buffer)); + } + }; + + public interface ProtoTraceParams { + File getTraceFile(); + S getEncapsulatingTraceProto(); + T updateBufferProto(T reuseObj, ArrayList> traceables); + byte[] serializeEncapsulatingProto(S encapsulatingProto, Queue buffer); + byte[] getProtoBytes(P proto); + int getProtoSize(P proto); + } + + public FrameProtoTracer(ProtoTraceParams params) { + mParams = params; + mBuffer = new TraceBuffer<>(BUFFER_CAPACITY, mProvider, new Consumer() { + @Override + public void accept(T t) { + onProtoDequeued(t); + } + }); + mTraceFile = params.getTraceFile(); + mChoreographer = Choreographer.getMainThreadInstance(); + } + + public void start() { + synchronized (mLock) { + if (mEnabled) { + return; + } + mBuffer.resetBuffer(); + mEnabled = true; + } + logState(); + } + + public void stop() { + synchronized (mLock) { + if (!mEnabled) { + return; + } + mEnabled = false; + } + writeToFile(); + } + + public boolean isEnabled() { + return mEnabled; + } + + public void add(ProtoTraceable traceable) { + synchronized (mLock) { + mTraceables.add(traceable); + } + } + + public void remove(ProtoTraceable traceable) { + synchronized (mLock) { + mTraceables.remove(traceable); + } + } + + public void scheduleFrameUpdate() { + if (!mEnabled || mFrameScheduled) { + return; + } + + // Schedule an update on the next frame + mChoreographer.postFrameCallback(this); + mFrameScheduled = true; + } + + public void update() { + if (!mEnabled) { + return; + } + + logState(); + } + + public float getBufferUsagePct() { + return (float) mBuffer.getBufferSize() / BUFFER_CAPACITY; + } + + @Override + public void doFrame(long frameTimeNanos) { + logState(); + } + + private void onProtoDequeued(T proto) { + mPool.add(proto); + } + + private void logState() { + synchronized (mLock) { + mTmpTraceables.addAll(mTraceables); + } + + mBuffer.add(mParams.updateBufferProto(mPool.poll(), mTmpTraceables)); + mTmpTraceables.clear(); + mFrameScheduled = false; + } + + private void writeToFile() { + try { + Trace.beginSection("ProtoTracer.writeToFile"); + mBuffer.writeTraceToFile(mTraceFile, mParams.getEncapsulatingTraceProto()); + } catch (IOException e) { + Log.e(TAG, "Unable to write buffer to file", e); + } finally { + Trace.endSection(); + } + } +} + + diff --git a/SystemUIShared/src/com/android/systemui/shared/tracing/ProtoTraceable.java b/SystemUIShared/src/com/android/systemui/shared/tracing/ProtoTraceable.java new file mode 100644 index 0000000000..e05b0b0744 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/tracing/ProtoTraceable.java @@ -0,0 +1,26 @@ +/* + * 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.tracing; + +/** + * @see FrameProtoTracer + */ +public interface ProtoTraceable { + + /** + * NOTE: Implementations should update all fields in this proto. + */ + void writeToProto(T proto); +} diff --git a/build.gradle b/build.gradle index 5d2fe6dc07..5372b243c3 100644 --- a/build.gradle +++ b/build.gradle @@ -264,7 +264,7 @@ dependencies { implementation fileTree(dir: "${FRAMEWORK_PREBUILTS_DIR}/libs", include: 'sysui_statslog.jar') // Recents lib dependency - withQuickstepImplementation fileTree(dir: "${FRAMEWORK_PREBUILTS_DIR}/libs", include: 'sysui_shared.jar') + withQuickstepImplementation project(':SystemUIShared') // Required for AOSP to compile. This is already included in the sysui_shared.jar withoutQuickstepImplementation fileTree(dir: "${FRAMEWORK_PREBUILTS_DIR}/libs", include: 'plugin_core.jar') diff --git a/settings.gradle b/settings.gradle index 313f363b91..7f11638c86 100644 --- a/settings.gradle +++ b/settings.gradle @@ -2,4 +2,5 @@ include ':IconLoader' project(':IconLoader').projectDir = new File(rootDir, 'IconLoader/iconloaderlib') include ':SharedLibWrapper' -project(':SharedLibWrapper').projectDir = new File(rootDir, 'SharedLibWrapper') \ No newline at end of file +project(':SharedLibWrapper').projectDir = new File(rootDir, 'SharedLibWrapper') +include ':SystemUIShared'