Merge "Revert "Show all apps app names in multi window landscape"" into ub-launcher3-master
diff --git a/Android.bp b/Android.bp
index fc99880..e132854 100644
--- a/Android.bp
+++ b/Android.bp
@@ -32,7 +32,7 @@
}
java_library_static {
- name: "launcher-log-protos-lite",
+ name: "launcher_log_protos_lite",
srcs: [
"protos/*.proto",
"proto_overrides/*.proto",
@@ -45,4 +45,16 @@
"proto_overrides",
],
},
+ static_libs: ["libprotobuf-java-lite"],
+}
+
+java_library {
+ name: "LauncherPluginLib",
+
+ static_libs: ["PluginCoreLib"],
+
+ srcs: ["src_plugins/**/*.java"],
+
+ sdk_version: "current",
+ min_sdk_version: "28",
}
diff --git a/Android.mk b/Android.mk
index 66ccae0..9cfcf17 100644
--- a/Android.mk
+++ b/Android.mk
@@ -17,24 +17,6 @@
LOCAL_PATH := $(call my-dir)
#
-# Build rule for plugin lib (needed to write a plugin).
-#
-include $(CLEAR_VARS)
-LOCAL_USE_AAPT2 := true
-LOCAL_AAPT2_ONLY := true
-LOCAL_MODULE_TAGS := optional
-LOCAL_STATIC_JAVA_LIBRARIES:= PluginCoreLib
-
-LOCAL_SRC_FILES := \
- $(call all-java-files-under, src_plugins)
-
-LOCAL_SDK_VERSION := current
-LOCAL_MIN_SDK_VERSION := 28
-LOCAL_MODULE := LauncherPluginLib
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
-
-#
# Build rule for Launcher3 dependencies lib.
#
include $(CLEAR_VARS)
@@ -48,7 +30,9 @@
androidx.preference_preference \
iconloader_base
-LOCAL_STATIC_JAVA_LIBRARIES := LauncherPluginLib
+LOCAL_STATIC_JAVA_LIBRARIES := \
+ LauncherPluginLib \
+ launcher_log_protos_lite
LOCAL_SRC_FILES := \
$(call all-proto-files-under, protos) \
@@ -144,7 +128,10 @@
LOCAL_AAPT2_ONLY := true
LOCAL_MODULE_TAGS := optional
-LOCAL_STATIC_JAVA_LIBRARIES := SystemUISharedLib launcherprotosnano
+LOCAL_STATIC_JAVA_LIBRARIES := \
+ SystemUISharedLib \
+ launcherprotosnano \
+ launcher_log_protos_lite
ifneq (,$(wildcard frameworks/base))
LOCAL_PRIVATE_PLATFORM_APIS := true
else
@@ -213,7 +200,10 @@
LOCAL_USE_AAPT2 := true
LOCAL_MODULE_TAGS := optional
-LOCAL_STATIC_JAVA_LIBRARIES := SystemUISharedLib launcherprotosnano
+LOCAL_STATIC_JAVA_LIBRARIES := \
+ SystemUISharedLib \
+ launcherprotosnano \
+ launcher_log_protos_lite
ifneq (,$(wildcard frameworks/base))
LOCAL_PRIVATE_PLATFORM_APIS := true
else
diff --git a/AndroidManifest-common.xml b/AndroidManifest-common.xml
index 26698eb..d7191b4 100644
--- a/AndroidManifest-common.xml
+++ b/AndroidManifest-common.xml
@@ -44,8 +44,11 @@
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
<uses-permission android:name="android.permission.READ_DEVICE_CONFIG" />
+ <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />
-
+ <!-- TODO(b/150802536): Enabled only for ENABLE_FIXED_ROTATION_TRANSFORM feature flag -->
+ <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>
+
<!--
Permissions required for read/write access to the workspace data. These permission name
should not conflict with that defined in other apps, as such an app should embed its package
@@ -70,6 +73,7 @@
<application
android:backupAgent="com.android.launcher3.LauncherBackupAgent"
android:fullBackupOnly="true"
+ android:backupInForeground="true"
android:fullBackupContent="@xml/backupscheme"
android:hardwareAccelerated="true"
android:icon="@drawable/ic_launcher_home"
@@ -134,14 +138,6 @@
</activity>
<!--
- Should point to the content provider which can be used to dump Launcher3 compatible
- worspace configuration to the dump's file descriptor by using launcher_dump.proto
- -->
- <meta-data
- android:name="com.android.launcher3.launcher_dump_provider"
- android:value="com.android.launcher3.LauncherProvider" />
-
- <!--
The settings provider contains Home's data, like the workspace favorites. The permissions
should be changed to what is defined above. The authorities should also be changed to
represent the package name.
diff --git a/OWNERS b/OWNERS
index 7340e84..3069afa 100644
--- a/OWNERS
+++ b/OWNERS
@@ -8,9 +8,26 @@
hyunyoungs@google.com
mrcasey@google.com
sunnygoyal@google.com
+awickham@google.com
twickham@google.com
winsonc@google.com
zakcohen@google.com
+santie@google.com
+vadimt@google.com
+mett@google.com
+jonmiranda@google.com
+pinyaoting@google.com
+sfufa@google.com
+gwasserman@google.com
+jamesoleary@google.com
+joshtrask@google.com
+mrenouf@google.com
+mkephart@google.com
+hwwang@google.com
+tracyzhou@google.com
+peanutbutter@google.com
+xuqiu@google.com
+sreyasr@google.com
-per-file FeatureFlags.java = sunnygoyal@google.com, adamcohen@google.com
-per-file BaseFlags.java = sunnygoyal@google.com, adamcohen@google.com
+per-file FeatureFlags.java, globs = set noparent
+per-file FeatureFlags.java = sunnygoyal@google.com, winsonc@google.com, zakcohen@google.com, mrcasey@google.com, adamcohen@google.com, hyunyoungs@google.com
diff --git a/SecondaryDisplayLauncher/Android.mk b/SecondaryDisplayLauncher/Android.mk
deleted file mode 100644
index 7f305bb..0000000
--- a/SecondaryDisplayLauncher/Android.mk
+++ /dev/null
@@ -1,39 +0,0 @@
-#
-# 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.
-#
-
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_USE_AAPT2 := true
-LOCAL_AAPT2_ONLY := true
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_STATIC_ANDROID_LIBRARIES := com.google.android.material_material
-
-LOCAL_STATIC_JAVA_LIBRARIES := LauncherPluginLib
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
-
-LOCAL_PROGUARD_ENABLED := disabled
-
-LOCAL_SDK_VERSION := current
-LOCAL_MIN_SDK_VERSION := 21
-LOCAL_MODULE := SecondaryDisplayLauncherLib
-LOCAL_PRIVILEGED_MODULE := true
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
diff --git a/SecondaryDisplayLauncher/AndroidManifest.xml b/SecondaryDisplayLauncher/AndroidManifest.xml
deleted file mode 100644
index ebf6b02..0000000
--- a/SecondaryDisplayLauncher/AndroidManifest.xml
+++ /dev/null
@@ -1,40 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-**
-** Copyright 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.
-*/
--->
-<manifest
- xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.launcher3">
-
- <application>
-
- <activity
- android:name="com.android.launcher3.SecondaryDisplayLauncher"
- android:theme="@style/SecondaryLauncherTheme"
- android:launchMode="singleTop"
- android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|colorMode|density"
- android:enabled="true">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.SECONDARY_HOME" />
- <category android:name="android.intent.category.DEFAULT" />
- </intent-filter>
- </activity>
-
- </application>
-</manifest>
diff --git a/SecondaryDisplayLauncher/res/drawable/ic_apps.xml b/SecondaryDisplayLauncher/res/drawable/ic_apps.xml
deleted file mode 100644
index db779c2..0000000
--- a/SecondaryDisplayLauncher/res/drawable/ic_apps.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- ~ 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.
- -->
-
-<vector android:height="24dp" android:tint="#FFFFFF"
- android:viewportHeight="24.0" android:viewportWidth="24.0"
- android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
- <path android:fillColor="#FF000000" android:pathData="M4,8h4L8,4L4,4v4zM10,20h4v-4h-4v4zM4,20h4v-4L4,16v4zM4,14h4v-4L4,10v4zM10,14h4v-4h-4v4zM16,4v4h4L20,4h-4zM10,8h4L14,4h-4v4zM16,14h4v-4h-4v4zM16,20h4v-4h-4v4z"/>
-</vector>
diff --git a/SecondaryDisplayLauncher/res/drawable/ic_settings.xml b/SecondaryDisplayLauncher/res/drawable/ic_settings.xml
deleted file mode 100644
index c269c3b..0000000
--- a/SecondaryDisplayLauncher/res/drawable/ic_settings.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- ~ 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.
- -->
-
-<vector android:height="24dp" android:tint="#FFFFFF"
- android:viewportHeight="24.0" android:viewportWidth="24.0"
- android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
- <path android:fillColor="#FF000000" android:pathData="M19.43,12.98c0.04,-0.32 0.07,-0.64 0.07,-0.98s-0.03,-0.66 -0.07,-0.98l2.11,-1.65c0.19,-0.15 0.24,-0.42 0.12,-0.64l-2,-3.46c-0.12,-0.22 -0.39,-0.3 -0.61,-0.22l-2.49,1c-0.52,-0.4 -1.08,-0.73 -1.69,-0.98l-0.38,-2.65C14.46,2.18 14.25,2 14,2h-4c-0.25,0 -0.46,0.18 -0.49,0.42l-0.38,2.65c-0.61,0.25 -1.17,0.59 -1.69,0.98l-2.49,-1c-0.23,-0.09 -0.49,0 -0.61,0.22l-2,3.46c-0.13,0.22 -0.07,0.49 0.12,0.64l2.11,1.65c-0.04,0.32 -0.07,0.65 -0.07,0.98s0.03,0.66 0.07,0.98l-2.11,1.65c-0.19,0.15 -0.24,0.42 -0.12,0.64l2,3.46c0.12,0.22 0.39,0.3 0.61,0.22l2.49,-1c0.52,0.4 1.08,0.73 1.69,0.98l0.38,2.65c0.03,0.24 0.24,0.42 0.49,0.42h4c0.25,0 0.46,-0.18 0.49,-0.42l0.38,-2.65c0.61,-0.25 1.17,-0.59 1.69,-0.98l2.49,1c0.23,0.09 0.49,0 0.61,-0.22l2,-3.46c0.12,-0.22 0.07,-0.49 -0.12,-0.64l-2.11,-1.65zM12,15.5c-1.93,0 -3.5,-1.57 -3.5,-3.5s1.57,-3.5 3.5,-3.5 3.5,1.57 3.5,3.5 -1.57,3.5 -3.5,3.5z"/>
-</vector>
diff --git a/SecondaryDisplayLauncher/res/layout-sw600dp/secondary_display_launcher.xml b/SecondaryDisplayLauncher/res/layout-sw600dp/secondary_display_launcher.xml
deleted file mode 100644
index 46f1674..0000000
--- a/SecondaryDisplayLauncher/res/layout-sw600dp/secondary_display_launcher.xml
+++ /dev/null
@@ -1,56 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- ~ 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.
- -->
-
-<androidx.coordinatorlayout.widget.CoordinatorLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/RootView"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="@color/launcher_bg_color"
- android:fitsSystemWindows="true" >
-
- <GridView
- android:id="@+id/pinned_app_grid"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:layout_marginTop="@dimen/app_grid_margin_top"
- android:layout_marginStart="@dimen/app_grid_margin_left"
- android:layout_marginEnd="@dimen/app_grid_margin_right"
- android:columnWidth="@dimen/app_list_col_width"
- android:verticalSpacing="@dimen/app_list_horizontal_spacing"
- android:horizontalSpacing="@dimen/app_list_vertical_spacing"
- android:numColumns="auto_fit" />
-
- <ImageButton
- android:id="@+id/OptionsButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="bottom|start"
- android:layout_marginStart="@dimen/options_button_margin"
- android:layout_marginBottom="@dimen/options_button_margin"
- android:src="@drawable/ic_settings"
- android:background="@null"/>
-
- <FrameLayout
- android:layout_width="@dimen/app_picker_width"
- android:layout_height="@dimen/app_picker_height"
- android:layout_gravity="bottom|end"
- android:layout_margin="@dimen/app_picker_fab_margin">
-
- <include layout="@layout/app_picker_layout"/>
- </FrameLayout>
-</androidx.coordinatorlayout.widget.CoordinatorLayout>
diff --git a/SecondaryDisplayLauncher/res/layout-sw720dp/secondary_display_launcher.xml b/SecondaryDisplayLauncher/res/layout-sw720dp/secondary_display_launcher.xml
deleted file mode 100644
index 6653a77..0000000
--- a/SecondaryDisplayLauncher/res/layout-sw720dp/secondary_display_launcher.xml
+++ /dev/null
@@ -1,57 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- ~ 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.
- -->
-
-<androidx.coordinatorlayout.widget.CoordinatorLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/RootView"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="@color/launcher_bg_color"
- android:fitsSystemWindows="true" >
-
- <GridView
- android:id="@+id/pinned_app_grid"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:layout_marginTop="@dimen/app_grid_margin_top"
- android:layout_marginStart="@dimen/app_grid_margin_left"
- android:layout_marginEnd="@dimen/app_grid_margin_right"
- android:columnWidth="@dimen/app_list_col_width"
- android:verticalSpacing="@dimen/app_list_horizontal_spacing"
- android:horizontalSpacing="@dimen/app_list_vertical_spacing"
- android:numColumns="auto_fit" />
-
- <ImageButton
- android:id="@+id/OptionsButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="bottom|start"
- android:layout_marginStart="@dimen/options_button_margin"
- android:layout_marginBottom="@dimen/options_button_margin"
- android:src="@drawable/ic_settings"
- android:background="@null"/>
-
- <FrameLayout
- android:layout_width="@dimen/app_picker_width"
- android:layout_height="@dimen/app_picker_height"
- android:layout_gravity="bottom|end"
- android:layout_marginEnd="@dimen/app_picker_fab_margin"
- android:layout_marginBottom="@dimen/app_picker_fab_margin">
-
- <include layout="@layout/app_picker_layout"/>
- </FrameLayout>
-</androidx.coordinatorlayout.widget.CoordinatorLayout>
diff --git a/SecondaryDisplayLauncher/res/layout/app_grid_item.xml b/SecondaryDisplayLauncher/res/layout/app_grid_item.xml
deleted file mode 100644
index ee5158a..0000000
--- a/SecondaryDisplayLauncher/res/layout/app_grid_item.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- ~ 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.
- -->
-
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:gravity="center">
-
- <ImageView
- android:id="@+id/app_icon"
- android:layout_width="@dimen/app_icon_width"
- android:layout_height="@dimen/app_icon_height" />
-
- <TextView
- android:id="@+id/app_name"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:gravity="center"
- android:maxLines="1" />
-</LinearLayout>
diff --git a/SecondaryDisplayLauncher/res/layout/app_picker_dialog.xml b/SecondaryDisplayLauncher/res/layout/app_picker_dialog.xml
deleted file mode 100644
index 563a1af..0000000
--- a/SecondaryDisplayLauncher/res/layout/app_picker_dialog.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- ~ 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.
- -->
-
-<FrameLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
-
- <GridView
- android:id="@+id/picker_app_grid"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:layout_marginTop="@dimen/app_grid_margin_top"
- android:layout_marginStart="@dimen/app_grid_margin_left"
- android:layout_marginEnd="@dimen/app_grid_margin_right"
- android:columnWidth="@dimen/app_list_col_width"
- android:verticalSpacing="@dimen/app_list_horizontal_spacing"
- android:horizontalSpacing="@dimen/app_list_vertical_spacing"
- android:numColumns="auto_fit" />
-</FrameLayout>
diff --git a/SecondaryDisplayLauncher/res/layout/app_picker_layout.xml b/SecondaryDisplayLauncher/res/layout/app_picker_layout.xml
deleted file mode 100644
index 20f85b1..0000000
--- a/SecondaryDisplayLauncher/res/layout/app_picker_layout.xml
+++ /dev/null
@@ -1,46 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- ~ 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.
- -->
-
-<androidx.coordinatorlayout.widget.CoordinatorLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
-
- <com.google.android.material.circularreveal.cardview.CircularRevealCardView
- android:id="@+id/FloatingSheet"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:visibility="invisible">
-
- <GridView
- android:id="@+id/app_grid"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:layout_marginTop="@dimen/app_grid_margin_top"
- android:columnWidth="@dimen/app_list_col_width"
- android:verticalSpacing="@dimen/app_list_horizontal_spacing"
- android:horizontalSpacing="@dimen/app_list_vertical_spacing"
- android:numColumns="auto_fit" />
- </com.google.android.material.circularreveal.cardview.CircularRevealCardView>
-
- <com.google.android.material.floatingactionbutton.FloatingActionButton
- android:id="@+id/FloatingActionButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="bottom|end"
- android:src="@drawable/ic_apps"/>
-</androidx.coordinatorlayout.widget.CoordinatorLayout>
diff --git a/SecondaryDisplayLauncher/res/layout/secondary_display_launcher.xml b/SecondaryDisplayLauncher/res/layout/secondary_display_launcher.xml
deleted file mode 100644
index 49cd499..0000000
--- a/SecondaryDisplayLauncher/res/layout/secondary_display_launcher.xml
+++ /dev/null
@@ -1,56 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- ~ 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.
- -->
-
-<androidx.coordinatorlayout.widget.CoordinatorLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/RootView"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="@color/launcher_bg_color"
- android:fitsSystemWindows="true" >
-
- <GridView
- android:id="@+id/pinned_app_grid"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:layout_marginTop="@dimen/app_grid_margin_top"
- android:layout_marginStart="@dimen/app_grid_margin_left"
- android:layout_marginEnd="@dimen/app_grid_margin_right"
- android:columnWidth="@dimen/app_list_col_width"
- android:verticalSpacing="@dimen/app_list_horizontal_spacing"
- android:horizontalSpacing="@dimen/app_list_vertical_spacing"
- android:numColumns="auto_fit" />
-
- <ImageButton
- android:id="@+id/OptionsButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="bottom|start"
- android:layout_marginStart="@dimen/options_button_margin"
- android:layout_marginBottom="@dimen/options_button_margin"
- android:src="@drawable/ic_settings"
- android:background="@null"/>
-
- <FrameLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:layout_gravity="bottom|end"
- android:layout_margin="@dimen/app_picker_fab_margin">
-
- <include layout="@layout/app_picker_layout"/>
- </FrameLayout>
-</androidx.coordinatorlayout.widget.CoordinatorLayout>
diff --git a/SecondaryDisplayLauncher/res/menu/context_menu.xml b/SecondaryDisplayLauncher/res/menu/context_menu.xml
deleted file mode 100644
index 6263842..0000000
--- a/SecondaryDisplayLauncher/res/menu/context_menu.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- ~ 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.
- -->
-
-<menu xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:id="@+id/add_app_shortcut"
- android:title="@string/add_app_shortcut" />
- <item android:id="@+id/set_wallpaper"
- android:title="@string/set_wallpaper" />
-</menu>
diff --git a/SecondaryDisplayLauncher/res/values-af/strings.xml b/SecondaryDisplayLauncher/res/values-af/strings.xml
deleted file mode 100644
index b544be7a..0000000
--- a/SecondaryDisplayLauncher/res/values-af/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Kon nie die aktiwiteit begin nie"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Voeg programkortpad by"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Stel muurpapier"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-am/strings.xml b/SecondaryDisplayLauncher/res/values-am/strings.xml
deleted file mode 100644
index 71854ad..0000000
--- a/SecondaryDisplayLauncher/res/values-am/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"እንቅስቃሴውን ማስጀመር አልተቻለም"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"የመተግበሪያ አቋራጭ ያክሉ"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"ልጣፍ አዘጋጅ"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-ar/strings.xml b/SecondaryDisplayLauncher/res/values-ar/strings.xml
deleted file mode 100644
index ba81c11..0000000
--- a/SecondaryDisplayLauncher/res/values-ar/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"تعذَّر تشغيل النشاط."</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"إضافة اختصار التطبيق"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"تعيين الخلفية"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-as/strings.xml b/SecondaryDisplayLauncher/res/values-as/strings.xml
deleted file mode 100644
index d199a26..0000000
--- a/SecondaryDisplayLauncher/res/values-as/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"কাৰ্যকলাপটো লঞ্চ কৰিব পৰা নগ’ল"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"এপৰ শ্বর্টকাট যোগ কৰক"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"ৱালপেপাৰ ছেট কৰক"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-az/strings.xml b/SecondaryDisplayLauncher/res/values-az/strings.xml
deleted file mode 100644
index cee70a0..0000000
--- a/SecondaryDisplayLauncher/res/values-az/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Fəaliyyəti başlatmaq mümkün olmadı"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Tətbiq qısayolu əlavə edin"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Divar kağızı ayarlayın"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-b+sr+Latn/strings.xml b/SecondaryDisplayLauncher/res/values-b+sr+Latn/strings.xml
deleted file mode 100644
index a8859d9..0000000
--- a/SecondaryDisplayLauncher/res/values-b+sr+Latn/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Pokretanje aktivnosti nije uspelo"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Dodaj prečicu za aplikaciju"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Podesite pozadinu"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-be/strings.xml b/SecondaryDisplayLauncher/res/values-be/strings.xml
deleted file mode 100644
index 3df3760..0000000
--- a/SecondaryDisplayLauncher/res/values-be/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Не ўдалося запусціць дзеянне"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Дадаць ярлык праграмы"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Устанавіць шпалеры"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-bg/strings.xml b/SecondaryDisplayLauncher/res/values-bg/strings.xml
deleted file mode 100644
index 4474815..0000000
--- a/SecondaryDisplayLauncher/res/values-bg/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Активността не можа да бъде стартирана"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Добавяне на пряк път към приложението"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Задаване на тапет"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-bn/strings.xml b/SecondaryDisplayLauncher/res/values-bn/strings.xml
deleted file mode 100644
index 7322691..0000000
--- a/SecondaryDisplayLauncher/res/values-bn/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"অ্যাক্টিভিটি চালু করা যায়নি"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"অ্যাপ শর্টকাট যোগ করুন"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"ওয়ালপেপার সেট করুন"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-bs/strings.xml b/SecondaryDisplayLauncher/res/values-bs/strings.xml
deleted file mode 100644
index 1e59d33..0000000
--- a/SecondaryDisplayLauncher/res/values-bs/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Pokretanje aktivnosti nije uspjelo"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Dodaj prečicu aplikacije"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Postavi pozadinsku sliku"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-ca/strings.xml b/SecondaryDisplayLauncher/res/values-ca/strings.xml
deleted file mode 100644
index c0274d1..0000000
--- a/SecondaryDisplayLauncher/res/values-ca/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"No s\'ha pogut iniciar l\'activitat"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Afegeix una drecera d\'aplicació"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Estableix el fons de pantalla"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-cs/strings.xml b/SecondaryDisplayLauncher/res/values-cs/strings.xml
deleted file mode 100644
index 92ed5fa..0000000
--- a/SecondaryDisplayLauncher/res/values-cs/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Aktivitu nelze zahájit"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Přidat zkratku aplikace"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Nastavení tapety"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-da/strings.xml b/SecondaryDisplayLauncher/res/values-da/strings.xml
deleted file mode 100644
index 16bdb33..0000000
--- a/SecondaryDisplayLauncher/res/values-da/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Aktiviteten kunne ikke startes"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Tilføj appgenvej"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Angiv baggrund"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-de/strings.xml b/SecondaryDisplayLauncher/res/values-de/strings.xml
deleted file mode 100644
index 3617a5b..0000000
--- a/SecondaryDisplayLauncher/res/values-de/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Aktivität konnte nicht gestartet werden"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"App-Verknüpfung hinzufügen"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Hintergrund festlegen"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-el/strings.xml b/SecondaryDisplayLauncher/res/values-el/strings.xml
deleted file mode 100644
index 8d19d09..0000000
--- a/SecondaryDisplayLauncher/res/values-el/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Δεν ήταν δυνατή η εκκίνηση της δραστηριότητας"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Προσθήκη συντόμευσης εφαρμογής"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Ορισμός ταπετσαρίας"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-en-rAU/strings.xml b/SecondaryDisplayLauncher/res/values-en-rAU/strings.xml
deleted file mode 100644
index 8d8c419..0000000
--- a/SecondaryDisplayLauncher/res/values-en-rAU/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Couldn\'t launch the activity"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Add app shortcut"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Set wallpaper"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-en-rGB/strings.xml b/SecondaryDisplayLauncher/res/values-en-rGB/strings.xml
deleted file mode 100644
index 8d8c419..0000000
--- a/SecondaryDisplayLauncher/res/values-en-rGB/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Couldn\'t launch the activity"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Add app shortcut"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Set wallpaper"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-en-rIN/strings.xml b/SecondaryDisplayLauncher/res/values-en-rIN/strings.xml
deleted file mode 100644
index 8d8c419..0000000
--- a/SecondaryDisplayLauncher/res/values-en-rIN/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Couldn\'t launch the activity"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Add app shortcut"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Set wallpaper"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-es-rUS/strings.xml b/SecondaryDisplayLauncher/res/values-es-rUS/strings.xml
deleted file mode 100644
index ff6772b..0000000
--- a/SecondaryDisplayLauncher/res/values-es-rUS/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"No se pudo iniciar la actividad"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Agregar acceso directo a app"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Establecer fondo de pantalla"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-es/strings.xml b/SecondaryDisplayLauncher/res/values-es/strings.xml
deleted file mode 100644
index 0654dcb..0000000
--- a/SecondaryDisplayLauncher/res/values-es/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"No se ha podido iniciar la acción"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Añadir acceso directo a la aplicación"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Establecer fondo de pantalla"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-et/strings.xml b/SecondaryDisplayLauncher/res/values-et/strings.xml
deleted file mode 100644
index 3410fd4..0000000
--- a/SecondaryDisplayLauncher/res/values-et/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Tegevust ei saanud käivitada"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Lisa rakenduse otsetee"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Määra taustapilt"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-eu/strings.xml b/SecondaryDisplayLauncher/res/values-eu/strings.xml
deleted file mode 100644
index d7abe33..0000000
--- a/SecondaryDisplayLauncher/res/values-eu/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Ezin izan da abiarazi jarduera"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Gehitu aplikaziorako lasterbidea"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Ezarri horma-papera"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-fa/strings.xml b/SecondaryDisplayLauncher/res/values-fa/strings.xml
deleted file mode 100644
index 4d3ec4d..0000000
--- a/SecondaryDisplayLauncher/res/values-fa/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"فعالیت راهاندازی نشد"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"افزودن میانبر برنامه"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"تنظیم کاغذدیواری"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-fi/strings.xml b/SecondaryDisplayLauncher/res/values-fi/strings.xml
deleted file mode 100644
index e56f67a..0000000
--- a/SecondaryDisplayLauncher/res/values-fi/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Käynnistäminen epäonnistui"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Lisää sovelluksen pikakuvake"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Aseta taustakuva"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-fr-rCA/strings.xml b/SecondaryDisplayLauncher/res/values-fr-rCA/strings.xml
deleted file mode 100644
index f5c9ba5..0000000
--- a/SecondaryDisplayLauncher/res/values-fr-rCA/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Impossible de lancer l\'activité"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Ajouter un raccourci vers l\'application"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Définir le fond d\'écran"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-fr/strings.xml b/SecondaryDisplayLauncher/res/values-fr/strings.xml
deleted file mode 100644
index daa186b..0000000
--- a/SecondaryDisplayLauncher/res/values-fr/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Impossible de lancer l\'activité"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Ajouter un raccourci vers l\'application"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Configurer le fond d\'écran"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-gl/strings.xml b/SecondaryDisplayLauncher/res/values-gl/strings.xml
deleted file mode 100644
index 0bcf969..0000000
--- a/SecondaryDisplayLauncher/res/values-gl/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Non se puido iniciar a actividade"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Engadir atallo da aplicación"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Definir fondo de pantalla"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-gu/strings.xml b/SecondaryDisplayLauncher/res/values-gu/strings.xml
deleted file mode 100644
index 82b4444..0000000
--- a/SecondaryDisplayLauncher/res/values-gu/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"પ્રવૃત્તિ લૉન્ચ કરી શકાઈ નથી"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"ઍપ શૉર્ટકટ ઉમેરો"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"વૉલપેપર સેટ કરો"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-hi/strings.xml b/SecondaryDisplayLauncher/res/values-hi/strings.xml
deleted file mode 100644
index 8adb519..0000000
--- a/SecondaryDisplayLauncher/res/values-hi/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"गतिविधि लॉन्च नहीं हो सकी"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"ऐप्लिकेशन शॉर्टकट जोड़ें"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"वॉलपेपर सेट करें"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-hr/strings.xml b/SecondaryDisplayLauncher/res/values-hr/strings.xml
deleted file mode 100644
index 87ac874..0000000
--- a/SecondaryDisplayLauncher/res/values-hr/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Pokretanje aktivnosti nije uspjelo"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Dodajte aplikacijski prečac"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Postavljanje pozadine"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-hu/strings.xml b/SecondaryDisplayLauncher/res/values-hu/strings.xml
deleted file mode 100644
index a8870fc..0000000
--- a/SecondaryDisplayLauncher/res/values-hu/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Nem sikerült elindítani a tevékenységet"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Alkalmazás parancsikonjának hozzáadása"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Háttérkép beállítása"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-hy/strings.xml b/SecondaryDisplayLauncher/res/values-hy/strings.xml
deleted file mode 100644
index a64233f..0000000
--- a/SecondaryDisplayLauncher/res/values-hy/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Չհաջողվեց գործարկել գործողությունը"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Ավելացնել հավելվածի դյուրանցումը"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Դարձնել պաստառ"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-in/strings.xml b/SecondaryDisplayLauncher/res/values-in/strings.xml
deleted file mode 100644
index f51d238..0000000
--- a/SecondaryDisplayLauncher/res/values-in/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Tidak dapat meluncurkan aktivitas"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Tambahkan pintasan app"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Setel wallpaper"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-is/strings.xml b/SecondaryDisplayLauncher/res/values-is/strings.xml
deleted file mode 100644
index e8b3e97..0000000
--- a/SecondaryDisplayLauncher/res/values-is/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Ekki tókst að ræsa aðgerðina"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Bæta við flýtileið forrita"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Velja veggfóður"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-it/strings.xml b/SecondaryDisplayLauncher/res/values-it/strings.xml
deleted file mode 100644
index 4941515..0000000
--- a/SecondaryDisplayLauncher/res/values-it/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Impossibile avviare l\'attività"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Aggiungi scorciatoia app"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Imposta sfondo"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-iw/strings.xml b/SecondaryDisplayLauncher/res/values-iw/strings.xml
deleted file mode 100644
index 06b0c42..0000000
--- a/SecondaryDisplayLauncher/res/values-iw/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"לא ניתן היה להפעיל את הפעילות"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"הוספת קיצור דרך של אפליקציה"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"הגדרת טפט"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-ja/strings.xml b/SecondaryDisplayLauncher/res/values-ja/strings.xml
deleted file mode 100644
index 3ed7b2b..0000000
--- a/SecondaryDisplayLauncher/res/values-ja/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"アクティビティを開始できませんでした"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"アプリのショートカットを追加"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"壁紙を設定"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-ka/strings.xml b/SecondaryDisplayLauncher/res/values-ka/strings.xml
deleted file mode 100644
index ac85f70..0000000
--- a/SecondaryDisplayLauncher/res/values-ka/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"აქტივობის გაშვება ვერ მოხერხდა"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"აპის მალსახმობის დამატება"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"ფონის დაყენება"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-kk/strings.xml b/SecondaryDisplayLauncher/res/values-kk/strings.xml
deleted file mode 100644
index f9ac455..0000000
--- a/SecondaryDisplayLauncher/res/values-kk/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Әрекет іске қосылмады"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Қолданба таңбашасын енгізу"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Тұсқағаз орнату"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-km/strings.xml b/SecondaryDisplayLauncher/res/values-km/strings.xml
deleted file mode 100644
index afc050f..0000000
--- a/SecondaryDisplayLauncher/res/values-km/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"មិនអាចចាប់ផ្តើមសកម្មភាពទេ"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"បញ្ចូលផ្លូវកាត់កម្មវិធី"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"កំណត់ផ្ទាំងរូបភាព"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-kn/strings.xml b/SecondaryDisplayLauncher/res/values-kn/strings.xml
deleted file mode 100644
index 09c327f..0000000
--- a/SecondaryDisplayLauncher/res/values-kn/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"ಚಟುವಟಿಕೆಯನ್ನು ಲಾಂಚ್ ಮಾಡಲು ಸಾಧ್ಯವಾಗಲಿಲ್ಲ"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"ಆ್ಯಪ್ ಶಾರ್ಟ್ಕಟ್ ಸೇರಿಸಿ"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"ವಾಲ್ಪೇಪರ್ ಹೊಂದಿಸಿ"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-ko/strings.xml b/SecondaryDisplayLauncher/res/values-ko/strings.xml
deleted file mode 100644
index 6a02ac0..0000000
--- a/SecondaryDisplayLauncher/res/values-ko/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"활동을 실행할 수 없음"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"앱 바로가기 추가"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"배경화면 설정"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-ky/strings.xml b/SecondaryDisplayLauncher/res/values-ky/strings.xml
deleted file mode 100644
index 56185fa..0000000
--- a/SecondaryDisplayLauncher/res/values-ky/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Аракет аткарылган жок"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Колдонмого кыска жол кошуу"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Тушкагаз орнотуу"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-lo/strings.xml b/SecondaryDisplayLauncher/res/values-lo/strings.xml
deleted file mode 100644
index 36a6275..0000000
--- a/SecondaryDisplayLauncher/res/values-lo/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"ບໍ່ສາມາດເປີດໃຊ້ການເຄື່ອນໄຫວໄດ້"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"ເພີ່ມທາງລັດແອັບ"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"ຕັ້ງເປັນຮູບພື້ນຫຼັງ"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-lt/strings.xml b/SecondaryDisplayLauncher/res/values-lt/strings.xml
deleted file mode 100644
index 8113eb6..0000000
--- a/SecondaryDisplayLauncher/res/values-lt/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Nepavyko paleisti veiklos"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Pridėti programos šaukinį"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Nustatyti ekrano foną"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-lv/strings.xml b/SecondaryDisplayLauncher/res/values-lv/strings.xml
deleted file mode 100644
index e267933..0000000
--- a/SecondaryDisplayLauncher/res/values-lv/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Nevarēja palaist darbību"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Pievienot lietotnes saīsni"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Iestatīt fona tapeti"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-mk/strings.xml b/SecondaryDisplayLauncher/res/values-mk/strings.xml
deleted file mode 100644
index e2cca03..0000000
--- a/SecondaryDisplayLauncher/res/values-mk/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Не можеше да се стартува активноста"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Додајте кратенка за апликација"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Поставете го тапетот"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-ml/strings.xml b/SecondaryDisplayLauncher/res/values-ml/strings.xml
deleted file mode 100644
index 864245b..0000000
--- a/SecondaryDisplayLauncher/res/values-ml/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"ആക്റ്റിവിറ്റി പ്രകാശിപ്പിക്കാനായില്ല"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"ആപ്പ് കുറുക്കുവഴികൾ ചേർക്കുക"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"വാൾപേപ്പർ സജ്ജീകരിക്കുക"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-mn/strings.xml b/SecondaryDisplayLauncher/res/values-mn/strings.xml
deleted file mode 100644
index 85fb020..0000000
--- a/SecondaryDisplayLauncher/res/values-mn/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Үйл ажиллагааг эхлүүж чадсангүй"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Аппын товчлол нэмэх"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Ханын зураг тохируулах"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-mr/strings.xml b/SecondaryDisplayLauncher/res/values-mr/strings.xml
deleted file mode 100644
index 6e92a2f..0000000
--- a/SecondaryDisplayLauncher/res/values-mr/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"अॅक्टिव्हिटी लाँच करता आली नाही"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"अॅप शॉर्टकट जोडा"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"वॉलपेपर सेट करा"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-ms/strings.xml b/SecondaryDisplayLauncher/res/values-ms/strings.xml
deleted file mode 100644
index fd78053..0000000
--- a/SecondaryDisplayLauncher/res/values-ms/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Tidak dapat melancarkan aktiviti"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Tambah pintasan apl"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Tetapkan kertas dinding"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-my/strings.xml b/SecondaryDisplayLauncher/res/values-my/strings.xml
deleted file mode 100644
index 1521402..0000000
--- a/SecondaryDisplayLauncher/res/values-my/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"လုပ်ဆောင်ချက်ကို စတင်၍မရပါ"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"အက်ပ်ဖြတ်လမ်းလင့်ခ်ထည့်ရန်"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"နောက်ခံ သတ်မှတ်ရန်"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-nb/strings.xml b/SecondaryDisplayLauncher/res/values-nb/strings.xml
deleted file mode 100644
index 945c87b..0000000
--- a/SecondaryDisplayLauncher/res/values-nb/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Kunne ikke starte aktiviteten"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Legg til en appsnarvei"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Angi bakgrunn"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-ne/strings.xml b/SecondaryDisplayLauncher/res/values-ne/strings.xml
deleted file mode 100644
index 9a5b0a0..0000000
--- a/SecondaryDisplayLauncher/res/values-ne/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"उक्त क्रियाकलाप सुरु गर्न सकिएन"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"अनुप्रयोगको सर्टकट थप्नुहोस्"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"वालपेपर सेट गर्नुहोस्"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-nl/strings.xml b/SecondaryDisplayLauncher/res/values-nl/strings.xml
deleted file mode 100644
index 8767708..0000000
--- a/SecondaryDisplayLauncher/res/values-nl/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Kan de activiteit niet starten"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"App-snelkoppeling toevoegen"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Achtergrond instellen"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-or/strings.xml b/SecondaryDisplayLauncher/res/values-or/strings.xml
deleted file mode 100644
index 9bc5725..0000000
--- a/SecondaryDisplayLauncher/res/values-or/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"ଗତିବିଧିକୁ ଲଞ୍ଚ କରାଯାଇପାରିଲା ନାହିଁ"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"ଆପ୍ ସର୍ଟକଟ୍ ଯୋଗ କରନ୍ତୁ"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"ୱାଲ୍ପେପର୍କୁ ସେଟ୍ କରନ୍ତୁ"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-pa/strings.xml b/SecondaryDisplayLauncher/res/values-pa/strings.xml
deleted file mode 100644
index c5dd582..0000000
--- a/SecondaryDisplayLauncher/res/values-pa/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"ਸਰਗਰਮੀ ਨੂੰ ਲਾਂਚ ਨਹੀਂ ਕੀਤਾ ਜਾ ਸਕਿਆ"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"ਐਪ ਸ਼ਾਰਟਕੱਟ ਸ਼ਾਮਲ ਕਰੋ"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"ਵਾਲਪੇਪਰ ਸੈੱਟ ਕਰੋ"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-pl/strings.xml b/SecondaryDisplayLauncher/res/values-pl/strings.xml
deleted file mode 100644
index e8efaed..0000000
--- a/SecondaryDisplayLauncher/res/values-pl/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Nie udało się uruchomić aktywności"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Dodaj skrót do aplikacji"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Ustaw tapetę"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-pt-rPT/strings.xml b/SecondaryDisplayLauncher/res/values-pt-rPT/strings.xml
deleted file mode 100644
index 67c7557..0000000
--- a/SecondaryDisplayLauncher/res/values-pt-rPT/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Não foi possível iniciar a atividade."</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Adicionar atalho de aplicação"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Definir imagem de fundo"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-pt/strings.xml b/SecondaryDisplayLauncher/res/values-pt/strings.xml
deleted file mode 100644
index 201fc07..0000000
--- a/SecondaryDisplayLauncher/res/values-pt/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Não foi possível abrir a atividade"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Adicionar atalho de apps"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Definir plano de fundo"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-ro/strings.xml b/SecondaryDisplayLauncher/res/values-ro/strings.xml
deleted file mode 100644
index e2e21c5..0000000
--- a/SecondaryDisplayLauncher/res/values-ro/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Nu s-a putut lansa activitatea"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Adăugați comanda rapidă pentru aplicație"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Setați imaginea de fundal"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-ru/strings.xml b/SecondaryDisplayLauncher/res/values-ru/strings.xml
deleted file mode 100644
index 64ba00e..0000000
--- a/SecondaryDisplayLauncher/res/values-ru/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Не удалось запустить объект activity"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Добавить ярлык приложения"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Установить обои"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-si/strings.xml b/SecondaryDisplayLauncher/res/values-si/strings.xml
deleted file mode 100644
index ac492eb..0000000
--- a/SecondaryDisplayLauncher/res/values-si/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"ක්රියාකාරකම දියත් කිරීමට නොහැකි විය"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"යෙදුම් කෙටිමඟ එක් කරන්න"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"බිතුපත සකසන්න"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-sk/strings.xml b/SecondaryDisplayLauncher/res/values-sk/strings.xml
deleted file mode 100644
index 5e6fa7a..0000000
--- a/SecondaryDisplayLauncher/res/values-sk/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Aktivitu sa nepodarilo spustiť"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Pridať odkaz do aplikácie"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Nastaviť tapetu"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-sl/strings.xml b/SecondaryDisplayLauncher/res/values-sl/strings.xml
deleted file mode 100644
index f54dec9..0000000
--- a/SecondaryDisplayLauncher/res/values-sl/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Dejavnosti ni bilo mogoče zagnati"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Dodaj bližnjico do aplikacije"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Nastavi ozadje"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-sq/strings.xml b/SecondaryDisplayLauncher/res/values-sq/strings.xml
deleted file mode 100644
index e626dd1..0000000
--- a/SecondaryDisplayLauncher/res/values-sq/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Aktiviteti nuk mund të hapej"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Shto shkurtoren e aplikacionit"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Cakto imazhin e sfondit"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-sr/strings.xml b/SecondaryDisplayLauncher/res/values-sr/strings.xml
deleted file mode 100644
index 94214f1..0000000
--- a/SecondaryDisplayLauncher/res/values-sr/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Покретање активности није успело"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Додај пречицу за апликацију"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Подесите позадину"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-sv/strings.xml b/SecondaryDisplayLauncher/res/values-sv/strings.xml
deleted file mode 100644
index 53e17ef..0000000
--- a/SecondaryDisplayLauncher/res/values-sv/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Det gick inte att starta aktiviteten"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Lägg till appgenväg"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Ange bakgrund"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-sw/strings.xml b/SecondaryDisplayLauncher/res/values-sw/strings.xml
deleted file mode 100644
index 490561a..0000000
--- a/SecondaryDisplayLauncher/res/values-sw/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Imeshindwa kuanzisha shughuli"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Ongeza njia ya mkato ya programu"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Weka mandhari"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-sw600dp/dimens.xml b/SecondaryDisplayLauncher/res/values-sw600dp/dimens.xml
deleted file mode 100644
index f33a8db..0000000
--- a/SecondaryDisplayLauncher/res/values-sw600dp/dimens.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- ~ 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.
- -->
-
-<resources>
- <dimen name="app_picker_width">400dp</dimen>
- <dimen name="app_picker_height">400dp</dimen>
- <dimen name="app_picker_fab_margin">60dp</dimen>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-sw720dp/dimens.xml b/SecondaryDisplayLauncher/res/values-sw720dp/dimens.xml
deleted file mode 100644
index 524e52a..0000000
--- a/SecondaryDisplayLauncher/res/values-sw720dp/dimens.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- ~ 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.
- -->
-
-<resources>
- <dimen name="app_picker_width">660dp</dimen>
- <dimen name="app_picker_height">660dp</dimen>
- <dimen name="app_picker_fab_margin">70dp</dimen>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-ta/strings.xml b/SecondaryDisplayLauncher/res/values-ta/strings.xml
deleted file mode 100644
index 6bb054a..0000000
--- a/SecondaryDisplayLauncher/res/values-ta/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"நடவடிக்கையைத் துவக்க இயலவில்லை"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"ஆப்ஸ் ஷார்ட்கட்டைச் சேர்"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"வால்பேப்பரை அமை"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-te/strings.xml b/SecondaryDisplayLauncher/res/values-te/strings.xml
deleted file mode 100644
index 3dd3c9b..0000000
--- a/SecondaryDisplayLauncher/res/values-te/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"కార్యకలాపాన్ని ప్రారంభించడం సాధ్యం కాలేదు"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"యాప్ షార్ట్కట్ని జోడించు"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"వాల్పేపర్ను సెట్ చేయండి"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-th/strings.xml b/SecondaryDisplayLauncher/res/values-th/strings.xml
deleted file mode 100644
index 6368950..0000000
--- a/SecondaryDisplayLauncher/res/values-th/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"เปิดกิจกรรมไม่ได้"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"เพิ่มทางลัดของแอป"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"ตั้งวอลเปเปอร์"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-tl/strings.xml b/SecondaryDisplayLauncher/res/values-tl/strings.xml
deleted file mode 100644
index 192e5c4..0000000
--- a/SecondaryDisplayLauncher/res/values-tl/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Hindi mailunsad ang aktibidad"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Magdagdag ng shortcut ng app"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Magtakda ng wallpaper"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-tr/strings.xml b/SecondaryDisplayLauncher/res/values-tr/strings.xml
deleted file mode 100644
index e7ed998..0000000
--- a/SecondaryDisplayLauncher/res/values-tr/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"İşlem başlatılamadı"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Uygulama kısayolu ekle"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Duvar kağıdı ayarla"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-uk/strings.xml b/SecondaryDisplayLauncher/res/values-uk/strings.xml
deleted file mode 100644
index e465995..0000000
--- a/SecondaryDisplayLauncher/res/values-uk/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Не вдалося запустити активність"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Розмістити ярлик додатка"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Вибрати фоновий малюнок"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-ur/strings.xml b/SecondaryDisplayLauncher/res/values-ur/strings.xml
deleted file mode 100644
index e4c8641..0000000
--- a/SecondaryDisplayLauncher/res/values-ur/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"سرگرمی کو شروع نہیں کیا جا سکا"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"ایپ شارٹ کٹ شامل کریں"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"وال پیپر سیٹ کریں"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-uz/strings.xml b/SecondaryDisplayLauncher/res/values-uz/strings.xml
deleted file mode 100644
index 585739d..0000000
--- a/SecondaryDisplayLauncher/res/values-uz/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Faollik ishga tushmadi"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Yorliq yaratish"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Fonga rasm oʻrnatish"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-vi/strings.xml b/SecondaryDisplayLauncher/res/values-vi/strings.xml
deleted file mode 100644
index 15a1a44..0000000
--- a/SecondaryDisplayLauncher/res/values-vi/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Không thể chạy hoạt động"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Thêm lối tắt ứng dụng"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Đặt hình nền"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-zh-rCN/strings.xml b/SecondaryDisplayLauncher/res/values-zh-rCN/strings.xml
deleted file mode 100644
index 3358499..0000000
--- a/SecondaryDisplayLauncher/res/values-zh-rCN/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"无法启动该操作组件"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"添加应用快捷方式"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"设置壁纸"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-zh-rHK/strings.xml b/SecondaryDisplayLauncher/res/values-zh-rHK/strings.xml
deleted file mode 100644
index bf76f29..0000000
--- a/SecondaryDisplayLauncher/res/values-zh-rHK/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"無法啟動活動"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"新增應用程式捷徑"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"設定桌布"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-zh-rTW/strings.xml b/SecondaryDisplayLauncher/res/values-zh-rTW/strings.xml
deleted file mode 100644
index c02fe2c..0000000
--- a/SecondaryDisplayLauncher/res/values-zh-rTW/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"無法啟動活動"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"新增應用程式捷徑"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"套用桌布"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values-zu/strings.xml b/SecondaryDisplayLauncher/res/values-zu/strings.xml
deleted file mode 100644
index ad2f6b9..0000000
--- a/SecondaryDisplayLauncher/res/values-zu/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
-* 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.
-*/
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch" msgid="7873588052226763866">"Ayikwazanga ukuqalisa umsebenzi"</string>
- <string name="add_app_shortcut" msgid="2756755330707509435">"Engeza isinqamuleli sohlelo lokusebenza"</string>
- <string name="set_wallpaper" msgid="6475195450505435904">"Setha isithombe sangemuva"</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values/colors.xml b/SecondaryDisplayLauncher/res/values/colors.xml
deleted file mode 100644
index 66b41a2..0000000
--- a/SecondaryDisplayLauncher/res/values/colors.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/* //device/apps/common/assets/res/any/colors.xml
-**
-** Copyright 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.
-*/
--->
-<resources>
- <color name="launcher_bg_color">#884e8391</color>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values/dimens.xml b/SecondaryDisplayLauncher/res/values/dimens.xml
deleted file mode 100644
index 7cca607..0000000
--- a/SecondaryDisplayLauncher/res/values/dimens.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 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.
--->
-
-<resources>
- <dimen name="app_list_col_width">72dp</dimen>
- <dimen name="app_list_horizontal_spacing">24dp</dimen>
- <dimen name="app_list_vertical_spacing">24dp</dimen>
- <dimen name="app_icon_width">64dp</dimen>
- <dimen name="app_icon_height">64dp</dimen>
- <dimen name="app_grid_margin_top">24dp</dimen>
- <dimen name="app_grid_margin_left">8dp</dimen>
- <dimen name="app_grid_margin_right">8dp</dimen>
-
- <dimen name="app_picker_width">300dp</dimen>
- <dimen name="app_picker_height">300dp</dimen>
- <dimen name="app_picker_fab_margin">20dp</dimen>
- <dimen name="options_button_margin">20dp</dimen>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values/strings.xml b/SecondaryDisplayLauncher/res/values/strings.xml
deleted file mode 100644
index b68918a..0000000
--- a/SecondaryDisplayLauncher/res/values/strings.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-* 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.
-*/
--->
-
-<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="couldnt_launch">Couldn\'t launch the activity</string>
- <string name="add_app_shortcut">Add app shortcut</string>
- <string name="set_wallpaper">Set wallpaper</string>
-</resources>
diff --git a/SecondaryDisplayLauncher/res/values/styles.xml b/SecondaryDisplayLauncher/res/values/styles.xml
deleted file mode 100644
index 4e41a98..0000000
--- a/SecondaryDisplayLauncher/res/values/styles.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-* 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.
-*/
--->
-
-<resources>
- <style name="SecondaryLauncherTheme" parent="Theme.MaterialComponents.NoActionBar" >
- <item name="android:windowShowWallpaper">true</item>
- <item name="android:windowNoTitle">true</item>
- <item name="android:windowIsTranslucent">true</item>
- <item name="android:windowTranslucentStatus">true</item>
- <item name="android:windowTranslucentNavigation">true</item>
- <item name="android:colorBackgroundCacheHint">@null</item>
- <item name="android:windowBackground">@android:color/transparent</item>
- </style>
-</resources>
diff --git a/SecondaryDisplayLauncher/src/com/android/launcher3/AppEntry.java b/SecondaryDisplayLauncher/src/com/android/launcher3/AppEntry.java
deleted file mode 100644
index 3017b81..0000000
--- a/SecondaryDisplayLauncher/src/com/android/launcher3/AppEntry.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/**
- * 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.launcher3;
-
-import android.content.ComponentName;
-import android.content.Intent;
-import android.content.pm.PackageManager;
-import android.content.pm.ResolveInfo;
-import android.graphics.drawable.Drawable;
-
-/** An entry that represents a single activity that can be launched. */
-public class AppEntry {
-
- private String mLabel;
- private Drawable mIcon;
- private Intent mLaunchIntent;
-
- AppEntry(ResolveInfo info, PackageManager packageManager) {
- mLabel = info.loadLabel(packageManager).toString();
- mIcon = info.loadIcon(packageManager);
- mLaunchIntent = new Intent();
- mLaunchIntent.setComponent(new ComponentName(info.activityInfo.packageName,
- info.activityInfo.name));
- }
-
- String getLabel() {
- return mLabel;
- }
-
- Drawable getIcon() {
- return mIcon;
- }
-
- Intent getLaunchIntent() { return mLaunchIntent; }
-
- ComponentName getComponentName() {
- return mLaunchIntent.getComponent();
- }
-
- @Override
- public String toString() {
- return mLabel;
- }
-}
diff --git a/SecondaryDisplayLauncher/src/com/android/launcher3/AppListAdapter.java b/SecondaryDisplayLauncher/src/com/android/launcher3/AppListAdapter.java
deleted file mode 100644
index aa115cb..0000000
--- a/SecondaryDisplayLauncher/src/com/android/launcher3/AppListAdapter.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/**
- * 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.launcher3;
-
-import android.content.Context;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ArrayAdapter;
-import android.widget.ImageView;
-import android.widget.TextView;
-
-import com.android.launcher3.R;
-
-import java.util.List;
-
-/** Adapter for available apps list. */
-public class AppListAdapter extends ArrayAdapter<AppEntry> {
- private final LayoutInflater mInflater;
-
- AppListAdapter(Context context) {
- super(context, android.R.layout.simple_list_item_2);
- mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- }
-
- void setData(List<AppEntry> data) {
- clear();
- if (data != null) {
- addAll(data);
- }
- }
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- View view;
-
- if (convertView == null) {
- view = mInflater.inflate(R.layout.app_grid_item, parent, false);
- } else {
- view = convertView;
- }
-
- AppEntry item = getItem(position);
- ((ImageView)view.findViewById(R.id.app_icon)).setImageDrawable(item.getIcon());
- ((TextView)view.findViewById(R.id.app_name)).setText(item.getLabel());
-
- return view;
- }
-}
diff --git a/SecondaryDisplayLauncher/src/com/android/launcher3/AppListViewModel.java b/SecondaryDisplayLauncher/src/com/android/launcher3/AppListViewModel.java
deleted file mode 100644
index 914fd5e..0000000
--- a/SecondaryDisplayLauncher/src/com/android/launcher3/AppListViewModel.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/**
- * 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.launcher3;
-
-import android.app.Application;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.pm.PackageManager;
-import android.content.pm.ResolveInfo;
-import android.os.AsyncTask;
-
-import androidx.lifecycle.AndroidViewModel;
-import androidx.lifecycle.LiveData;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * A view model that provides a list of activities that can be launched.
- */
-public class AppListViewModel extends AndroidViewModel {
-
- private final AppListLiveData mLiveData;
- private final PackageIntentReceiver
- mPackageIntentReceiver;
-
- public AppListViewModel(Application application) {
- super(application);
- mLiveData = new AppListLiveData(application);
- mPackageIntentReceiver = new PackageIntentReceiver(mLiveData, application);
- }
-
- public LiveData<List<AppEntry>> getAppList() {
- return mLiveData;
- }
-
- protected void onCleared() {
- getApplication().unregisterReceiver(mPackageIntentReceiver);
- }
-}
-
-class AppListLiveData extends LiveData<List<AppEntry>> {
-
- private final PackageManager mPackageManager;
- private int mCurrentDataVersion;
-
- public AppListLiveData(Context context) {
- mPackageManager = context.getPackageManager();
- loadData();
- }
-
- void loadData() {
- final int loadDataVersion = ++mCurrentDataVersion;
-
- new AsyncTask<Void, Void, List<AppEntry>>() {
- @Override
- protected List<AppEntry> doInBackground(Void... voids) {
- Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
- mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
-
- List<ResolveInfo> apps = mPackageManager.queryIntentActivities(mainIntent,
- PackageManager.GET_META_DATA);
-
- List<AppEntry> entries = new ArrayList<>();
- if (apps != null) {
- for (ResolveInfo app : apps) {
- AppEntry entry = new AppEntry(app, mPackageManager);
- entries.add(entry);
- }
- }
- return entries;
- }
-
- @Override
- protected void onPostExecute(List<AppEntry> data) {
- if (mCurrentDataVersion == loadDataVersion) {
- setValue(data);
- }
- }
- }.execute();
- }
-}
-
-/**
- * Receiver used to notify live data about app list changes.
- */
-class PackageIntentReceiver extends BroadcastReceiver {
-
- private final AppListLiveData mLiveData;
-
- public PackageIntentReceiver(AppListLiveData liveData, Context context) {
- mLiveData = liveData;
- IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
- filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
- filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
- filter.addDataScheme("package");
- context.registerReceiver(this, filter);
-
- // Register for events related to sdcard installation.
- IntentFilter sdFilter = new IntentFilter();
- sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
- sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
- context.registerReceiver(this, sdFilter);
- }
-
- @Override
- public void onReceive(Context context, Intent intent) {
- mLiveData.loadData();
- }
-}
\ No newline at end of file
diff --git a/SecondaryDisplayLauncher/src/com/android/launcher3/PinnedAppListViewModel.java b/SecondaryDisplayLauncher/src/com/android/launcher3/PinnedAppListViewModel.java
deleted file mode 100644
index 4f92038..0000000
--- a/SecondaryDisplayLauncher/src/com/android/launcher3/PinnedAppListViewModel.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/**
- * 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.launcher3;
-
-import static com.android.launcher3.PinnedAppListViewModel.PINNED_APPS_KEY;
-
-import android.app.Application;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.SharedPreferences;
-import android.content.pm.PackageManager;
-import android.content.pm.ResolveInfo;
-import android.os.AsyncTask;
-
-import androidx.lifecycle.AndroidViewModel;
-import androidx.lifecycle.LiveData;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
-/**
- * A view model that provides a list of activities that were pinned by user to always display on
- * home screen.
- * The pinned activities are stored in {@link SharedPreferences} to keep the sample simple :).
- */
-public class PinnedAppListViewModel extends AndroidViewModel {
-
- final static String PINNED_APPS_KEY = "pinned_apps";
-
- private final PinnedAppListLiveData mLiveData;
-
- public PinnedAppListViewModel(Application application) {
- super(application);
- mLiveData = new PinnedAppListLiveData(application);
- }
-
- public LiveData<List<AppEntry>> getPinnedAppList() {
- return mLiveData;
- }
-}
-
-class PinnedAppListLiveData extends LiveData<List<AppEntry>> {
-
- private final Context mContext;
- private final PackageManager mPackageManager;
- // Store listener reference, so it won't be GC-ed.
- private final SharedPreferences.OnSharedPreferenceChangeListener mChangeListener;
- private int mCurrentDataVersion;
-
- public PinnedAppListLiveData(Context context) {
- mContext = context;
- mPackageManager = context.getPackageManager();
-
- final SharedPreferences prefs = context.getSharedPreferences(PINNED_APPS_KEY, 0);
- mChangeListener = (preferences, key) -> {
- loadData();
- };
- prefs.registerOnSharedPreferenceChangeListener(mChangeListener);
-
- loadData();
- }
-
- private void loadData() {
- final int loadDataVersion = ++mCurrentDataVersion;
-
- new AsyncTask<Void, Void, List<AppEntry>>() {
- @Override
- protected List<AppEntry> doInBackground(Void... voids) {
- List<AppEntry> entries = new ArrayList<>();
-
- final SharedPreferences sp = mContext.getSharedPreferences(PINNED_APPS_KEY, 0);
- final Set<String> pinnedAppsComponents = sp.getStringSet(PINNED_APPS_KEY, null);
- if (pinnedAppsComponents == null) {
- return null;
- }
-
- for (String componentString : pinnedAppsComponents) {
- final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
- mainIntent.setComponent(ComponentName.unflattenFromString(componentString));
- mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
-
- final List<ResolveInfo> apps = mPackageManager.queryIntentActivities(mainIntent,
- PackageManager.GET_META_DATA);
-
- if (apps != null) {
- for (ResolveInfo app : apps) {
- final AppEntry entry = new AppEntry(app, mPackageManager);
- entries.add(entry);
- }
- }
- }
-
- return entries;
- }
-
- @Override
- protected void onPostExecute(List<AppEntry> data) {
- if (mCurrentDataVersion == loadDataVersion) {
- setValue(data);
- }
- }
- }.execute();
- }
-}
\ No newline at end of file
diff --git a/SecondaryDisplayLauncher/src/com/android/launcher3/PinnedAppPickerDialog.java b/SecondaryDisplayLauncher/src/com/android/launcher3/PinnedAppPickerDialog.java
deleted file mode 100644
index 02e6e4a..0000000
--- a/SecondaryDisplayLauncher/src/com/android/launcher3/PinnedAppPickerDialog.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/**
- * 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.launcher3;
-
-import android.os.Bundle;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.GridView;
-
-import androidx.fragment.app.DialogFragment;
-
-import com.android.launcher3.R;
-
-/**
- * Callback to be invoked when an app was picked.
- */
-interface AppPickedCallback {
- void onAppPicked(AppEntry appEntry);
-}
-
-/**
- * Dialog that provides the user with a list of available apps to pin to the home screen.
- */
-public class PinnedAppPickerDialog extends DialogFragment {
-
- private AppListAdapter mAppListAdapter;
- private AppPickedCallback mAppPickerCallback;
-
- public PinnedAppPickerDialog() {
- }
-
- public static PinnedAppPickerDialog newInstance(AppListAdapter appListAdapter,
- AppPickedCallback callback) {
- PinnedAppPickerDialog
- frag = new PinnedAppPickerDialog();
- frag.mAppListAdapter = appListAdapter;
- frag.mAppPickerCallback = callback;
- return frag;
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- return inflater.inflate(R.layout.app_picker_dialog, container);
- }
-
- @Override
- public void onViewCreated(View view, Bundle savedInstanceState) {
- super.onViewCreated(view, savedInstanceState);
-
- GridView appGridView = view.findViewById(R.id.picker_app_grid);
- appGridView.setAdapter(mAppListAdapter);
- appGridView.setOnItemClickListener((adapterView, itemView, position, id) -> {
- final AppEntry entry = mAppListAdapter.getItem(position);
- mAppPickerCallback.onAppPicked(entry);
- dismiss();
- });
- }
-}
\ No newline at end of file
diff --git a/SecondaryDisplayLauncher/src/com/android/launcher3/SecondaryDisplayLauncher.java b/SecondaryDisplayLauncher/src/com/android/launcher3/SecondaryDisplayLauncher.java
deleted file mode 100644
index 0a2f18f..0000000
--- a/SecondaryDisplayLauncher/src/com/android/launcher3/SecondaryDisplayLauncher.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/**
- * 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.launcher3;
-
-import static com.android.launcher3.PinnedAppListViewModel.PINNED_APPS_KEY;
-
-import android.animation.Animator;
-import android.animation.AnimatorListenerAdapter;
-import android.app.AlertDialog;
-import android.app.Application;
-import android.content.Intent;
-import android.content.SharedPreferences;
-import android.content.res.Configuration;
-import android.os.Bundle;
-import android.view.MenuInflater;
-import android.view.MenuItem;
-import android.view.View;
-import android.view.ViewAnimationUtils;
-import android.view.inputmethod.InputMethodManager;
-import android.widget.GridView;
-import android.widget.ImageButton;
-import android.widget.PopupMenu;
-
-import androidx.fragment.app.FragmentActivity;
-import androidx.fragment.app.FragmentManager;
-import androidx.lifecycle.ViewModelProvider;
-import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory;
-
-import com.google.android.material.circularreveal.cardview.CircularRevealCardView;
-import com.google.android.material.floatingactionbutton.FloatingActionButton;
-
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * Secondary launcher activity. It's launch mode is configured as "singleTop" to allow showing on
- * multiple displays and to ensure a single instance per each display.
- */
-public class SecondaryDisplayLauncher extends FragmentActivity implements AppPickedCallback,
- PopupMenu.OnMenuItemClickListener {
-
- private AppListAdapter mAppListAdapter;
- private AppListAdapter mPinnedAppListAdapter;
- private CircularRevealCardView mAppDrawerView;
- private FloatingActionButton mFab;
-
- private boolean mAppDrawerShown;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.secondary_display_launcher);
-
- mAppDrawerView = findViewById(R.id.FloatingSheet);
- mFab = findViewById(R.id.FloatingActionButton);
-
- mFab.setOnClickListener((View v) -> {
- showAppDrawer(true);
- });
-
- final ViewModelProvider viewModelProvider = new ViewModelProvider(getViewModelStore(),
- new AndroidViewModelFactory((Application) getApplicationContext()));
-
- mPinnedAppListAdapter = new AppListAdapter(this);
- final GridView pinnedAppGridView = findViewById(R.id.pinned_app_grid);
- pinnedAppGridView.setAdapter(mPinnedAppListAdapter);
- pinnedAppGridView.setOnItemClickListener((adapterView, view, position, id) -> {
- final AppEntry entry = mPinnedAppListAdapter.getItem(position);
- launch(entry.getLaunchIntent());
- });
- final PinnedAppListViewModel pinnedAppListViewModel =
- viewModelProvider.get(PinnedAppListViewModel.class);
- pinnedAppListViewModel.getPinnedAppList().observe(this, data -> {
- mPinnedAppListAdapter.setData(data);
- });
-
- mAppListAdapter = new AppListAdapter(this);
- final GridView appGridView = findViewById(R.id.app_grid);
- appGridView.setAdapter(mAppListAdapter);
- appGridView.setOnItemClickListener((adapterView, view, position, id) -> {
- final AppEntry entry = mAppListAdapter.getItem(position);
- launch(entry.getLaunchIntent());
- });
- final AppListViewModel appListViewModel = viewModelProvider.get(AppListViewModel.class);
- appListViewModel.getAppList().observe(this, data -> {
- mAppListAdapter.setData(data);
- });
-
- ImageButton optionsButton = findViewById(R.id.OptionsButton);
- optionsButton.setOnClickListener((View v) -> {
- PopupMenu popup = new PopupMenu(this,v);
- popup.setOnMenuItemClickListener(this);
- MenuInflater inflater = popup.getMenuInflater();
- inflater.inflate(R.menu.context_menu, popup.getMenu());
- popup.show();
- });
- }
-
- @Override
- public boolean onMenuItemClick(MenuItem item) {
- // Respond to picking one of the popup menu items.
- final int id = item.getItemId();
- if (id == R.id.add_app_shortcut) {
- FragmentManager fm = getSupportFragmentManager();
- PinnedAppPickerDialog pickerDialogFragment =
- PinnedAppPickerDialog.newInstance(mAppListAdapter, this);
- pickerDialogFragment.show(fm, "fragment_app_picker");
- return true;
- } else if (id == R.id.set_wallpaper) {
- Intent intent = new Intent(Intent.ACTION_SET_WALLPAPER);
- startActivity(Intent.createChooser(intent, getString(R.string.set_wallpaper)));
- return true;
- }
-
- return true;
- }
-
- @Override
- public void onConfigurationChanged(Configuration newConfig) {
- super.onConfigurationChanged(newConfig);
- showAppDrawer(false);
- }
-
- public void onBackPressed() {
- // If the app drawer was shown - hide it. Otherwise, not doing anything since we don't want
- // to close the launcher.
- showAppDrawer(false);
- }
-
- public void onNewIntent(Intent intent) {
- super.onNewIntent(intent);
-
- if (Intent.ACTION_MAIN.equals(intent.getAction())) {
- // Hide keyboard.
- final View v = getWindow().peekDecorView();
- if (v != null && v.getWindowToken() != null) {
- getSystemService(InputMethodManager.class).hideSoftInputFromWindow(
- v.getWindowToken(), 0);
- }
- }
-
- // A new intent will bring the launcher to top. Hide the app drawer to reset the state.
- showAppDrawer(false);
- }
-
- void launch(Intent launchIntent) {
- launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- try {
- startActivity(launchIntent);
- } catch (Exception e) {
- final AlertDialog.Builder builder =
- new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
- builder.setTitle(R.string.couldnt_launch)
- .setMessage(e.getLocalizedMessage())
- .setIcon(android.R.drawable.ic_dialog_alert)
- .show();
- }
- }
-
- /**
- * Store the picked app to persistent pinned list and update the loader.
- */
- @Override
- public void onAppPicked(AppEntry appEntry) {
- final SharedPreferences sp = getSharedPreferences(PINNED_APPS_KEY, 0);
- Set<String> pinnedApps = sp.getStringSet(PINNED_APPS_KEY, null);
- if (pinnedApps == null) {
- pinnedApps = new HashSet<String>();
- } else {
- // Always need to create a new object to make sure that the changes are persisted.
- pinnedApps = new HashSet<String>(pinnedApps);
- }
- pinnedApps.add(appEntry.getComponentName().flattenToString());
-
- final SharedPreferences.Editor editor = sp.edit();
- editor.putStringSet(PINNED_APPS_KEY, pinnedApps);
- editor.apply();
- }
-
- /**
- * Show/hide app drawer card with animation.
- */
- private void showAppDrawer(boolean show) {
- if (show == mAppDrawerShown) {
- return;
- }
-
- final Animator animator = revealAnimator(mAppDrawerView, show);
- if (show) {
- mAppDrawerShown = true;
- mAppDrawerView.setVisibility(View.VISIBLE);
- mFab.setVisibility(View.INVISIBLE);
- } else {
- mAppDrawerShown = false;
- animator.addListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationEnd(Animator animation) {
- super.onAnimationEnd(animation);
- mAppDrawerView.setVisibility(View.INVISIBLE);
- mFab.setVisibility(View.VISIBLE);
- }
- });
- }
- animator.start();
- }
-
- /**
- * Create reveal/hide animator for app list card.
- */
- private Animator revealAnimator(View view, boolean open) {
- final int radius = (int) Math.hypot((double) view.getWidth(), (double) view.getHeight());
- return ViewAnimationUtils.createCircularReveal(view, view.getRight(), view.getBottom(),
- open ? 0 : radius, open ? radius : 0);
- }
-}
diff --git a/go/src/com/android/launcher3/model/WidgetsModel.java b/go/src/com/android/launcher3/model/WidgetsModel.java
index 7690b9d..3b3dc01 100644
--- a/go/src/com/android/launcher3/model/WidgetsModel.java
+++ b/go/src/com/android/launcher3/model/WidgetsModel.java
@@ -16,6 +16,7 @@
package com.android.launcher3.model;
+import android.content.ComponentName;
import android.content.Context;
import android.os.UserHandle;
@@ -68,4 +69,9 @@
public void onPackageIconsUpdated(Set<String> packageNames, UserHandle user,
LauncherAppState app) {
}
+
+ public WidgetItem getWidgetProviderInfoByProviderName(
+ ComponentName providerName) {
+ return null;
+ }
}
\ No newline at end of file
diff --git a/iconloaderlib/Android.bp b/iconloaderlib/Android.bp
deleted file mode 100644
index f12d16e..0000000
--- a/iconloaderlib/Android.bp
+++ /dev/null
@@ -1,44 +0,0 @@
-// 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.
-
-android_library {
- name: "iconloader_base",
- sdk_version: "28",
- min_sdk_version: "21",
- static_libs: [
- "androidx.core_core",
- ],
- resource_dirs: [
- "res",
- ],
- srcs: [
- "src/**/*.java",
- ],
-}
-
-android_library {
- name: "iconloader",
- sdk_version: "system_current",
- min_sdk_version: "21",
- static_libs: [
- "androidx.core_core",
- ],
- resource_dirs: [
- "res",
- ],
- srcs: [
- "src/**/*.java",
- "src_full_lib/**/*.java",
- ],
-}
diff --git a/iconloaderlib/AndroidManifest.xml b/iconloaderlib/AndroidManifest.xml
deleted file mode 100644
index b30258d..0000000
--- a/iconloaderlib/AndroidManifest.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- 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.
--->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.launcher3.icons">
-</manifest>
diff --git a/iconloaderlib/build.gradle b/iconloaderlib/build.gradle
deleted file mode 100644
index d7a62e1..0000000
--- a/iconloaderlib/build.gradle
+++ /dev/null
@@ -1,38 +0,0 @@
-apply plugin: 'com.android.library'
-
-android {
- compileSdkVersion COMPILE_SDK
- buildToolsVersion BUILD_TOOLS_VERSION
-
- defaultConfig {
- minSdkVersion 25
- targetSdkVersion 28
- versionCode 1
- versionName "1.0"
- }
-
- sourceSets {
- main {
- java.srcDirs = ['src', 'src_full_lib']
- 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
- }
-}
-
-dependencies {
- implementation "androidx.core:core:${ANDROID_X_VERSION}"
-}
diff --git a/iconloaderlib/res/drawable/ic_instant_app_badge.xml b/iconloaderlib/res/drawable/ic_instant_app_badge.xml
deleted file mode 100644
index b74317e..0000000
--- a/iconloaderlib/res/drawable/ic_instant_app_badge.xml
+++ /dev/null
@@ -1,39 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 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.
--->
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
- android:width="@dimen/profile_badge_size"
- android:height="@dimen/profile_badge_size"
- android:viewportWidth="18"
- android:viewportHeight="18">
-
- <path
- android:fillColor="@android:color/black"
- android:strokeWidth="1"
- android:pathData="M 9 0 C 13.9705627485 0 18 4.02943725152 18 9 C 18 13.9705627485 13.9705627485 18 9 18 C 4.02943725152 18 0 13.9705627485 0 9 C 0 4.02943725152 4.02943725152 0 9 0 Z" />
- <path
- android:fillColor="@android:color/white"
- android:strokeWidth="1"
- android:pathData="M 9 0 C 13.9705627485 0 18 4.02943725152 18 9 C 18 13.9705627485 13.9705627485 18 9 18 C 4.02943725152 18 0 13.9705627485 0 9 C 0 4.02943725152 4.02943725152 0 9 0 Z" />
- <path
- android:fillColor="@android:color/white"
- android:strokeWidth="1"
- android:pathData="M 9 0 C 13.9705627485 0 18 4.02943725152 18 9 C 18 13.9705627485 13.9705627485 18 9 18 C 4.02943725152 18 0 13.9705627485 0 9 C 0 4.02943725152 4.02943725152 0 9 0 Z" />
- <path
- android:fillColor="@android:color/black"
- android:fillAlpha="0.87"
- android:strokeWidth="1"
- android:pathData="M 6 10.4123279 L 8.63934949 10.4123279 L 8.63934949 15.6 L 12.5577168 7.84517705 L 9.94547194 7.84517705 L 9.94547194 2 Z" />
-</vector>
diff --git a/iconloaderlib/res/values/colors.xml b/iconloaderlib/res/values/colors.xml
deleted file mode 100644
index 873b2fc..0000000
--- a/iconloaderlib/res/values/colors.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-**
-** Copyright 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.
-*/
--->
-<resources>
- <color name="legacy_icon_background">#FFFFFF</color>
-</resources>
diff --git a/iconloaderlib/res/values/config.xml b/iconloaderlib/res/values/config.xml
deleted file mode 100644
index 68c2d2e..0000000
--- a/iconloaderlib/res/values/config.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-**
-** Copyright 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.
-*/
--->
-<resources>
-
- <!-- Various configurations to control the simple cache implementation -->
-
- <dimen name="default_icon_bitmap_size">56dp</dimen>
- <bool name="simple_cache_enable_im_memory">false</bool>
- <string name="cache_db_name" translatable="false">app_icons.db</string>
-
-</resources>
\ No newline at end of file
diff --git a/iconloaderlib/src/com/android/launcher3/icons/BaseIconFactory.java b/iconloaderlib/src/com/android/launcher3/icons/BaseIconFactory.java
deleted file mode 100644
index 31a923e..0000000
--- a/iconloaderlib/src/com/android/launcher3/icons/BaseIconFactory.java
+++ /dev/null
@@ -1,396 +0,0 @@
-package com.android.launcher3.icons;
-
-import static android.graphics.Paint.DITHER_FLAG;
-import static android.graphics.Paint.FILTER_BITMAP_FLAG;
-
-import static com.android.launcher3.icons.ShadowGenerator.BLUR_FACTOR;
-
-import android.content.Context;
-import android.content.Intent;
-import android.content.pm.PackageManager;
-import android.content.res.Resources;
-import android.graphics.Bitmap;
-import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.PaintFlagsDrawFilter;
-import android.graphics.Rect;
-import android.graphics.RectF;
-import android.graphics.drawable.AdaptiveIconDrawable;
-import android.graphics.drawable.BitmapDrawable;
-import android.graphics.drawable.ColorDrawable;
-import android.graphics.drawable.Drawable;
-import android.os.Build;
-import android.os.Process;
-import android.os.UserHandle;
-
-import androidx.annotation.NonNull;
-
-/**
- * This class will be moved to androidx library. There shouldn't be any dependency outside
- * this package.
- */
-public class BaseIconFactory implements AutoCloseable {
-
- private static final String TAG = "BaseIconFactory";
- private static final int DEFAULT_WRAPPER_BACKGROUND = Color.WHITE;
- static final boolean ATLEAST_OREO = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O;
- static final boolean ATLEAST_P = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P;
-
- private static final float ICON_BADGE_SCALE = 0.444f;
-
- private final Rect mOldBounds = new Rect();
- protected final Context mContext;
- private final Canvas mCanvas;
- private final PackageManager mPm;
- private final ColorExtractor mColorExtractor;
- private boolean mDisableColorExtractor;
- private boolean mBadgeOnLeft = false;
-
- protected final int mFillResIconDpi;
- protected final int mIconBitmapSize;
-
- private IconNormalizer mNormalizer;
- private ShadowGenerator mShadowGenerator;
- private final boolean mShapeDetection;
-
- private Drawable mWrapperIcon;
- private int mWrapperBackgroundColor = DEFAULT_WRAPPER_BACKGROUND;
-
- protected BaseIconFactory(Context context, int fillResIconDpi, int iconBitmapSize,
- boolean shapeDetection) {
- mContext = context.getApplicationContext();
- mShapeDetection = shapeDetection;
- mFillResIconDpi = fillResIconDpi;
- mIconBitmapSize = iconBitmapSize;
-
- mPm = mContext.getPackageManager();
- mColorExtractor = new ColorExtractor();
-
- mCanvas = new Canvas();
- mCanvas.setDrawFilter(new PaintFlagsDrawFilter(DITHER_FLAG, FILTER_BITMAP_FLAG));
- clear();
- }
-
- protected BaseIconFactory(Context context, int fillResIconDpi, int iconBitmapSize) {
- this(context, fillResIconDpi, iconBitmapSize, false);
- }
-
- protected void clear() {
- mWrapperBackgroundColor = DEFAULT_WRAPPER_BACKGROUND;
- mDisableColorExtractor = false;
- mBadgeOnLeft = false;
- }
-
- public ShadowGenerator getShadowGenerator() {
- if (mShadowGenerator == null) {
- mShadowGenerator = new ShadowGenerator(mIconBitmapSize);
- }
- return mShadowGenerator;
- }
-
- public IconNormalizer getNormalizer() {
- if (mNormalizer == null) {
- mNormalizer = new IconNormalizer(mContext, mIconBitmapSize, mShapeDetection);
- }
- return mNormalizer;
- }
-
- @SuppressWarnings("deprecation")
- public BitmapInfo createIconBitmap(Intent.ShortcutIconResource iconRes) {
- try {
- Resources resources = mPm.getResourcesForApplication(iconRes.packageName);
- if (resources != null) {
- final int id = resources.getIdentifier(iconRes.resourceName, null, null);
- // do not stamp old legacy shortcuts as the app may have already forgotten about it
- return createBadgedIconBitmap(
- resources.getDrawableForDensity(id, mFillResIconDpi),
- Process.myUserHandle() /* only available on primary user */,
- false /* do not apply legacy treatment */);
- }
- } catch (Exception e) {
- // Icon not found.
- }
- return null;
- }
-
- public BitmapInfo createIconBitmap(Bitmap icon) {
- if (mIconBitmapSize != icon.getWidth() || mIconBitmapSize != icon.getHeight()) {
- icon = createIconBitmap(new BitmapDrawable(mContext.getResources(), icon), 1f);
- }
-
- return BitmapInfo.of(icon, extractColor(icon));
- }
-
- public BitmapInfo createBadgedIconBitmap(Drawable icon, UserHandle user,
- boolean shrinkNonAdaptiveIcons) {
- return createBadgedIconBitmap(icon, user, shrinkNonAdaptiveIcons, false, null);
- }
-
- public BitmapInfo createBadgedIconBitmap(Drawable icon, UserHandle user,
- int iconAppTargetSdk) {
- return createBadgedIconBitmap(icon, user, iconAppTargetSdk, false);
- }
-
- public BitmapInfo createBadgedIconBitmap(Drawable icon, UserHandle user,
- int iconAppTargetSdk, boolean isInstantApp) {
- return createBadgedIconBitmap(icon, user, iconAppTargetSdk, isInstantApp, null);
- }
-
- public BitmapInfo createBadgedIconBitmap(Drawable icon, UserHandle user,
- int iconAppTargetSdk, boolean isInstantApp, float[] scale) {
- boolean shrinkNonAdaptiveIcons = ATLEAST_P ||
- (ATLEAST_OREO && iconAppTargetSdk >= Build.VERSION_CODES.O);
- return createBadgedIconBitmap(icon, user, shrinkNonAdaptiveIcons, isInstantApp, scale);
- }
-
- public Bitmap createScaledBitmapWithoutShadow(Drawable icon, int iconAppTargetSdk) {
- boolean shrinkNonAdaptiveIcons = ATLEAST_P ||
- (ATLEAST_OREO && iconAppTargetSdk >= Build.VERSION_CODES.O);
- return createScaledBitmapWithoutShadow(icon, shrinkNonAdaptiveIcons);
- }
-
- /**
- * Creates bitmap using the source drawable and various parameters.
- * The bitmap is visually normalized with other icons and has enough spacing to add shadow.
- *
- * @param icon source of the icon
- * @param user info can be used for a badge
- * @param shrinkNonAdaptiveIcons {@code true} if non adaptive icons should be treated
- * @param isInstantApp info can be used for a badge
- * @param scale returns the scale result from normalization
- * @return a bitmap suitable for disaplaying as an icon at various system UIs.
- */
- public BitmapInfo createBadgedIconBitmap(@NonNull Drawable icon, UserHandle user,
- boolean shrinkNonAdaptiveIcons, boolean isInstantApp, float[] scale) {
- if (scale == null) {
- scale = new float[1];
- }
- icon = normalizeAndWrapToAdaptiveIcon(icon, shrinkNonAdaptiveIcons, null, scale);
- Bitmap bitmap = createIconBitmap(icon, scale[0]);
- if (ATLEAST_OREO && icon instanceof AdaptiveIconDrawable) {
- mCanvas.setBitmap(bitmap);
- getShadowGenerator().recreateIcon(Bitmap.createBitmap(bitmap), mCanvas);
- mCanvas.setBitmap(null);
- }
-
- if (isInstantApp) {
- badgeWithDrawable(bitmap, mContext.getDrawable(R.drawable.ic_instant_app_badge));
- }
- if (user != null) {
- BitmapDrawable drawable = new FixedSizeBitmapDrawable(bitmap);
- Drawable badged = mPm.getUserBadgedIcon(drawable, user);
- if (badged instanceof BitmapDrawable) {
- bitmap = ((BitmapDrawable) badged).getBitmap();
- } else {
- bitmap = createIconBitmap(badged, 1f);
- }
- }
- int color = extractColor(bitmap);
- return icon instanceof BitmapInfo.Extender
- ? ((BitmapInfo.Extender) icon).getExtendedInfo(bitmap, color, this)
- : BitmapInfo.of(bitmap, color);
- }
-
- public Bitmap createScaledBitmapWithoutShadow(Drawable icon, boolean shrinkNonAdaptiveIcons) {
- RectF iconBounds = new RectF();
- float[] scale = new float[1];
- icon = normalizeAndWrapToAdaptiveIcon(icon, shrinkNonAdaptiveIcons, iconBounds, scale);
- return createIconBitmap(icon,
- Math.min(scale[0], ShadowGenerator.getScaleForBounds(iconBounds)));
- }
-
- /**
- * Switches badging to left/right
- */
- public void setBadgeOnLeft(boolean badgeOnLeft) {
- mBadgeOnLeft = badgeOnLeft;
- }
-
- /**
- * Sets the background color used for wrapped adaptive icon
- */
- public void setWrapperBackgroundColor(int color) {
- mWrapperBackgroundColor = (Color.alpha(color) < 255) ? DEFAULT_WRAPPER_BACKGROUND : color;
- }
-
- /**
- * Disables the dominant color extraction for all icons loaded.
- */
- public void disableColorExtraction() {
- mDisableColorExtractor = true;
- }
-
- private Drawable normalizeAndWrapToAdaptiveIcon(@NonNull Drawable icon,
- boolean shrinkNonAdaptiveIcons, RectF outIconBounds, float[] outScale) {
- if (icon == null) {
- return null;
- }
- float scale = 1f;
-
- if (shrinkNonAdaptiveIcons && ATLEAST_OREO) {
- if (mWrapperIcon == null) {
- mWrapperIcon = mContext.getDrawable(R.drawable.adaptive_icon_drawable_wrapper)
- .mutate();
- }
- AdaptiveIconDrawable dr = (AdaptiveIconDrawable) mWrapperIcon;
- dr.setBounds(0, 0, 1, 1);
- boolean[] outShape = new boolean[1];
- scale = getNormalizer().getScale(icon, outIconBounds, dr.getIconMask(), outShape);
- if (!(icon instanceof AdaptiveIconDrawable) && !outShape[0]) {
- FixedScaleDrawable fsd = ((FixedScaleDrawable) dr.getForeground());
- fsd.setDrawable(icon);
- fsd.setScale(scale);
- icon = dr;
- scale = getNormalizer().getScale(icon, outIconBounds, null, null);
-
- ((ColorDrawable) dr.getBackground()).setColor(mWrapperBackgroundColor);
- }
- } else {
- scale = getNormalizer().getScale(icon, outIconBounds, null, null);
- }
-
- outScale[0] = scale;
- return icon;
- }
-
- /**
- * Adds the {@param badge} on top of {@param target} using the badge dimensions.
- */
- public void badgeWithDrawable(Bitmap target, Drawable badge) {
- mCanvas.setBitmap(target);
- badgeWithDrawable(mCanvas, badge);
- mCanvas.setBitmap(null);
- }
-
- /**
- * Adds the {@param badge} on top of {@param target} using the badge dimensions.
- */
- public void badgeWithDrawable(Canvas target, Drawable badge) {
- int badgeSize = getBadgeSizeForIconSize(mIconBitmapSize);
- if (mBadgeOnLeft) {
- badge.setBounds(0, mIconBitmapSize - badgeSize, badgeSize, mIconBitmapSize);
- } else {
- badge.setBounds(mIconBitmapSize - badgeSize, mIconBitmapSize - badgeSize,
- mIconBitmapSize, mIconBitmapSize);
- }
- badge.draw(target);
- }
-
- private Bitmap createIconBitmap(Drawable icon, float scale) {
- return createIconBitmap(icon, scale, mIconBitmapSize);
- }
-
- /**
- * @param icon drawable that should be flattened to a bitmap
- * @param scale the scale to apply before drawing {@param icon} on the canvas
- */
- public Bitmap createIconBitmap(@NonNull Drawable icon, float scale, int size) {
- Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
- if (icon == null) {
- return bitmap;
- }
- mCanvas.setBitmap(bitmap);
- mOldBounds.set(icon.getBounds());
-
- if (ATLEAST_OREO && icon instanceof AdaptiveIconDrawable) {
- int offset = Math.max((int) Math.ceil(BLUR_FACTOR * size),
- Math.round(size * (1 - scale) / 2 ));
- icon.setBounds(offset, offset, size - offset, size - offset);
- icon.draw(mCanvas);
- } else {
- if (icon instanceof BitmapDrawable) {
- BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
- Bitmap b = bitmapDrawable.getBitmap();
- if (bitmap != null && b.getDensity() == Bitmap.DENSITY_NONE) {
- bitmapDrawable.setTargetDensity(mContext.getResources().getDisplayMetrics());
- }
- }
- int width = size;
- int height = size;
-
- int intrinsicWidth = icon.getIntrinsicWidth();
- int intrinsicHeight = icon.getIntrinsicHeight();
- if (intrinsicWidth > 0 && intrinsicHeight > 0) {
- // Scale the icon proportionally to the icon dimensions
- final float ratio = (float) intrinsicWidth / intrinsicHeight;
- if (intrinsicWidth > intrinsicHeight) {
- height = (int) (width / ratio);
- } else if (intrinsicHeight > intrinsicWidth) {
- width = (int) (height * ratio);
- }
- }
- final int left = (size - width) / 2;
- final int top = (size - height) / 2;
- icon.setBounds(left, top, left + width, top + height);
- mCanvas.save();
- mCanvas.scale(scale, scale, size / 2, size / 2);
- icon.draw(mCanvas);
- mCanvas.restore();
-
- }
- icon.setBounds(mOldBounds);
- mCanvas.setBitmap(null);
- return bitmap;
- }
-
- @Override
- public void close() {
- clear();
- }
-
- public BitmapInfo makeDefaultIcon(UserHandle user) {
- return createBadgedIconBitmap(getFullResDefaultActivityIcon(mFillResIconDpi),
- user, Build.VERSION.SDK_INT);
- }
-
- public static Drawable getFullResDefaultActivityIcon(int iconDpi) {
- return Resources.getSystem().getDrawableForDensity(
- Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
- ? android.R.drawable.sym_def_app_icon : android.R.mipmap.sym_def_app_icon,
- iconDpi);
- }
-
- /**
- * Badges the provided source with the badge info
- */
- public BitmapInfo badgeBitmap(Bitmap source, BitmapInfo badgeInfo) {
- Bitmap icon = BitmapRenderer.createHardwareBitmap(mIconBitmapSize, mIconBitmapSize, (c) -> {
- getShadowGenerator().recreateIcon(source, c);
- badgeWithDrawable(c, new FixedSizeBitmapDrawable(badgeInfo.icon));
- });
- return BitmapInfo.of(icon, badgeInfo.color);
- }
-
- private int extractColor(Bitmap bitmap) {
- return mDisableColorExtractor ? 0 : mColorExtractor.findDominantColorByHue(bitmap);
- }
-
- /**
- * Returns the correct badge size given an icon size
- */
- public static int getBadgeSizeForIconSize(int iconSize) {
- return (int) (ICON_BADGE_SCALE * iconSize);
- }
-
- /**
- * An extension of {@link BitmapDrawable} which returns the bitmap pixel size as intrinsic size.
- * This allows the badging to be done based on the action bitmap size rather than
- * the scaled bitmap size.
- */
- private static class FixedSizeBitmapDrawable extends BitmapDrawable {
-
- public FixedSizeBitmapDrawable(Bitmap bitmap) {
- super(null, bitmap);
- }
-
- @Override
- public int getIntrinsicHeight() {
- return getBitmap().getWidth();
- }
-
- @Override
- public int getIntrinsicWidth() {
- return getBitmap().getWidth();
- }
- }
-}
diff --git a/iconloaderlib/src/com/android/launcher3/icons/BitmapInfo.java b/iconloaderlib/src/com/android/launcher3/icons/BitmapInfo.java
deleted file mode 100644
index d33f9b1..0000000
--- a/iconloaderlib/src/com/android/launcher3/icons/BitmapInfo.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * 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.launcher3.icons;
-
-import android.graphics.Bitmap;
-import android.graphics.Bitmap.Config;
-
-import androidx.annotation.NonNull;
-
-public class BitmapInfo {
-
- public static final Bitmap LOW_RES_ICON = Bitmap.createBitmap(1, 1, Config.ALPHA_8);
- public static final BitmapInfo LOW_RES_INFO = fromBitmap(LOW_RES_ICON);
-
- public final Bitmap icon;
- public final int color;
-
- public BitmapInfo(Bitmap icon, int color) {
- this.icon = icon;
- this.color = color;
- }
-
- /**
- * Ideally icon should not be null, except in cases when generating hardware bitmap failed
- */
- public final boolean isNullOrLowRes() {
- return icon == null || icon == LOW_RES_ICON;
- }
-
- public final boolean isLowRes() {
- return LOW_RES_ICON == icon;
- }
-
- public static BitmapInfo fromBitmap(@NonNull Bitmap bitmap) {
- return of(bitmap, 0);
- }
-
- public static BitmapInfo of(@NonNull Bitmap bitmap, int color) {
- return new BitmapInfo(bitmap, color);
- }
-
- /**
- * Interface to be implemented by drawables to provide a custom BitmapInfo
- */
- public interface Extender {
-
- /**
- * Called for creating a custom BitmapInfo
- */
- default BitmapInfo getExtendedInfo(Bitmap bitmap, int color, BaseIconFactory iconFactory) {
- return BitmapInfo.of(bitmap, color);
- }
-
- /**
- * Notifies the drawable that it will be drawn directly in the UI, without any preprocessing
- */
- default void prepareToDrawOnUi() { }
- }
-}
diff --git a/iconloaderlib/src/com/android/launcher3/icons/BitmapRenderer.java b/iconloaderlib/src/com/android/launcher3/icons/BitmapRenderer.java
deleted file mode 100644
index 5751ed9..0000000
--- a/iconloaderlib/src/com/android/launcher3/icons/BitmapRenderer.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * 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.launcher3.icons;
-
-import android.annotation.TargetApi;
-import android.graphics.Bitmap;
-import android.graphics.Bitmap.Config;
-import android.graphics.Canvas;
-import android.graphics.Picture;
-import android.graphics.Rect;
-import android.graphics.RectF;
-import android.os.Build;
-import android.os.Build.VERSION_CODES;
-
-/**
- * Interface representing a bitmap draw operation.
- */
-public interface BitmapRenderer {
-
- boolean USE_HARDWARE_BITMAP = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P;
-
- static Bitmap createSoftwareBitmap(int width, int height, BitmapRenderer renderer) {
- GraphicsUtils.noteNewBitmapCreated();
- Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
- renderer.draw(new Canvas(result));
- return result;
- }
-
- @TargetApi(Build.VERSION_CODES.P)
- static Bitmap createHardwareBitmap(int width, int height, BitmapRenderer renderer) {
- if (!USE_HARDWARE_BITMAP) {
- return createSoftwareBitmap(width, height, renderer);
- }
-
- GraphicsUtils.noteNewBitmapCreated();
- Picture picture = new Picture();
- renderer.draw(picture.beginRecording(width, height));
- picture.endRecording();
- return Bitmap.createBitmap(picture);
- }
-
- /**
- * Returns a bitmap from subset of the source bitmap. The new bitmap may be the
- * same object as source, or a copy may have been made.
- */
- static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height) {
- if (Build.VERSION.SDK_INT >= VERSION_CODES.O && source.getConfig() == Config.HARDWARE) {
- return createHardwareBitmap(width, height, c -> c.drawBitmap(source,
- new Rect(x, y, x + width, y + height), new RectF(0, 0, width, height), null));
- } else {
- GraphicsUtils.noteNewBitmapCreated();
- return Bitmap.createBitmap(source, x, y, width, height);
- }
- }
-
- void draw(Canvas out);
-}
diff --git a/iconloaderlib/src/com/android/launcher3/icons/ColorExtractor.java b/iconloaderlib/src/com/android/launcher3/icons/ColorExtractor.java
deleted file mode 100644
index 87bda82..0000000
--- a/iconloaderlib/src/com/android/launcher3/icons/ColorExtractor.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * 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.launcher3.icons;
-
-import android.graphics.Bitmap;
-import android.graphics.Color;
-import android.util.SparseArray;
-import java.util.Arrays;
-
-/**
- * Utility class for extracting colors from a bitmap.
- */
-public class ColorExtractor {
-
- private final int NUM_SAMPLES = 20;
- private final float[] mTmpHsv = new float[3];
- private final float[] mTmpHueScoreHistogram = new float[360];
- private final int[] mTmpPixels = new int[NUM_SAMPLES];
- private final SparseArray<Float> mTmpRgbScores = new SparseArray<>();
-
- /**
- * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
- * @param bitmap The bitmap to scan
- */
- public int findDominantColorByHue(Bitmap bitmap) {
- return findDominantColorByHue(bitmap, NUM_SAMPLES);
- }
-
- /**
- * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
- * @param bitmap The bitmap to scan
- */
- public int findDominantColorByHue(Bitmap bitmap, int samples) {
- final int height = bitmap.getHeight();
- final int width = bitmap.getWidth();
- int sampleStride = (int) Math.sqrt((height * width) / samples);
- if (sampleStride < 1) {
- sampleStride = 1;
- }
-
- // This is an out-param, for getting the hsv values for an rgb
- float[] hsv = mTmpHsv;
- Arrays.fill(hsv, 0);
-
- // First get the best hue, by creating a histogram over 360 hue buckets,
- // where each pixel contributes a score weighted by saturation, value, and alpha.
- float[] hueScoreHistogram = mTmpHueScoreHistogram;
- Arrays.fill(hueScoreHistogram, 0);
- float highScore = -1;
- int bestHue = -1;
-
- int[] pixels = mTmpPixels;
- Arrays.fill(pixels, 0);
- int pixelCount = 0;
-
- for (int y = 0; y < height; y += sampleStride) {
- for (int x = 0; x < width; x += sampleStride) {
- int argb = bitmap.getPixel(x, y);
- int alpha = 0xFF & (argb >> 24);
- if (alpha < 0x80) {
- // Drop mostly-transparent pixels.
- continue;
- }
- // Remove the alpha channel.
- int rgb = argb | 0xFF000000;
- Color.colorToHSV(rgb, hsv);
- // Bucket colors by the 360 integer hues.
- int hue = (int) hsv[0];
- if (hue < 0 || hue >= hueScoreHistogram.length) {
- // Defensively avoid array bounds violations.
- continue;
- }
- if (pixelCount < samples) {
- pixels[pixelCount++] = rgb;
- }
- float score = hsv[1] * hsv[2];
- hueScoreHistogram[hue] += score;
- if (hueScoreHistogram[hue] > highScore) {
- highScore = hueScoreHistogram[hue];
- bestHue = hue;
- }
- }
- }
-
- SparseArray<Float> rgbScores = mTmpRgbScores;
- rgbScores.clear();
- int bestColor = 0xff000000;
- highScore = -1;
- // Go back over the RGB colors that match the winning hue,
- // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
- // The highest-scoring RGB color wins.
- for (int i = 0; i < pixelCount; i++) {
- int rgb = pixels[i];
- Color.colorToHSV(rgb, hsv);
- int hue = (int) hsv[0];
- if (hue == bestHue) {
- float s = hsv[1];
- float v = hsv[2];
- int bucket = (int) (s * 100) + (int) (v * 10000);
- // Score by cumulative saturation * value.
- float score = s * v;
- Float oldTotal = rgbScores.get(bucket);
- float newTotal = oldTotal == null ? score : oldTotal + score;
- rgbScores.put(bucket, newTotal);
- if (newTotal > highScore) {
- highScore = newTotal;
- // All the colors in the winning bucket are very similar. Last in wins.
- bestColor = rgb;
- }
- }
- }
- return bestColor;
- }
-}
diff --git a/iconloaderlib/src/com/android/launcher3/icons/DotRenderer.java b/iconloaderlib/src/com/android/launcher3/icons/DotRenderer.java
deleted file mode 100644
index 97a0fd3..0000000
--- a/iconloaderlib/src/com/android/launcher3/icons/DotRenderer.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * 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.launcher3.icons;
-
-import static android.graphics.Paint.ANTI_ALIAS_FLAG;
-import static android.graphics.Paint.FILTER_BITMAP_FLAG;
-
-import android.graphics.Bitmap;
-import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.Paint;
-import android.graphics.Path;
-import android.graphics.PathMeasure;
-import android.graphics.Rect;
-import android.graphics.RectF;
-import android.util.Log;
-import android.view.ViewDebug;
-
-/**
- * Used to draw a notification dot on top of an icon.
- */
-public class DotRenderer {
-
- private static final String TAG = "DotRenderer";
-
- // The dot size is defined as a percentage of the app icon size.
- private static final float SIZE_PERCENTAGE = 0.228f;
-
- private final float mCircleRadius;
- private final Paint mCirclePaint = new Paint(ANTI_ALIAS_FLAG | FILTER_BITMAP_FLAG);
-
- private final Bitmap mBackgroundWithShadow;
- private final float mBitmapOffset;
-
- // Stores the center x and y position as a percentage (0 to 1) of the icon size
- private final float[] mRightDotPosition;
- private final float[] mLeftDotPosition;
-
- public DotRenderer(int iconSizePx, Path iconShapePath, int pathSize) {
- int size = Math.round(SIZE_PERCENTAGE * iconSizePx);
- ShadowGenerator.Builder builder = new ShadowGenerator.Builder(Color.TRANSPARENT);
- builder.ambientShadowAlpha = 88;
- mBackgroundWithShadow = builder.setupBlurForSize(size).createPill(size, size);
- mCircleRadius = builder.radius;
-
- mBitmapOffset = -mBackgroundWithShadow.getHeight() * 0.5f; // Same as width.
-
- // Find the points on the path that are closest to the top left and right corners.
- mLeftDotPosition = getPathPoint(iconShapePath, pathSize, -1);
- mRightDotPosition = getPathPoint(iconShapePath, pathSize, 1);
- }
-
- private static float[] getPathPoint(Path path, float size, float direction) {
- float halfSize = size / 2;
- // Small delta so that we don't get a zero size triangle
- float delta = 1;
-
- float x = halfSize + direction * halfSize;
- Path trianglePath = new Path();
- trianglePath.moveTo(halfSize, halfSize);
- trianglePath.lineTo(x + delta * direction, 0);
- trianglePath.lineTo(x, -delta);
- trianglePath.close();
-
- trianglePath.op(path, Path.Op.INTERSECT);
- float[] pos = new float[2];
- new PathMeasure(trianglePath, false).getPosTan(0, pos, null);
-
- pos[0] = pos[0] / size;
- pos[1] = pos[1] / size;
- return pos;
- }
-
- public float[] getLeftDotPosition() {
- return mLeftDotPosition;
- }
-
- public float[] getRightDotPosition() {
- return mRightDotPosition;
- }
-
- /**
- * Draw a circle on top of the canvas according to the given params.
- */
- public void draw(Canvas canvas, DrawParams params) {
- if (params == null) {
- Log.e(TAG, "Invalid null argument(s) passed in call to draw.");
- return;
- }
- canvas.save();
-
- Rect iconBounds = params.iconBounds;
- float[] dotPosition = params.leftAlign ? mLeftDotPosition : mRightDotPosition;
- float dotCenterX = iconBounds.left + iconBounds.width() * dotPosition[0];
- float dotCenterY = iconBounds.top + iconBounds.height() * dotPosition[1];
-
- // Ensure dot fits entirely in canvas clip bounds.
- Rect canvasBounds = canvas.getClipBounds();
- float offsetX = params.leftAlign
- ? Math.max(0, canvasBounds.left - (dotCenterX + mBitmapOffset))
- : Math.min(0, canvasBounds.right - (dotCenterX - mBitmapOffset));
- float offsetY = Math.max(0, canvasBounds.top - (dotCenterY + mBitmapOffset));
-
- // We draw the dot relative to its center.
- canvas.translate(dotCenterX + offsetX, dotCenterY + offsetY);
- canvas.scale(params.scale, params.scale);
-
- mCirclePaint.setColor(Color.BLACK);
- canvas.drawBitmap(mBackgroundWithShadow, mBitmapOffset, mBitmapOffset, mCirclePaint);
- mCirclePaint.setColor(params.color);
- canvas.drawCircle(0, 0, mCircleRadius, mCirclePaint);
- canvas.restore();
- }
-
- public static class DrawParams {
- /** The color (possibly based on the icon) to use for the dot. */
- @ViewDebug.ExportedProperty(category = "notification dot", formatToHexString = true)
- public int color;
- /** The bounds of the icon that the dot is drawn on top of. */
- @ViewDebug.ExportedProperty(category = "notification dot")
- public Rect iconBounds = new Rect();
- /** The progress of the animation, from 0 to 1. */
- @ViewDebug.ExportedProperty(category = "notification dot")
- public float scale;
- /** Whether the dot should align to the top left of the icon rather than the top right. */
- @ViewDebug.ExportedProperty(category = "notification dot")
- public boolean leftAlign;
- }
-}
diff --git a/iconloaderlib/src/com/android/launcher3/icons/FixedScaleDrawable.java b/iconloaderlib/src/com/android/launcher3/icons/FixedScaleDrawable.java
deleted file mode 100644
index 516965e..0000000
--- a/iconloaderlib/src/com/android/launcher3/icons/FixedScaleDrawable.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package com.android.launcher3.icons;
-
-import android.content.res.Resources;
-import android.content.res.Resources.Theme;
-import android.graphics.Canvas;
-import android.graphics.drawable.ColorDrawable;
-import android.graphics.drawable.DrawableWrapper;
-import android.util.AttributeSet;
-
-import org.xmlpull.v1.XmlPullParser;
-
-/**
- * Extension of {@link DrawableWrapper} which scales the child drawables by a fixed amount.
- */
-public class FixedScaleDrawable extends DrawableWrapper {
-
- // TODO b/33553066 use the constant defined in MaskableIconDrawable
- private static final float LEGACY_ICON_SCALE = .7f * .6667f;
- private float mScaleX, mScaleY;
-
- public FixedScaleDrawable() {
- super(new ColorDrawable());
- mScaleX = LEGACY_ICON_SCALE;
- mScaleY = LEGACY_ICON_SCALE;
- }
-
- @Override
- public void draw(Canvas canvas) {
- int saveCount = canvas.save();
- canvas.scale(mScaleX, mScaleY,
- getBounds().exactCenterX(), getBounds().exactCenterY());
- super.draw(canvas);
- canvas.restoreToCount(saveCount);
- }
-
- @Override
- public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs) { }
-
- @Override
- public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs, Theme theme) { }
-
- public void setScale(float scale) {
- float h = getIntrinsicHeight();
- float w = getIntrinsicWidth();
- mScaleX = scale * LEGACY_ICON_SCALE;
- mScaleY = scale * LEGACY_ICON_SCALE;
- if (h > w && w > 0) {
- mScaleX *= w / h;
- } else if (w > h && h > 0) {
- mScaleY *= h / w;
- }
- }
-}
diff --git a/iconloaderlib/src/com/android/launcher3/icons/GraphicsUtils.java b/iconloaderlib/src/com/android/launcher3/icons/GraphicsUtils.java
deleted file mode 100644
index 22f1f23..0000000
--- a/iconloaderlib/src/com/android/launcher3/icons/GraphicsUtils.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * 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.launcher3.icons;
-
-import android.graphics.Bitmap;
-import android.graphics.Rect;
-import android.graphics.Region;
-import android.graphics.RegionIterator;
-import android.util.Log;
-
-import androidx.annotation.ColorInt;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-
-public class GraphicsUtils {
-
- private static final String TAG = "GraphicsUtils";
-
- public static Runnable sOnNewBitmapRunnable = () -> { };
-
- /**
- * Set the alpha component of {@code color} to be {@code alpha}. Unlike the support lib version,
- * it bounds the alpha in valid range instead of throwing an exception to allow for safer
- * interpolation of color animations
- */
- @ColorInt
- public static int setColorAlphaBound(int color, int alpha) {
- if (alpha < 0) {
- alpha = 0;
- } else if (alpha > 255) {
- alpha = 255;
- }
- return (color & 0x00ffffff) | (alpha << 24);
- }
-
- /**
- * Compresses the bitmap to a byte array for serialization.
- */
- public static byte[] flattenBitmap(Bitmap bitmap) {
- // Try go guesstimate how much space the icon will take when serialized
- // to avoid unnecessary allocations/copies during the write (4 bytes per pixel).
- int size = bitmap.getWidth() * bitmap.getHeight() * 4;
- ByteArrayOutputStream out = new ByteArrayOutputStream(size);
- try {
- bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
- out.flush();
- out.close();
- return out.toByteArray();
- } catch (IOException e) {
- Log.w(TAG, "Could not write bitmap");
- return null;
- }
- }
-
- public static int getArea(Region r) {
- RegionIterator itr = new RegionIterator(r);
- int area = 0;
- Rect tempRect = new Rect();
- while (itr.next(tempRect)) {
- area += tempRect.width() * tempRect.height();
- }
- return area;
- }
-
- /**
- * Utility method to track new bitmap creation
- */
- public static void noteNewBitmapCreated() {
- sOnNewBitmapRunnable.run();
- }
-}
diff --git a/iconloaderlib/src/com/android/launcher3/icons/IconNormalizer.java b/iconloaderlib/src/com/android/launcher3/icons/IconNormalizer.java
deleted file mode 100644
index de39e79..0000000
--- a/iconloaderlib/src/com/android/launcher3/icons/IconNormalizer.java
+++ /dev/null
@@ -1,411 +0,0 @@
-/*
- * 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.launcher3.icons;
-
-import android.annotation.TargetApi;
-import android.content.Context;
-import android.content.res.Resources;
-import android.graphics.Bitmap;
-import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.Matrix;
-import android.graphics.Paint;
-import android.graphics.Path;
-import android.graphics.PorterDuff;
-import android.graphics.PorterDuffXfermode;
-import android.graphics.Rect;
-import android.graphics.RectF;
-import android.graphics.Region;
-import android.graphics.drawable.AdaptiveIconDrawable;
-import android.graphics.drawable.Drawable;
-import android.os.Build;
-import android.util.Log;
-
-import java.nio.ByteBuffer;
-
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
-
-public class IconNormalizer {
-
- private static final String TAG = "IconNormalizer";
- private static final boolean DEBUG = false;
- // Ratio of icon visible area to full icon size for a square shaped icon
- private static final float MAX_SQUARE_AREA_FACTOR = 375.0f / 576;
- // Ratio of icon visible area to full icon size for a circular shaped icon
- private static final float MAX_CIRCLE_AREA_FACTOR = 380.0f / 576;
-
- private static final float CIRCLE_AREA_BY_RECT = (float) Math.PI / 4;
-
- // Slope used to calculate icon visible area to full icon size for any generic shaped icon.
- private static final float LINEAR_SCALE_SLOPE =
- (MAX_CIRCLE_AREA_FACTOR - MAX_SQUARE_AREA_FACTOR) / (1 - CIRCLE_AREA_BY_RECT);
-
- private static final int MIN_VISIBLE_ALPHA = 40;
-
- // Shape detection related constants
- private static final float BOUND_RATIO_MARGIN = .05f;
- private static final float PIXEL_DIFF_PERCENTAGE_THRESHOLD = 0.005f;
- private static final float SCALE_NOT_INITIALIZED = 0;
-
- // Ratio of the diameter of an normalized circular icon to the actual icon size.
- public static final float ICON_VISIBLE_AREA_FACTOR = 0.92f;
-
- private final int mMaxSize;
- private final Bitmap mBitmap;
- private final Canvas mCanvas;
- private final Paint mPaintMaskShape;
- private final Paint mPaintMaskShapeOutline;
- private final byte[] mPixels;
-
- private final RectF mAdaptiveIconBounds;
- private float mAdaptiveIconScale;
-
- private boolean mEnableShapeDetection;
-
- // for each y, stores the position of the leftmost x and the rightmost x
- private final float[] mLeftBorder;
- private final float[] mRightBorder;
- private final Rect mBounds;
- private final Path mShapePath;
- private final Matrix mMatrix;
-
- /** package private **/
- IconNormalizer(Context context, int iconBitmapSize, boolean shapeDetection) {
- // Use twice the icon size as maximum size to avoid scaling down twice.
- mMaxSize = iconBitmapSize * 2;
- mBitmap = Bitmap.createBitmap(mMaxSize, mMaxSize, Bitmap.Config.ALPHA_8);
- mCanvas = new Canvas(mBitmap);
- mPixels = new byte[mMaxSize * mMaxSize];
- mLeftBorder = new float[mMaxSize];
- mRightBorder = new float[mMaxSize];
- mBounds = new Rect();
- mAdaptiveIconBounds = new RectF();
-
- mPaintMaskShape = new Paint();
- mPaintMaskShape.setColor(Color.RED);
- mPaintMaskShape.setStyle(Paint.Style.FILL);
- mPaintMaskShape.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.XOR));
-
- mPaintMaskShapeOutline = new Paint();
- mPaintMaskShapeOutline.setStrokeWidth(
- 2 * context.getResources().getDisplayMetrics().density);
- mPaintMaskShapeOutline.setStyle(Paint.Style.STROKE);
- mPaintMaskShapeOutline.setColor(Color.BLACK);
- mPaintMaskShapeOutline.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
-
- mShapePath = new Path();
- mMatrix = new Matrix();
- mAdaptiveIconScale = SCALE_NOT_INITIALIZED;
- mEnableShapeDetection = shapeDetection;
- }
-
- private static float getScale(float hullArea, float boundingArea, float fullArea) {
- float hullByRect = hullArea / boundingArea;
- float scaleRequired;
- if (hullByRect < CIRCLE_AREA_BY_RECT) {
- scaleRequired = MAX_CIRCLE_AREA_FACTOR;
- } else {
- scaleRequired = MAX_SQUARE_AREA_FACTOR + LINEAR_SCALE_SLOPE * (1 - hullByRect);
- }
-
- float areaScale = hullArea / fullArea;
- // Use sqrt of the final ratio as the images is scaled across both width and height.
- return areaScale > scaleRequired ? (float) Math.sqrt(scaleRequired / areaScale) : 1;
- }
-
- /**
- * @param d Should be AdaptiveIconDrawable
- * @param size Canvas size to use
- */
- @TargetApi(Build.VERSION_CODES.O)
- public static float normalizeAdaptiveIcon(Drawable d, int size, @Nullable RectF outBounds) {
- Rect tmpBounds = new Rect(d.getBounds());
- d.setBounds(0, 0, size, size);
-
- Path path = ((AdaptiveIconDrawable) d).getIconMask();
- Region region = new Region();
- region.setPath(path, new Region(0, 0, size, size));
-
- Rect hullBounds = region.getBounds();
- int hullArea = GraphicsUtils.getArea(region);
-
- if (outBounds != null) {
- float sizeF = size;
- outBounds.set(
- hullBounds.left / sizeF,
- hullBounds.top / sizeF,
- 1 - (hullBounds.right / sizeF),
- 1 - (hullBounds.bottom / sizeF));
- }
- d.setBounds(tmpBounds);
- return getScale(hullArea, hullArea, size * size);
- }
-
- /**
- * Returns if the shape of the icon is same as the path.
- * For this method to work, the shape path bounds should be in [0,1]x[0,1] bounds.
- */
- private boolean isShape(Path maskPath) {
- // Condition1:
- // If width and height of the path not close to a square, then the icon shape is
- // not same as the mask shape.
- float iconRatio = ((float) mBounds.width()) / mBounds.height();
- if (Math.abs(iconRatio - 1) > BOUND_RATIO_MARGIN) {
- if (DEBUG) {
- Log.d(TAG, "Not same as mask shape because width != height. " + iconRatio);
- }
- return false;
- }
-
- // Condition 2:
- // Actual icon (white) and the fitted shape (e.g., circle)(red) XOR operation
- // should generate transparent image, if the actual icon is equivalent to the shape.
-
- // Fit the shape within the icon's bounding box
- mMatrix.reset();
- mMatrix.setScale(mBounds.width(), mBounds.height());
- mMatrix.postTranslate(mBounds.left, mBounds.top);
- maskPath.transform(mMatrix, mShapePath);
-
- // XOR operation
- mCanvas.drawPath(mShapePath, mPaintMaskShape);
-
- // DST_OUT operation around the mask path outline
- mCanvas.drawPath(mShapePath, mPaintMaskShapeOutline);
-
- // Check if the result is almost transparent
- return isTransparentBitmap();
- }
-
- /**
- * Used to determine if certain the bitmap is transparent.
- */
- private boolean isTransparentBitmap() {
- ByteBuffer buffer = ByteBuffer.wrap(mPixels);
- buffer.rewind();
- mBitmap.copyPixelsToBuffer(buffer);
-
- int y = mBounds.top;
- // buffer position
- int index = y * mMaxSize;
- // buffer shift after every row, width of buffer = mMaxSize
- int rowSizeDiff = mMaxSize - mBounds.right;
-
- int sum = 0;
- for (; y < mBounds.bottom; y++) {
- index += mBounds.left;
- for (int x = mBounds.left; x < mBounds.right; x++) {
- if ((mPixels[index] & 0xFF) > MIN_VISIBLE_ALPHA) {
- sum++;
- }
- index++;
- }
- index += rowSizeDiff;
- }
-
- float percentageDiffPixels = ((float) sum) / (mBounds.width() * mBounds.height());
- return percentageDiffPixels < PIXEL_DIFF_PERCENTAGE_THRESHOLD;
- }
-
- /**
- * Returns the amount by which the {@param d} should be scaled (in both dimensions) so that it
- * matches the design guidelines for a launcher icon.
- *
- * We first calculate the convex hull of the visible portion of the icon.
- * This hull then compared with the bounding rectangle of the hull to find how closely it
- * resembles a circle and a square, by comparing the ratio of the areas. Note that this is not an
- * ideal solution but it gives satisfactory result without affecting the performance.
- *
- * This closeness is used to determine the ratio of hull area to the full icon size.
- * Refer {@link #MAX_CIRCLE_AREA_FACTOR} and {@link #MAX_SQUARE_AREA_FACTOR}
- *
- * @param outBounds optional rect to receive the fraction distance from each edge.
- */
- public synchronized float getScale(@NonNull Drawable d, @Nullable RectF outBounds,
- @Nullable Path path, @Nullable boolean[] outMaskShape) {
- if (BaseIconFactory.ATLEAST_OREO && d instanceof AdaptiveIconDrawable) {
- if (mAdaptiveIconScale == SCALE_NOT_INITIALIZED) {
- mAdaptiveIconScale = normalizeAdaptiveIcon(d, mMaxSize, mAdaptiveIconBounds);
- }
- if (outBounds != null) {
- outBounds.set(mAdaptiveIconBounds);
- }
- return mAdaptiveIconScale;
- }
- int width = d.getIntrinsicWidth();
- int height = d.getIntrinsicHeight();
- if (width <= 0 || height <= 0) {
- width = width <= 0 || width > mMaxSize ? mMaxSize : width;
- height = height <= 0 || height > mMaxSize ? mMaxSize : height;
- } else if (width > mMaxSize || height > mMaxSize) {
- int max = Math.max(width, height);
- width = mMaxSize * width / max;
- height = mMaxSize * height / max;
- }
-
- mBitmap.eraseColor(Color.TRANSPARENT);
- d.setBounds(0, 0, width, height);
- d.draw(mCanvas);
-
- ByteBuffer buffer = ByteBuffer.wrap(mPixels);
- buffer.rewind();
- mBitmap.copyPixelsToBuffer(buffer);
-
- // Overall bounds of the visible icon.
- int topY = -1;
- int bottomY = -1;
- int leftX = mMaxSize + 1;
- int rightX = -1;
-
- // Create border by going through all pixels one row at a time and for each row find
- // the first and the last non-transparent pixel. Set those values to mLeftBorder and
- // mRightBorder and use -1 if there are no visible pixel in the row.
-
- // buffer position
- int index = 0;
- // buffer shift after every row, width of buffer = mMaxSize
- int rowSizeDiff = mMaxSize - width;
- // first and last position for any row.
- int firstX, lastX;
-
- for (int y = 0; y < height; y++) {
- firstX = lastX = -1;
- for (int x = 0; x < width; x++) {
- if ((mPixels[index] & 0xFF) > MIN_VISIBLE_ALPHA) {
- if (firstX == -1) {
- firstX = x;
- }
- lastX = x;
- }
- index++;
- }
- index += rowSizeDiff;
-
- mLeftBorder[y] = firstX;
- mRightBorder[y] = lastX;
-
- // If there is at least one visible pixel, update the overall bounds.
- if (firstX != -1) {
- bottomY = y;
- if (topY == -1) {
- topY = y;
- }
-
- leftX = Math.min(leftX, firstX);
- rightX = Math.max(rightX, lastX);
- }
- }
-
- if (topY == -1 || rightX == -1) {
- // No valid pixels found. Do not scale.
- return 1;
- }
-
- convertToConvexArray(mLeftBorder, 1, topY, bottomY);
- convertToConvexArray(mRightBorder, -1, topY, bottomY);
-
- // Area of the convex hull
- float area = 0;
- for (int y = 0; y < height; y++) {
- if (mLeftBorder[y] <= -1) {
- continue;
- }
- area += mRightBorder[y] - mLeftBorder[y] + 1;
- }
-
- mBounds.left = leftX;
- mBounds.right = rightX;
-
- mBounds.top = topY;
- mBounds.bottom = bottomY;
-
- if (outBounds != null) {
- outBounds.set(((float) mBounds.left) / width, ((float) mBounds.top) / height,
- 1 - ((float) mBounds.right) / width,
- 1 - ((float) mBounds.bottom) / height);
- }
- if (outMaskShape != null && mEnableShapeDetection && outMaskShape.length > 0) {
- outMaskShape[0] = isShape(path);
- }
- // Area of the rectangle required to fit the convex hull
- float rectArea = (bottomY + 1 - topY) * (rightX + 1 - leftX);
- return getScale(area, rectArea, width * height);
- }
-
- /**
- * Modifies {@param xCoordinates} to represent a convex border. Fills in all missing values
- * (except on either ends) with appropriate values.
- * @param xCoordinates map of x coordinate per y.
- * @param direction 1 for left border and -1 for right border.
- * @param topY the first Y position (inclusive) with a valid value.
- * @param bottomY the last Y position (inclusive) with a valid value.
- */
- private static void convertToConvexArray(
- float[] xCoordinates, int direction, int topY, int bottomY) {
- int total = xCoordinates.length;
- // The tangent at each pixel.
- float[] angles = new float[total - 1];
-
- int first = topY; // First valid y coordinate
- int last = -1; // Last valid y coordinate which didn't have a missing value
-
- float lastAngle = Float.MAX_VALUE;
-
- for (int i = topY + 1; i <= bottomY; i++) {
- if (xCoordinates[i] <= -1) {
- continue;
- }
- int start;
-
- if (lastAngle == Float.MAX_VALUE) {
- start = first;
- } else {
- float currentAngle = (xCoordinates[i] - xCoordinates[last]) / (i - last);
- start = last;
- // If this position creates a concave angle, keep moving up until we find a
- // position which creates a convex angle.
- if ((currentAngle - lastAngle) * direction < 0) {
- while (start > first) {
- start --;
- currentAngle = (xCoordinates[i] - xCoordinates[start]) / (i - start);
- if ((currentAngle - angles[start]) * direction >= 0) {
- break;
- }
- }
- }
- }
-
- // Reset from last check
- lastAngle = (xCoordinates[i] - xCoordinates[start]) / (i - start);
- // Update all the points from start.
- for (int j = start; j < i; j++) {
- angles[j] = lastAngle;
- xCoordinates[j] = xCoordinates[start] + lastAngle * (j - start);
- }
- last = i;
- }
- }
-
- /**
- * @return The diameter of the normalized circle that fits inside of the square (size x size).
- */
- public static int getNormalizedCircleSize(int size) {
- float area = size * size * MAX_CIRCLE_AREA_FACTOR;
- return (int) Math.round(Math.sqrt((4 * area) / Math.PI));
- }
-}
diff --git a/iconloaderlib/src/com/android/launcher3/icons/ShadowGenerator.java b/iconloaderlib/src/com/android/launcher3/icons/ShadowGenerator.java
deleted file mode 100644
index 7702727..0000000
--- a/iconloaderlib/src/com/android/launcher3/icons/ShadowGenerator.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * 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.launcher3.icons;
-
-import static com.android.launcher3.icons.GraphicsUtils.setColorAlphaBound;
-
-import android.graphics.Bitmap;
-import android.graphics.BlurMaskFilter;
-import android.graphics.BlurMaskFilter.Blur;
-import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.Paint;
-import android.graphics.PorterDuff;
-import android.graphics.PorterDuffXfermode;
-import android.graphics.RectF;
-
-/**
- * Utility class to add shadows to bitmaps.
- */
-public class ShadowGenerator {
- public static final float BLUR_FACTOR = 0.5f/48;
-
- // Percent of actual icon size
- public static final float KEY_SHADOW_DISTANCE = 1f/48;
- private static final int KEY_SHADOW_ALPHA = 61;
- // Percent of actual icon size
- private static final float HALF_DISTANCE = 0.5f;
- private static final int AMBIENT_SHADOW_ALPHA = 30;
-
- private final int mIconSize;
-
- private final Paint mBlurPaint;
- private final Paint mDrawPaint;
- private final BlurMaskFilter mDefaultBlurMaskFilter;
-
- public ShadowGenerator(int iconSize) {
- mIconSize = iconSize;
- mBlurPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
- mDrawPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
- mDefaultBlurMaskFilter = new BlurMaskFilter(mIconSize * BLUR_FACTOR, Blur.NORMAL);
- }
-
- public synchronized void recreateIcon(Bitmap icon, Canvas out) {
- recreateIcon(icon, mDefaultBlurMaskFilter, AMBIENT_SHADOW_ALPHA, KEY_SHADOW_ALPHA, out);
- }
-
- public synchronized void recreateIcon(Bitmap icon, BlurMaskFilter blurMaskFilter,
- int ambientAlpha, int keyAlpha, Canvas out) {
- int[] offset = new int[2];
- mBlurPaint.setMaskFilter(blurMaskFilter);
- Bitmap shadow = icon.extractAlpha(mBlurPaint, offset);
-
- // Draw ambient shadow
- mDrawPaint.setAlpha(ambientAlpha);
- out.drawBitmap(shadow, offset[0], offset[1], mDrawPaint);
-
- // Draw key shadow
- mDrawPaint.setAlpha(keyAlpha);
- out.drawBitmap(shadow, offset[0], offset[1] + KEY_SHADOW_DISTANCE * mIconSize, mDrawPaint);
-
- // Draw the icon
- mDrawPaint.setAlpha(255);
- out.drawBitmap(icon, 0, 0, mDrawPaint);
- }
-
- /**
- * Returns the minimum amount by which an icon with {@param bounds} should be scaled
- * so that the shadows do not get clipped.
- */
- public static float getScaleForBounds(RectF bounds) {
- float scale = 1;
-
- // For top, left & right, we need same space.
- float minSide = Math.min(Math.min(bounds.left, bounds.right), bounds.top);
- if (minSide < BLUR_FACTOR) {
- scale = (HALF_DISTANCE - BLUR_FACTOR) / (HALF_DISTANCE - minSide);
- }
-
- float bottomSpace = BLUR_FACTOR + KEY_SHADOW_DISTANCE;
- if (bounds.bottom < bottomSpace) {
- scale = Math.min(scale, (HALF_DISTANCE - bottomSpace) / (HALF_DISTANCE - bounds.bottom));
- }
- return scale;
- }
-
- public static class Builder {
-
- public final RectF bounds = new RectF();
- public final int color;
-
- public int ambientShadowAlpha = AMBIENT_SHADOW_ALPHA;
-
- public float shadowBlur;
-
- public float keyShadowDistance;
- public int keyShadowAlpha = KEY_SHADOW_ALPHA;
- public float radius;
-
- public Builder(int color) {
- this.color = color;
- }
-
- public Builder setupBlurForSize(int height) {
- shadowBlur = height * 1f / 24;
- keyShadowDistance = height * 1f / 16;
- return this;
- }
-
- public Bitmap createPill(int width, int height) {
- return createPill(width, height, height / 2f);
- }
-
- public Bitmap createPill(int width, int height, float r) {
- radius = r;
-
- int centerX = Math.round(width / 2f + shadowBlur);
- int centerY = Math.round(radius + shadowBlur + keyShadowDistance);
- int center = Math.max(centerX, centerY);
- bounds.set(0, 0, width, height);
- bounds.offsetTo(center - width / 2f, center - height / 2f);
-
- int size = center * 2;
- return BitmapRenderer.createHardwareBitmap(size, size, this::drawShadow);
- }
-
- public void drawShadow(Canvas c) {
- Paint p = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
- p.setColor(color);
-
- // Key shadow
- p.setShadowLayer(shadowBlur, 0, keyShadowDistance,
- setColorAlphaBound(Color.BLACK, keyShadowAlpha));
- c.drawRoundRect(bounds, radius, radius, p);
-
- // Ambient shadow
- p.setShadowLayer(shadowBlur, 0, 0,
- setColorAlphaBound(Color.BLACK, ambientShadowAlpha));
- c.drawRoundRect(bounds, radius, radius, p);
-
- if (Color.alpha(color) < 255) {
- // Clear any content inside the pill-rect for translucent fill.
- p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
- p.clearShadowLayer();
- p.setColor(Color.BLACK);
- c.drawRoundRect(bounds, radius, radius, p);
-
- p.setXfermode(null);
- p.setColor(color);
- c.drawRoundRect(bounds, radius, radius, p);
- }
- }
- }
-}
diff --git a/iconloaderlib/src/com/android/launcher3/icons/cache/BaseIconCache.java b/iconloaderlib/src/com/android/launcher3/icons/cache/BaseIconCache.java
deleted file mode 100644
index 4c634cb..0000000
--- a/iconloaderlib/src/com/android/launcher3/icons/cache/BaseIconCache.java
+++ /dev/null
@@ -1,582 +0,0 @@
-/*
- * 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.launcher3.icons.cache;
-
-import static com.android.launcher3.icons.BaseIconFactory.getFullResDefaultActivityIcon;
-import static com.android.launcher3.icons.BitmapInfo.LOW_RES_ICON;
-import static com.android.launcher3.icons.GraphicsUtils.setColorAlphaBound;
-
-import android.content.ComponentName;
-import android.content.ContentValues;
-import android.content.Context;
-import android.content.pm.ActivityInfo;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager;
-import android.content.pm.PackageManager.NameNotFoundException;
-import android.content.res.Resources;
-import android.database.Cursor;
-import android.database.sqlite.SQLiteDatabase;
-import android.database.sqlite.SQLiteException;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.graphics.drawable.Drawable;
-import android.os.Build;
-import android.os.Handler;
-import android.os.LocaleList;
-import android.os.Looper;
-import android.os.Process;
-import android.os.UserHandle;
-import android.text.TextUtils;
-import android.util.Log;
-
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
-import androidx.annotation.VisibleForTesting;
-
-import com.android.launcher3.icons.BaseIconFactory;
-import com.android.launcher3.icons.BitmapInfo;
-import com.android.launcher3.icons.BitmapRenderer;
-import com.android.launcher3.icons.GraphicsUtils;
-import com.android.launcher3.util.ComponentKey;
-import com.android.launcher3.util.SQLiteCacheHelper;
-
-import java.util.AbstractMap;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.function.Supplier;
-
-public abstract class BaseIconCache {
-
- private static final String TAG = "BaseIconCache";
- private static final boolean DEBUG = false;
-
- private static final int INITIAL_ICON_CACHE_CAPACITY = 50;
-
- // Empty class name is used for storing package default entry.
- public static final String EMPTY_CLASS_NAME = ".";
-
- public static class CacheEntry {
-
- @NonNull
- public BitmapInfo bitmap = BitmapInfo.LOW_RES_INFO;
- public CharSequence title = "";
- public CharSequence contentDescription = "";
- }
-
- private final HashMap<UserHandle, BitmapInfo> mDefaultIcons = new HashMap<>();
-
- protected final Context mContext;
- protected final PackageManager mPackageManager;
-
- private final Map<ComponentKey, CacheEntry> mCache;
- protected final Handler mWorkerHandler;
-
- protected int mIconDpi;
- protected IconDB mIconDb;
- protected LocaleList mLocaleList = LocaleList.getEmptyLocaleList();
- protected String mSystemState = "";
-
- private final String mDbFileName;
- private final BitmapFactory.Options mDecodeOptions;
- private final Looper mBgLooper;
-
- public BaseIconCache(Context context, String dbFileName, Looper bgLooper,
- int iconDpi, int iconPixelSize, boolean inMemoryCache) {
- mContext = context;
- mDbFileName = dbFileName;
- mPackageManager = context.getPackageManager();
- mBgLooper = bgLooper;
- mWorkerHandler = new Handler(mBgLooper);
-
- if (inMemoryCache) {
- mCache = new HashMap<>(INITIAL_ICON_CACHE_CAPACITY);
- } else {
- // Use a dummy cache
- mCache = new AbstractMap<ComponentKey, CacheEntry>() {
- @Override
- public Set<Entry<ComponentKey, CacheEntry>> entrySet() {
- return Collections.emptySet();
- }
-
- @Override
- public CacheEntry put(ComponentKey key, CacheEntry value) {
- return value;
- }
- };
- }
-
- if (BitmapRenderer.USE_HARDWARE_BITMAP && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- mDecodeOptions = new BitmapFactory.Options();
- mDecodeOptions.inPreferredConfig = Bitmap.Config.HARDWARE;
- } else {
- mDecodeOptions = null;
- }
-
- updateSystemState();
- mIconDpi = iconDpi;
- mIconDb = new IconDB(context, dbFileName, iconPixelSize);
- }
-
- /**
- * Returns the persistable serial number for {@param user}. Subclass should implement proper
- * caching strategy to avoid making binder call every time.
- */
- protected abstract long getSerialNumberForUser(UserHandle user);
-
- /**
- * Return true if the given app is an instant app and should be badged appropriately.
- */
- protected abstract boolean isInstantApp(ApplicationInfo info);
-
- /**
- * Opens and returns an icon factory. The factory is recycled by the caller.
- */
- protected abstract BaseIconFactory getIconFactory();
-
- public void updateIconParams(int iconDpi, int iconPixelSize) {
- mWorkerHandler.post(() -> updateIconParamsBg(iconDpi, iconPixelSize));
- }
-
- private synchronized void updateIconParamsBg(int iconDpi, int iconPixelSize) {
- mIconDpi = iconDpi;
- mDefaultIcons.clear();
- mIconDb.clear();
- mIconDb.close();
- mIconDb = new IconDB(mContext, mDbFileName, iconPixelSize);
- mCache.clear();
- }
-
- private Drawable getFullResIcon(Resources resources, int iconId) {
- if (resources != null && iconId != 0) {
- try {
- return resources.getDrawableForDensity(iconId, mIconDpi);
- } catch (Resources.NotFoundException e) { }
- }
- return getFullResDefaultActivityIcon(mIconDpi);
- }
-
- public Drawable getFullResIcon(String packageName, int iconId) {
- try {
- return getFullResIcon(mPackageManager.getResourcesForApplication(packageName), iconId);
- } catch (PackageManager.NameNotFoundException e) { }
- return getFullResDefaultActivityIcon(mIconDpi);
- }
-
- public Drawable getFullResIcon(ActivityInfo info) {
- try {
- return getFullResIcon(mPackageManager.getResourcesForApplication(info.applicationInfo),
- info.getIconResource());
- } catch (PackageManager.NameNotFoundException e) { }
- return getFullResDefaultActivityIcon(mIconDpi);
- }
-
- private BitmapInfo makeDefaultIcon(UserHandle user) {
- try (BaseIconFactory li = getIconFactory()) {
- return li.makeDefaultIcon(user);
- }
- }
-
- /**
- * Remove any records for the supplied ComponentName.
- */
- public synchronized void remove(ComponentName componentName, UserHandle user) {
- mCache.remove(new ComponentKey(componentName, user));
- }
-
- /**
- * Remove any records for the supplied package name from memory.
- */
- private void removeFromMemCacheLocked(String packageName, UserHandle user) {
- HashSet<ComponentKey> forDeletion = new HashSet<>();
- for (ComponentKey key: mCache.keySet()) {
- if (key.componentName.getPackageName().equals(packageName)
- && key.user.equals(user)) {
- forDeletion.add(key);
- }
- }
- for (ComponentKey condemned: forDeletion) {
- mCache.remove(condemned);
- }
- }
-
- /**
- * Removes the entries related to the given package in memory and persistent DB.
- */
- public synchronized void removeIconsForPkg(String packageName, UserHandle user) {
- removeFromMemCacheLocked(packageName, user);
- long userSerial = getSerialNumberForUser(user);
- mIconDb.delete(
- IconDB.COLUMN_COMPONENT + " LIKE ? AND " + IconDB.COLUMN_USER + " = ?",
- new String[]{packageName + "/%", Long.toString(userSerial)});
- }
-
- public IconCacheUpdateHandler getUpdateHandler() {
- updateSystemState();
- return new IconCacheUpdateHandler(this);
- }
-
- /**
- * Refreshes the system state definition used to check the validity of the cache. It
- * incorporates all the properties that can affect the cache like the list of enabled locale
- * and system-version.
- */
- private void updateSystemState() {
- mLocaleList = mContext.getResources().getConfiguration().getLocales();
- mSystemState = mLocaleList.toLanguageTags() + "," + Build.VERSION.SDK_INT;
- }
-
- protected String getIconSystemState(String packageName) {
- return mSystemState;
- }
-
- /**
- * Adds an entry into the DB and the in-memory cache.
- * @param replaceExisting if true, it will recreate the bitmap even if it already exists in
- * the memory. This is useful then the previous bitmap was created using
- * old data.
- */
- @VisibleForTesting
- public synchronized <T> void addIconToDBAndMemCache(T object, CachingLogic<T> cachingLogic,
- PackageInfo info, long userSerial, boolean replaceExisting) {
- UserHandle user = cachingLogic.getUser(object);
- ComponentName componentName = cachingLogic.getComponent(object);
-
- final ComponentKey key = new ComponentKey(componentName, user);
- CacheEntry entry = null;
- if (!replaceExisting) {
- entry = mCache.get(key);
- // We can't reuse the entry if the high-res icon is not present.
- if (entry == null || entry.bitmap.isNullOrLowRes()) {
- entry = null;
- }
- }
- if (entry == null) {
- entry = new CacheEntry();
- entry.bitmap = cachingLogic.loadIcon(mContext, object);
- }
- // Icon can't be loaded from cachingLogic, which implies alternative icon was loaded
- // (e.g. fallback icon, default icon). So we drop here since there's no point in caching
- // an empty entry.
- if (entry.bitmap.isNullOrLowRes()) return;
- entry.title = cachingLogic.getLabel(object);
- entry.contentDescription = mPackageManager.getUserBadgedLabel(entry.title, user);
- if (cachingLogic.addToMemCache()) mCache.put(key, entry);
-
- ContentValues values = newContentValues(entry.bitmap, entry.title.toString(),
- componentName.getPackageName(), cachingLogic.getKeywords(object, mLocaleList));
- addIconToDB(values, componentName, info, userSerial,
- cachingLogic.getLastUpdatedTime(object, info));
- }
-
- /**
- * Updates {@param values} to contain versioning information and adds it to the DB.
- * @param values {@link ContentValues} containing icon & title
- */
- private void addIconToDB(ContentValues values, ComponentName key,
- PackageInfo info, long userSerial, long lastUpdateTime) {
- values.put(IconDB.COLUMN_COMPONENT, key.flattenToString());
- values.put(IconDB.COLUMN_USER, userSerial);
- values.put(IconDB.COLUMN_LAST_UPDATED, lastUpdateTime);
- values.put(IconDB.COLUMN_VERSION, info.versionCode);
- mIconDb.insertOrReplace(values);
- }
-
- public synchronized BitmapInfo getDefaultIcon(UserHandle user) {
- if (!mDefaultIcons.containsKey(user)) {
- mDefaultIcons.put(user, makeDefaultIcon(user));
- }
- return mDefaultIcons.get(user);
- }
-
- public boolean isDefaultIcon(BitmapInfo icon, UserHandle user) {
- return getDefaultIcon(user).icon == icon.icon;
- }
-
- /**
- * Retrieves the entry from the cache. If the entry is not present, it creates a new entry.
- * This method is not thread safe, it must be called from a synchronized method.
- */
- protected <T> CacheEntry cacheLocked(
- @NonNull ComponentName componentName, @NonNull UserHandle user,
- @NonNull Supplier<T> infoProvider, @NonNull CachingLogic<T> cachingLogic,
- boolean usePackageIcon, boolean useLowResIcon) {
- assertWorkerThread();
- ComponentKey cacheKey = new ComponentKey(componentName, user);
- CacheEntry entry = mCache.get(cacheKey);
- if (entry == null || (entry.bitmap.isLowRes() && !useLowResIcon)) {
- entry = new CacheEntry();
- if (cachingLogic.addToMemCache()) {
- mCache.put(cacheKey, entry);
- }
-
- // Check the DB first.
- T object = null;
- boolean providerFetchedOnce = false;
-
- if (!getEntryFromDB(cacheKey, entry, useLowResIcon)) {
- object = infoProvider.get();
- providerFetchedOnce = true;
-
- if (object != null) {
- entry.bitmap = cachingLogic.loadIcon(mContext, object);
- } else {
- if (usePackageIcon) {
- CacheEntry packageEntry = getEntryForPackageLocked(
- componentName.getPackageName(), user, false);
- if (packageEntry != null) {
- if (DEBUG) Log.d(TAG, "using package default icon for " +
- componentName.toShortString());
- entry.bitmap = packageEntry.bitmap;
- entry.title = packageEntry.title;
- entry.contentDescription = packageEntry.contentDescription;
- }
- }
- if (entry.bitmap == null) {
- if (DEBUG) Log.d(TAG, "using default icon for " +
- componentName.toShortString());
- entry.bitmap = getDefaultIcon(user);
- }
- }
- }
-
- if (TextUtils.isEmpty(entry.title)) {
- if (object == null && !providerFetchedOnce) {
- object = infoProvider.get();
- providerFetchedOnce = true;
- }
- if (object != null) {
- entry.title = cachingLogic.getLabel(object);
- entry.contentDescription = mPackageManager.getUserBadgedLabel(
- cachingLogic.getDescription(object, entry.title), user);
- }
- }
- }
- return entry;
- }
-
- public synchronized void clear() {
- assertWorkerThread();
- mIconDb.clear();
- }
-
- /**
- * Adds a default package entry in the cache. This entry is not persisted and will be removed
- * when the cache is flushed.
- */
- protected synchronized void cachePackageInstallInfo(String packageName, UserHandle user,
- Bitmap icon, CharSequence title) {
- removeFromMemCacheLocked(packageName, user);
-
- ComponentKey cacheKey = getPackageKey(packageName, user);
- CacheEntry entry = mCache.get(cacheKey);
-
- // For icon caching, do not go through DB. Just update the in-memory entry.
- if (entry == null) {
- entry = new CacheEntry();
- }
- if (!TextUtils.isEmpty(title)) {
- entry.title = title;
- }
- if (icon != null) {
- BaseIconFactory li = getIconFactory();
- entry.bitmap = li.createIconBitmap(icon);
- li.close();
- }
- if (!TextUtils.isEmpty(title) && entry.bitmap.icon != null) {
- mCache.put(cacheKey, entry);
- }
- }
-
- private static ComponentKey getPackageKey(String packageName, UserHandle user) {
- ComponentName cn = new ComponentName(packageName, packageName + EMPTY_CLASS_NAME);
- return new ComponentKey(cn, user);
- }
-
- /**
- * Gets an entry for the package, which can be used as a fallback entry for various components.
- * This method is not thread safe, it must be called from a synchronized method.
- */
- protected CacheEntry getEntryForPackageLocked(String packageName, UserHandle user,
- boolean useLowResIcon) {
- assertWorkerThread();
- ComponentKey cacheKey = getPackageKey(packageName, user);
- CacheEntry entry = mCache.get(cacheKey);
-
- if (entry == null || (entry.bitmap.isLowRes() && !useLowResIcon)) {
- entry = new CacheEntry();
- boolean entryUpdated = true;
-
- // Check the DB first.
- if (!getEntryFromDB(cacheKey, entry, useLowResIcon)) {
- try {
- int flags = Process.myUserHandle().equals(user) ? 0 :
- PackageManager.GET_UNINSTALLED_PACKAGES;
- PackageInfo info = mPackageManager.getPackageInfo(packageName, flags);
- ApplicationInfo appInfo = info.applicationInfo;
- if (appInfo == null) {
- throw new NameNotFoundException("ApplicationInfo is null");
- }
-
- BaseIconFactory li = getIconFactory();
- // Load the full res icon for the application, but if useLowResIcon is set, then
- // only keep the low resolution icon instead of the larger full-sized icon
- BitmapInfo iconInfo = li.createBadgedIconBitmap(
- appInfo.loadIcon(mPackageManager), user, appInfo.targetSdkVersion,
- isInstantApp(appInfo));
- li.close();
-
- entry.title = appInfo.loadLabel(mPackageManager);
- entry.contentDescription = mPackageManager.getUserBadgedLabel(entry.title, user);
- entry.bitmap = BitmapInfo.of(
- useLowResIcon ? LOW_RES_ICON : iconInfo.icon, iconInfo.color);
-
- // Add the icon in the DB here, since these do not get written during
- // package updates.
- ContentValues values = newContentValues(
- iconInfo, entry.title.toString(), packageName, null);
- addIconToDB(values, cacheKey.componentName, info, getSerialNumberForUser(user),
- info.lastUpdateTime);
-
- } catch (NameNotFoundException e) {
- if (DEBUG) Log.d(TAG, "Application not installed " + packageName);
- entryUpdated = false;
- }
- }
-
- // Only add a filled-out entry to the cache
- if (entryUpdated) {
- mCache.put(cacheKey, entry);
- }
- }
- return entry;
- }
-
- protected boolean getEntryFromDB(ComponentKey cacheKey, CacheEntry entry, boolean lowRes) {
- Cursor c = null;
- try {
- c = mIconDb.query(
- lowRes ? IconDB.COLUMNS_LOW_RES : IconDB.COLUMNS_HIGH_RES,
- IconDB.COLUMN_COMPONENT + " = ? AND " + IconDB.COLUMN_USER + " = ?",
- new String[]{
- cacheKey.componentName.flattenToString(),
- Long.toString(getSerialNumberForUser(cacheKey.user))});
- if (c.moveToNext()) {
- // Set the alpha to be 255, so that we never have a wrong color
- entry.bitmap = BitmapInfo.of(LOW_RES_ICON, setColorAlphaBound(c.getInt(0), 255));
- entry.title = c.getString(1);
- if (entry.title == null) {
- entry.title = "";
- entry.contentDescription = "";
- } else {
- entry.contentDescription = mPackageManager.getUserBadgedLabel(
- entry.title, cacheKey.user);
- }
-
- if (!lowRes) {
- byte[] data = c.getBlob(2);
- try {
- entry.bitmap = BitmapInfo.of(
- BitmapFactory.decodeByteArray(data, 0, data.length, mDecodeOptions),
- entry.bitmap.color);
- } catch (Exception e) { }
- }
- return true;
- }
- } catch (SQLiteException e) {
- Log.d(TAG, "Error reading icon cache", e);
- } finally {
- if (c != null) {
- c.close();
- }
- }
- return false;
- }
-
- /**
- * Returns a cursor for an arbitrary query to the cache db
- */
- public synchronized Cursor queryCacheDb(String[] columns, String selection,
- String[] selectionArgs) {
- return mIconDb.query(columns, selection, selectionArgs);
- }
-
- /**
- * Cache class to store the actual entries on disk
- */
- public static final class IconDB extends SQLiteCacheHelper {
- private static final int RELEASE_VERSION = 27;
-
- public static final String TABLE_NAME = "icons";
- public static final String COLUMN_ROWID = "rowid";
- public static final String COLUMN_COMPONENT = "componentName";
- public static final String COLUMN_USER = "profileId";
- public static final String COLUMN_LAST_UPDATED = "lastUpdated";
- public static final String COLUMN_VERSION = "version";
- public static final String COLUMN_ICON = "icon";
- public static final String COLUMN_ICON_COLOR = "icon_color";
- public static final String COLUMN_LABEL = "label";
- public static final String COLUMN_SYSTEM_STATE = "system_state";
- public static final String COLUMN_KEYWORDS = "keywords";
-
- public static final String[] COLUMNS_HIGH_RES = new String[] {
- IconDB.COLUMN_ICON_COLOR, IconDB.COLUMN_LABEL, IconDB.COLUMN_ICON };
- public static final String[] COLUMNS_LOW_RES = new String[] {
- IconDB.COLUMN_ICON_COLOR, IconDB.COLUMN_LABEL };
-
- public IconDB(Context context, String dbFileName, int iconPixelSize) {
- super(context, dbFileName, (RELEASE_VERSION << 16) + iconPixelSize, TABLE_NAME);
- }
-
- @Override
- protected void onCreateTable(SQLiteDatabase db) {
- db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " ("
- + COLUMN_COMPONENT + " TEXT NOT NULL, "
- + COLUMN_USER + " INTEGER NOT NULL, "
- + COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, "
- + COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, "
- + COLUMN_ICON + " BLOB, "
- + COLUMN_ICON_COLOR + " INTEGER NOT NULL DEFAULT 0, "
- + COLUMN_LABEL + " TEXT, "
- + COLUMN_SYSTEM_STATE + " TEXT, "
- + COLUMN_KEYWORDS + " TEXT, "
- + "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ") "
- + ");");
- }
- }
-
- private ContentValues newContentValues(BitmapInfo bitmapInfo, String label,
- String packageName, @Nullable String keywords) {
- ContentValues values = new ContentValues();
- values.put(IconDB.COLUMN_ICON,
- bitmapInfo.isLowRes() ? null : GraphicsUtils.flattenBitmap(bitmapInfo.icon));
- values.put(IconDB.COLUMN_ICON_COLOR, bitmapInfo.color);
-
- values.put(IconDB.COLUMN_LABEL, label);
- values.put(IconDB.COLUMN_SYSTEM_STATE, getIconSystemState(packageName));
- values.put(IconDB.COLUMN_KEYWORDS, keywords);
- return values;
- }
-
- private void assertWorkerThread() {
- if (Looper.myLooper() != mBgLooper) {
- throw new IllegalStateException("Cache accessed on wrong thread " + Looper.myLooper());
- }
- }
-}
diff --git a/iconloaderlib/src/com/android/launcher3/icons/cache/CachingLogic.java b/iconloaderlib/src/com/android/launcher3/icons/cache/CachingLogic.java
deleted file mode 100644
index c12e9dc..0000000
--- a/iconloaderlib/src/com/android/launcher3/icons/cache/CachingLogic.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * 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.launcher3.icons.cache;
-
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.pm.PackageInfo;
-import android.os.LocaleList;
-import android.os.UserHandle;
-
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
-
-import com.android.launcher3.icons.BitmapInfo;
-
-public interface CachingLogic<T> {
-
- ComponentName getComponent(T object);
-
- UserHandle getUser(T object);
-
- CharSequence getLabel(T object);
-
- default CharSequence getDescription(T object, CharSequence fallback) {
- return fallback;
- }
-
- @NonNull
- BitmapInfo loadIcon(Context context, T object);
-
- /**
- * Provides a option list of keywords to associate with this object
- */
- @Nullable
- default String getKeywords(T object, LocaleList localeList) {
- return null;
- }
-
- /**
- * Returns the timestamp the entry was last updated in cache.
- */
- default long getLastUpdatedTime(T object, PackageInfo info) {
- return info.lastUpdateTime;
- }
-
- /**
- * Returns true the object should be added to mem cache; otherwise returns false.
- */
- default boolean addToMemCache() {
- return true;
- }
-}
diff --git a/iconloaderlib/src/com/android/launcher3/icons/cache/HandlerRunnable.java b/iconloaderlib/src/com/android/launcher3/icons/cache/HandlerRunnable.java
deleted file mode 100644
index ee52934..0000000
--- a/iconloaderlib/src/com/android/launcher3/icons/cache/HandlerRunnable.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * 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.launcher3.icons.cache;
-
-import android.os.Handler;
-
-/**
- * A runnable that can be posted to a {@link Handler} which can be canceled.
- */
-public abstract class HandlerRunnable implements Runnable {
-
- private final Handler mHandler;
- private final Runnable mEndRunnable;
-
- private boolean mEnded = false;
- private boolean mCanceled = false;
-
- public HandlerRunnable(Handler handler, Runnable endRunnable) {
- mHandler = handler;
- mEndRunnable = endRunnable;
- }
-
- /**
- * Cancels this runnable from being run, only if it has not already run.
- */
- public void cancel() {
- mHandler.removeCallbacks(this);
- // TODO: This can actually cause onEnd to be called twice if the handler is already running
- // this runnable
- // NOTE: This is currently run on whichever thread the caller is run on.
- mCanceled = true;
- onEnd();
- }
-
- /**
- * @return whether this runnable was canceled.
- */
- protected boolean isCanceled() {
- return mCanceled;
- }
-
- /**
- * To be called by the implemention of this runnable. The end callback is done on whichever
- * thread the caller is calling from.
- */
- public void onEnd() {
- if (!mEnded) {
- mEnded = true;
- if (mEndRunnable != null) {
- mEndRunnable.run();
- }
- }
- }
-}
diff --git a/iconloaderlib/src/com/android/launcher3/icons/cache/IconCacheUpdateHandler.java b/iconloaderlib/src/com/android/launcher3/icons/cache/IconCacheUpdateHandler.java
index aec1cdd..7b8070a 100644
--- a/iconloaderlib/src/com/android/launcher3/icons/cache/IconCacheUpdateHandler.java
+++ b/iconloaderlib/src/com/android/launcher3/icons/cache/IconCacheUpdateHandler.java
@@ -1,3 +1,4 @@
+<<<<<<< HEAD (cc6caf Merge "Let launcher to provide its own OverscrollPlugin" int)
/*
* Copyright (C) 2018 The Android Open Source Project
*
@@ -312,3 +313,5 @@
void onPackageIconsUpdated(HashSet<String> updatedPackages, UserHandle user);
}
}
+=======
+>>>>>>> CHANGE (805b52 Removes iconloaderlib from Launcher3.)
diff --git a/iconloaderlib/src/com/android/launcher3/util/ComponentKey.java b/iconloaderlib/src/com/android/launcher3/util/ComponentKey.java
deleted file mode 100644
index 34bed94..0000000
--- a/iconloaderlib/src/com/android/launcher3/util/ComponentKey.java
+++ /dev/null
@@ -1,59 +0,0 @@
-package com.android.launcher3.util;
-
-/**
- * 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.
- */
-
-import android.content.ComponentName;
-import android.os.UserHandle;
-
-import java.util.Arrays;
-
-public class ComponentKey {
-
- public final ComponentName componentName;
- public final UserHandle user;
-
- private final int mHashCode;
-
- public ComponentKey(ComponentName componentName, UserHandle user) {
- if (componentName == null || user == null) {
- throw new NullPointerException();
- }
- this.componentName = componentName;
- this.user = user;
- mHashCode = Arrays.hashCode(new Object[] {componentName, user});
-
- }
-
- @Override
- public int hashCode() {
- return mHashCode;
- }
-
- @Override
- public boolean equals(Object o) {
- ComponentKey other = (ComponentKey) o;
- return other.componentName.equals(componentName) && other.user.equals(user);
- }
-
- /**
- * Encodes a component key as a string of the form [flattenedComponentString#userId].
- */
- @Override
- public String toString() {
- return componentName.flattenToString() + "#" + user;
- }
-}
\ No newline at end of file
diff --git a/iconloaderlib/src/com/android/launcher3/util/NoLocaleSQLiteHelper.java b/iconloaderlib/src/com/android/launcher3/util/NoLocaleSQLiteHelper.java
deleted file mode 100644
index fe864a2..0000000
--- a/iconloaderlib/src/com/android/launcher3/util/NoLocaleSQLiteHelper.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * 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.launcher3.util;
-
-import static android.database.sqlite.SQLiteDatabase.NO_LOCALIZED_COLLATORS;
-
-import android.content.Context;
-import android.content.ContextWrapper;
-import android.database.DatabaseErrorHandler;
-import android.database.sqlite.SQLiteDatabase;
-import android.database.sqlite.SQLiteDatabase.CursorFactory;
-import android.database.sqlite.SQLiteDatabase.OpenParams;
-import android.database.sqlite.SQLiteOpenHelper;
-import android.os.Build;
-
-/**
- * Extension of {@link SQLiteOpenHelper} which avoids creating default locale table by
- * A context wrapper which creates databases without support for localized collators.
- */
-public abstract class NoLocaleSQLiteHelper extends SQLiteOpenHelper {
-
- private static final boolean ATLEAST_P =
- Build.VERSION.SDK_INT >= Build.VERSION_CODES.P;
-
- public NoLocaleSQLiteHelper(Context context, String name, int version) {
- super(ATLEAST_P ? context : new NoLocalContext(context), name, null, version);
- if (ATLEAST_P) {
- setOpenParams(new OpenParams.Builder().addOpenFlags(NO_LOCALIZED_COLLATORS).build());
- }
- }
-
- private static class NoLocalContext extends ContextWrapper {
- public NoLocalContext(Context base) {
- super(base);
- }
-
- @Override
- public SQLiteDatabase openOrCreateDatabase(
- String name, int mode, CursorFactory factory, DatabaseErrorHandler errorHandler) {
- return super.openOrCreateDatabase(
- name, mode | Context.MODE_NO_LOCALIZED_COLLATORS, factory, errorHandler);
- }
- }
-}
diff --git a/iconloaderlib/src/com/android/launcher3/util/SQLiteCacheHelper.java b/iconloaderlib/src/com/android/launcher3/util/SQLiteCacheHelper.java
deleted file mode 100644
index 49de4bd..0000000
--- a/iconloaderlib/src/com/android/launcher3/util/SQLiteCacheHelper.java
+++ /dev/null
@@ -1,125 +0,0 @@
-package com.android.launcher3.util;
-
-import android.content.ContentValues;
-import android.content.Context;
-import android.database.Cursor;
-import android.database.sqlite.SQLiteDatabase;
-import android.database.sqlite.SQLiteException;
-import android.database.sqlite.SQLiteFullException;
-import android.database.sqlite.SQLiteOpenHelper;
-import android.util.Log;
-
-/**
- * An extension of {@link SQLiteOpenHelper} with utility methods for a single table cache DB.
- * Any exception during write operations are ignored, and any version change causes a DB reset.
- */
-public abstract class SQLiteCacheHelper {
- private static final String TAG = "SQLiteCacheHelper";
-
- private static final boolean IN_MEMORY_CACHE = false;
-
- private final String mTableName;
- private final MySQLiteOpenHelper mOpenHelper;
-
- private boolean mIgnoreWrites;
-
- public SQLiteCacheHelper(Context context, String name, int version, String tableName) {
- if (IN_MEMORY_CACHE) {
- name = null;
- }
- mTableName = tableName;
- mOpenHelper = new MySQLiteOpenHelper(context, name, version);
-
- mIgnoreWrites = false;
- }
-
- /**
- * @see SQLiteDatabase#delete(String, String, String[])
- */
- public void delete(String whereClause, String[] whereArgs) {
- if (mIgnoreWrites) {
- return;
- }
- try {
- mOpenHelper.getWritableDatabase().delete(mTableName, whereClause, whereArgs);
- } catch (SQLiteFullException e) {
- onDiskFull(e);
- } catch (SQLiteException e) {
- Log.d(TAG, "Ignoring sqlite exception", e);
- }
- }
-
- /**
- * @see SQLiteDatabase#insertWithOnConflict(String, String, ContentValues, int)
- */
- public void insertOrReplace(ContentValues values) {
- if (mIgnoreWrites) {
- return;
- }
- try {
- mOpenHelper.getWritableDatabase().insertWithOnConflict(
- mTableName, null, values, SQLiteDatabase.CONFLICT_REPLACE);
- } catch (SQLiteFullException e) {
- onDiskFull(e);
- } catch (SQLiteException e) {
- Log.d(TAG, "Ignoring sqlite exception", e);
- }
- }
-
- private void onDiskFull(SQLiteFullException e) {
- Log.e(TAG, "Disk full, all write operations will be ignored", e);
- mIgnoreWrites = true;
- }
-
- /**
- * @see SQLiteDatabase#query(String, String[], String, String[], String, String, String)
- */
- public Cursor query(String[] columns, String selection, String[] selectionArgs) {
- return mOpenHelper.getReadableDatabase().query(
- mTableName, columns, selection, selectionArgs, null, null, null);
- }
-
- public void clear() {
- mOpenHelper.clearDB(mOpenHelper.getWritableDatabase());
- }
-
- public void close() {
- mOpenHelper.close();
- }
-
- protected abstract void onCreateTable(SQLiteDatabase db);
-
- /**
- * A private inner class to prevent direct DB access.
- */
- private class MySQLiteOpenHelper extends NoLocaleSQLiteHelper {
-
- public MySQLiteOpenHelper(Context context, String name, int version) {
- super(context, name, version);
- }
-
- @Override
- public void onCreate(SQLiteDatabase db) {
- onCreateTable(db);
- }
-
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- if (oldVersion != newVersion) {
- clearDB(db);
- }
- }
-
- @Override
- public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- if (oldVersion != newVersion) {
- clearDB(db);
- }
- }
-
- private void clearDB(SQLiteDatabase db) {
- db.execSQL("DROP TABLE IF EXISTS " + mTableName);
- onCreate(db);
- }
- }
-}
diff --git a/iconloaderlib/src_full_lib/com/android/launcher3/icons/IconFactory.java b/iconloaderlib/src_full_lib/com/android/launcher3/icons/IconFactory.java
deleted file mode 100644
index 48f11fd..0000000
--- a/iconloaderlib/src_full_lib/com/android/launcher3/icons/IconFactory.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * 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.launcher3.icons;
-
-import android.content.Context;
-
-/**
- * Wrapper class to provide access to {@link BaseIconFactory} and also to provide pool of this class
- * that are threadsafe.
- */
-public class IconFactory extends BaseIconFactory {
-
- private static final Object sPoolSync = new Object();
- private static IconFactory sPool;
- private static int sPoolId = 0;
-
- /**
- * Return a new Message instance from the global pool. Allows us to
- * avoid allocating new objects in many cases.
- */
- public static IconFactory obtain(Context context) {
- int poolId;
- synchronized (sPoolSync) {
- if (sPool != null) {
- IconFactory m = sPool;
- sPool = m.next;
- m.next = null;
- return m;
- }
- poolId = sPoolId;
- }
-
- return new IconFactory(context,
- context.getResources().getConfiguration().densityDpi,
- context.getResources().getDimensionPixelSize(R.dimen.default_icon_bitmap_size),
- poolId);
- }
-
- public static void clearPool() {
- synchronized (sPoolSync) {
- sPool = null;
- sPoolId++;
- }
- }
-
- private final int mPoolId;
-
- private IconFactory next;
-
- private IconFactory(Context context, int fillResIconDpi, int iconBitmapSize, int poolId) {
- super(context, fillResIconDpi, iconBitmapSize);
- mPoolId = poolId;
- }
-
- /**
- * Recycles a LauncherIcons that may be in-use.
- */
- public void recycle() {
- synchronized (sPoolSync) {
- if (sPoolId != mPoolId) {
- return;
- }
- // Clear any temporary state variables
- clear();
-
- next = sPool;
- sPool = this;
- }
- }
-
- @Override
- public void close() {
- recycle();
- }
-}
diff --git a/iconloaderlib/src_full_lib/com/android/launcher3/icons/SimpleIconCache.java b/iconloaderlib/src_full_lib/com/android/launcher3/icons/SimpleIconCache.java
deleted file mode 100644
index 1337975..0000000
--- a/iconloaderlib/src_full_lib/com/android/launcher3/icons/SimpleIconCache.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * 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.launcher3.icons;
-
-import static android.content.Intent.ACTION_MANAGED_PROFILE_ADDED;
-import static android.content.Intent.ACTION_MANAGED_PROFILE_REMOVED;
-
-import android.annotation.TargetApi;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.pm.ApplicationInfo;
-import android.os.Build;
-import android.os.Handler;
-import android.os.HandlerThread;
-import android.os.Looper;
-import android.os.UserHandle;
-import android.os.UserManager;
-import android.util.SparseLongArray;
-
-import com.android.launcher3.icons.cache.BaseIconCache;
-
-/**
- * Wrapper class to provide access to {@link BaseIconFactory} and also to provide pool of this class
- * that are threadsafe.
- */
-@TargetApi(Build.VERSION_CODES.P)
-public class SimpleIconCache extends BaseIconCache {
-
- private static SimpleIconCache sIconCache = null;
- private static final Object CACHE_LOCK = new Object();
-
- private final SparseLongArray mUserSerialMap = new SparseLongArray(2);
- private final UserManager mUserManager;
-
- public SimpleIconCache(Context context, String dbFileName, Looper bgLooper, int iconDpi,
- int iconPixelSize, boolean inMemoryCache) {
- super(context, dbFileName, bgLooper, iconDpi, iconPixelSize, inMemoryCache);
- mUserManager = context.getSystemService(UserManager.class);
-
- // Listen for user cache changes.
- IntentFilter filter = new IntentFilter(ACTION_MANAGED_PROFILE_ADDED);
- filter.addAction(ACTION_MANAGED_PROFILE_REMOVED);
- context.registerReceiver(new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- resetUserCache();
- }
- }, filter, null, new Handler(bgLooper), 0);
- }
-
- @Override
- protected long getSerialNumberForUser(UserHandle user) {
- synchronized (mUserSerialMap) {
- int index = mUserSerialMap.indexOfKey(user.getIdentifier());
- if (index >= 0) {
- return mUserSerialMap.valueAt(index);
- }
- long serial = mUserManager.getSerialNumberForUser(user);
- mUserSerialMap.put(user.getIdentifier(), serial);
- return serial;
- }
- }
-
- private void resetUserCache() {
- synchronized (mUserSerialMap) {
- mUserSerialMap.clear();
- }
- }
-
- @Override
- protected boolean isInstantApp(ApplicationInfo info) {
- return info.isInstantApp();
- }
-
- @Override
- protected BaseIconFactory getIconFactory() {
- return IconFactory.obtain(mContext);
- }
-
- public static SimpleIconCache getIconCache(Context context) {
- synchronized (CACHE_LOCK) {
- if (sIconCache != null) {
- return sIconCache;
- }
- boolean inMemoryCache =
- context.getResources().getBoolean(R.bool.simple_cache_enable_im_memory);
- String dbFileName = context.getString(R.string.cache_db_name);
-
- HandlerThread bgThread = new HandlerThread("simple-icon-cache");
- bgThread.start();
-
- sIconCache = new SimpleIconCache(context.getApplicationContext(), dbFileName,
- bgThread.getLooper(), context.getResources().getConfiguration().densityDpi,
- context.getResources().getDimensionPixelSize(R.dimen.default_icon_bitmap_size),
- inMemoryCache);
- return sIconCache;
- }
- }
-}
diff --git a/proguard.flags b/proguard.flags
index 01302cf..37b8093 100644
--- a/proguard.flags
+++ b/proguard.flags
@@ -48,3 +48,15 @@
-dontwarn android.view.**
-dontwarn android.os.**
-dontwarn android.graphics.**
+
+# Ignore warnings for hidden utility classes referenced from the shared lib
+-dontwarn com.android.internal.util.**
+
+################ Do not optimize recents lib #############
+-keep class com.android.systemui.** {
+ *;
+}
+
+-keep class com.android.quickstep.** {
+ *;
+}
diff --git a/protos/launcher_atom.proto b/protos/launcher_atom.proto
new file mode 100644
index 0000000..a89fe5c
--- /dev/null
+++ b/protos/launcher_atom.proto
@@ -0,0 +1,108 @@
+/*
+ * 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.
+ */
+syntax = "proto2";
+
+option java_package = "com.android.launcher3.logger";
+option java_outer_classname = "LauncherAtom";
+
+//
+// ItemInfos
+message ItemInfo {
+ oneof Item {
+ Application application = 1;
+ Task task= 2;
+ Shortcut shortcut = 3;
+ Widget widget = 4;
+ }
+ // When used for launch event, stores the global predictive rank
+ optional int32 rank = 5;
+
+ // Stores whether the Item belows to non primary user
+ optional bool is_work = 6;
+
+ // Item can be child node to parent container or parent containers (nested)
+ oneof Container {
+ WorkspaceContainer workspace = 7;
+ HotseatContainer hotseat = 8;
+ FolderContainer folder = 9;
+ }
+ // Stores the origin of the Item
+ optional Origin source = 10;
+}
+
+enum Origin {
+ UNKNOWN = 0;
+ DEFAULT_LAYOUT = 1; // icon automatically placed in workspace, folder, hotseat
+ BACKUP_RESTORE = 2; // icon layout restored from backup
+ PINITEM = 3; // from another app (e.g., Chrome's "Add to Home screen")
+ ALLAPPS_ATOZ = 4; // within launcher surface, all aps a-z
+ WIDGETS = 5; // within launcher, widgets tray
+ ADD_TO_HOMESCREEN = 6; // play install + launcher home setting
+ ALLAPPS_PREDICTION = 7; // from prediction bar in all apps container
+ HOTSEAT_PREDICTION = 8; // from prediction bar in hotseat container
+}
+
+// Main app icons
+message Application {
+ optional string package_name = 1;
+ optional string component_name = 2;
+}
+
+// Legacy shortcuts and shortcuts handled by ShortcutManager
+message Shortcut {
+ optional string shortcut_name = 1;
+}
+
+// AppWidgets handled by AppWidgetManager
+message Widget {
+ optional int32 span_x = 1;
+ optional int32 span_y = 2;
+ optional int32 app_widget_id = 3;
+ optional string package_name = 4; // only populated during snapshot if from workspace
+ optional string component_name = 5; // only populated during snapshot if from workspace
+}
+
+// Tasks handled by PackageManager
+message Task {
+ optional string package_name = 1;
+ optional string component_name = 2;
+ optional int32 index = 3;
+}
+
+//////////////////////////////////////////////
+// Containers
+
+message WorkspaceContainer {
+ optional int32 page_index = 1; // range [-1, l], 0 is the index of the main homescreen
+ optional int32 grid_x = 2; // [0, m], m varies based on the display density and resolution
+ optional int32 grid_y = 3; // [0, n], n varies based on the display density and resolution
+}
+
+message HotseatContainer {
+ optional int32 index = 1;
+}
+
+message FolderContainer {
+ optional int32 page_index = 1;
+ optional int32 grid_x = 2;
+ optional int32 grid_y = 3;
+ oneof Container {
+ WorkspaceContainer workspace = 4;
+ HotseatContainer hotseat = 5;
+ }
+}
+
+
diff --git a/protos/launcher_dump.proto b/protos/launcher_dump.proto
deleted file mode 100644
index dc8fbda..0000000
--- a/protos/launcher_dump.proto
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * 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.
- */
-syntax = "proto2";
-
-option java_package = "com.android.launcher3.model";
-option java_outer_classname = "LauncherDumpProto";
-
-package model;
-
-message DumpTarget {
- enum Type {
- NONE = 0;
- ITEM = 1;
- CONTAINER = 2;
- }
-
- optional Type type = 1;
- optional int32 page_id = 2;
- optional int32 grid_x = 3;
- optional int32 grid_y = 4;
-
- // For container types only
- optional ContainerType container_type = 5;
-
- // For item types only
- optional ItemType item_type = 6;
-
- optional string package_name = 7; // All ItemTypes except UNKNOWN type
- optional string component = 8; // All ItemTypes except UNKNOWN type
- optional string item_id = 9; // For Pinned Shortcuts and appWidgetId
-
- optional int32 span_x = 10 [default = 1];// Used for ItemType.WIDGET
- optional int32 span_y = 11 [default = 1];// Used for ItemType.WIDGET
- optional UserType user_type = 12;
-}
-
-// Used to define what type of item a Target would represent.
-enum ItemType {
- UNKNOWN_ITEMTYPE = 0; // Launcher specific items
- APP_ICON = 1; // Regular app icons
- WIDGET = 2; // Elements from AppWidgetManager
- SHORTCUT = 3; // ShortcutManager
-}
-
-// Used to define what type of container a Target would represent.
-enum ContainerType {
- UNKNOWN_CONTAINERTYPE = 0;
- WORKSPACE = 1;
- HOTSEAT = 2;
- FOLDER = 3;
-}
-
-// Used to define what type of control a Target would represent.
-enum UserType {
- DEFAULT = 0;
- WORK = 1;
-}
-
-// Main message;
-message LauncherImpression {
- repeated DumpTarget targets = 1;
-}
diff --git a/protos/launcher_log.proto b/protos/launcher_log.proto
index 0560d68..9423cb2 100644
--- a/protos/launcher_log.proto
+++ b/protos/launcher_log.proto
@@ -58,6 +58,39 @@
optional TipType tip_type = 17;
optional int32 search_query_length = 18;
optional bool is_work_app = 19;
+ optional FromFolderLabelState from_folder_label_state = 20;
+ optional ToFolderLabelState to_folder_label_state = 21;
+
+ // Note: proto does not support duplicate enum values, even if they belong to different enum type.
+ // Hence "FROM" and "TO" prefix added.
+ enum FromFolderLabelState {
+ FROM_FOLDER_LABEL_STATE_UNSPECIFIED = 0;
+ FROM_EMPTY = 1;
+ FROM_CUSTOM = 2;
+ FROM_SUGGESTED = 3;
+ }
+
+ enum ToFolderLabelState {
+ TO_FOLDER_LABEL_STATE_UNSPECIFIED = 0;
+ TO_SUGGESTION0_WITH_VALID_PRIMARY = 1;
+ TO_SUGGESTION1_WITH_VALID_PRIMARY = 2;
+ TO_SUGGESTION1_WITH_EMPTY_PRIMARY = 3;
+ TO_SUGGESTION2_WITH_VALID_PRIMARY = 4;
+ TO_SUGGESTION2_WITH_EMPTY_PRIMARY = 5;
+ TO_SUGGESTION3_WITH_VALID_PRIMARY = 6;
+ TO_SUGGESTION3_WITH_EMPTY_PRIMARY = 7;
+ TO_EMPTY_WITH_VALID_SUGGESTIONS = 8 [deprecated = true];
+ TO_EMPTY_WITH_VALID_PRIMARY = 15;
+ TO_EMPTY_WITH_VALID_SUGGESTIONS_AND_EMPTY_PRIMARY = 16;
+ TO_EMPTY_WITH_EMPTY_SUGGESTIONS = 9;
+ TO_EMPTY_WITH_SUGGESTIONS_DISABLED = 10;
+ TO_CUSTOM_WITH_VALID_SUGGESTIONS = 11 [deprecated = true];
+ TO_CUSTOM_WITH_VALID_PRIMARY = 17;
+ TO_CUSTOM_WITH_VALID_SUGGESTIONS_AND_EMPTY_PRIMARY = 18;
+ TO_CUSTOM_WITH_EMPTY_SUGGESTIONS = 12;
+ TO_CUSTOM_WITH_SUGGESTIONS_DISABLED = 13;
+ UNCHANGED = 14;
+ }
}
// Used to define what type of item a Target would represent.
@@ -120,6 +153,13 @@
BACK_GESTURE = 19;
UNDO = 20;
DISMISS_PREDICTION = 21;
+ HYBRID_HOTSEAT_ACCEPTED = 22;
+ HYBRID_HOTSEAT_CANCELED = 23;
+ OVERVIEW_ACTIONS_SHARE_BUTTON = 24;
+ OVERVIEW_ACTIONS_SCREENSHOT_BUTTON = 25;
+ OVERVIEW_ACTIONS_SELECT_BUTTON = 26;
+ SELECT_MODE_CLOSE_BUTTON = 27;
+ SELECT_MODE_ITEM = 28;
}
enum TipType {
@@ -129,6 +169,7 @@
QUICK_SCRUB_TEXT = 3;
PREDICTION_TEXT = 4;
DWB_TOAST = 5;
+ HYBRID_HOTSEAT = 6;
}
// Used to define the action component of the LauncherEvent.
@@ -138,7 +179,8 @@
AUTOMATED = 1;
COMMAND = 2;
TIP = 3;
- // SOFT_KEYBOARD, HARD_KEYBOARD, ASSIST
+ SOFT_KEYBOARD = 4;
+ // HARD_KEYBOARD, ASSIST
}
enum Touch {
diff --git a/src/com/android/launcher3/views/Transposable.java b/protos/launcher_trace.proto
similarity index 67%
rename from src/com/android/launcher3/views/Transposable.java
rename to protos/launcher_trace.proto
index 929c1aa..c6f3543 100644
--- a/src/com/android/launcher3/views/Transposable.java
+++ b/protos/launcher_trace.proto
@@ -1,4 +1,4 @@
-/**
+/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -13,14 +13,19 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package com.android.launcher3.views;
-import com.android.launcher3.graphics.RotationMode;
+syntax = "proto2";
-/**
- * Indicates that a view can be transposed.
- */
-public interface Transposable {
+package com.android.launcher3.tracing;
- RotationMode getRotationMode();
+option java_multiple_files = true;
+
+message LauncherTraceProto {
+
+ optional TouchInteractionServiceProto touch_interaction_service = 1;
+}
+
+message TouchInteractionServiceProto {
+
+ optional bool service_connected = 1;
}
diff --git a/protos/launcher_trace_file.proto b/protos/launcher_trace_file.proto
new file mode 100644
index 0000000..6ce182a
--- /dev/null
+++ b/protos/launcher_trace_file.proto
@@ -0,0 +1,49 @@
+/*
+ * 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.
+ */
+
+syntax = "proto2";
+
+import "launcher_trace.proto";
+
+package com.android.launcher3.tracing;
+
+option java_multiple_files = true;
+
+/* represents a file full of launcher trace entries.
+ Encoded, it should start with 0x9 0x4C 0x4E 0x43 0x48 0x52 0x54 0x52 0x43 (.LNCHRTRC), such
+ that they can be easily identified. */
+message LauncherTraceFileProto {
+
+ /* constant; MAGIC_NUMBER = (long) MAGIC_NUMBER_H << 32 | MagicNumber.MAGIC_NUMBER_L
+ (this is needed because enums have to be 32 bits and there's no nice way to put 64bit
+ constants into .proto files. */
+ enum MagicNumber {
+ INVALID = 0;
+ MAGIC_NUMBER_L = 0x48434E4C; /* LNCH (little-endian ASCII) */
+ MAGIC_NUMBER_H = 0x43525452; /* RTRC (little-endian ASCII) */
+ }
+
+ optional fixed64 magic_number = 1; /* Must be the first field, set to value in MagicNumber */
+ repeated LauncherTraceEntryProto entry = 2;
+}
+
+/* one launcher trace entry. */
+message LauncherTraceEntryProto {
+ /* required: elapsed realtime in nanos since boot of when this entry was logged */
+ optional fixed64 elapsed_realtime_nanos = 1;
+
+ optional LauncherTraceProto launcher = 3;
+}
diff --git a/quickstep/AndroidManifest-launcher.xml b/quickstep/AndroidManifest-launcher.xml
index 60afddb..527bfc3 100644
--- a/quickstep/AndroidManifest-launcher.xml
+++ b/quickstep/AndroidManifest-launcher.xml
@@ -52,7 +52,7 @@
android:configChanges="keyboard|keyboardHidden|mcc|mnc|navigation|orientation|screenSize|screenLayout|smallestScreenSize"
android:resizeableActivity="true"
android:resumeWhilePausing="true"
- android:taskAffinity=""
+ android:taskAffinity="${packageName}.launcher"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
diff --git a/quickstep/AndroidManifest.xml b/quickstep/AndroidManifest.xml
index 5d871c3..04506b5 100644
--- a/quickstep/AndroidManifest.xml
+++ b/quickstep/AndroidManifest.xml
@@ -24,7 +24,9 @@
<uses-permission android:name="android.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS" />
<uses-permission android:name="android.permission.VIBRATE" />
+ <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />
+
<application
android:backupAgent="com.android.launcher3.LauncherBackupAgent"
android:fullBackupOnly="true"
@@ -46,10 +48,7 @@
</intent-filter>
</service>
- <!-- STOPSHIP: Change exported to false once all the integration is complete.
- It is set to true so that the activity can be started from command line -->
<activity android:name="com.android.quickstep.RecentsActivity"
- android:exported="true"
android:excludeFromRecents="true"
android:launchMode="singleTask"
android:clearTaskOnLaunch="true"
@@ -74,6 +73,17 @@
</intent-filter>
</provider>
+ <!-- FileProvider used for sharing images. -->
+ <provider
+ android:name="androidx.core.content.FileProvider"
+ android:authorities="${packageName}.overview.fileprovider"
+ android:exported="false"
+ android:grantUriPermissions="true">
+ <meta-data
+ android:name="android.support.FILE_PROVIDER_PATHS"
+ android:resource="@xml/overview_file_provider_paths" />
+ </provider>
+
<service
android:name="com.android.launcher3.uioverrides.dynamicui.WallpaperManagerCompatVL$ColorExtractionService"
tools:node="remove" />
@@ -92,12 +102,13 @@
android:directBootAware="true" />
<activity
- android:name="com.android.quickstep.interaction.BackGestureTutorialActivity"
+ android:name="com.android.quickstep.interaction.GestureSandboxActivity"
android:autoRemoveFromRecents="true"
android:excludeFromRecents="true"
+ android:taskAffinity="${packageName}.launcher"
android:screenOrientation="portrait">
<intent-filter>
- <action android:name="com.android.quickstep.action.BACK_GESTURE_TUTORIAL" />
+ <action android:name="com.android.quickstep.action.GESTURE_SANDBOX" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
diff --git a/quickstep/recents_ui_overrides/res/drawable/hotseat_edu_notification_icon.xml b/quickstep/recents_ui_overrides/res/drawable/hotseat_edu_notification_icon.xml
index fa3a0f8..4fda2a9 100644
--- a/quickstep/recents_ui_overrides/res/drawable/hotseat_edu_notification_icon.xml
+++ b/quickstep/recents_ui_overrides/res/drawable/hotseat_edu_notification_icon.xml
@@ -15,5 +15,5 @@
-->
<vector android:height="24dp" android:viewportHeight="24"
android:viewportWidth="24" android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
- <path android:fillColor="@color/bottom_panel_background" android:pathData="M19 9l1.25-2.75L23 5l-2.75-1.25L19 1l-1.25 2.75L15 5l2.75 1.25L19 9zm-7.5.5L9 4 6.5 9.5 1 12l5.5 2.5L9 20l2.5-5.5L17 12l-5.5-2.5zM19 15l-1.25 2.75L15 19l2.75 1.25L19 23l1.25-2.75L23 19l-2.75-1.25L19 15z"/>
+ <path android:fillColor="?android:attr/colorAccent" android:pathData="M19 9l1.25-2.75L23 5l-2.75-1.25L19 1l-1.25 2.75L15 5l2.75 1.25L19 9zm-7.5.5L9 4 6.5 9.5 1 12l5.5 2.5L9 20l2.5-5.5L17 12l-5.5-2.5zM19 15l-1.25 2.75L15 19l2.75 1.25L19 23l1.25-2.75L23 19l-2.75-1.25L19 15z"/>
</vector>
diff --git a/quickstep/recents_ui_overrides/res/layout/fallback_recents_activity.xml b/quickstep/recents_ui_overrides/res/layout/fallback_recents_activity.xml
index ef272ed..ffe906c 100644
--- a/quickstep/recents_ui_overrides/res/layout/fallback_recents_activity.xml
+++ b/quickstep/recents_ui_overrides/res/layout/fallback_recents_activity.xml
@@ -28,4 +28,9 @@
android:clipToPadding="false"
android:outlineProvider="none"
android:theme="@style/HomeScreenElementTheme" />
+
+ <include
+ android:id="@+id/overview_actions_view"
+ layout="@layout/overview_actions_container" />
+
</com.android.quickstep.fallback.RecentsRootView>
diff --git a/quickstep/recents_ui_overrides/res/layout/overview_panel.xml b/quickstep/recents_ui_overrides/res/layout/overview_panel.xml
index 7f1425b..eac0bfa 100644
--- a/quickstep/recents_ui_overrides/res/layout/overview_panel.xml
+++ b/quickstep/recents_ui_overrides/res/layout/overview_panel.xml
@@ -1,5 +1,4 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
+<?xml version="1.0" encoding="utf-8"?><!--
Copyright (C) 2017 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
@@ -16,10 +15,10 @@
-->
<com.android.quickstep.views.LauncherRecentsView
xmlns:android="http://schemas.android.com/apk/res/android"
- android:theme="@style/HomeScreenElementTheme"
android:layout_width="match_parent"
android:layout_height="match_parent"
+ android:accessibilityPaneTitle="@string/accessibility_recent_apps"
android:clipChildren="false"
android:clipToPadding="false"
- android:accessibilityPaneTitle="@string/accessibility_recent_apps"
- android:visibility="invisible" />
\ No newline at end of file
+ android:theme="@style/HomeScreenElementTheme"
+ android:visibility="invisible" />
diff --git a/quickstep/recents_ui_overrides/res/layout/predicted_hotseat_edu.xml b/quickstep/recents_ui_overrides/res/layout/predicted_hotseat_edu.xml
index d94c665..c93cad6 100644
--- a/quickstep/recents_ui_overrides/res/layout/predicted_hotseat_edu.xml
+++ b/quickstep/recents_ui_overrides/res/layout/predicted_hotseat_edu.xml
@@ -24,36 +24,38 @@
<View
android:layout_width="match_parent"
android:layout_height="32dp"
- android:backgroundTint="@color/bottom_panel_background"
+ android:backgroundTint="?android:attr/colorAccent"
android:background="@drawable/bottom_sheet_top_border" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:background="@color/bottom_panel_background"
+ android:background="?android:attr/colorAccent"
android:orientation="vertical">
<TextView
style="@style/TextHeadline"
+ android:id="@+id/hotseat_edu_heading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="18dp"
android:paddingLeft="@dimen/bottom_sheet_edu_padding"
android:paddingRight="@dimen/bottom_sheet_edu_padding"
- android:text="@string/hotseat_migrate_title"
+ android:text="@string/hotseat_edu_title_migrate"
android:textAlignment="center"
android:textColor="@android:color/white"
android:textSize="20sp" />
<TextView
android:layout_width="match_parent"
+ android:id="@+id/hotseat_edu_content"
android:layout_height="wrap_content"
android:layout_marginTop="18dp"
android:layout_marginBottom="18dp"
android:fontFamily="roboto-medium"
android:paddingLeft="@dimen/bottom_sheet_edu_padding"
android:paddingRight="@dimen/bottom_sheet_edu_padding"
- android:text="@string/hotseat_migrate_message"
+ android:text="@string/hotseat_edu_message_migrate"
android:textAlignment="center"
android:textColor="@android:color/white"
android:textSize="16sp" />
@@ -83,7 +85,7 @@
android:layout_height="wrap_content"
android:layout_gravity="end"
android:background="?android:attr/selectableItemBackground"
- android:text="@string/hotseat_migrate_accept"
+ android:text="@string/hotseat_edu_accept"
android:textAlignment="textEnd"
android:textColor="@android:color/white" />
@@ -91,7 +93,7 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/no_thanks"
- android:text="@string/hotseat_migrate_dismiss"
+ android:text="@string/hotseat_edu_dismiss"
android:layout_gravity="start"
android:background="?android:attr/selectableItemBackground"
android:textColor="@android:color/white" />
diff --git a/quickstep/recents_ui_overrides/res/values/colors.xml b/quickstep/recents_ui_overrides/res/values/colors.xml
index 7426e30..361f5f7 100644
--- a/quickstep/recents_ui_overrides/res/values/colors.xml
+++ b/quickstep/recents_ui_overrides/res/values/colors.xml
@@ -1,4 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
<resources>
<color name="chip_hint_foreground_color">#fff</color>
diff --git a/iconloaderlib/res/values/dimens.xml b/quickstep/recents_ui_overrides/res/values/config.xml
similarity index 77%
rename from iconloaderlib/res/values/dimens.xml
rename to quickstep/recents_ui_overrides/res/values/config.xml
index e8c0c44..120e034 100644
--- a/iconloaderlib/res/values/dimens.xml
+++ b/quickstep/recents_ui_overrides/res/values/config.xml
@@ -1,11 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2018 The Android Open Source Project
+<!-- 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
+ http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
@@ -13,7 +13,6 @@
See the License for the specific language governing permissions and
limitations under the License.
-->
-
<resources>
- <dimen name="profile_badge_size">24dp</dimen>
-</resources>
+ <integer name="max_depth_blur_radius">150</integer>
+</resources>
\ No newline at end of file
diff --git a/quickstep/recents_ui_overrides/res/values/dimens.xml b/quickstep/recents_ui_overrides/res/values/dimens.xml
index de97d08..363840a 100644
--- a/quickstep/recents_ui_overrides/res/values/dimens.xml
+++ b/quickstep/recents_ui_overrides/res/values/dimens.xml
@@ -1,4 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
<resources>
<dimen name="chip_hint_border_width">1dp</dimen>
<dimen name="chip_hint_corner_radius">20dp</dimen>
@@ -17,16 +31,7 @@
<dimen name="all_apps_label_top_padding">16dp</dimen>
<dimen name="all_apps_label_bottom_padding">8dp</dimen>
<dimen name="all_apps_label_text_size">14sp</dimen>
- <dimen name="all_apps_tip_bottom_margin">8dp</dimen>
- <!-- The size of corner radius of the arrow in the arrow toast. -->
- <dimen name="arrow_toast_corner_radius">2dp</dimen>
<!-- Minimum distance to swipe to trigger accessibility gesture -->
<dimen name="accessibility_gesture_min_swipe_distance">80dp</dimen>
-
- <!-- Swipe up to home related -->
- <dimen name="swipe_up_fling_min_visible_change">18dp</dimen>
- <dimen name="swipe_up_y_overshoot">10dp</dimen>
- <dimen name="swipe_up_max_workspace_trans_y">-60dp</dimen>
-
</resources>
\ No newline at end of file
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/LauncherAppTransitionManagerImpl.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/LauncherAppTransitionManagerImpl.java
index 51ee216..0019ecb 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/LauncherAppTransitionManagerImpl.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/LauncherAppTransitionManagerImpl.java
@@ -16,20 +16,18 @@
package com.android.launcher3;
-import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_X;
import static com.android.launcher3.LauncherState.BACKGROUND_APP;
import static com.android.launcher3.LauncherState.HOTSEAT_ICONS;
import static com.android.launcher3.LauncherState.NORMAL;
import static com.android.launcher3.LauncherState.OVERVIEW;
-import static com.android.launcher3.LauncherStateManager.ANIM_ALL;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_ALL_APPS_FADE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_HOTSEAT_SCALE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_HOTSEAT_TRANSLATE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_VERTICAL_PROGRESS;
import static com.android.launcher3.anim.Interpolators.AGGRESSIVE_EASE;
import static com.android.launcher3.anim.Interpolators.DEACCEL_3;
import static com.android.launcher3.anim.Interpolators.LINEAR;
import static com.android.launcher3.anim.Interpolators.OVERSHOOT_1_2;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_ALL_APPS_FADE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_HOTSEAT_SCALE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_HOTSEAT_TRANSLATE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_VERTICAL_PROGRESS;
import static com.android.quickstep.TaskViewUtils.findTaskViewToLaunch;
import static com.android.quickstep.TaskViewUtils.getRecentsWindowAnimator;
@@ -39,6 +37,7 @@
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
+import android.util.FloatProperty;
import android.view.View;
import androidx.annotation.NonNull;
@@ -47,9 +46,10 @@
import com.android.launcher3.LauncherState.ScaleAndTranslation;
import com.android.launcher3.allapps.AllAppsTransitionController;
import com.android.launcher3.anim.AnimatorPlaybackController;
-import com.android.launcher3.anim.AnimatorSetBuilder;
import com.android.launcher3.anim.Interpolators;
import com.android.launcher3.anim.SpringAnimationBuilder;
+import com.android.launcher3.states.StateAnimationConfig;
+import com.android.launcher3.touch.PagedOrientationHandler;
import com.android.quickstep.util.AppWindowAnimationHelper;
import com.android.quickstep.views.RecentsView;
import com.android.quickstep.views.TaskView;
@@ -88,9 +88,11 @@
TaskView taskView = findTaskViewToLaunch(mLauncher, v, appTargets);
- AppWindowAnimationHelper helper = new AppWindowAnimationHelper(mLauncher);
- anim.play(getRecentsWindowAnimator(taskView, skipLauncherChanges, appTargets,
- wallpaperTargets, helper).setDuration(RECENTS_LAUNCH_DURATION));
+ AppWindowAnimationHelper helper =
+ new AppWindowAnimationHelper(recentsView.getPagedViewOrientedState(), mLauncher);
+ Animator recentsAnimator = getRecentsWindowAnimator(taskView, skipLauncherChanges,
+ appTargets, wallpaperTargets, mLauncher.getDepthController(), helper);
+ anim.play(recentsAnimator.setDuration(RECENTS_LAUNCH_DURATION));
Animator childStateAnimation = null;
// Found a visible recents task that matches the opening app, lets launch the app from there
@@ -197,23 +199,30 @@
return ObjectAnimator.ofFloat(mLauncher.getOverviewPanel(),
RecentsView.CONTENT_ALPHA, values);
case INDEX_RECENTS_TRANSLATE_X_ANIM:
- return new SpringAnimationBuilder<>(mLauncher.getOverviewPanel(), VIEW_TRANSLATE_X)
+ PagedOrientationHandler orientationHandler =
+ ((RecentsView)mLauncher.getOverviewPanel()).getPagedViewOrientedState()
+ .getOrientationHandler();
+ FloatProperty<View> translate = orientationHandler.getPrimaryViewTranslate();
+ return new SpringAnimationBuilder<>(mLauncher.getOverviewPanel(), translate)
.setDampingRatio(0.8f)
.setStiffness(250)
.setValues(values)
.build(mLauncher);
case INDEX_PAUSE_TO_OVERVIEW_ANIM: {
- AnimatorSetBuilder builder = new AnimatorSetBuilder();
- builder.setInterpolator(ANIM_VERTICAL_PROGRESS, OVERSHOOT_1_2);
- builder.setInterpolator(ANIM_ALL_APPS_FADE, DEACCEL_3);
+ StateAnimationConfig config = new StateAnimationConfig();
+ config.duration = ATOMIC_DURATION_FROM_PAUSED_TO_OVERVIEW;
+
+ config.setInterpolator(ANIM_VERTICAL_PROGRESS, OVERSHOOT_1_2);
+ config.setInterpolator(ANIM_ALL_APPS_FADE, DEACCEL_3);
if ((OVERVIEW.getVisibleElements(mLauncher) & HOTSEAT_ICONS) != 0) {
- builder.setInterpolator(ANIM_HOTSEAT_SCALE, OVERSHOOT_1_2);
- builder.setInterpolator(ANIM_HOTSEAT_TRANSLATE, OVERSHOOT_1_2);
+ config.setInterpolator(ANIM_HOTSEAT_SCALE, OVERSHOOT_1_2);
+ config.setInterpolator(ANIM_HOTSEAT_TRANSLATE, OVERSHOOT_1_2);
}
+
+
LauncherStateManager stateManager = mLauncher.getStateManager();
return stateManager.createAtomicAnimation(
- stateManager.getCurrentStableState(), OVERVIEW, builder,
- ANIM_ALL, ATOMIC_DURATION_FROM_PAUSED_TO_OVERVIEW);
+ stateManager.getCurrentStableState(), OVERVIEW, config);
}
default:
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/AllAppsTipView.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/AllAppsTipView.java
index 0ae7435..079a738 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/AllAppsTipView.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/AllAppsTipView.java
@@ -16,25 +16,12 @@
package com.android.launcher3.appprediction;
+import static com.android.launcher3.AbstractFloatingView.TYPE_DISCOVERY_BOUNCE;
+import static com.android.launcher3.AbstractFloatingView.TYPE_ON_BOARD_POPUP;
import static com.android.launcher3.LauncherState.ALL_APPS;
import static com.android.quickstep.logging.UserEventDispatcherExtension.ALL_APPS_PREDICTION_TIPS;
-import android.content.Context;
-import android.graphics.CornerPathEffect;
-import android.graphics.Paint;
-import android.graphics.drawable.ShapeDrawable;
-import android.os.Handler;
import android.os.UserManager;
-import android.util.AttributeSet;
-import android.util.TypedValue;
-import android.view.Gravity;
-import android.view.MotionEvent;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.LinearLayout;
-import android.widget.TextView;
-
-import androidx.core.content.ContextCompat;
import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.Launcher;
@@ -43,106 +30,16 @@
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.allapps.FloatingHeaderView;
-import com.android.launcher3.anim.Interpolators;
-import com.android.launcher3.dragndrop.DragLayer;
-import com.android.launcher3.graphics.TriangleShape;
+import com.android.launcher3.views.ArrowTipView;
import com.android.systemui.shared.system.LauncherEventUtil;
/**
- * All apps tip view aligned just above prediction apps, shown to users that enter all apps for the
+ * ArrowTip helper aligned just above prediction apps, shown to users that enter all apps for the
* first time.
*/
-public class AllAppsTipView extends AbstractFloatingView {
+public class AllAppsTipView {
private static final String ALL_APPS_TIP_SEEN = "launcher.all_apps_tip_seen";
- private static final long AUTO_CLOSE_TIMEOUT_MILLIS = 10 * 1000;
- private static final long SHOW_DELAY_MS = 200;
- private static final long SHOW_DURATION_MS = 300;
- private static final long HIDE_DURATION_MS = 100;
-
- private final Launcher mLauncher;
- private final Handler mHandler = new Handler();
-
- private AllAppsTipView(Context context, AttributeSet attrs) {
- this(context, attrs, 0);
- }
-
- private AllAppsTipView(Context context, AttributeSet attrs, int defStyleAttr) {
- super(context, attrs, defStyleAttr);
- setOrientation(LinearLayout.VERTICAL);
-
- mLauncher = Launcher.getLauncher(context);
-
- init(context);
- }
-
- @Override
- public boolean onControllerInterceptTouchEvent(MotionEvent ev) {
- if (ev.getAction() == MotionEvent.ACTION_DOWN) {
- close(true);
- }
- return false;
- }
-
- @Override
- protected void handleClose(boolean animate) {
- if (mIsOpen) {
- if (animate) {
- animate().alpha(0f)
- .withLayer()
- .setStartDelay(0)
- .setDuration(HIDE_DURATION_MS)
- .setInterpolator(Interpolators.ACCEL)
- .withEndAction(() -> mLauncher.getDragLayer().removeView(this))
- .start();
- } else {
- animate().cancel();
- mLauncher.getDragLayer().removeView(this);
- }
- mLauncher.getSharedPrefs().edit().putBoolean(ALL_APPS_TIP_SEEN, true).apply();
- mIsOpen = false;
- }
- }
-
- @Override
- public void logActionCommand(int command) {
- }
-
- @Override
- protected boolean isOfType(int type) {
- return (type & TYPE_ON_BOARD_POPUP) != 0;
- }
-
- private void init(Context context) {
- inflate(context, R.layout.arrow_toast, this);
-
- TextView textView = findViewById(R.id.text);
- textView.setText(R.string.all_apps_prediction_tip);
-
- View dismissButton = findViewById(R.id.dismiss);
- dismissButton.setOnClickListener(view -> {
- mLauncher.getUserEventDispatcher().logActionTip(
- LauncherEventUtil.DISMISS, ALL_APPS_PREDICTION_TIPS);
- handleClose(true);
- });
-
- View arrowView = findViewById(R.id.arrow);
- ViewGroup.LayoutParams arrowLp = arrowView.getLayoutParams();
- ShapeDrawable arrowDrawable = new ShapeDrawable(TriangleShape.create(
- arrowLp.width, arrowLp.height, false));
- Paint arrowPaint = arrowDrawable.getPaint();
- TypedValue typedValue = new TypedValue();
- context.getTheme().resolveAttribute(android.R.attr.colorAccent, typedValue, true);
- arrowPaint.setColor(ContextCompat.getColor(getContext(), typedValue.resourceId));
- // The corner path effect won't be reflected in the shadow, but shouldn't be noticeable.
- arrowPaint.setPathEffect(new CornerPathEffect(
- context.getResources().getDimension(R.dimen.arrow_toast_corner_radius)));
- arrowView.setBackground(arrowDrawable);
-
- mIsOpen = true;
-
- mHandler.postDelayed(() -> handleClose(true), AUTO_CLOSE_TIMEOUT_MILLIS);
- }
private static boolean showAllAppsTipIfNecessary(Launcher launcher) {
FloatingHeaderView floatingHeaderView = launcher.getAppsView().getFloatingHeaderView();
@@ -156,28 +53,15 @@
return false;
}
- AllAppsTipView allAppsTipView = new AllAppsTipView(launcher.getAppsView().getContext(),
- null);
- launcher.getDragLayer().addView(allAppsTipView);
+ int[] coords = new int[2];
+ floatingHeaderView.findFixedRowByType(PredictionRowView.class).getLocationOnScreen(coords);
+ ArrowTipView arrowTipView = new ArrowTipView(launcher).setOnClosedCallback(() -> {
+ launcher.getSharedPrefs().edit().putBoolean(ALL_APPS_TIP_SEEN, true).apply();
+ launcher.getUserEventDispatcher().logActionTip(LauncherEventUtil.DISMISS,
+ ALL_APPS_PREDICTION_TIPS);
+ });
+ arrowTipView.show(launcher.getString(R.string.all_apps_prediction_tip), coords[1]);
- DragLayer.LayoutParams params = (DragLayer.LayoutParams) allAppsTipView.getLayoutParams();
- params.gravity = Gravity.CENTER_HORIZONTAL;
-
- int top = floatingHeaderView.findFixedRowByType(PredictionRowView.class).getTop();
- allAppsTipView.setY(top - launcher.getResources().getDimensionPixelSize(
- R.dimen.all_apps_tip_bottom_margin));
-
- allAppsTipView.setAlpha(0);
- allAppsTipView.animate()
- .alpha(1f)
- .withLayer()
- .setStartDelay(SHOW_DELAY_MS)
- .setDuration(SHOW_DURATION_MS)
- .setInterpolator(Interpolators.DEACCEL)
- .start();
-
- launcher.getUserEventDispatcher().logActionTip(
- LauncherEventUtil.VISIBLE, ALL_APPS_PREDICTION_TIPS);
return true;
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/AppsDividerView.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/AppsDividerView.java
index 425fb13..ec46418 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/AppsDividerView.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/AppsDividerView.java
@@ -16,6 +16,7 @@
package com.android.launcher3.appprediction;
+import static com.android.launcher3.LauncherAnimUtils.VIEW_ALPHA;
import static com.android.launcher3.LauncherState.ALL_APPS;
import android.annotation.TargetApi;
@@ -291,7 +292,7 @@
public void setContentVisibility(boolean hasHeaderExtra, boolean hasAllAppsContent,
PropertySetter setter, Interpolator headerFade, Interpolator allAppsFade) {
// Don't use setViewAlpha as we want to control the visibility ourselves.
- setter.setFloat(this, ALPHA, hasAllAppsContent ? 1 : 0, allAppsFade);
+ setter.setFloat(this, VIEW_ALPHA, hasAllAppsContent ? 1 : 0, allAppsFade);
}
@Override
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/ComponentKeyMapper.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/ComponentKeyMapper.java
index 0712285..fdb8e4c 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/ComponentKeyMapper.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/ComponentKeyMapper.java
@@ -18,9 +18,9 @@
import static com.android.quickstep.InstantAppResolverImpl.COMPONENT_CLASS_MARKER;
-import com.android.launcher3.AppInfo;
-import com.android.launcher3.ItemInfoWithIcon;
import com.android.launcher3.allapps.AllAppsStore;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.ItemInfoWithIcon;
import com.android.launcher3.shortcuts.ShortcutKey;
import com.android.launcher3.util.ComponentKey;
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/DynamicItemCache.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/DynamicItemCache.java
index 54f58e2..6c4bfe8 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/DynamicItemCache.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/DynamicItemCache.java
@@ -38,11 +38,11 @@
import androidx.annotation.UiThread;
import androidx.annotation.WorkerThread;
-import com.android.launcher3.AppInfo;
import com.android.launcher3.LauncherAppState;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.allapps.AllAppsStore;
import com.android.launcher3.icons.IconCache;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.shortcuts.ShortcutKey;
import com.android.launcher3.shortcuts.ShortcutRequest;
import com.android.launcher3.util.InstantAppResolver;
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/InstantAppItemInfo.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/InstantAppItemInfo.java
index 6e5f461..6c4c601 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/InstantAppItemInfo.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/InstantAppItemInfo.java
@@ -21,9 +21,9 @@
import android.content.ComponentName;
import android.content.Intent;
-import com.android.launcher3.AppInfo;
import com.android.launcher3.LauncherSettings;
-import com.android.launcher3.WorkspaceItemInfo;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
public class InstantAppItemInfo extends AppInfo {
@@ -44,7 +44,7 @@
workspaceItemInfo.status = WorkspaceItemInfo.FLAG_AUTOINSTALL_ICON
| WorkspaceItemInfo.FLAG_RESTORE_STARTED
| WorkspaceItemInfo.FLAG_SUPPORTS_WEB_UI;
- workspaceItemInfo.intent.setPackage(componentName.getPackageName());
+ workspaceItemInfo.getIntent().setPackage(componentName.getPackageName());
return workspaceItemInfo;
}
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/PredictionRowView.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/PredictionRowView.java
index f82af62..d4cc129 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/PredictionRowView.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/PredictionRowView.java
@@ -1,5 +1,5 @@
-/**
- * Copyright (C) 2019 The Android Open Source Project
+/*
+ * Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,8 +16,11 @@
package com.android.launcher3.appprediction;
+import static com.android.launcher3.LauncherState.OVERVIEW;
import static com.android.launcher3.anim.Interpolators.LINEAR;
import static com.android.launcher3.icons.GraphicsUtils.setColorAlphaBound;
+import static com.android.launcher3.logging.LoggerUtils.newContainerTarget;
+import static com.android.launcher3.logging.LoggerUtils.newTarget;
import android.annotation.TargetApi;
import android.content.Context;
@@ -35,17 +38,14 @@
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
-import com.android.launcher3.AppInfo;
import com.android.launcher3.BubbleTextView;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.DeviceProfile.OnDeviceProfileChangeListener;
-import com.android.launcher3.ItemInfo;
-import com.android.launcher3.ItemInfoWithIcon;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherSettings;
+import com.android.launcher3.LauncherState;
import com.android.launcher3.R;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.allapps.AllAppsStore;
import com.android.launcher3.allapps.FloatingHeaderRow;
import com.android.launcher3.allapps.FloatingHeaderView;
@@ -56,6 +56,10 @@
import com.android.launcher3.keyboard.FocusIndicatorHelper.SimpleFocusIndicatorHelper;
import com.android.launcher3.logging.StatsLogUtils.LogContainerProvider;
import com.android.launcher3.model.AppLaunchTracker;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.ItemInfoWithIcon;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.touch.ItemClickHandler;
import com.android.launcher3.touch.ItemLongClickListener;
import com.android.launcher3.userevent.nano.LauncherLogProto;
@@ -187,7 +191,7 @@
public int getExpectedHeight() {
return getVisibility() == GONE ? 0 :
Launcher.getLauncher(getContext()).getDeviceProfile().allAppsCellHeightPx
- + getPaddingTop() + getPaddingBottom();
+ + getPaddingTop() + getPaddingBottom();
}
@Override
@@ -282,7 +286,8 @@
mParent.onHeightUpdated();
}
- private List<ItemInfoWithIcon> processPredictedAppComponents(List<ComponentKeyMapper> components) {
+ private List<ItemInfoWithIcon> processPredictedAppComponents(
+ List<ComponentKeyMapper> components) {
if (getAppsStore().getApps().length == 0) {
// Apps have not been bound yet.
return Collections.emptyList();
@@ -296,7 +301,7 @@
predictedApp.container = LauncherSettings.Favorites.CONTAINER_PREDICTION;
predictedApps.add(predictedApp);
} else {
- if (FeatureFlags.IS_DOGFOOD_BUILD) {
+ if (FeatureFlags.IS_STUDIO_BUILD) {
Log.e(TAG, "Predicted app not found: " + mapper);
}
}
@@ -309,16 +314,26 @@
}
@Override
- public void fillInLogContainerData(View v, ItemInfo info, LauncherLogProto.Target target,
- LauncherLogProto.Target targetParent) {
+ public void fillInLogContainerData(ItemInfo childInfo, LauncherLogProto.Target child,
+ ArrayList<LauncherLogProto.Target> parents) {
for (int i = 0; i < mPredictedApps.size(); i++) {
ItemInfoWithIcon appInfo = mPredictedApps.get(i);
- if (appInfo == info) {
- targetParent.containerType = LauncherLogProto.ContainerType.PREDICTION;
- target.predictedRank = i;
+ if (appInfo == childInfo) {
+ child.predictedRank = i;
break;
}
}
+ parents.add(newContainerTarget(LauncherLogProto.ContainerType.PREDICTION));
+
+ // include where the prediction is coming this used to be Launcher#modifyUserEvent
+ LauncherLogProto.Target parent = newTarget(LauncherLogProto.Target.Type.CONTAINER);
+ LauncherState state = mLauncher.getStateManager().getState();
+ if (state == LauncherState.ALL_APPS) {
+ parent.containerType = LauncherLogProto.ContainerType.ALLAPPS;
+ } else if (state == OVERVIEW) {
+ parent.containerType = LauncherLogProto.ContainerType.TASKSWITCHER;
+ }
+ parents.add(parent);
}
public void setTextAlpha(int textAlpha) {
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/PredictionUiStateManager.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/PredictionUiStateManager.java
index 632b9b5..8e55609 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/PredictionUiStateManager.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/appprediction/PredictionUiStateManager.java
@@ -28,8 +28,6 @@
import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.InvariantDeviceProfile.OnIDPChangeListener;
-import com.android.launcher3.ItemInfo;
-import com.android.launcher3.ItemInfoWithIcon;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherSettings;
@@ -40,6 +38,8 @@
import com.android.launcher3.allapps.AllAppsStore.OnUpdateListener;
import com.android.launcher3.hybridhotseat.HotseatPredictionController;
import com.android.launcher3.icons.IconCache.ItemInfoUpdateReceiver;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.ItemInfoWithIcon;
import com.android.launcher3.shortcuts.ShortcutKey;
import com.android.launcher3.userevent.nano.LauncherLogProto;
import com.android.launcher3.util.ComponentKey;
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/hybridhotseat/HotseatEduController.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/hybridhotseat/HotseatEduController.java
index bfbd00e..f907089 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/hybridhotseat/HotseatEduController.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/hybridhotseat/HotseatEduController.java
@@ -23,18 +23,30 @@
import android.content.res.Configuration;
import android.os.Build;
import android.view.View;
-import android.view.ViewGroup;
import androidx.core.app.NotificationCompat;
-import com.android.launcher3.ItemInfo;
+import com.android.launcher3.CellLayout;
+import com.android.launcher3.Hotseat;
+import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.R;
-import com.android.launcher3.WorkspaceItemInfo;
+import com.android.launcher3.Workspace;
+import com.android.launcher3.config.FeatureFlags;
+import com.android.launcher3.model.data.FolderInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.uioverrides.QuickstepLauncher;
import com.android.launcher3.util.ActivityTracker;
+import com.android.launcher3.util.GridOccupancy;
+import com.android.launcher3.util.IntArray;
+import com.android.launcher3.util.Themes;
+import com.android.launcher3.views.ArrowTipView;
+import com.android.launcher3.views.Snackbar;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
import java.util.List;
/**
@@ -46,40 +58,198 @@
private static final String NOTIFICATION_CHANNEL_ID = "launcher_onboarding";
private static final int ONBOARDING_NOTIFICATION_ID = 7641;
+ private static final String SETTINGS_ACTION =
+ "android.settings.ACTION_CONTENT_SUGGESTIONS_SETTINGS";
+
private final Launcher mLauncher;
+ private final Hotseat mHotseat;
+ private final NotificationManager mNotificationManager;
+ private final Notification mNotification;
private List<WorkspaceItemInfo> mPredictedApps;
private HotseatEduDialog mActiveDialog;
- private final NotificationManager mNotificationManager;
- private final Notification mNotification;
+ private ArrayList<ItemInfo> mNewItems = new ArrayList<>();
+ private IntArray mNewScreens = null;
+ private Runnable mOnOnboardingComplete;
- HotseatEduController(Launcher launcher) {
+ HotseatEduController(Launcher launcher, Runnable runnable) {
mLauncher = launcher;
+ mHotseat = launcher.getHotseat();
+ mOnOnboardingComplete = runnable;
mNotificationManager = mLauncher.getSystemService(NotificationManager.class);
createNotificationChannel();
mNotification = createNotification();
}
+ /**
+ * Checks what type of migration should be used and migrates hotseat
+ */
void migrate() {
- ViewGroup hotseatVG = mLauncher.getHotseat().getShortcutsAndWidgets();
- int workspacePageCount = mLauncher.getWorkspace().getPageCount();
- for (int i = 0; i < hotseatVG.getChildCount(); i++) {
- View child = hotseatVG.getChildAt(i);
- ItemInfo tag = (ItemInfo) child.getTag();
- mLauncher.getModelWriter().moveItemInDatabase(tag,
- LauncherSettings.Favorites.CONTAINER_DESKTOP, workspacePageCount, tag.screenId,
- 0);
+ if (FeatureFlags.HOTSEAT_MIGRATE_TO_FOLDER.get()) {
+ migrateToFolder();
+ } else {
+ migrateHotseatWhole();
}
}
+ /**
+ * This migration places all non folder items in the hotseat into a folder and then moves
+ * all folders in the hotseat to a workspace page that has enough empty spots.
+ *
+ * @return pageId that has accepted the items.
+ */
+ private int migrateToFolder() {
+ ArrayDeque<FolderInfo> folders = new ArrayDeque<>();
+
+ ArrayList<WorkspaceItemInfo> putIntoFolder = new ArrayList<>();
+
+ //separate folders and items that can get in folders
+ for (int i = 0; i < mLauncher.getDeviceProfile().inv.numHotseatIcons; i++) {
+ View view = mHotseat.getChildAt(i, 0);
+ if (view == null) continue;
+ ItemInfo info = (ItemInfo) view.getTag();
+ if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_FOLDER) {
+ folders.add((FolderInfo) info);
+ } else if (info instanceof WorkspaceItemInfo) {
+ putIntoFolder.add((WorkspaceItemInfo) info);
+ }
+ }
+
+ // create a temp folder and add non folder items to it
+ if (!putIntoFolder.isEmpty()) {
+ ItemInfo firstItem = putIntoFolder.get(0);
+ FolderInfo folderInfo = new FolderInfo();
+ folderInfo.title = "";
+ mLauncher.getModelWriter().addItemToDatabase(folderInfo, firstItem.container,
+ firstItem.screenId, firstItem.cellX, firstItem.cellY);
+ folderInfo.contents.addAll(putIntoFolder);
+ for (int i = 0; i < folderInfo.contents.size(); i++) {
+ ItemInfo item = folderInfo.contents.get(i);
+ item.rank = i;
+ mLauncher.getModelWriter().moveItemInDatabase(item, folderInfo.id, 0,
+ item.cellX, item.cellY);
+ }
+ folders.add(folderInfo);
+ }
+ mNewItems.addAll(folders);
+
+ return placeFoldersInWorkspace(folders);
+ }
+
+ private int placeFoldersInWorkspace(ArrayDeque<FolderInfo> folders) {
+ if (folders.isEmpty()) return 0;
+
+ Workspace workspace = mLauncher.getWorkspace();
+ InvariantDeviceProfile idp = mLauncher.getDeviceProfile().inv;
+
+ GridOccupancy[] occupancyList = new GridOccupancy[workspace.getChildCount()];
+ for (int i = 0; i < occupancyList.length; i++) {
+ occupancyList[i] = ((CellLayout) workspace.getChildAt(i)).cloneGridOccupancy();
+ }
+ //scan every screen to find available spots to place folders
+ int occupancyIndex = 0;
+ int[] itemXY = new int[2];
+ while (occupancyIndex < occupancyList.length && !folders.isEmpty()) {
+ GridOccupancy occupancy = occupancyList[occupancyIndex];
+ if (occupancy.findVacantCell(itemXY, 1, 1)) {
+ FolderInfo info = folders.poll();
+ mLauncher.getModelWriter().moveItemInDatabase(info,
+ LauncherSettings.Favorites.CONTAINER_DESKTOP,
+ workspace.getScreenIdForPageIndex(occupancyIndex), itemXY[0], itemXY[1]);
+ occupancy.markCells(info, true);
+ } else {
+ occupancyIndex++;
+ }
+ }
+ if (folders.isEmpty()) return workspace.getScreenIdForPageIndex(occupancyIndex);
+ int screenId = LauncherSettings.Settings.call(mLauncher.getContentResolver(),
+ LauncherSettings.Settings.METHOD_NEW_SCREEN_ID)
+ .getInt(LauncherSettings.Settings.EXTRA_VALUE);
+ // if all screens are full and we still have folders left, put those on a new page
+ FolderInfo folderInfo;
+ int col = 0;
+ while ((folderInfo = folders.poll()) != null) {
+ mLauncher.getModelWriter().moveItemInDatabase(folderInfo,
+ LauncherSettings.Favorites.CONTAINER_DESKTOP, screenId, col++,
+ idp.numRows - 1);
+ }
+ mNewScreens = IntArray.wrap(screenId);
+ return workspace.getPageCount();
+ }
+
+ /**
+ * This migration option attempts to move the entire hotseat up to the first workspace that
+ * has space to host items. If no such page is found, it moves items to a new page.
+ *
+ * @return pageId where items are migrated
+ */
+ private int migrateHotseatWhole() {
+ Workspace workspace = mLauncher.getWorkspace();
+
+ int pageId = -1;
+ int toRow = 0;
+ for (int i = 0; i < workspace.getPageCount(); i++) {
+ CellLayout target = workspace.getScreenWithId(workspace.getScreenIdForPageIndex(i));
+ if (target.makeSpaceForHotseatMigration(true)) {
+ toRow = mLauncher.getDeviceProfile().inv.numRows - 1;
+ pageId = i;
+ break;
+ }
+ }
+ if (pageId == -1) {
+ pageId = LauncherSettings.Settings.call(mLauncher.getContentResolver(),
+ LauncherSettings.Settings.METHOD_NEW_SCREEN_ID)
+ .getInt(LauncherSettings.Settings.EXTRA_VALUE);
+ }
+ for (int i = 0; i < mLauncher.getDeviceProfile().inv.numHotseatIcons; i++) {
+ View child = mHotseat.getChildAt(i, 0);
+ if (child == null || child.getTag() == null) continue;
+ ItemInfo tag = (ItemInfo) child.getTag();
+ mLauncher.getModelWriter().moveItemInDatabase(tag,
+ LauncherSettings.Favorites.CONTAINER_DESKTOP, pageId, i, toRow);
+ mNewItems.add(tag);
+ }
+ return pageId;
+ }
+
+
void removeNotification() {
mNotificationManager.cancel(ONBOARDING_NOTIFICATION_ID);
}
+ void moveHotseatItems() {
+ mHotseat.removeAllViewsInLayout();
+ if (!mNewItems.isEmpty()) {
+ int lastPage = mNewItems.get(mNewItems.size() - 1).screenId;
+ ArrayList<ItemInfo> animated = new ArrayList<>();
+ ArrayList<ItemInfo> nonAnimated = new ArrayList<>();
+
+ for (ItemInfo info : mNewItems) {
+ if (info.screenId == lastPage) {
+ animated.add(info);
+ } else {
+ nonAnimated.add(info);
+ }
+ }
+ mLauncher.bindAppsAdded(mNewScreens, nonAnimated, animated);
+ }
+ }
+
void finishOnboarding() {
- mLauncher.getModel().rebindCallbacks();
+ mOnOnboardingComplete.run();
+ destroy();
mLauncher.getSharedPrefs().edit().putBoolean(KEY_HOTSEAT_EDU_SEEN, true).apply();
- removeNotification();
+ }
+
+ void showDimissTip() {
+ if (mHotseat.getShortcutsAndWidgets().getChildCount()
+ < mLauncher.getDeviceProfile().inv.numHotseatIcons) {
+ Snackbar.show(mLauncher, R.string.hotseat_tip_gaps_filled, R.string.hotseat_turn_off,
+ null, () -> mLauncher.startActivity(new Intent(SETTINGS_ACTION)));
+ } else {
+ new ArrowTipView(mLauncher).show(
+ mLauncher.getString(R.string.hotseat_tip_no_empty_slots), mHotseat.getTop());
+ }
}
void setPredictedApps(List<WorkspaceItemInfo> predictedApps) {
@@ -88,11 +258,14 @@
&& mLauncher.getOrientation() == Configuration.ORIENTATION_PORTRAIT) {
mNotificationManager.notify(ONBOARDING_NOTIFICATION_ID, mNotification);
}
+ else {
+ removeNotification();
+ }
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return;
- CharSequence name = mLauncher.getString(R.string.hotseat_migrate_title);
+ CharSequence name = mLauncher.getString(R.string.hotseat_edu_prompt_title);
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, name,
importance);
@@ -103,13 +276,13 @@
Intent intent = new Intent(mLauncher.getApplicationContext(), mLauncher.getClass());
intent = new NotificationHandler().addToIntent(intent);
- CharSequence name = mLauncher.getString(R.string.hotseat_migrate_prompt_title);
- String description = mLauncher.getString(R.string.hotseat_migrate_prompt_content);
+ CharSequence name = mLauncher.getString(R.string.hotseat_edu_prompt_title);
+ String description = mLauncher.getString(R.string.hotseat_edu_prompt_content);
NotificationCompat.Builder builder = new NotificationCompat.Builder(mLauncher,
NOTIFICATION_CHANNEL_ID)
.setContentTitle(name)
.setOngoing(true)
- .setColor(mLauncher.getColor(R.color.bottom_panel_background))
+ .setColor(Themes.getColorAccent(mLauncher))
.setContentIntent(PendingIntent.getActivity(mLauncher, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT))
.setSmallIcon(R.drawable.hotseat_edu_notification_icon)
@@ -125,6 +298,17 @@
}
}
+ void showEdu() {
+ // hotseat is already empty and does not require migration. show edu tip
+ if (mHotseat.getShortcutsAndWidgets().getChildCount() == 0) {
+ new ArrowTipView(mLauncher).show(mLauncher.getString(R.string.hotseat_auto_enrolled),
+ mHotseat.getTop());
+ finishOnboarding();
+ } else {
+ showDialog();
+ }
+ }
+
void showDialog() {
if (mPredictedApps == null || mPredictedApps.isEmpty()) {
return;
@@ -141,7 +325,7 @@
ActivityTracker.SchedulerCallback<QuickstepLauncher> {
@Override
public boolean init(QuickstepLauncher activity, boolean alreadyOnHome) {
- activity.getHotseatPredictionController().showEduDialog();
+ activity.getHotseatPredictionController().showEdu();
return true;
}
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/hybridhotseat/HotseatEduDialog.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/hybridhotseat/HotseatEduDialog.java
index 4c87945..4213740 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/hybridhotseat/HotseatEduDialog.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/hybridhotseat/HotseatEduDialog.java
@@ -15,6 +15,9 @@
*/
package com.android.launcher3.hybridhotseat;
+import static com.android.launcher3.logging.LoggerUtils.newLauncherEvent;
+import static com.android.launcher3.userevent.nano.LauncherLogProto.ControlType.HYBRID_HOTSEAT_CANCELED;
+
import android.animation.PropertyValuesHolder;
import android.content.Context;
import android.content.res.Configuration;
@@ -23,15 +26,17 @@
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
-import android.widget.Toast;
+import android.widget.TextView;
import com.android.launcher3.CellLayout;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.Insettable;
import com.android.launcher3.Launcher;
import com.android.launcher3.R;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.anim.Interpolators;
+import com.android.launcher3.config.FeatureFlags;
+import com.android.launcher3.logging.UserEventDispatcher;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.uioverrides.PredictedAppIcon;
import com.android.launcher3.userevent.nano.LauncherLogProto;
import com.android.launcher3.views.AbstractSlideInView;
@@ -45,12 +50,16 @@
public class HotseatEduDialog extends AbstractSlideInView implements Insettable {
private static final int DEFAULT_CLOSE_DURATION = 200;
+ protected static final int FINAL_SCRIM_BG_COLOR = 0x88000000;
- public static boolean shown = false;
+
+ // we use this value to keep track of migration logs as we experiment with different migrations
+ private static final int MIGRATION_EXPERIMENT_IDENTIFIER = 1;
private final Rect mInsets = new Rect();
private View mHotseatWrapper;
private CellLayout mSampleHotseat;
+ private Button mDismissBtn;
public void setHotseatEduController(HotseatEduController hotseatEduController) {
mHotseatEduController = hotseatEduController;
@@ -83,25 +92,33 @@
mSampleHotseat.setPadding(padding.left, 0, padding.right, 0);
Button turnOnBtn = findViewById(R.id.turn_predictions_on);
- turnOnBtn.setOnClickListener(this::onMigrate);
+ turnOnBtn.setOnClickListener(this::onAccept);
- Button learnMoreBtn = findViewById(R.id.no_thanks);
- learnMoreBtn.setOnClickListener(this::onKeepDefault);
+ mDismissBtn = findViewById(R.id.no_thanks);
+ mDismissBtn.setOnClickListener(this::onDismiss);
+ // update ui to reflect which migration method is going to be used
+ if (FeatureFlags.HOTSEAT_MIGRATE_TO_FOLDER.get()) {
+ ((TextView) findViewById(R.id.hotseat_edu_content)).setText(
+ R.string.hotseat_edu_message_migrate_alt);
+ }
}
- private void onMigrate(View v) {
- if (mHotseatEduController == null) return;
- handleClose(true);
+ private void onAccept(View v) {
mHotseatEduController.migrate();
+ handleClose(true);
+
+ mHotseatEduController.moveHotseatItems();
mHotseatEduController.finishOnboarding();
- Toast.makeText(mLauncher, R.string.hotseat_items_migrated, Toast.LENGTH_LONG).show();
+ //TODO: pass actual page index here.
+ // Temporarily we're passing 1 for folder migration and 2 for page migration
+ logUserAction(true, FeatureFlags.HOTSEAT_MIGRATE_TO_FOLDER.get() ? 1 : 2);
}
- private void onKeepDefault(View v) {
- if (mHotseatEduController == null) return;
- Toast.makeText(getContext(), R.string.hotseat_no_migration, Toast.LENGTH_LONG).show();
+ private void onDismiss(View v) {
+ mHotseatEduController.showDimissTip();
mHotseatEduController.finishOnboarding();
+ logUserAction(false, -1);
handleClose(true);
}
@@ -133,6 +150,32 @@
mLauncher.getDeviceProfile().hotseatBarSizePx + insets.bottom;
}
+ private void logUserAction(boolean migrated, int pageIndex) {
+ LauncherLogProto.Action action = new LauncherLogProto.Action();
+ LauncherLogProto.Target target = new LauncherLogProto.Target();
+ action.type = LauncherLogProto.Action.Type.TOUCH;
+ action.touch = LauncherLogProto.Action.Touch.TAP;
+ target.containerType = LauncherLogProto.ContainerType.TIP;
+ target.tipType = LauncherLogProto.TipType.HYBRID_HOTSEAT;
+ target.controlType = migrated ? LauncherLogProto.ControlType.HYBRID_HOTSEAT_ACCEPTED
+ : HYBRID_HOTSEAT_CANCELED;
+ target.rank = MIGRATION_EXPERIMENT_IDENTIFIER;
+ // encoding migration type on pageIndex
+ target.pageIndex = pageIndex;
+ target.cardinality = HotseatPredictionController.MAX_ITEMS_FOR_MIGRATION;
+ LauncherLogProto.LauncherEvent event = newLauncherEvent(action, target);
+ UserEventDispatcher.newInstance(getContext()).dispatchUserEvent(event, null);
+ }
+
+ private void logOnBoardingSeen() {
+ LauncherLogProto.Action action = new LauncherLogProto.Action();
+ LauncherLogProto.Target target = new LauncherLogProto.Target();
+ action.type = LauncherLogProto.Action.Type.TIP;
+ target.containerType = LauncherLogProto.ContainerType.TIP;
+ target.tipType = LauncherLogProto.TipType.HYBRID_HOTSEAT;
+ LauncherLogProto.LauncherEvent event = newLauncherEvent(action, target);
+ UserEventDispatcher.newInstance(getContext()).dispatchUserEvent(event, null);
+ }
private void animateOpen() {
if (mIsOpen || mOpenCloseAnimator.isRunning()) {
@@ -156,24 +199,36 @@
handleClose(false);
}
+ @Override
+ protected int getScrimColor(Context context) {
+ return FINAL_SCRIM_BG_COLOR;
+ }
+
+ private void populatePreview(List<WorkspaceItemInfo> predictions) {
+ for (int i = 0; i < mLauncher.getDeviceProfile().inv.numHotseatIcons; i++) {
+ WorkspaceItemInfo info = predictions.get(i);
+ PredictedAppIcon icon = PredictedAppIcon.createIcon(mSampleHotseat, info);
+ icon.setEnabled(false);
+ icon.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
+ icon.verifyHighRes();
+ CellLayout.LayoutParams lp = new CellLayout.LayoutParams(i, 0, 1, 1);
+ mSampleHotseat.addViewToCellLayout(icon, i, info.getViewId(), lp, true);
+ }
+ }
+
/**
* Opens User education dialog with a list of suggested apps
*/
public void show(List<WorkspaceItemInfo> predictions) {
if (getParent() != null
- || predictions.size() < mLauncher.getDeviceProfile().inv.numHotseatIcons) {
+ || predictions.size() < mLauncher.getDeviceProfile().inv.numHotseatIcons
+ || mHotseatEduController == null) {
return;
}
- mLauncher.getDragLayer().addView(this);
+ attachToContainer();
+ logOnBoardingSeen();
animateOpen();
- for (int i = 0; i < mLauncher.getDeviceProfile().inv.numHotseatIcons; i++) {
- WorkspaceItemInfo info = predictions.get(i);
- PredictedAppIcon icon = PredictedAppIcon.createIcon(mSampleHotseat, info);
- icon.setEnabled(false);
- icon.verifyHighRes();
- CellLayout.LayoutParams lp = new CellLayout.LayoutParams(i, 0, 1, 1);
- mSampleHotseat.addViewToCellLayout(icon, i, info.getViewId(), lp, true);
- }
+ populatePreview(predictions);
}
/**
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/hybridhotseat/HotseatPredictionController.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/hybridhotseat/HotseatPredictionController.java
index 0b05427..63277d2 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/hybridhotseat/HotseatPredictionController.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/hybridhotseat/HotseatPredictionController.java
@@ -16,6 +16,9 @@
package com.android.launcher3.hybridhotseat;
import static com.android.launcher3.LauncherAnimUtils.SCALE_PROPERTY;
+import static com.android.launcher3.logging.LoggerUtils.newAction;
+import static com.android.launcher3.logging.LoggerUtils.newContainerTarget;
+import static com.android.launcher3.logging.LoggerUtils.newLauncherEvent;
import android.animation.Animator;
import android.animation.AnimatorSet;
@@ -28,6 +31,8 @@
import android.app.prediction.AppTargetId;
import android.content.ComponentName;
import android.os.Bundle;
+import android.os.Process;
+import android.provider.DeviceConfig;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
@@ -35,21 +40,18 @@
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
-import com.android.launcher3.AppInfo;
import com.android.launcher3.BubbleTextView;
+import com.android.launcher3.CellLayout;
import com.android.launcher3.DragSource;
import com.android.launcher3.DropTarget;
-import com.android.launcher3.FolderInfo;
import com.android.launcher3.Hotseat;
import com.android.launcher3.InvariantDeviceProfile;
-import com.android.launcher3.ItemInfo;
-import com.android.launcher3.ItemInfoWithIcon;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.LauncherState;
import com.android.launcher3.R;
+import com.android.launcher3.Utilities;
import com.android.launcher3.Workspace;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.allapps.AllAppsStore;
import com.android.launcher3.anim.AnimationSuccessListener;
import com.android.launcher3.appprediction.ComponentKeyMapper;
@@ -58,9 +60,17 @@
import com.android.launcher3.dragndrop.DragOptions;
import com.android.launcher3.icons.IconCache;
import com.android.launcher3.logging.FileLog;
+import com.android.launcher3.logging.UserEventDispatcher;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.FolderInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.ItemInfoWithIcon;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.popup.SystemShortcut;
import com.android.launcher3.shortcuts.ShortcutKey;
import com.android.launcher3.touch.ItemLongClickListener;
+import com.android.launcher3.uioverrides.DeviceFlag;
import com.android.launcher3.uioverrides.PredictedAppIcon;
import com.android.launcher3.uioverrides.QuickstepLauncher;
import com.android.launcher3.userevent.nano.LauncherLogProto;
@@ -69,6 +79,7 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import java.util.Locale;
import java.util.OptionalInt;
import java.util.stream.IntStream;
@@ -84,6 +95,9 @@
private static final String TAG = "PredictiveHotseat";
private static final boolean DEBUG = false;
+ public static final int MAX_ITEMS_FOR_MIGRATION = DeviceConfig.getInt(
+ DeviceFlag.NAMESPACE_LAUNCHER, "max_homepage_items_for_migration", 5);
+
//TODO: replace this with AppTargetEvent.ACTION_UNPIN (b/144119543)
private static final int APPTARGET_ACTION_UNPIN = 4;
@@ -93,8 +107,9 @@
private static final String BUNDLE_KEY_HOTSEAT = "hotseat_apps";
private static final String BUNDLE_KEY_WORKSPACE = "workspace_apps";
- private static final String PREDICTION_CLIENT = "hotseat";
+ private static final String BUNDLE_KEY_PIN_EVENTS = "pin_events";
+ private static final String PREDICTION_CLIENT = "hotseat";
private DropTarget.DragObject mDragObject;
private int mHotSeatItemsCount;
private int mPredictedSpotsCount = 0;
@@ -113,6 +128,7 @@
private HotseatEduController mHotseatEduController;
+
private List<PredictedAppIcon.PredictedIconOutlineDrawing> mOutlineDrawings = new ArrayList<>();
private final View.OnLongClickListener mPredictionLongClickListener = v -> {
@@ -146,12 +162,12 @@
}
/**
- * Transitions to NORMAL workspace mode and shows edu dialog
+ * Transitions to NORMAL workspace mode and shows edu
*/
- public void showEduDialog() {
+ public void showEdu() {
if (mHotseatEduController == null) return;
mLauncher.getStateManager().goToState(LauncherState.NORMAL, true,
- () -> mHotseatEduController.showDialog());
+ () -> mHotseatEduController.showEdu());
}
@Override
@@ -226,12 +242,9 @@
}
}
if (animate) {
- animationSet.addListener(new AnimationSuccessListener() {
- @Override
- public void onAnimationSuccess(Animator animator) {
- if (callback != null) callback.run();
- }
- });
+ if (callback != null) {
+ animationSet.addListener(AnimationSuccessListener.forRunnable(callback));
+ }
animationSet.start();
} else {
if (callback != null) callback.run();
@@ -279,27 +292,55 @@
.build());
mAppPredictor.registerPredictionUpdates(mLauncher.getMainExecutor(),
this::setPredictedApps);
-
+ setPauseUIUpdate(false);
+ performBetaCheck();
if (!isReady()) {
- if (mHotseatEduController != null) {
- mHotseatEduController.destroy();
- }
- mHotseatEduController = new HotseatEduController(mLauncher);
+ mHotseatEduController = new HotseatEduController(mLauncher, this::createPredictor);
}
mAppPredictor.requestPredictionUpdate();
}
private Bundle getAppPredictionContextExtra() {
Bundle bundle = new Bundle();
+
+ //TODO: remove this way of reporting items
bundle.putParcelableArrayList(BUNDLE_KEY_HOTSEAT,
getPinnedAppTargetsInViewGroup((mHotseat.getShortcutsAndWidgets())));
bundle.putParcelableArrayList(BUNDLE_KEY_WORKSPACE, getPinnedAppTargetsInViewGroup(
mLauncher.getWorkspace().getScreenWithId(
Workspace.FIRST_SCREEN_ID).getShortcutsAndWidgets()));
+ ArrayList<AppTargetEvent> pinEvents = new ArrayList<>();
+ getPinEventsForViewGroup(pinEvents, mHotseat.getShortcutsAndWidgets(),
+ APP_LOCATION_HOTSEAT);
+ getPinEventsForViewGroup(pinEvents, mLauncher.getWorkspace().getScreenWithId(
+ Workspace.FIRST_SCREEN_ID).getShortcutsAndWidgets(), APP_LOCATION_WORKSPACE);
+ bundle.putParcelableArrayList(BUNDLE_KEY_PIN_EVENTS, pinEvents);
+
return bundle;
}
+ private ArrayList<AppTargetEvent> getPinEventsForViewGroup(ArrayList<AppTargetEvent> pinEvents,
+ ViewGroup views, String root) {
+ for (int i = 0; i < views.getChildCount(); i++) {
+ View child = views.getChildAt(i);
+ final AppTargetEvent event;
+ if (child.getTag() instanceof ItemInfo && getAppTargetFromInfo(
+ (ItemInfo) child.getTag()) != null) {
+ ItemInfo info = (ItemInfo) child.getTag();
+ event = wrapAppTargetWithLocation(getAppTargetFromInfo(info),
+ AppTargetEvent.ACTION_PIN, info);
+ } else {
+ CellLayout.LayoutParams params = (CellLayout.LayoutParams) views.getLayoutParams();
+ event = wrapAppTargetWithLocation(getBlockAppTarget(), AppTargetEvent.ACTION_PIN,
+ root, 0, params.cellX, params.cellY, params.cellHSpan, params.cellVSpan);
+ }
+ pinEvents.add(event);
+ }
+ return pinEvents;
+ }
+
+
private ArrayList<AppTarget> getPinnedAppTargetsInViewGroup(ViewGroup viewGroup) {
ArrayList<AppTarget> pinnedApps = new ArrayList<>();
for (int i = 0; i < viewGroup.getChildCount(); i++) {
@@ -330,7 +371,7 @@
mComponentKeyMappers.add(new ComponentKeyMapper(key, mDynamicItemCache));
}
predictionLog.append("]");
- FileLog.d(TAG, predictionLog.toString());
+ if (Utilities.IS_DEBUG_DEVICE) FileLog.d(TAG, predictionLog.toString());
updateDependencies();
if (isReady()) {
fillGapsWithPrediction();
@@ -344,7 +385,10 @@
mHotSeatItemsCount);
}
- private void pinPrediction(ItemInfo info) {
+ /**
+ * Pins a predicted app icon into place.
+ */
+ public void pinPrediction(ItemInfo info) {
PredictedAppIcon icon = (PredictedAppIcon) mHotseat.getChildAt(
mHotseat.getCellXFromOrder(info.rank),
mHotseat.getCellYFromOrder(info.rank));
@@ -491,7 +535,6 @@
}
}
-
@Override
public void onDragEnd() {
if (mDragObject == null) {
@@ -567,7 +610,8 @@
}
@Override
- public void reapplyItemInfo(ItemInfoWithIcon info) {}
+ public void reapplyItemInfo(ItemInfoWithIcon info) {
+ }
@Override
public void onDropCompleted(View target, DropTarget.DragObject d, boolean success) {
@@ -575,9 +619,9 @@
}
@Override
- public void fillInLogContainerData(View v, ItemInfo info, LauncherLogProto.Target target,
- LauncherLogProto.Target targetParent) {
- mHotseat.fillInLogContainerData(v, info, target, targetParent);
+ public void fillInLogContainerData(ItemInfo childInfo, LauncherLogProto.Target child,
+ ArrayList<LauncherLogProto.Target> parents) {
+ mHotseat.fillInLogContainerData(childInfo, child, parents);
}
private class PinPrediction extends SystemShortcut<QuickstepLauncher> {
@@ -594,6 +638,39 @@
}
}
+ private void performBetaCheck() {
+ if (isReady()) return;
+ int hotseatItemsCount = mHotseat.getShortcutsAndWidgets().getChildCount();
+
+ // -1 to exclude smart space
+ int workspaceItemCount = mLauncher.getWorkspace().getScreenWithId(
+ Workspace.FIRST_SCREEN_ID).getShortcutsAndWidgets().getChildCount() - 1;
+
+ // opt user into the feature without onboarding tip or migration if they don't have any
+ // open spots in their hotseat and have more than maxItems in their hotseat + workspace
+
+ if (hotseatItemsCount == mHotSeatItemsCount && workspaceItemCount + hotseatItemsCount
+ > MAX_ITEMS_FOR_MIGRATION) {
+ mLauncher.getSharedPrefs().edit().putBoolean(HotseatEduController.KEY_HOTSEAT_EDU_SEEN,
+ true).apply();
+
+ LauncherLogProto.Action action = newAction(LauncherLogProto.Action.Type.TOUCH);
+ LauncherLogProto.Target target = newContainerTarget(LauncherLogProto.ContainerType.TIP);
+ action.touch = LauncherLogProto.Action.Touch.TAP;
+ target.tipType = LauncherLogProto.TipType.HYBRID_HOTSEAT;
+ target.controlType = LauncherLogProto.ControlType.HYBRID_HOTSEAT_CANCELED;
+
+ // temporarily encode details in log target (go/hotseat_migration)
+ target.rank = 2;
+ target.cardinality = MAX_ITEMS_FOR_MIGRATION;
+ target.pageIndex = (workspaceItemCount * 1000) + hotseatItemsCount;
+ LauncherLogProto.LauncherEvent event = newLauncherEvent(action, target);
+ UserEventDispatcher.newInstance(mLauncher).dispatchUserEvent(event, null);
+
+
+ }
+ }
+
/**
* Fill in predicted_rank field based on app prediction.
* Only applicable when {@link ItemInfo#itemType} is PREDICTED_HOTSEAT
@@ -648,4 +725,52 @@
return new AppTarget.Builder(new AppTargetId("app:" + cn.getPackageName()),
cn.getPackageName(), info.user).setClassName(cn.getClassName()).build();
}
+
+ private AppTarget getAppTargetFromInfo(ItemInfo info) {
+ if (info == null) return null;
+ if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET
+ && info instanceof LauncherAppWidgetInfo
+ && ((LauncherAppWidgetInfo) info).providerName != null) {
+ ComponentName cn = ((LauncherAppWidgetInfo) info).providerName;
+ return new AppTarget.Builder(new AppTargetId("widget:" + cn.getPackageName()),
+ cn.getPackageName(), info.user).setClassName(cn.getClassName()).build();
+ } else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION
+ && info.getTargetComponent() != null) {
+ ComponentName cn = info.getTargetComponent();
+ return new AppTarget.Builder(new AppTargetId("app:" + cn.getPackageName()),
+ cn.getPackageName(), info.user).setClassName(cn.getClassName()).build();
+ } else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT
+ && info instanceof WorkspaceItemInfo) {
+ ShortcutKey shortcutKey = ShortcutKey.fromItemInfo(info);
+ //TODO: switch to using full shortcut info
+ return new AppTarget.Builder(new AppTargetId("shortcut:" + shortcutKey.getId()),
+ shortcutKey.componentName.getPackageName(), shortcutKey.user).build();
+ } else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_FOLDER) {
+ return new AppTarget.Builder(new AppTargetId("folder:" + info.id),
+ mLauncher.getPackageName(), info.user).build();
+ }
+ return null;
+ }
+
+ private AppTargetEvent wrapAppTargetWithLocation(AppTarget target, int action, ItemInfo info) {
+ return wrapAppTargetWithLocation(target, action,
+ info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT
+ ? APP_LOCATION_HOTSEAT : APP_LOCATION_WORKSPACE, info.screenId, info.cellX,
+ info.cellY, info.spanX, info.spanY);
+ }
+
+ private AppTargetEvent wrapAppTargetWithLocation(AppTarget target, int action, String root,
+ int screenId, int x, int y, int spanX, int spanY) {
+ return new AppTargetEvent.Builder(target, action).setLaunchLocation(
+ String.format(Locale.ENGLISH, "%s/%d/[%d,%d]/[%d,%d]", root, screenId, x, y, spanX,
+ spanY)).build();
+ }
+
+ /**
+ * A helper method to generate an AppTarget that's used to communicate workspace layout
+ */
+ private AppTarget getBlockAppTarget() {
+ return new AppTarget.Builder(new AppTargetId("block"),
+ mLauncher.getPackageName(), Process.myUserHandle()).build();
+ }
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/PredictedAppIcon.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/PredictedAppIcon.java
index b2e1798..8af26c6 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/PredictedAppIcon.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/PredictedAppIcon.java
@@ -15,6 +15,7 @@
*/
package com.android.launcher3.uioverrides;
+import static com.android.launcher3.accessibility.LauncherAccessibilityDelegate.PIN_PREDICTION;
import static com.android.launcher3.graphics.IconShape.getShape;
import android.content.Context;
@@ -26,6 +27,7 @@
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.ViewGroup;
+import android.view.accessibility.AccessibilityNodeInfo;
import androidx.core.graphics.ColorUtils;
@@ -33,9 +35,12 @@
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.Launcher;
import com.android.launcher3.R;
-import com.android.launcher3.WorkspaceItemInfo;
+import com.android.launcher3.accessibility.LauncherAccessibilityDelegate;
import com.android.launcher3.graphics.IconPalette;
+import com.android.launcher3.hybridhotseat.HotseatPredictionController;
import com.android.launcher3.icons.IconNormalizer;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.touch.ItemClickHandler;
import com.android.launcher3.touch.ItemLongClickListener;
import com.android.launcher3.views.DoubleShadowBubbleTextView;
@@ -43,7 +48,8 @@
/**
* A BubbleTextView with a ring around it's drawable
*/
-public class PredictedAppIcon extends DoubleShadowBubbleTextView {
+public class PredictedAppIcon extends DoubleShadowBubbleTextView implements
+ LauncherAccessibilityDelegate.AccessibilityActionHandler {
private static final float RING_EFFECT_RATIO = 0.11f;
@@ -86,6 +92,7 @@
mIsDrawingDot = true;
int count = canvas.save();
canvas.translate(-getWidth() * RING_EFFECT_RATIO, -getHeight() * RING_EFFECT_RATIO);
+ canvas.scale(1 + 2 * RING_EFFECT_RATIO, 1 + 2 * RING_EFFECT_RATIO);
super.drawDotIfNecessary(canvas);
canvas.restoreToCount(count);
mIsDrawingDot = false;
@@ -96,6 +103,13 @@
super.applyFromWorkspaceItem(info);
int color = IconPalette.getMutedColor(info.bitmap.color, 0.54f);
mIconRingPaint.setColor(ColorUtils.setAlphaComponent(color, 200));
+ if (mIsPinned) {
+ setContentDescription(info.contentDescription);
+ } else {
+ setContentDescription(
+ getContext().getString(R.string.hotseat_prediction_content_description,
+ info.contentDescription));
+ }
}
/**
@@ -103,9 +117,9 @@
*/
public void pin(WorkspaceItemInfo info) {
if (mIsPinned) return;
+ mIsPinned = true;
applyFromWorkspaceItem(info);
setOnLongClickListener(ItemLongClickListener.INSTANCE_WORKSPACE);
- mIsPinned = true;
((CellLayout.LayoutParams) getLayoutParams()).canReorder = true;
invalidate();
}
@@ -121,6 +135,29 @@
}
@Override
+ public void addSupportedAccessibilityActions(AccessibilityNodeInfo accessibilityNodeInfo) {
+ if (!mIsPinned) {
+ accessibilityNodeInfo.addAction(
+ new AccessibilityNodeInfo.AccessibilityAction(PIN_PREDICTION,
+ getContext().getText(R.string.pin_prediction)));
+ }
+ }
+
+ @Override
+ public boolean performAccessibilityAction(int action, ItemInfo info) {
+ QuickstepLauncher launcher = Launcher.cast(Launcher.getLauncher(getContext()));
+ if (action == PIN_PREDICTION) {
+ if (launcher == null || launcher.getHotseatPredictionController() == null) {
+ return false;
+ }
+ HotseatPredictionController controller = launcher.getHotseatPredictionController();
+ controller.pinPrediction(info);
+ return true;
+ }
+ return false;
+ }
+
+ @Override
public void getIconBounds(Rect outBounds) {
super.getIconBounds(outBounds);
if (!mIsPinned && !mIsDrawingDot) {
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/QuickstepLauncher.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/QuickstepLauncher.java
index d1a487a..87ca2b6 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/QuickstepLauncher.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/QuickstepLauncher.java
@@ -19,27 +19,23 @@
import static com.android.launcher3.LauncherState.OVERVIEW;
import static com.android.quickstep.SysUINavigationMode.Mode.NO_BUTTON;
-import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
-import android.graphics.Rect;
import android.os.Bundle;
-import android.view.Gravity;
import android.view.View;
import androidx.annotation.Nullable;
import com.android.launcher3.BaseQuickstepLauncher;
import com.android.launcher3.DeviceProfile;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherState;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.anim.AnimatorPlaybackController;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.folder.Folder;
-import com.android.launcher3.graphics.RotationMode;
import com.android.launcher3.hybridhotseat.HotseatPredictionController;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.popup.SystemShortcut;
import com.android.launcher3.uioverrides.touchcontrollers.FlingAndHoldTouchController;
import com.android.launcher3.uioverrides.touchcontrollers.LandscapeEdgeSwipeController;
@@ -71,77 +67,6 @@
*/
public static final AsyncCommand SET_SHELF_HEIGHT = (context, arg1, arg2) ->
SystemUiProxy.INSTANCE.get(context).setShelfHeight(arg1 != 0, arg2);
- public static final RotationMode ROTATION_LANDSCAPE = new RotationMode(-90) {
- @Override
- public void mapRect(int left, int top, int right, int bottom, Rect out) {
- out.left = top;
- out.top = right;
- out.right = bottom;
- out.bottom = left;
- }
-
- @Override
- public void mapInsets(Context context, Rect insets, Rect out) {
- // If there is a display cutout, the top insets in portrait would also include the
- // cutout, which we will get as the left inset in landscape. Using the max of left and
- // top allows us to cover both cases (with or without cutout).
- if (SysUINavigationMode.getMode(context) == NO_BUTTON) {
- out.top = Math.max(insets.top, insets.left);
- out.bottom = Math.max(insets.right, insets.bottom);
- out.left = out.right = 0;
- } else {
- out.top = Math.max(insets.top, insets.left);
- out.bottom = insets.right;
- out.left = insets.bottom;
- out.right = 0;
- }
- }
- };
- public static final RotationMode ROTATION_SEASCAPE = new RotationMode(90) {
- @Override
- public void mapRect(int left, int top, int right, int bottom, Rect out) {
- out.left = bottom;
- out.top = left;
- out.right = top;
- out.bottom = right;
- }
-
- @Override
- public void mapInsets(Context context, Rect insets, Rect out) {
- if (SysUINavigationMode.getMode(context) == NO_BUTTON) {
- out.top = Math.max(insets.top, insets.right);
- out.bottom = Math.max(insets.left, insets.bottom);
- out.left = out.right = 0;
- } else {
- out.top = Math.max(insets.top, insets.right);
- out.bottom = insets.left;
- out.right = insets.bottom;
- out.left = 0;
- }
- }
-
- @Override
- public int toNaturalGravity(int absoluteGravity) {
- int horizontalGravity = absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK;
- int verticalGravity = absoluteGravity & Gravity.VERTICAL_GRAVITY_MASK;
-
- if (horizontalGravity == Gravity.RIGHT) {
- horizontalGravity = Gravity.LEFT;
- } else if (horizontalGravity == Gravity.LEFT) {
- horizontalGravity = Gravity.RIGHT;
- }
-
- if (verticalGravity == Gravity.TOP) {
- verticalGravity = Gravity.BOTTOM;
- } else if (verticalGravity == Gravity.BOTTOM) {
- verticalGravity = Gravity.TOP;
- }
-
- return ((absoluteGravity & ~Gravity.HORIZONTAL_GRAVITY_MASK)
- & ~Gravity.VERTICAL_GRAVITY_MASK)
- | horizontalGravity | verticalGravity;
- }
- };
private HotseatPredictionController mHotseatPredictionController;
@Override
@@ -153,12 +78,6 @@
}
@Override
- protected RotationMode getFakeRotationMode(DeviceProfile dp) {
- return !dp.isVerticalBarLayout() ? RotationMode.NORMAL
- : (dp.isSeascape() ? ROTATION_SEASCAPE : ROTATION_LANDSCAPE);
- }
-
- @Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
onStateOrResumeChanged();
@@ -183,8 +102,8 @@
onStateOrResumeChanged();
}
- if ((changeBits & ACTIVITY_STATE_STARTED) != 0 && mHotseatPredictionController != null
- && (getActivityFlags() & ACTIVITY_STATE_USER_ACTIVE) == 0) {
+ if (mHotseatPredictionController != null && ((changeBits & ACTIVITY_STATE_STARTED) != 0
+ || (changeBits & getActivityFlags() & ACTIVITY_STATE_DEFERRED_RESUMED) != 0)) {
mHotseatPredictionController.setPauseUIUpdate(false);
}
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/RecentsViewStateController.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/RecentsViewStateController.java
index b5d8424..3d6e519 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/RecentsViewStateController.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/RecentsViewStateController.java
@@ -15,23 +15,28 @@
*/
package com.android.launcher3.uioverrides;
-import static com.android.launcher3.LauncherState.RECENTS_CLEAR_ALL_BUTTON;
+import static com.android.launcher3.LauncherAnimUtils.VIEW_ALPHA;
+import static com.android.launcher3.LauncherState.OVERVIEW_BUTTONS;
+import static com.android.launcher3.anim.Interpolators.AGGRESSIVE_EASE_IN_OUT;
import static com.android.launcher3.anim.Interpolators.LINEAR;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_FADE;
import static com.android.quickstep.views.RecentsView.CONTENT_ALPHA;
import static com.android.quickstep.views.RecentsView.FULLSCREEN_PROGRESS;
-import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.os.Build;
import android.util.FloatProperty;
+import android.view.View;
+import android.view.animation.Interpolator;
import androidx.annotation.NonNull;
-import com.android.launcher3.Launcher;
+import com.android.launcher3.BaseQuickstepLauncher;
import com.android.launcher3.LauncherState;
-import com.android.launcher3.LauncherStateManager.AnimationConfig;
-import com.android.launcher3.anim.AnimatorSetBuilder;
+import com.android.launcher3.anim.AnimationSuccessListener;
+import com.android.launcher3.anim.PendingAnimation;
import com.android.launcher3.anim.PropertySetter;
+import com.android.launcher3.states.StateAnimationConfig;
import com.android.quickstep.views.ClearAllButton;
import com.android.quickstep.views.LauncherRecentsView;
import com.android.quickstep.views.RecentsView;
@@ -44,7 +49,7 @@
public final class RecentsViewStateController extends
BaseRecentsViewStateController<LauncherRecentsView> {
- public RecentsViewStateController(Launcher launcher) {
+ public RecentsViewStateController(BaseQuickstepLauncher launcher) {
super(launcher);
}
@@ -55,40 +60,40 @@
mRecentsView.updateEmptyMessage();
mRecentsView.resetTaskVisuals();
}
- setAlphas(PropertySetter.NO_ANIM_PROPERTY_SETTER, state.getVisibleElements(mLauncher));
+ setAlphas(PropertySetter.NO_ANIM_PROPERTY_SETTER, state, LINEAR);
mRecentsView.setFullscreenProgress(state.getOverviewFullscreenProgress());
}
@Override
- void setStateWithAnimationInternal(@NonNull final LauncherState toState,
- @NonNull AnimatorSetBuilder builder, @NonNull AnimationConfig config) {
- super.setStateWithAnimationInternal(toState, builder, config);
-
- if (!toState.overviewUi) {
- builder.addOnFinishRunnable(mRecentsView::resetTaskVisuals);
- }
+ void setStateWithAnimationInternal(@NonNull LauncherState toState,
+ @NonNull StateAnimationConfig config, @NonNull PendingAnimation builder) {
+ super.setStateWithAnimationInternal(toState, config, builder);
if (toState.overviewUi) {
- ValueAnimator updateAnim = ValueAnimator.ofFloat(0, 1);
- updateAnim.addUpdateListener(valueAnimator -> {
- // While animating into recents, update the visible task data as needed
- mRecentsView.loadVisibleTaskData();
- });
- updateAnim.setDuration(config.duration);
- builder.play(updateAnim);
+ // While animating into recents, update the visible task data as needed
+ builder.addOnFrameCallback(mRecentsView::loadVisibleTaskData);
mRecentsView.updateEmptyMessage();
+ } else {
+ builder.getAnim().addListener(
+ AnimationSuccessListener.forRunnable(mRecentsView::resetTaskVisuals));
}
- PropertySetter propertySetter = config.getPropertySetter(builder);
- setAlphas(propertySetter, toState.getVisibleElements(mLauncher));
- float fullscreenProgress = toState.getOverviewFullscreenProgress();
- propertySetter.setFloat(mRecentsView, FULLSCREEN_PROGRESS, fullscreenProgress, LINEAR);
+ setAlphas(builder, toState,
+ config.getInterpolator(ANIM_OVERVIEW_FADE, AGGRESSIVE_EASE_IN_OUT));
+ builder.setFloat(mRecentsView, FULLSCREEN_PROGRESS,
+ toState.getOverviewFullscreenProgress(), LINEAR);
}
- private void setAlphas(PropertySetter propertySetter, int visibleElements) {
- boolean hasClearAllButton = (visibleElements & RECENTS_CLEAR_ALL_BUTTON) != 0;
+ private void setAlphas(PropertySetter propertySetter, LauncherState state,
+ Interpolator actionInterpolator) {
+ float buttonAlpha = (state.getVisibleElements(mLauncher) & OVERVIEW_BUTTONS) != 0 ? 1 : 0;
propertySetter.setFloat(mRecentsView.getClearAllButton(), ClearAllButton.VISIBILITY_ALPHA,
- hasClearAllButton ? 1f : 0f, LINEAR);
+ buttonAlpha, LINEAR);
+
+ View actionsView = mLauncher.getActionsView();
+ if (actionsView != null) {
+ propertySetter.setFloat(actionsView, VIEW_ALPHA, buttonAlpha, actionInterpolator);
+ }
}
@Override
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/states/BackgroundAppState.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/states/BackgroundAppState.java
index 48a2f32..a87d6d1 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/states/BackgroundAppState.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/states/BackgroundAppState.java
@@ -15,6 +15,8 @@
*/
package com.android.launcher3.uioverrides.states;
+import android.content.Context;
+
import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.Launcher;
import com.android.launcher3.allapps.AllAppsTransitionController;
@@ -88,7 +90,7 @@
@Override
public int getVisibleElements(Launcher launcher) {
return super.getVisibleElements(launcher)
- & ~RECENTS_CLEAR_ALL_BUTTON & ~VERTICAL_SWIPE_INDICATOR;
+ & ~OVERVIEW_BUTTONS & ~VERTICAL_SWIPE_INDICATOR;
}
@Override
@@ -102,4 +104,9 @@
}
return super.getHotseatScaleAndTranslation(launcher);
}
+
+ @Override
+ public float getDepth(Context context) {
+ return 1f;
+ }
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/states/OverviewPeekState.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/states/OverviewPeekState.java
index 427206a..1288e7b 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/states/OverviewPeekState.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/states/OverviewPeekState.java
@@ -14,17 +14,19 @@
* limitations under the License.
*/
package com.android.launcher3.uioverrides.states;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_FADE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_SCRIM_FADE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_TRANSLATE_X;
+
import static com.android.launcher3.anim.Interpolators.FAST_OUT_SLOW_IN;
import static com.android.launcher3.anim.Interpolators.INSTANT;
import static com.android.launcher3.anim.Interpolators.OVERSHOOT_1_7;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_FADE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_SCRIM_FADE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_TRANSLATE_X;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherState;
import com.android.launcher3.R;
-import com.android.launcher3.anim.AnimatorSetBuilder;
+import com.android.launcher3.Utilities;
+import com.android.launcher3.states.StateAnimationConfig;
public class OverviewPeekState extends OverviewState {
public OverviewPeekState(int id) {
@@ -36,16 +38,19 @@
ScaleAndTranslation result = super.getOverviewScaleAndTranslation(launcher);
result.translationX = NORMAL.getOverviewScaleAndTranslation(launcher).translationX
- launcher.getResources().getDimension(R.dimen.overview_peek_distance);
+ if (Utilities.isRtl(launcher.getResources())) {
+ result.translationX = -result.translationX;
+ }
return result;
}
@Override
public void prepareForAtomicAnimation(Launcher launcher, LauncherState fromState,
- AnimatorSetBuilder builder) {
+ StateAnimationConfig config) {
if (this == OVERVIEW_PEEK && fromState == NORMAL) {
- builder.setInterpolator(ANIM_OVERVIEW_FADE, INSTANT);
- builder.setInterpolator(ANIM_OVERVIEW_TRANSLATE_X, OVERSHOOT_1_7);
- builder.setInterpolator(ANIM_OVERVIEW_SCRIM_FADE, FAST_OUT_SLOW_IN);
+ config.setInterpolator(ANIM_OVERVIEW_FADE, INSTANT);
+ config.setInterpolator(ANIM_OVERVIEW_TRANSLATE_X, OVERSHOOT_1_7);
+ config.setInterpolator(ANIM_OVERVIEW_SCRIM_FADE, FAST_OUT_SLOW_IN);
}
}
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/states/OverviewState.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/states/OverviewState.java
index a1c8378..bcfb11c 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/states/OverviewState.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/states/OverviewState.java
@@ -18,13 +18,6 @@
import static android.view.View.VISIBLE;
import static com.android.launcher3.LauncherAnimUtils.SCALE_PROPERTY;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_FADE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_SCALE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_TRANSLATE_X;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_TRANSLATE_Y;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_WORKSPACE_FADE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_WORKSPACE_SCALE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_WORKSPACE_TRANSLATE;
import static com.android.launcher3.anim.Interpolators.ACCEL;
import static com.android.launcher3.anim.Interpolators.DEACCEL_2;
import static com.android.launcher3.anim.Interpolators.OVERSHOOT_1_2;
@@ -32,11 +25,20 @@
import static com.android.launcher3.config.FeatureFlags.ENABLE_OVERVIEW_ACTIONS;
import static com.android.launcher3.logging.LoggerUtils.newContainerTarget;
import static com.android.launcher3.states.RotationHelper.REQUEST_ROTATE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_FADE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_SCALE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_TRANSLATE_X;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_TRANSLATE_Y;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_WORKSPACE_FADE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_WORKSPACE_SCALE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_WORKSPACE_TRANSLATE;
import static com.android.quickstep.SysUINavigationMode.Mode.NO_BUTTON;
import static com.android.quickstep.SysUINavigationMode.removeShelfFromOverview;
+import android.content.Context;
import android.graphics.Rect;
import android.view.View;
+import android.view.accessibility.AccessibilityEvent;
import android.view.animation.Interpolator;
import com.android.launcher3.AbstractFloatingView;
@@ -46,7 +48,8 @@
import com.android.launcher3.R;
import com.android.launcher3.Workspace;
import com.android.launcher3.allapps.DiscoveryBounce;
-import com.android.launcher3.anim.AnimatorSetBuilder;
+import com.android.launcher3.compat.AccessibilityManagerCompat;
+import com.android.launcher3.states.StateAnimationConfig;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action;
import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
import com.android.quickstep.SysUINavigationMode;
@@ -143,6 +146,10 @@
public void onStateTransitionEnd(Launcher launcher) {
launcher.getRotationHelper().setCurrentStateRequest(REQUEST_ROTATE);
DiscoveryBounce.showForOverviewIfNeeded(launcher);
+ RecentsView recentsView = launcher.getOverviewPanel();
+ AccessibilityManagerCompat.sendCustomAccessibilityEvent(
+ recentsView.getPageAt(recentsView.getCurrentPage()),
+ AccessibilityEvent.TYPE_VIEW_FOCUSED, null);
}
@Override
@@ -157,17 +164,15 @@
@Override
public int getVisibleElements(Launcher launcher) {
- if (launcher.getDeviceProfile().isVerticalBarLayout()) {
- return VERTICAL_SWIPE_INDICATOR | RECENTS_CLEAR_ALL_BUTTON;
+ if (ENABLE_OVERVIEW_ACTIONS.get() && removeShelfFromOverview(launcher)) {
+ return OVERVIEW_BUTTONS;
+ } else if (launcher.getDeviceProfile().isVerticalBarLayout()) {
+ return VERTICAL_SWIPE_INDICATOR | OVERVIEW_BUTTONS;
} else {
- if (ENABLE_OVERVIEW_ACTIONS.get() && removeShelfFromOverview(launcher)) {
- return VERTICAL_SWIPE_INDICATOR | RECENTS_CLEAR_ALL_BUTTON;
- }
-
boolean hasAllAppsHeaderExtra = launcher.getAppsView() != null
&& launcher.getAppsView().getFloatingHeaderView().hasVisibleContent();
- return HOTSEAT_SEARCH_BOX | VERTICAL_SWIPE_INDICATOR | RECENTS_CLEAR_ALL_BUTTON |
- (hasAllAppsHeaderExtra ? ALL_APPS_HEADER_EXTRA : HOTSEAT_ICONS);
+ return HOTSEAT_SEARCH_BOX | VERTICAL_SWIPE_INDICATOR | OVERVIEW_BUTTONS
+ | (hasAllAppsHeaderExtra ? ALL_APPS_HEADER_EXTRA : HOTSEAT_ICONS);
}
}
@@ -200,6 +205,11 @@
}
@Override
+ public float getDepth(Context context) {
+ return 1f;
+ }
+
+ @Override
public void onBackPressed(Launcher launcher) {
TaskView taskView = launcher.<RecentsView>getOverviewPanel().getRunningTaskView();
if (taskView != null) {
@@ -213,14 +223,14 @@
@Override
public void prepareForAtomicAnimation(Launcher launcher, LauncherState fromState,
- AnimatorSetBuilder builder) {
+ StateAnimationConfig config) {
if ((fromState == NORMAL || fromState == HINT_STATE) && this == OVERVIEW) {
if (SysUINavigationMode.getMode(launcher) == NO_BUTTON) {
- builder.setInterpolator(ANIM_WORKSPACE_SCALE,
+ config.setInterpolator(ANIM_WORKSPACE_SCALE,
fromState == NORMAL ? ACCEL : OVERSHOOT_1_2);
- builder.setInterpolator(ANIM_WORKSPACE_TRANSLATE, ACCEL);
+ config.setInterpolator(ANIM_WORKSPACE_TRANSLATE, ACCEL);
} else {
- builder.setInterpolator(ANIM_WORKSPACE_SCALE, OVERSHOOT_1_2);
+ config.setInterpolator(ANIM_WORKSPACE_SCALE, OVERSHOOT_1_2);
// Scale up the recents, if it is not coming from the side
RecentsView overview = launcher.getOverviewPanel();
@@ -228,15 +238,15 @@
SCALE_PROPERTY.set(overview, RECENTS_PREPARE_SCALE);
}
}
- builder.setInterpolator(ANIM_WORKSPACE_FADE, OVERSHOOT_1_2);
- builder.setInterpolator(ANIM_OVERVIEW_SCALE, OVERSHOOT_1_2);
+ config.setInterpolator(ANIM_WORKSPACE_FADE, OVERSHOOT_1_2);
+ config.setInterpolator(ANIM_OVERVIEW_SCALE, OVERSHOOT_1_2);
Interpolator translationInterpolator = ENABLE_OVERVIEW_ACTIONS.get()
&& removeShelfFromOverview(launcher)
? OVERSHOOT_1_2
: OVERSHOOT_1_7;
- builder.setInterpolator(ANIM_OVERVIEW_TRANSLATE_X, translationInterpolator);
- builder.setInterpolator(ANIM_OVERVIEW_TRANSLATE_Y, translationInterpolator);
- builder.setInterpolator(ANIM_OVERVIEW_FADE, OVERSHOOT_1_2);
+ config.setInterpolator(ANIM_OVERVIEW_TRANSLATE_X, translationInterpolator);
+ config.setInterpolator(ANIM_OVERVIEW_TRANSLATE_Y, translationInterpolator);
+ config.setInterpolator(ANIM_OVERVIEW_FADE, OVERSHOOT_1_2);
}
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/FlingAndHoldTouchController.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/FlingAndHoldTouchController.java
index b80830a..8af2747 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/FlingAndHoldTouchController.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/FlingAndHoldTouchController.java
@@ -21,15 +21,16 @@
import static com.android.launcher3.LauncherState.NORMAL;
import static com.android.launcher3.LauncherState.OVERVIEW;
import static com.android.launcher3.LauncherState.OVERVIEW_PEEK;
-import static com.android.launcher3.LauncherStateManager.ATOMIC_OVERVIEW_PEEK_COMPONENT;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_ALL_APPS_FADE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_ALL_APPS_HEADER_FADE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_WORKSPACE_FADE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_WORKSPACE_SCALE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_WORKSPACE_TRANSLATE;
import static com.android.launcher3.anim.Interpolators.ACCEL;
import static com.android.launcher3.anim.Interpolators.DEACCEL;
import static com.android.launcher3.anim.Interpolators.DEACCEL_3;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_ALL_APPS_FADE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_ALL_APPS_HEADER_FADE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_WORKSPACE_FADE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_WORKSPACE_SCALE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_WORKSPACE_TRANSLATE;
+import static com.android.launcher3.states.StateAnimationConfig.PLAY_ATOMIC_OVERVIEW_PEEK;
+import static com.android.launcher3.states.StateAnimationConfig.SKIP_OVERVIEW;
import static com.android.launcher3.util.VibratorWrapper.OVERVIEW_HAPTIC;
import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_OVERVIEW_DISABLED;
@@ -44,8 +45,9 @@
import com.android.launcher3.LauncherAppTransitionManagerImpl;
import com.android.launcher3.LauncherState;
import com.android.launcher3.anim.AnimationSuccessListener;
-import com.android.launcher3.anim.AnimatorSetBuilder;
import com.android.launcher3.anim.Interpolators;
+import com.android.launcher3.states.StateAnimationConfig;
+import com.android.launcher3.states.StateAnimationConfig.AnimationFlags;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action.Touch;
import com.android.launcher3.util.VibratorWrapper;
import com.android.quickstep.SystemUiProxy;
@@ -71,7 +73,11 @@
super(l, false /* allowDragToOverview */);
mMotionPauseDetector = new MotionPauseDetector(l);
mMotionPauseMinDisplacement = ViewConfiguration.get(l).getScaledTouchSlop();
- mMotionPauseMaxDisplacement = getShiftRange() * MAX_DISPLACEMENT_PERCENT;
+ mMotionPauseMaxDisplacement = getMotionPauseMaxDisplacement();
+ }
+
+ protected float getMotionPauseMaxDisplacement() {
+ return getShiftRange() * MAX_DISPLACEMENT_PERCENT;
}
@Override
@@ -80,10 +86,10 @@
}
@Override
- public void onDragStart(boolean start) {
+ public void onDragStart(boolean start, float startDisplacement) {
mMotionPauseDetector.clear();
- super.onDragStart(start);
+ super.onDragStart(start, startDisplacement);
if (handlingOverviewAnim()) {
mMotionPauseDetector.setOnMotionPauseListener(this::onMotionPauseChanged);
@@ -103,8 +109,12 @@
LauncherState fromState = isPaused ? NORMAL : OVERVIEW_PEEK;
LauncherState toState = isPaused ? OVERVIEW_PEEK : NORMAL;
long peekDuration = isPaused ? PEEK_IN_ANIM_DURATION : PEEK_OUT_ANIM_DURATION;
- mPeekAnim = mLauncher.getStateManager().createAtomicAnimation(fromState, toState,
- new AnimatorSetBuilder(), ATOMIC_OVERVIEW_PEEK_COMPONENT, peekDuration);
+
+ StateAnimationConfig config = new StateAnimationConfig();
+ config.duration = peekDuration;
+ config.animFlags = PLAY_ATOMIC_OVERVIEW_PEEK;
+ mPeekAnim = mLauncher.getStateManager().createAtomicAnimation(
+ fromState, toState, config);
mPeekAnim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
@@ -114,8 +124,8 @@
mPeekAnim.start();
VibratorWrapper.INSTANCE.get(mLauncher).vibrate(OVERVIEW_HAPTIC);
- mLauncher.getDragLayer().getScrim().animateToSysuiMultiplier(isPaused ? 0 : 1,
- peekDuration, 0);
+ mLauncher.getDragLayer().getScrim().createSysuiMultiplierAnim(isPaused ? 0 : 1)
+ .setDuration(peekDuration).start();
}
/**
@@ -128,10 +138,10 @@
}
@Override
- protected AnimatorSetBuilder getAnimatorSetBuilderForStates(LauncherState fromState,
- LauncherState toState) {
+ protected StateAnimationConfig getConfigForStates(
+ LauncherState fromState, LauncherState toState) {
if (fromState == NORMAL && toState == ALL_APPS) {
- AnimatorSetBuilder builder = new AnimatorSetBuilder();
+ StateAnimationConfig builder = new StateAnimationConfig();
// Fade in prediction icons quickly, then rest of all apps after reaching overview.
float progressToReachOverview = NORMAL.getVerticalProgress(mLauncher)
- OVERVIEW.getVerticalProgress(mLauncher);
@@ -150,7 +160,7 @@
builder.setInterpolator(ANIM_WORKSPACE_FADE, DEACCEL_3);
return builder;
} else if (fromState == ALL_APPS && toState == NORMAL) {
- AnimatorSetBuilder builder = new AnimatorSetBuilder();
+ StateAnimationConfig builder = new StateAnimationConfig();
// Keep all apps/predictions opaque until the very end of the transition.
float progressToReachOverview = OVERVIEW.getVerticalProgress(mLauncher);
builder.setInterpolator(ANIM_ALL_APPS_FADE, Interpolators.clampToProgress(
@@ -163,7 +173,7 @@
1));
return builder;
}
- return super.getAnimatorSetBuilderForStates(fromState, toState);
+ return super.getConfigForStates(fromState, toState);
}
@Override
@@ -172,7 +182,7 @@
mMotionPauseDetector.setDisallowPause(!handlingOverviewAnim()
|| upDisplacement < mMotionPauseMinDisplacement
|| upDisplacement > mMotionPauseMaxDisplacement);
- mMotionPauseDetector.addPosition(displacement, event.getEventTime());
+ mMotionPauseDetector.addPosition(event);
return super.onDrag(displacement, event);
}
@@ -209,9 +219,11 @@
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
if (mCancelled) {
- mPeekAnim = mLauncher.getStateManager().createAtomicAnimation(mFromState,
- mToState, new AnimatorSetBuilder(), ATOMIC_OVERVIEW_PEEK_COMPONENT,
- PEEK_OUT_ANIM_DURATION);
+ StateAnimationConfig config = new StateAnimationConfig();
+ config.animFlags = PLAY_ATOMIC_OVERVIEW_PEEK;
+ config.duration = PEEK_OUT_ANIM_DURATION;
+ mPeekAnim = mLauncher.getStateManager().createAtomicAnimation(
+ mFromState, mToState, config);
mPeekAnim.start();
}
mAtomicAnim = null;
@@ -237,11 +249,14 @@
}
@Override
- protected void updateAnimatorBuilderOnReinit(AnimatorSetBuilder builder) {
+ @AnimationFlags
+ protected int updateAnimComponentsOnReinit(@AnimationFlags int animComponents) {
if (handlingOverviewAnim()) {
// We don't want the state transition to all apps to animate overview,
// as that will cause a jump after our atomic animation.
- builder.addFlag(AnimatorSetBuilder.FLAG_DONT_ANIMATE_OVERVIEW);
+ return animComponents | SKIP_OVERVIEW;
+ } else {
+ return animComponents;
}
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/NavBarToHomeTouchController.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/NavBarToHomeTouchController.java
index ad4a343..77118d5 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/NavBarToHomeTouchController.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/NavBarToHomeTouchController.java
@@ -15,8 +15,7 @@
*/
package com.android.launcher3.uioverrides.touchcontrollers;
-import static android.view.View.TRANSLATION_X;
-
+import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_X;
import static com.android.launcher3.LauncherState.ALL_APPS;
import static com.android.launcher3.LauncherState.NORMAL;
import static com.android.launcher3.LauncherState.OVERVIEW;
@@ -26,9 +25,6 @@
import static com.android.launcher3.touch.AbstractStateChangeTouchController.SUCCESS_TRANSITION_PROGRESS;
import static com.android.systemui.shared.system.ActivityManagerWrapper.CLOSE_SYSTEM_WINDOWS_REASON_RECENTS;
-import android.animation.Animator;
-import android.animation.AnimatorSet;
-import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.view.MotionEvent;
import android.view.animation.Interpolator;
@@ -36,16 +32,16 @@
import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherState;
-import com.android.launcher3.LauncherStateManager.AnimationConfig;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.allapps.AllAppsTransitionController;
import com.android.launcher3.anim.AnimationSuccessListener;
import com.android.launcher3.anim.AnimatorPlaybackController;
-import com.android.launcher3.anim.AnimatorSetBuilder;
import com.android.launcher3.anim.Interpolators;
+import com.android.launcher3.anim.PendingAnimation;
import com.android.launcher3.compat.AccessibilityManagerCompat;
import com.android.launcher3.config.FeatureFlags;
+import com.android.launcher3.states.StateAnimationConfig;
import com.android.launcher3.touch.SingleAxisSwipeDetector;
import com.android.launcher3.userevent.nano.LauncherLogProto;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action.Touch;
@@ -126,52 +122,44 @@
}
@Override
- public void onDragStart(boolean start) {
+ public void onDragStart(boolean start, float startDisplacement) {
initCurrentAnimation();
}
private void initCurrentAnimation() {
long accuracy = (long) (getShiftRange() * 2);
- final AnimatorSet anim = new AnimatorSet();
+ final PendingAnimation builder = new PendingAnimation(accuracy);
if (mStartState == OVERVIEW) {
RecentsView recentsView = mLauncher.getOverviewPanel();
float pullbackDist = mPullbackDistance;
if (!recentsView.isRtl()) {
pullbackDist = -pullbackDist;
}
- ObjectAnimator pullback = ObjectAnimator.ofFloat(recentsView, TRANSLATION_X,
- pullbackDist);
- pullback.setInterpolator(PULLBACK_INTERPOLATOR);
+
+ builder.setFloat(recentsView, VIEW_TRANSLATE_X, pullbackDist, PULLBACK_INTERPOLATOR);
if (ENABLE_QUICKSTEP_LIVE_TILE.get()) {
- pullback.addUpdateListener(
- valueAnimator -> recentsView.redrawLiveTile(false /* mightNeedToRefill */));
+ builder.addOnFrameCallback(
+ () -> recentsView.redrawLiveTile(false /* mightNeedToRefill */));
}
- anim.play(pullback);
} else if (mStartState == ALL_APPS) {
- AnimatorSetBuilder builder = new AnimatorSetBuilder();
AllAppsTransitionController allAppsController = mLauncher.getAllAppsController();
- Animator allAppsProgress = ObjectAnimator.ofFloat(allAppsController, ALL_APPS_PROGRESS,
- -mPullbackDistance / allAppsController.getShiftRange());
- allAppsProgress.setInterpolator(PULLBACK_INTERPOLATOR);
- builder.play(allAppsProgress);
+ builder.setFloat(allAppsController, ALL_APPS_PROGRESS,
+ -mPullbackDistance / allAppsController.getShiftRange(), PULLBACK_INTERPOLATOR);
+
// Slightly fade out all apps content to further distinguish from scrolling.
- builder.setInterpolator(AnimatorSetBuilder.ANIM_ALL_APPS_FADE, Interpolators
- .mapToProgress(PULLBACK_INTERPOLATOR, 0, 0.5f));
- AnimationConfig config = new AnimationConfig();
+ StateAnimationConfig config = new StateAnimationConfig();
config.duration = accuracy;
- allAppsController.setAlphas(mEndState.getVisibleElements(mLauncher), config, builder);
- anim.play(builder.build());
+ config.setInterpolator(StateAnimationConfig.ANIM_ALL_APPS_FADE, Interpolators
+ .mapToProgress(PULLBACK_INTERPOLATOR, 0, 0.5f));
+
+ allAppsController.setAlphas(mEndState, config, builder);
}
AbstractFloatingView topView = AbstractFloatingView.getTopOpenView(mLauncher);
if (topView != null) {
- Animator hintCloseAnim = topView.createHintCloseAnim(mPullbackDistance);
- if (hintCloseAnim != null) {
- hintCloseAnim.setInterpolator(PULLBACK_INTERPOLATOR);
- anim.play(hintCloseAnim);
- }
+ topView.addHintCloseAnim(mPullbackDistance, PULLBACK_INTERPOLATOR, builder);
}
- anim.setDuration(accuracy);
- mCurrentAnimation = AnimatorPlaybackController.wrap(anim, accuracy, this::clearState);
+ mCurrentAnimation = builder.createPlaybackController()
+ .setOnCancelRunnable(this::clearState);
}
private void clearState() {
@@ -219,12 +207,8 @@
// Quickly return to the state we came from (we didn't move far).
ValueAnimator anim = mCurrentAnimation.getAnimationPlayer();
anim.setFloatValues(progress, 0);
- anim.addListener(new AnimationSuccessListener() {
- @Override
- public void onAnimationSuccess(Animator animator) {
- onSwipeInteractionCompleted(mStartState);
- }
- });
+ anim.addListener(AnimationSuccessListener.forRunnable(
+ () -> onSwipeInteractionCompleted(mStartState)));
anim.setDuration(80).start();
}
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/NoButtonNavbarToOverviewTouchController.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/NoButtonNavbarToOverviewTouchController.java
index 34fc3e4..71aa2e8 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/NoButtonNavbarToOverviewTouchController.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/NoButtonNavbarToOverviewTouchController.java
@@ -19,12 +19,11 @@
import static com.android.launcher3.LauncherState.HINT_STATE;
import static com.android.launcher3.LauncherState.NORMAL;
import static com.android.launcher3.LauncherState.OVERVIEW;
-import static com.android.launcher3.LauncherStateManager.ATOMIC_OVERVIEW_PEEK_COMPONENT;
import static com.android.launcher3.Utilities.EDGE_NAV_BAR;
import static com.android.launcher3.anim.Interpolators.ACCEL_DEACCEL;
+import static com.android.launcher3.states.StateAnimationConfig.PLAY_ATOMIC_OVERVIEW_PEEK;
import static com.android.launcher3.util.VibratorWrapper.OVERVIEW_HAPTIC;
-import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.graphics.PointF;
@@ -35,7 +34,7 @@
import com.android.launcher3.LauncherStateManager;
import com.android.launcher3.Utilities;
import com.android.launcher3.anim.AnimationSuccessListener;
-import com.android.launcher3.anim.AnimatorSetBuilder;
+import com.android.launcher3.states.StateAnimationConfig;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action.Touch;
import com.android.launcher3.util.VibratorWrapper;
import com.android.quickstep.util.StaggeredWorkspaceAnim;
@@ -67,6 +66,13 @@
}
@Override
+ protected float getMotionPauseMaxDisplacement() {
+ // No need to disallow pause when swiping up all the way up the screen (unlike
+ // FlingAndHoldTouchController where user is probably intending to go to all apps).
+ return Float.MAX_VALUE;
+ }
+
+ @Override
protected boolean canInterceptTouch(MotionEvent ev) {
mDidTouchStartInNavBar = (ev.getEdgeFlags() & EDGE_NAV_BAR) != 0;
return super.canInterceptTouch(ev);
@@ -94,8 +100,8 @@
}
@Override
- public void onDragStart(boolean start) {
- super.onDragStart(start);
+ public void onDragStart(boolean start, float startDisplacement) {
+ super.onDragStart(start, startDisplacement);
mReachedOverview = false;
}
@@ -172,17 +178,13 @@
// StaggeredWorkspaceAnim doesn't animate overview, so we handle it here.
stateManager.cancelAnimation();
- AnimatorSetBuilder builder = new AnimatorSetBuilder();
- long duration = OVERVIEW.getTransitionDuration(mLauncher);
+ StateAnimationConfig config = new StateAnimationConfig();
+ config.duration = OVERVIEW.getTransitionDuration(mLauncher);
+ config.animFlags = PLAY_ATOMIC_OVERVIEW_PEEK;
AnimatorSet anim = stateManager.createAtomicAnimation(
- stateManager.getState(), NORMAL, builder,
- ATOMIC_OVERVIEW_PEEK_COMPONENT, duration);
- anim.addListener(new AnimationSuccessListener() {
- @Override
- public void onAnimationSuccess(Animator animator) {
- onSwipeInteractionCompleted(NORMAL, Touch.SWIPE);
- }
- });
+ stateManager.getState(), NORMAL, config);
+ anim.addListener(AnimationSuccessListener.forRunnable(
+ () -> onSwipeInteractionCompleted(NORMAL, Touch.SWIPE)));
anim.start();
}
} else {
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/NoButtonQuickSwitchTouchController.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/NoButtonQuickSwitchTouchController.java
index 8628db0..c92a872 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/NoButtonQuickSwitchTouchController.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/NoButtonQuickSwitchTouchController.java
@@ -21,18 +21,18 @@
import static com.android.launcher3.LauncherState.NORMAL;
import static com.android.launcher3.LauncherState.OVERVIEW;
import static com.android.launcher3.LauncherState.QUICK_SWITCH;
-import static com.android.launcher3.LauncherStateManager.ANIM_ALL;
import static com.android.launcher3.anim.AlphaUpdateListener.ALPHA_CUTOFF_THRESHOLD;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_ALL_APPS_FADE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_VERTICAL_PROGRESS;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_WORKSPACE_FADE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_WORKSPACE_TRANSLATE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.FLAG_DONT_ANIMATE_OVERVIEW;
import static com.android.launcher3.anim.Interpolators.ACCEL_0_75;
import static com.android.launcher3.anim.Interpolators.DEACCEL;
import static com.android.launcher3.anim.Interpolators.DEACCEL_5;
import static com.android.launcher3.anim.Interpolators.LINEAR;
import static com.android.launcher3.anim.Interpolators.scrollInterpolatorForVelocity;
+import static com.android.launcher3.anim.PropertySetter.NO_ANIM_PROPERTY_SETTER;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_ALL_APPS_FADE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_VERTICAL_PROGRESS;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_WORKSPACE_FADE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_WORKSPACE_TRANSLATE;
+import static com.android.launcher3.states.StateAnimationConfig.SKIP_OVERVIEW;
import static com.android.launcher3.touch.BothAxesSwipeDetector.DIRECTION_RIGHT;
import static com.android.launcher3.touch.BothAxesSwipeDetector.DIRECTION_UP;
import static com.android.launcher3.util.DefaultDisplay.getSingleFrameMs;
@@ -55,15 +55,13 @@
import com.android.launcher3.BaseQuickstepLauncher;
import com.android.launcher3.LauncherState;
-import com.android.launcher3.LauncherStateManager;
-import com.android.launcher3.LauncherStateManager.AnimationConfig;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.allapps.AllAppsTransitionController;
import com.android.launcher3.anim.AnimatorPlaybackController;
-import com.android.launcher3.anim.AnimatorSetBuilder;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.graphics.OverviewScrim;
+import com.android.launcher3.states.StateAnimationConfig;
import com.android.launcher3.touch.BaseSwipeDetector;
import com.android.launcher3.touch.BothAxesSwipeDetector;
import com.android.launcher3.userevent.nano.LauncherLogProto;
@@ -116,12 +114,13 @@
mLauncher = launcher;
mSwipeDetector = new BothAxesSwipeDetector(mLauncher, this);
mShelfPeekAnim = mLauncher.getShelfPeekAnim();
+ mRecentsView = mLauncher.getOverviewPanel();
mXRange = mLauncher.getDeviceProfile().widthPx / 2f;
- mYRange = LayoutUtils.getShelfTrackingDistance(mLauncher, mLauncher.getDeviceProfile());
+ mYRange = LayoutUtils.getShelfTrackingDistance(
+ mLauncher, mLauncher.getDeviceProfile());
mMotionPauseDetector = new MotionPauseDetector(mLauncher);
mMotionPauseMinDisplacement = mLauncher.getResources().getDimension(
R.dimen.motion_pause_detector_min_displacement_from_app);
- mRecentsView = mLauncher.getOverviewPanel();
}
@Override
@@ -191,11 +190,9 @@
ShelfAnimState shelfState = isPaused ? PEEK : HIDE;
if (shelfState == PEEK) {
// Some shelf elements (e.g. qsb) were hidden, but we need them visible when peeking.
- AnimatorSetBuilder builder = new AnimatorSetBuilder();
AllAppsTransitionController allAppsController = mLauncher.getAllAppsController();
- allAppsController.setAlphas(NORMAL.getVisibleElements(mLauncher),
- new AnimationConfig(), builder);
- builder.build().setDuration(0).start();
+ allAppsController.setAlphas(
+ NORMAL, new StateAnimationConfig(), NO_ANIM_PROPERTY_SETTER);
if ((OVERVIEW.getVisibleElements(mLauncher) & HOTSEAT_ICONS) != 0) {
// Hotseat was hidden, but we need it visible when peeking.
@@ -208,12 +205,12 @@
private void setupAnimators() {
// Animate the non-overview components (e.g. workspace, shelf) out of the way.
- AnimatorSetBuilder nonOverviewBuilder = new AnimatorSetBuilder();
+ StateAnimationConfig nonOverviewBuilder = new StateAnimationConfig();
nonOverviewBuilder.setInterpolator(ANIM_WORKSPACE_FADE, FADE_OUT_INTERPOLATOR);
nonOverviewBuilder.setInterpolator(ANIM_ALL_APPS_FADE, FADE_OUT_INTERPOLATOR);
nonOverviewBuilder.setInterpolator(ANIM_WORKSPACE_TRANSLATE, TRANSLATE_OUT_INTERPOLATOR);
nonOverviewBuilder.setInterpolator(ANIM_VERTICAL_PROGRESS, TRANSLATE_OUT_INTERPOLATOR);
- updateNonOverviewAnim(QUICK_SWITCH, nonOverviewBuilder, ANIM_ALL);
+ updateNonOverviewAnim(QUICK_SWITCH, nonOverviewBuilder);
mNonOverviewAnim.dispatchOnStart();
if (mRecentsView.getTaskViewCount() == 0) {
@@ -229,12 +226,12 @@
}
/** Create state animation to control non-overview components. */
- private void updateNonOverviewAnim(LauncherState toState, AnimatorSetBuilder builder,
- @LauncherStateManager.AnimationComponents int animComponents) {
- builder.addFlag(FLAG_DONT_ANIMATE_OVERVIEW);
- long accuracy = (long) (Math.max(mXRange, mYRange) * 2);
- mNonOverviewAnim = mLauncher.getStateManager().createAnimationToNewWorkspace(toState,
- builder, accuracy, this::clearState, animComponents);
+ private void updateNonOverviewAnim(LauncherState toState, StateAnimationConfig config) {
+ config.duration = (long) (Math.max(mXRange, mYRange) * 2);
+ config.animFlags = config.animFlags | SKIP_OVERVIEW;
+ mNonOverviewAnim = mLauncher.getStateManager()
+ .createAnimationToNewWorkspace(toState, config)
+ .setOnCancelRunnable(this::clearState);
}
private void setupOverviewAnimators() {
@@ -317,7 +314,7 @@
// home screen elements will appear in the shelf on motion pause.
mMotionPauseDetector.setDisallowPause(mIsHomeScreenVisible
|| -displacement.y < mMotionPauseMinDisplacement);
- mMotionPauseDetector.addPosition(displacement.y, ev.getEventTime());
+ mMotionPauseDetector.addPosition(ev);
if (mIsHomeScreenVisible) {
// Cancel the shelf anim so it doesn't clobber mNonOverviewAnim.
@@ -392,7 +389,7 @@
xOverviewAnim.setFloatValues(startXProgress, endXProgress);
xOverviewAnim.setDuration(xDuration)
.setInterpolator(scrollInterpolatorForVelocity(velocity.x));
- mXOverviewAnim.dispatchOnStartWithVelocity(endXProgress, velocity.x);
+ mXOverviewAnim.dispatchOnStart();
boolean flingUpToNormal = verticalFling && velocity.y < 0 && targetState == NORMAL;
@@ -413,14 +410,16 @@
ValueAnimator yOverviewAnim = mYOverviewAnim.getAnimationPlayer();
yOverviewAnim.setFloatValues(startYProgress, endYProgress);
yOverviewAnim.setDuration(yDuration);
- mYOverviewAnim.dispatchOnStartWithVelocity(endYProgress, velocity.y);
+ mYOverviewAnim.dispatchOnStart();
ValueAnimator nonOverviewAnim = mNonOverviewAnim.getAnimationPlayer();
if (flingUpToNormal && !mIsHomeScreenVisible) {
// We are flinging to home while workspace is invisible, run the same staggered
// animation as from an app.
+ StateAnimationConfig config = new StateAnimationConfig();
// Update mNonOverviewAnim to do nothing so it doesn't interfere.
- updateNonOverviewAnim(targetState, new AnimatorSetBuilder(), 0 /* animComponents */);
+ config.animFlags = 0;
+ updateNonOverviewAnim(targetState, config);
nonOverviewAnim = mNonOverviewAnim.getAnimationPlayer();
new StaggeredWorkspaceAnim(mLauncher, velocity.y, false /* animateOverviewScrim */)
@@ -435,8 +434,7 @@
float startProgress = mNonOverviewAnim.getProgressFraction();
float endProgress = canceled ? 0 : 1;
nonOverviewAnim.setFloatValues(startProgress, endProgress);
- mNonOverviewAnim.dispatchOnStartWithVelocity(endProgress,
- horizontalFling ? velocity.x : velocity.y);
+ mNonOverviewAnim.dispatchOnStart();
}
nonOverviewAnim.setDuration(Math.max(xDuration, yDuration));
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/PortraitOverviewStateTouchHelper.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/PortraitOverviewStateTouchHelper.java
index 03862db..845699a 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/PortraitOverviewStateTouchHelper.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/PortraitOverviewStateTouchHelper.java
@@ -19,9 +19,10 @@
import static com.android.launcher3.uioverrides.touchcontrollers.PortraitStatesTouchController.isTouchOverHotseat;
import android.view.MotionEvent;
+import android.view.animation.Interpolator;
import com.android.launcher3.Launcher;
-import com.android.launcher3.util.PendingAnimation;
+import com.android.launcher3.anim.PendingAnimation;
import com.android.quickstep.views.RecentsView;
import com.android.quickstep.views.TaskView;
@@ -74,12 +75,12 @@
* @param duration how long the animation should be
* @return the animation
*/
- PendingAnimation createSwipeDownToTaskAppAnimation(long duration) {
+ PendingAnimation createSwipeDownToTaskAppAnimation(long duration, Interpolator interpolator) {
mRecentsView.setCurrentPage(mRecentsView.getPageNearestToCenterOfScreen());
TaskView taskView = mRecentsView.getCurrentPageTaskView();
if (taskView == null) {
throw new IllegalStateException("There is no task view to animate to.");
}
- return mRecentsView.createTaskLauncherAnimation(taskView, duration);
+ return mRecentsView.createTaskLaunchAnimation(taskView, duration, interpolator);
}
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/QuickSwitchTouchController.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/QuickSwitchTouchController.java
index 912be98..9e53959 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/QuickSwitchTouchController.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/QuickSwitchTouchController.java
@@ -17,17 +17,17 @@
import static com.android.launcher3.LauncherState.NORMAL;
import static com.android.launcher3.LauncherState.QUICK_SWITCH;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_ALL_APPS_FADE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_FADE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_SCALE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_TRANSLATE_Y;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_VERTICAL_PROGRESS;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_WORKSPACE_FADE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_WORKSPACE_TRANSLATE;
import static com.android.launcher3.anim.Interpolators.ACCEL_2;
import static com.android.launcher3.anim.Interpolators.DEACCEL_2;
import static com.android.launcher3.anim.Interpolators.INSTANT;
import static com.android.launcher3.anim.Interpolators.LINEAR;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_ALL_APPS_FADE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_FADE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_SCALE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_TRANSLATE_Y;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_VERTICAL_PROGRESS;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_WORKSPACE_FADE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_WORKSPACE_TRANSLATE;
import static com.android.launcher3.util.SystemUiController.UI_STATE_OVERVIEW;
import static com.android.quickstep.views.RecentsView.UPDATE_SYSUI_FLAGS_THRESHOLD;
import static com.android.systemui.shared.system.ActivityManagerWrapper.CLOSE_SYSTEM_WINDOWS_REASON_RECENTS;
@@ -39,9 +39,8 @@
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherState;
-import com.android.launcher3.LauncherStateManager;
import com.android.launcher3.Utilities;
-import com.android.launcher3.anim.AnimatorSetBuilder;
+import com.android.launcher3.states.StateAnimationConfig;
import com.android.launcher3.touch.AbstractStateChangeTouchController;
import com.android.launcher3.touch.SingleAxisSwipeDetector;
import com.android.launcher3.userevent.nano.LauncherLogProto;
@@ -92,8 +91,8 @@
}
@Override
- public void onDragStart(boolean start) {
- super.onDragStart(start);
+ public void onDragStart(boolean start, float startDisplacement) {
+ super.onDragStart(start, startDisplacement);
mStartContainerType = LauncherLogProto.ContainerType.NAVBAR;
mTaskToLaunch = mLauncher.<RecentsView>getOverviewPanel().getTaskViewAt(0);
ActivityManagerWrapper.getInstance()
@@ -108,30 +107,30 @@
@Override
protected float initCurrentAnimation(int animComponents) {
- AnimatorSetBuilder animatorSetBuilder = new AnimatorSetBuilder();
- setupInterpolators(animatorSetBuilder);
- long accuracy = (long) (getShiftRange() * 2);
- mCurrentAnimation = mLauncher.getStateManager().createAnimationToNewWorkspace(mToState,
- animatorSetBuilder, accuracy, this::clearState, LauncherStateManager.ANIM_ALL);
- mCurrentAnimation.getAnimationPlayer().addUpdateListener(valueAnimator -> {
- updateFullscreenProgress((Float) valueAnimator.getAnimatedValue());
- });
+ StateAnimationConfig config = new StateAnimationConfig();
+ setupInterpolators(config);
+ config.duration = (long) (getShiftRange() * 2);
+ mCurrentAnimation = mLauncher.getStateManager()
+ .createAnimationToNewWorkspace(mToState, config)
+ .setOnCancelRunnable(this::clearState);
+ mCurrentAnimation.getAnimationPlayer().addUpdateListener(valueAnimator ->
+ updateFullscreenProgress((Float) valueAnimator.getAnimatedValue()));
return 1 / getShiftRange();
}
- private void setupInterpolators(AnimatorSetBuilder animatorSetBuilder) {
- animatorSetBuilder.setInterpolator(ANIM_WORKSPACE_FADE, DEACCEL_2);
- animatorSetBuilder.setInterpolator(ANIM_ALL_APPS_FADE, DEACCEL_2);
+ private void setupInterpolators(StateAnimationConfig stateAnimationConfig) {
+ stateAnimationConfig.setInterpolator(ANIM_WORKSPACE_FADE, DEACCEL_2);
+ stateAnimationConfig.setInterpolator(ANIM_ALL_APPS_FADE, DEACCEL_2);
if (SysUINavigationMode.getMode(mLauncher) == Mode.NO_BUTTON) {
// Overview lives to the left of workspace, so translate down later than over
- animatorSetBuilder.setInterpolator(ANIM_WORKSPACE_TRANSLATE, ACCEL_2);
- animatorSetBuilder.setInterpolator(ANIM_VERTICAL_PROGRESS, ACCEL_2);
- animatorSetBuilder.setInterpolator(ANIM_OVERVIEW_SCALE, ACCEL_2);
- animatorSetBuilder.setInterpolator(ANIM_OVERVIEW_TRANSLATE_Y, ACCEL_2);
- animatorSetBuilder.setInterpolator(ANIM_OVERVIEW_FADE, INSTANT);
+ stateAnimationConfig.setInterpolator(ANIM_WORKSPACE_TRANSLATE, ACCEL_2);
+ stateAnimationConfig.setInterpolator(ANIM_VERTICAL_PROGRESS, ACCEL_2);
+ stateAnimationConfig.setInterpolator(ANIM_OVERVIEW_SCALE, ACCEL_2);
+ stateAnimationConfig.setInterpolator(ANIM_OVERVIEW_TRANSLATE_Y, ACCEL_2);
+ stateAnimationConfig.setInterpolator(ANIM_OVERVIEW_FADE, INSTANT);
} else {
- animatorSetBuilder.setInterpolator(ANIM_WORKSPACE_TRANSLATE, LINEAR);
- animatorSetBuilder.setInterpolator(ANIM_VERTICAL_PROGRESS, LINEAR);
+ stateAnimationConfig.setInterpolator(ANIM_WORKSPACE_TRANSLATE, LINEAR);
+ stateAnimationConfig.setInterpolator(ANIM_VERTICAL_PROGRESS, LINEAR);
}
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewTouchController.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewTouchController.java
index 32855d7..1b3610a 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewTouchController.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewTouchController.java
@@ -16,17 +16,13 @@
package com.android.launcher3.uioverrides.touchcontrollers;
import static com.android.launcher3.AbstractFloatingView.TYPE_ACCESSIBLE;
-import static com.android.launcher3.anim.Interpolators.scrollInterpolatorForVelocity;
import static com.android.launcher3.config.FeatureFlags.ENABLE_QUICKSTEP_LIVE_TILE;
-import static com.android.launcher3.config.FeatureFlags.UNSTABLE_SPRINGS;
import static com.android.launcher3.touch.SingleAxisSwipeDetector.DIRECTION_BOTH;
import static com.android.launcher3.touch.SingleAxisSwipeDetector.DIRECTION_NEGATIVE;
import static com.android.launcher3.touch.SingleAxisSwipeDetector.DIRECTION_POSITIVE;
-import static com.android.launcher3.util.DefaultDisplay.getSingleFrameMs;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
-import android.animation.ValueAnimator;
import android.view.MotionEvent;
import com.android.launcher3.AbstractFloatingView;
@@ -35,11 +31,12 @@
import com.android.launcher3.Utilities;
import com.android.launcher3.anim.AnimatorPlaybackController;
import com.android.launcher3.anim.Interpolators;
+import com.android.launcher3.anim.PendingAnimation;
import com.android.launcher3.touch.BaseSwipeDetector;
+import com.android.launcher3.touch.PagedOrientationHandler;
import com.android.launcher3.touch.SingleAxisSwipeDetector;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action.Touch;
import com.android.launcher3.util.FlingBlockCheck;
-import com.android.launcher3.util.PendingAnimation;
import com.android.launcher3.util.TouchController;
import com.android.launcher3.views.BaseDragLayer;
import com.android.quickstep.SysUINavigationMode;
@@ -77,11 +74,16 @@
public TaskViewTouchController(T activity) {
mActivity = activity;
mRecentsView = activity.getOverviewPanel();
- mDetector = new SingleAxisSwipeDetector(activity, this, SingleAxisSwipeDetector.VERTICAL);
+ SingleAxisSwipeDetector.Direction dir =
+ mRecentsView.getPagedOrientationHandler().getOppositeSwipeDirection();
+ mDetector = new SingleAxisSwipeDetector(activity, this, dir);
}
private boolean canInterceptTouch() {
if (mCurrentAnimation != null) {
+ mCurrentAnimation.forceFinishIfCloseToEnd();
+ }
+ if (mCurrentAnimation != null) {
// If we are already animating from a previous state, we can intercept.
return true;
}
@@ -105,6 +107,10 @@
@Override
public boolean onControllerInterceptTouchEvent(MotionEvent ev) {
+ if ((ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL)
+ && mCurrentAnimation == null) {
+ clearState();
+ }
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
mNoIntercept = !canInterceptTouch();
if (mNoIntercept) {
@@ -123,8 +129,14 @@
for (int i = 0; i < mRecentsView.getTaskViewCount(); i++) {
TaskView view = mRecentsView.getTaskViewAt(i);
+
if (mRecentsView.isTaskViewVisible(view) && mActivity.getDragLayer()
.isEventOverView(view, ev)) {
+ // Disable swiping up and down if the task overlay is modal.
+ if (view.isTaskOverlayModal()) {
+ mTaskBeingDragged = null;
+ break;
+ }
mTaskBeingDragged = view;
if (!SysUINavigationMode.getMode(mActivity).hasGestures) {
// Don't allow swipe down to open if we don't support swipe up
@@ -181,30 +193,33 @@
mPendingAnimation = null;
}
+ PagedOrientationHandler orientationHandler = mRecentsView.getPagedOrientationHandler();
mCurrentAnimationIsGoingUp = goingUp;
BaseDragLayer dl = mActivity.getDragLayer();
- long maxDuration = (long) (2 * dl.getHeight());
-
+ final int secondaryLayerDimension = orientationHandler.getSecondaryDimension(dl);
+ long maxDuration = (long) (2 * secondaryLayerDimension);
+ int verticalFactor = -orientationHandler.getTaskDismissDirectionFactor();
+ int secondaryTaskDimension = orientationHandler.getSecondaryDimension(mTaskBeingDragged);
if (goingUp) {
mPendingAnimation = mRecentsView.createTaskDismissAnimation(mTaskBeingDragged,
true /* animateTaskView */, true /* removeTask */, maxDuration);
- mEndDisplacement = -mTaskBeingDragged.getHeight();
+ mEndDisplacement = -secondaryTaskDimension;
} else {
- mPendingAnimation = mRecentsView.createTaskLauncherAnimation(
- mTaskBeingDragged, maxDuration);
- mPendingAnimation.anim.setInterpolator(Interpolators.ZOOM_IN);
+ mPendingAnimation = mRecentsView.createTaskLaunchAnimation(
+ mTaskBeingDragged, maxDuration, Interpolators.ZOOM_IN);
mTempCords[1] = mTaskBeingDragged.getHeight();
dl.getDescendantCoordRelativeToSelf(mTaskBeingDragged, mTempCords);
mEndDisplacement = dl.getHeight() - mTempCords[1];
}
+ mEndDisplacement *= verticalFactor;
if (mCurrentAnimation != null) {
mCurrentAnimation.setOnCancelRunnable(null);
}
- mCurrentAnimation = AnimatorPlaybackController
- .wrap(mPendingAnimation.anim, maxDuration, this::clearState);
+ mCurrentAnimation = mPendingAnimation.createPlaybackController()
+ .setOnCancelRunnable(this::clearState);
onUserControlledAnimationCreated(mCurrentAnimation);
mCurrentAnimation.getTarget().addListener(this);
mCurrentAnimation.dispatchOnStart();
@@ -212,9 +227,10 @@
}
@Override
- public void onDragStart(boolean start) {
+ public void onDragStart(boolean start, float startDisplacement) {
+ PagedOrientationHandler orientationHandler = mRecentsView.getPagedOrientationHandler();
if (mCurrentAnimation == null) {
- reInitAnimationController(mDetector.wasInitialTouchPositive());
+ reInitAnimationController(orientationHandler.isGoingUp(startDisplacement));
mDisplacementShift = 0;
} else {
mDisplacementShift = mCurrentAnimation.getProgressFraction() / mProgressMultiplier;
@@ -225,9 +241,10 @@
@Override
public boolean onDrag(float displacement) {
+ PagedOrientationHandler orientationHandler = mRecentsView.getPagedOrientationHandler();
float totalDisplacement = displacement + mDisplacementShift;
- boolean isGoingUp =
- totalDisplacement == 0 ? mCurrentAnimationIsGoingUp : totalDisplacement < 0;
+ boolean isGoingUp = totalDisplacement == 0 ? mCurrentAnimationIsGoingUp :
+ orientationHandler.isGoingUp(totalDisplacement);
if (isGoingUp != mCurrentAnimationIsGoingUp) {
reInitAnimationController(isGoingUp);
mFlingBlockCheck.blockFling();
@@ -254,11 +271,12 @@
if (blockedFling) {
fling = false;
}
+ PagedOrientationHandler orientationHandler = mRecentsView.getPagedOrientationHandler();
float progress = mCurrentAnimation.getProgressFraction();
float interpolatedProgress = mCurrentAnimation.getInterpolatedProgress();
if (fling) {
logAction = Touch.FLING;
- boolean goingUp = velocity < 0;
+ boolean goingUp = orientationHandler.isGoingUp(velocity);
goingToEnd = goingUp == mCurrentAnimationIsGoingUp;
} else {
logAction = Touch.SWIPE;
@@ -270,26 +288,16 @@
animationDuration *= LauncherAnimUtils.blockedFlingDurationFactor(velocity);
}
- float nextFrameProgress = Utilities.boundToRange(progress
- + velocity * getSingleFrameMs(mActivity) / Math.abs(mEndDisplacement), 0f, 1f);
-
mCurrentAnimation.setEndAction(() -> onCurrentAnimationEnd(goingToEnd, logAction));
-
- ValueAnimator anim = mCurrentAnimation.getAnimationPlayer();
- anim.setFloatValues(nextFrameProgress, goingToEnd ? 1f : 0f);
- anim.setDuration(animationDuration);
- anim.setInterpolator(scrollInterpolatorForVelocity(velocity));
if (ENABLE_QUICKSTEP_LIVE_TILE.get()) {
- anim.addUpdateListener(valueAnimator -> {
+ mCurrentAnimation.getAnimationPlayer().addUpdateListener(valueAnimator -> {
if (mRecentsView.getCurrentPage() != 0 || mCurrentAnimationIsGoingUp) {
mRecentsView.redrawLiveTile(true);
}
});
}
- if (UNSTABLE_SPRINGS.get()) {
- mCurrentAnimation.dispatchOnStartWithVelocity(goingToEnd ? 1f : 0f, velocity);
- }
- anim.start();
+ mCurrentAnimation.startWithVelocity(mActivity, goingToEnd,
+ velocity, mEndDisplacement, animationDuration);
}
private void onCurrentAnimationEnd(boolean wasSuccess, int logAction) {
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/AppToOverviewAnimationProvider.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/AppToOverviewAnimationProvider.java
index 59b117f..9dce984 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/AppToOverviewAnimationProvider.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/AppToOverviewAnimationProvider.java
@@ -15,13 +15,17 @@
*/
package com.android.quickstep;
+import static com.android.launcher3.LauncherState.BACKGROUND_APP;
+import static com.android.launcher3.LauncherState.OVERVIEW;
import static com.android.launcher3.anim.Interpolators.FAST_OUT_SLOW_IN;
import static com.android.launcher3.anim.Interpolators.TOUCH_RESPONSE_INTERPOLATOR;
+import static com.android.launcher3.statehandlers.DepthController.DEPTH;
import static com.android.systemui.shared.system.RemoteAnimationTargetCompat.MODE_CLOSING;
import static com.android.systemui.shared.system.RemoteAnimationTargetCompat.MODE_OPENING;
import android.animation.Animator;
import android.animation.AnimatorSet;
+import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.graphics.Rect;
import android.util.Log;
@@ -30,7 +34,9 @@
import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.BaseDraggingActivity;
import com.android.launcher3.anim.AnimationSuccessListener;
+import com.android.launcher3.statehandlers.DepthController;
import com.android.quickstep.util.AppWindowAnimationHelper;
+import com.android.quickstep.util.AppWindowAnimationHelper.TransformParams;
import com.android.quickstep.util.RemoteAnimationProvider;
import com.android.quickstep.views.RecentsView;
import com.android.systemui.shared.system.RemoteAnimationTargetCompat;
@@ -38,25 +44,25 @@
import com.android.systemui.shared.system.TransactionCompat;
/**
- * Provider for the atomic remote window animation from the app to the overview.
+ * Provider for the atomic (for 3-button mode) remote window animation from the app to the overview.
*
* @param <T> activity that contains the overview
*/
-final class AppToOverviewAnimationProvider<T extends BaseDraggingActivity> implements
+final class AppToOverviewAnimationProvider<T extends BaseDraggingActivity> extends
RemoteAnimationProvider {
private static final long RECENTS_LAUNCH_DURATION = 250;
private static final String TAG = "AppToOverviewAnimationProvider";
- private final BaseActivityInterface<T> mHelper;
+ private final BaseActivityInterface<T> mActivityInterface;
// The id of the currently running task that is transitioning to overview.
private final int mTargetTaskId;
private T mActivity;
private RecentsView mRecentsView;
- AppToOverviewAnimationProvider(BaseActivityInterface<T> helper, int targetTaskId) {
- mHelper = helper;
+ AppToOverviewAnimationProvider(BaseActivityInterface<T> activityInterface, int targetTaskId) {
+ mActivityInterface = activityInterface;
mTargetTaskId = targetTaskId;
}
@@ -70,7 +76,7 @@
activity.<RecentsView>getOverviewPanel().showCurrentTask(mTargetTaskId);
AbstractFloatingView.closeAllOpenViews(activity, wasVisible);
BaseActivityInterface.AnimationFactory factory =
- mHelper.prepareRecentsUI(wasVisible,
+ mActivityInterface.prepareRecentsUI(wasVisible,
false /* animate activity */, (controller) -> {
controller.dispatchOnStart();
ValueAnimator anim = controller.getAnimationPlayer()
@@ -98,11 +104,12 @@
if (mRecentsView != null) {
mRecentsView.setRunningTaskIconScaledDown(true);
}
+
AnimatorSet anim = new AnimatorSet();
anim.addListener(new AnimationSuccessListener() {
@Override
public void onAnimationSuccess(Animator animator) {
- mHelper.onSwipeUpToRecentsComplete();
+ mActivityInterface.onSwipeUpToRecentsComplete();
if (mRecentsView != null) {
mRecentsView.animateUpRunningTaskIconScale();
}
@@ -110,10 +117,17 @@
});
if (mActivity == null) {
Log.e(TAG, "Animation created, before activity");
- anim.play(ValueAnimator.ofInt(0, 1).setDuration(RECENTS_LAUNCH_DURATION));
return anim;
}
+ DepthController depthController = mActivityInterface.getDepthController();
+ if (depthController != null) {
+ anim.play(ObjectAnimator.ofFloat(depthController, DEPTH,
+ BACKGROUND_APP.getDepth(mActivity),
+ OVERVIEW.getDepth(mActivity))
+ .setDuration(RECENTS_LAUNCH_DURATION));
+ }
+
RemoteAnimationTargets targets = new RemoteAnimationTargets(appTargets,
wallpaperTargets, MODE_CLOSING);
@@ -121,11 +135,11 @@
RemoteAnimationTargetCompat runningTaskTarget = targets.findTask(mTargetTaskId);
if (runningTaskTarget == null) {
Log.e(TAG, "No closing app");
- anim.play(ValueAnimator.ofInt(0, 1).setDuration(RECENTS_LAUNCH_DURATION));
return anim;
}
- final AppWindowAnimationHelper clipHelper = new AppWindowAnimationHelper(mActivity);
+ final AppWindowAnimationHelper clipHelper = new AppWindowAnimationHelper(
+ mRecentsView.getPagedViewOrientedState(), mActivity);
// At this point, the activity is already started and laid-out. Get the home-bounds
// relative to the screen using the rootView of the activity.
@@ -137,11 +151,12 @@
clipHelper.updateSource(homeBounds, runningTaskTarget);
Rect targetRect = new Rect();
- mHelper.getSwipeUpDestinationAndLength(mActivity.getDeviceProfile(), mActivity, targetRect);
+ mActivityInterface.getSwipeUpDestinationAndLength(mActivity.getDeviceProfile(), mActivity,
+ targetRect);
clipHelper.updateTargetRect(targetRect);
clipHelper.prepareAnimation(mActivity.getDeviceProfile(), false /* isOpening */);
- AppWindowAnimationHelper.TransformParams params = new AppWindowAnimationHelper.TransformParams()
+ TransformParams params = new TransformParams()
.setSyncTransactionApplier(new SyncRtSurfaceTransactionApplierCompat(rootView));
ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1);
valueAnimator.setDuration(RECENTS_LAUNCH_DURATION);
@@ -166,7 +181,6 @@
transaction.apply();
});
}
- anim.play(valueAnimator);
return anim;
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/BaseSwipeUpHandler.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/BaseSwipeUpHandler.java
index 7ff8969..70b139d 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/BaseSwipeUpHandler.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/BaseSwipeUpHandler.java
@@ -17,7 +17,6 @@
import static com.android.launcher3.anim.Interpolators.ACCEL_1_5;
import static com.android.launcher3.anim.Interpolators.DEACCEL;
-import static com.android.launcher3.config.FeatureFlags.ENABLE_OVERVIEW_ACTIONS;
import static com.android.launcher3.config.FeatureFlags.ENABLE_QUICKSTEP_LIVE_TILE;
import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
import static com.android.launcher3.util.VibratorWrapper.OVERVIEW_HAPTIC;
@@ -32,6 +31,8 @@
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Build;
+import android.util.Log;
+import android.util.Pair;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Interpolator;
@@ -45,7 +46,8 @@
import com.android.launcher3.Utilities;
import com.android.launcher3.anim.AnimationSuccessListener;
import com.android.launcher3.anim.AnimatorPlaybackController;
-import com.android.launcher3.graphics.RotationMode;
+import com.android.launcher3.testing.TestProtocol;
+import com.android.launcher3.touch.PagedOrientationHandler;
import com.android.launcher3.util.VibratorWrapper;
import com.android.launcher3.views.FloatingIconView;
import com.android.quickstep.BaseActivityInterface.HomeAnimationFactory;
@@ -54,6 +56,7 @@
import com.android.quickstep.util.ActivityInitListener;
import com.android.quickstep.util.AppWindowAnimationHelper;
import com.android.quickstep.util.AppWindowAnimationHelper.TransformParams;
+import com.android.quickstep.util.RecentsOrientedState;
import com.android.quickstep.util.RectFSpringAnim;
import com.android.quickstep.views.RecentsView;
import com.android.quickstep.views.TaskView;
@@ -75,18 +78,17 @@
private static final String TAG = "BaseSwipeUpHandler";
protected static final Rect TEMP_RECT = new Rect();
- // Start resisting when swiping past this factor of mTransitionDragLength.
- private static final float DRAG_LENGTH_FACTOR_START_PULLBACK = ENABLE_OVERVIEW_ACTIONS.get()
- ? 2.8f : 1.4f;
- // This is how far down we can scale down, where 0f is full screen and 1f is recents.
- private static final float DRAG_LENGTH_FACTOR_MAX_PULLBACK = ENABLE_OVERVIEW_ACTIONS.get()
- ? 3.6f : 1.8f;
+ public static final float MIN_PROGRESS_FOR_OVERVIEW = 0.7f;
private static final Interpolator PULLBACK_INTERPOLATOR = DEACCEL;
// The distance needed to drag to reach the task size in recents.
protected int mTransitionDragLength;
// How much further we can drag past recents, as a factor of mTransitionDragLength.
protected float mDragLengthFactor = 1;
+ // Start resisting when swiping past this factor of mTransitionDragLength.
+ private float mDragLengthFactorStartPullback = 1f;
+ // This is how far down we can scale down, where 0f is full screen and 1f is recents.
+ private float mDragLengthFactorMaxPullback = 1f;
protected final Context mContext;
protected final RecentsAnimationDeviceState mDeviceState;
@@ -94,7 +96,7 @@
protected final BaseActivityInterface<T> mActivityInterface;
protected final InputConsumerController mInputConsumer;
- protected final AppWindowAnimationHelper mAppWindowAnimationHelper;
+ protected AppWindowAnimationHelper mAppWindowAnimationHelper;
protected final TransformParams mTransformParams = new TransformParams();
// Shift in the range of [0, 1].
@@ -123,6 +125,8 @@
protected boolean mCanceled;
protected int mFinishingRecentsAnimationForNewTaskId = -1;
+ private RecentsOrientedState mOrientedState;
+
protected BaseSwipeUpHandler(Context context, RecentsAnimationDeviceState deviceState,
GestureState gestureState, InputConsumerController inputConsumer) {
mContext = context;
@@ -132,20 +136,18 @@
mActivityInitListener =
mActivityInterface.createActivityInitListener(this::onActivityInit);
mInputConsumer = inputConsumer;
-
mAppWindowAnimationHelper = new AppWindowAnimationHelper(context);
mPageSpacing = context.getResources().getDimensionPixelSize(R.dimen.recents_page_spacing);
-
initTransitionEndpoints(InvariantDeviceProfile.INSTANCE.get(mContext)
- .getDeviceProfile(mContext));
+ .getDeviceProfile(mContext));
}
protected void performHapticFeedback() {
VibratorWrapper.INSTANCE.get(mContext).vibrate(OVERVIEW_HAPTIC);
}
- public Consumer<MotionEvent> getRecentsViewDispatcher(RotationMode rotationMode) {
- return mRecentsView != null ? mRecentsView.getEventDispatcher(rotationMode) : null;
+ public Consumer<MotionEvent> getRecentsViewDispatcher(float navbarRotation) {
+ return mRecentsView != null ? mRecentsView.getEventDispatcher(navbarRotation) : null;
}
@UiThread
@@ -158,12 +160,12 @@
} else {
float translation = Math.max(displacement, 0);
shift = mTransitionDragLength == 0 ? 0 : translation / mTransitionDragLength;
- if (shift > DRAG_LENGTH_FACTOR_START_PULLBACK) {
+ if (shift > mDragLengthFactorStartPullback) {
float pullbackProgress = Utilities.getProgress(shift,
- DRAG_LENGTH_FACTOR_START_PULLBACK, mDragLengthFactor);
+ mDragLengthFactorStartPullback, mDragLengthFactor);
pullbackProgress = PULLBACK_INTERPOLATOR.getInterpolation(pullbackProgress);
- shift = DRAG_LENGTH_FACTOR_START_PULLBACK + pullbackProgress
- * (DRAG_LENGTH_FACTOR_MAX_PULLBACK - DRAG_LENGTH_FACTOR_START_PULLBACK);
+ shift = mDragLengthFactorStartPullback + pullbackProgress
+ * (mDragLengthFactorMaxPullback - mDragLengthFactorStartPullback);
}
}
@@ -326,10 +328,27 @@
// we otherwise use the minimized home bounds provided by the system.
mAppWindowAnimationHelper.updateHomeBounds(getStackBounds(dp));
}
+ int displayRotation = 0;
+ if (mOrientedState != null) {
+ // TODO(b/150300347): The first recents animation after launcher is started with the
+ // foreground app not in landscape will look funky until that bug is fixed
+ displayRotation = mOrientedState.getDisplayRotation();
+
+ RectF tempRectF = new RectF(TEMP_RECT);
+ mOrientedState.mapRectFromNormalOrientation(tempRectF, dp.widthPx, dp.heightPx);
+ tempRectF.roundOut(TEMP_RECT);
+ }
mAppWindowAnimationHelper.updateTargetRect(TEMP_RECT);
if (mDeviceState.isFullyGesturalNavMode()) {
// We can drag all the way to the top of the screen.
- mDragLengthFactor = (float) dp.heightPx / mTransitionDragLength;
+ // TODO(b/149609070): Landscape apps are currently limited in
+ // their ability to scale past the target rect.
+ float dragFactor = (float) dp.heightPx / mTransitionDragLength;
+ mDragLengthFactor = displayRotation == 0 ? dragFactor : Math.min(1.0f, dragFactor);
+ Pair<Float, Float> dragFactorStartAndMaxProgress =
+ mActivityInterface.getSwipeUpPullbackStartAndMaxProgress();
+ mDragLengthFactorStartPullback = dragFactorStartAndMaxProgress.first;
+ mDragLengthFactorMaxPullback = dragFactorStartAndMaxProgress.second;
}
}
@@ -338,7 +357,17 @@
*/
protected abstract boolean moveWindowWithRecentsScroll();
- protected abstract boolean onActivityInit(Boolean alreadyOnHome);
+ protected boolean onActivityInit(Boolean alreadyOnHome) {
+ T createdActivity = mActivityInterface.getCreatedActivity();
+ if (createdActivity != null) {
+ mOrientedState = ((RecentsView) createdActivity.getOverviewPanel())
+ .getPagedViewOrientedState();
+ mAppWindowAnimationHelper = new AppWindowAnimationHelper(mOrientedState, mContext);
+ initTransitionEndpoints(InvariantDeviceProfile.INSTANCE.get(mContext)
+ .getDeviceProfile(mContext));
+ }
+ return true;
+ }
/**
* Called to create a input proxy for the running task
@@ -382,23 +411,32 @@
*/
protected void applyTransformUnchecked() {
float shift = mCurrentShift.value;
- float offsetX = mRecentsView == null ? 0 : mRecentsView.getScrollOffset();
- float offsetScale = getTaskCurveScaleForOffsetX(offsetX,
- mAppWindowAnimationHelper.getTargetRect().width());
+ float offset = mRecentsView == null ? 0 : mRecentsView.getScrollOffset();
+ float taskSize = getOrientationHandler()
+ .getPrimarySize(mAppWindowAnimationHelper.getTargetRect());
+ float offsetScale = getTaskCurveScaleForOffset(offset, taskSize);
mTransformParams.setProgress(shift)
- .setOffsetX(offsetX)
+ .setOffset(offset)
.setOffsetScale(offsetScale)
.setTargetSet(mRecentsAnimationTargets)
.setLauncherOnTop(true);
mAppWindowAnimationHelper.applyTransform(mTransformParams);
}
- private float getTaskCurveScaleForOffsetX(float offsetX, float taskWidth) {
- float distanceToReachEdge = mDp.widthPx / 2 + taskWidth / 2 + mPageSpacing;
- float interpolation = Math.min(1, offsetX / distanceToReachEdge);
+ private float getTaskCurveScaleForOffset(float offset, float taskSize) {
+ int dpPixel = getOrientationHandler().getShortEdgeLength(mDp);
+ float distanceToReachEdge = dpPixel / 2 + taskSize / 2 + mPageSpacing;
+ float interpolation = Math.min(1, offset / distanceToReachEdge);
return TaskView.getCurveScaleForInterpolation(interpolation);
}
+ protected PagedOrientationHandler getOrientationHandler() {
+ if (mOrientedState == null) {
+ return PagedOrientationHandler.PORTRAIT;
+ }
+ return mOrientedState.getOrientationHandler();
+ }
+
/**
* Creates an animation that transforms the current app window into the home app.
* @param startProgress The progress of {@link #mCurrentShift} to start the window from.
@@ -406,16 +444,19 @@
*/
protected RectFSpringAnim createWindowAnimationToHome(float startProgress,
HomeAnimationFactory homeAnimationFactory) {
- final RectF startRect = new RectF(
- mAppWindowAnimationHelper.applyTransform(
- mTransformParams.setProgress(startProgress)
- .setTargetSet(mRecentsAnimationTargets)
- .setLauncherOnTop(false)));
final RectF targetRect = homeAnimationFactory.getWindowTargetRect();
-
final View floatingView = homeAnimationFactory.getFloatingView();
final boolean isFloatingIconView = floatingView instanceof FloatingIconView;
- RectFSpringAnim anim = new RectFSpringAnim(startRect, targetRect, mContext.getResources());
+ final RectF startRect = new RectF(
+ mAppWindowAnimationHelper.applyTransform(
+ mTransformParams.setProgress(startProgress)
+ .setTargetSet(mRecentsAnimationTargets)
+ .setLauncherOnTop(false)));
+ if (isFloatingIconView) {
+ mOrientedState.mapInverseRectFromNormalOrientation(
+ startRect, mDp.widthPx, mDp.heightPx);
+ }
+ RectFSpringAnim anim = new RectFSpringAnim(startRect, targetRect, mContext);
if (isFloatingIconView) {
FloatingIconView fiv = (FloatingIconView) floatingView;
anim.addAnimatorListener(fiv);
@@ -428,21 +469,31 @@
// rounding at the end of the animation.
float startRadius = mAppWindowAnimationHelper.getCurrentCornerRadius();
float endRadius = startRect.width() / 6f;
+
+ float startTransformProgress = mTransformParams.getProgress();
+ float endTransformProgress = 1;
+
// We want the window alpha to be 0 once this threshold is met, so that the
// FolderIconView can be seen morphing into the icon shape.
final float windowAlphaThreshold = isFloatingIconView ? 1f - SHAPE_PROGRESS_DURATION : 1f;
+ final RectF rotatedRect = new RectF();
anim.addOnUpdateListener(new RectFSpringAnim.OnUpdateListener() {
@Override
public void onUpdate(RectF currentRect, float progress) {
homeAnim.setPlayFraction(progress);
- mTransformParams.setProgress(progress)
- .setCurrentRectAndTargetAlpha(currentRect, getWindowAlpha(progress));
+ rotatedRect.set(currentRect);
if (isFloatingIconView) {
+ mOrientedState.mapRectFromNormalOrientation(
+ rotatedRect, mDp.widthPx, mDp.heightPx);
mTransformParams.setCornerRadius(endRadius * progress + startRadius
- * (1f - progress));
+ * (1f - progress));
}
+ mTransformParams.setProgress(
+ Utilities.mapRange(progress, startTransformProgress, endTransformProgress))
+ .setCurrentRect(rotatedRect)
+ .setTargetAlpha(getWindowAlpha(progress));
mAppWindowAnimationHelper.applyTransform(mTransformParams);
if (isFloatingIconView) {
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/FallbackActivityInterface.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/FallbackActivityInterface.java
index 6574d22..2214dd0 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/FallbackActivityInterface.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/FallbackActivityInterface.java
@@ -30,7 +30,6 @@
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
-import com.android.launcher3.BaseActivity;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.anim.AnimationSuccessListener;
import com.android.launcher3.anim.AnimatorPlaybackController;
@@ -212,7 +211,7 @@
@Override
public Rect getOverviewWindowBounds(Rect homeBounds, RemoteAnimationTargetCompat target) {
// TODO: Remove this once b/77875376 is fixed
- return target.sourceContainerBounds;
+ return target.screenSpaceBounds;
}
@Override
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/FallbackSwipeHandler.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/FallbackSwipeHandler.java
index 700feef..46b026e 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/FallbackSwipeHandler.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/FallbackSwipeHandler.java
@@ -21,7 +21,6 @@
import static com.android.quickstep.GestureState.GestureEndTarget.LAST_TASK;
import static com.android.quickstep.GestureState.GestureEndTarget.NEW_TASK;
import static com.android.quickstep.GestureState.GestureEndTarget.RECENTS;
-import static com.android.quickstep.LauncherSwipeHandler.MIN_PROGRESS_FOR_OVERVIEW;
import static com.android.quickstep.MultiStateCallback.DEBUG_STATES;
import static com.android.quickstep.RecentsActivity.EXTRA_TASK_ID;
import static com.android.quickstep.RecentsActivity.EXTRA_THUMBNAIL;
@@ -41,6 +40,7 @@
import com.android.launcher3.R;
import com.android.launcher3.anim.AnimationSuccessListener;
import com.android.launcher3.anim.AnimatorPlaybackController;
+import com.android.launcher3.touch.PagedOrientationHandler;
import com.android.launcher3.util.ObjectWrapper;
import com.android.quickstep.BaseActivityInterface.HomeAnimationFactory;
import com.android.quickstep.GestureState.GestureEndTarget;
@@ -94,7 +94,7 @@
private final AnimatedFloat mLauncherAlpha = new AnimatedFloat(this::onLauncherAlphaChanged);
- private boolean mIsMotionPaused = false;
+ private boolean mOverviewThresholdPassed = false;
private final boolean mInQuickSwitchMode;
private final boolean mContinuingLastGesture;
@@ -161,12 +161,13 @@
@Override
protected boolean onActivityInit(Boolean alreadyOnHome) {
+ super.onActivityInit(alreadyOnHome);
mActivity = mActivityInterface.getCreatedActivity();
mRecentsView = mActivity.getOverviewPanel();
+ mRecentsView.setOnPageTransitionEndCallback(null);
linkRecentsViewScroll();
mRecentsView.setDisallowScrollToClearAll(true);
mRecentsView.getClearAllButton().setVisibilityAlpha(0);
-
mRecentsView.setZoomProgress(1);
if (!mContinuingLastGesture) {
@@ -177,6 +178,7 @@
}
}
mStateCallback.setStateOnUiThread(STATE_RECENTS_PRESENT);
+ mDeviceState.enableMultipleRegions(false);
return true;
}
@@ -218,10 +220,16 @@
@Override
public void onMotionPauseChanged(boolean isPaused) {
- if (!mInQuickSwitchMode) {
- mIsMotionPaused = isPaused;
+ if (!mInQuickSwitchMode && mDeviceState.isFullyGesturalNavMode()) {
+ updateOverviewThresholdPassed(isPaused);
+ }
+ }
+
+ private void updateOverviewThresholdPassed(boolean passed) {
+ if (passed != mOverviewThresholdPassed) {
+ mOverviewThresholdPassed = passed;
if (mSwipeUpOverHome) {
- mLauncherAlpha.animateToValue(mLauncherAlpha.value, isPaused ? 0 : 1)
+ mLauncherAlpha.animateToValue(mLauncherAlpha.value, passed ? 0 : 1)
.setDuration(150).start();
}
performHapticFeedback();
@@ -230,7 +238,7 @@
@Override
public Intent getLaunchIntent() {
- if (mInQuickSwitchMode || mSwipeUpOverHome) {
+ if (mInQuickSwitchMode || mSwipeUpOverHome || !mDeviceState.isFullyGesturalNavMode()) {
return mGestureState.getOverviewIntent();
} else {
return mGestureState.getHomeIntent();
@@ -244,6 +252,11 @@
mRecentsAnimationController.setWindowThresholdCrossed(!mInQuickSwitchMode
&& (mCurrentShift.value > 1 - UPDATE_SYSUI_FLAGS_THRESHOLD));
}
+
+ if (!mInQuickSwitchMode && !mDeviceState.isFullyGesturalNavMode()) {
+ updateOverviewThresholdPassed(mCurrentShift.value >= MIN_PROGRESS_FOR_OVERVIEW);
+ }
+
if (mRecentsAnimationTargets != null) {
applyTransformUnchecked();
}
@@ -267,14 +280,25 @@
.getDimension(R.dimen.quickstep_fling_threshold_velocity);
boolean isFling = Math.abs(endVelocity) > flingThreshold;
- if (isFling) {
- mGestureState.setEndTarget(endVelocity < 0 ? HOME : LAST_TASK);
- } else if (mIsMotionPaused) {
- mGestureState.setEndTarget(RECENTS);
+ if (mDeviceState.isFullyGesturalNavMode()) {
+ if (isFling) {
+ mGestureState.setEndTarget(endVelocity < 0 ? HOME : LAST_TASK);
+ } else if (mOverviewThresholdPassed) {
+ mGestureState.setEndTarget(RECENTS);
+ } else {
+ mGestureState.setEndTarget(mCurrentShift.value >= MIN_PROGRESS_FOR_OVERVIEW
+ ? HOME
+ : LAST_TASK);
+ }
} else {
- mGestureState.setEndTarget(mCurrentShift.value >= MIN_PROGRESS_FOR_OVERVIEW
- ? HOME
- : LAST_TASK);
+ GestureEndTarget startState = mSwipeUpOverHome ? HOME : LAST_TASK;
+ if (isFling) {
+ mGestureState.setEndTarget(endVelocity < 0 ? RECENTS : startState);
+ } else {
+ mGestureState.setEndTarget(mCurrentShift.value >= MIN_PROGRESS_FOR_OVERVIEW
+ ? RECENTS
+ : startState);
+ }
}
}
mStateCallback.setStateOnUiThread(STATE_GESTURE_COMPLETED);
@@ -332,6 +356,8 @@
// Send a home intent to clear the task stack
mContext.startActivity(mGestureState.getHomeIntent());
} else {
+ // Notify swipe-to-home (recents animation) is finished
+ SystemUiProxy.INSTANCE.get(mContext).notifySwipeToHomeFinished();
mRecentsAnimationController.finish(true, () -> {
if (!mTouchedHomeDuringTransition) {
// If the user hasn't interacted with the screen during the transition,
@@ -347,7 +373,7 @@
mRecentsAnimationController.finish(false, null, false);
break;
case RECENTS: {
- if (mSwipeUpOverHome) {
+ if (mSwipeUpOverHome || !mDeviceState.isFullyGesturalNavMode()) {
mRecentsAnimationController.finish(true, null, true);
break;
}
@@ -407,7 +433,12 @@
@Override
public void onAnimationSuccess(Animator animator) {
- finishAnimationTargetSetAnimationComplete();
+ if (mRecentsView != null) {
+ mRecentsView.setOnPageTransitionEndCallback(FallbackSwipeHandler.this
+ ::finishAnimationTargetSetAnimationComplete);
+ } else {
+ finishAnimationTargetSetAnimationComplete();
+ }
mFinishAnimation = null;
}
};
@@ -417,7 +448,7 @@
this::createNewInputProxyHandler);
RectFSpringAnim anim = createWindowAnimationToHome(mCurrentShift.value, duration);
anim.addAnimatorListener(endListener);
- anim.start(mEndVelocityPxPerMs);
+ anim.start(mContext, mEndVelocityPxPerMs);
mFinishAnimation = RunningWindowAnim.wrap(anim);
} else {
@@ -467,7 +498,13 @@
HomeAnimationFactory factory = new HomeAnimationFactory() {
@Override
public RectF getWindowTargetRect() {
- return HomeAnimationFactory.getDefaultWindowTargetRect(mDp);
+ PagedOrientationHandler orientationHandler = mRecentsView != null
+ ? mRecentsView.getPagedOrientationHandler()
+ : (mDp.isLandscape
+ ? PagedOrientationHandler.LANDSCAPE
+ : PagedOrientationHandler.PORTRAIT);
+ return HomeAnimationFactory
+ .getDefaultWindowTargetRect(orientationHandler, mDp);
}
@Override
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/ImageActionsApi.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/ImageActionsApi.java
new file mode 100644
index 0000000..33fe5a9
--- /dev/null
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/ImageActionsApi.java
@@ -0,0 +1,94 @@
+/*
+ * 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.quickstep;
+
+import static android.content.Intent.EXTRA_STREAM;
+
+import static com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR;
+import static com.android.quickstep.util.ImageActionUtils.persistBitmapAndStartActivity;
+
+import android.content.Context;
+import android.content.Intent;
+import android.graphics.Bitmap;
+import android.graphics.Insets;
+import android.graphics.Rect;
+import android.util.Log;
+
+import androidx.annotation.Nullable;
+import androidx.annotation.UiThread;
+
+import com.android.launcher3.BuildConfig;
+import com.android.quickstep.util.ImageActionUtils;
+
+import java.util.function.Supplier;
+
+/**
+ * Contains image selection functions necessary to complete overview action button functions.
+ */
+public class ImageActionsApi {
+
+ private static final String TAG = BuildConfig.APPLICATION_ID + "ImageActionsApi";
+ private final Context mContext;
+ private final Supplier<Bitmap> mBitmapSupplier;
+ private final SystemUiProxy mSystemUiProxy;
+
+ public ImageActionsApi(Context context, Supplier<Bitmap> bitmapSupplier) {
+ mContext = context;
+ mBitmapSupplier = bitmapSupplier;
+ mSystemUiProxy = SystemUiProxy.INSTANCE.get(context);
+ }
+
+ /**
+ * Share the image this api was constructed with using the provided intent. The implementation
+ * should add an {@link Intent#EXTRA_STREAM} with the URI pointing to the image to the intent.
+ */
+ @UiThread
+ public void shareWithExplicitIntent(@Nullable Rect crop, Intent intent) {
+ if (mBitmapSupplier.get() == null) {
+ Log.e(TAG, "No snapshot available, not starting share.");
+ return;
+ }
+
+ UI_HELPER_EXECUTOR.execute(() -> persistBitmapAndStartActivity(mContext,
+ mBitmapSupplier.get(), crop, intent, (uri, intentForUri) -> {
+ intentForUri.putExtra(EXTRA_STREAM, uri);
+ return new Intent[]{intentForUri};
+ }, TAG));
+
+ }
+
+ /**
+ * Share the image this api was constructed with.
+ */
+ @UiThread
+ public void startShareActivity() {
+ ImageActionUtils.startShareActivity(mContext, mBitmapSupplier, null, null, TAG);
+ }
+
+ /**
+ * @param screenshot to be saved to the media store.
+ * @param screenshotBounds the location of where the bitmap was laid out on the screen in
+ * screen coordinates.
+ * @param visibleInsets that are used to draw the screenshot within the bounds.
+ * @param taskId of the task that the screenshot was taken of.
+ */
+ public void saveScreenshot(Bitmap screenshot, Rect screenshotBounds,
+ Insets visibleInsets, int taskId) {
+ ImageActionUtils.saveScreenshot(mSystemUiProxy, screenshot, screenshotBounds, visibleInsets,
+ taskId);
+ }
+}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/LauncherActivityInterface.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/LauncherActivityInterface.java
index 28fc3da..455ae76 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/LauncherActivityInterface.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/LauncherActivityInterface.java
@@ -38,6 +38,7 @@
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.UserHandle;
+import android.util.Pair;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Interpolator;
@@ -54,6 +55,9 @@
import com.android.launcher3.allapps.DiscoveryBounce;
import com.android.launcher3.anim.AnimatorPlaybackController;
import com.android.launcher3.appprediction.PredictionUiStateManager;
+import com.android.launcher3.statehandlers.DepthController;
+import com.android.launcher3.statehandlers.DepthController.ClampedDepthProperty;
+import com.android.launcher3.touch.PagedOrientationHandler;
import com.android.launcher3.userevent.nano.LauncherLogProto;
import com.android.launcher3.views.FloatingIconView;
import com.android.quickstep.SysUINavigationMode.Mode;
@@ -78,6 +82,8 @@
public final class LauncherActivityInterface implements BaseActivityInterface<Launcher> {
private Runnable mAdjustInterpolatorsRunnable;
+ private Pair<Float, Float> mSwipeUpPullbackStartAndMaxProgress =
+ BaseActivityInterface.super.getSwipeUpPullbackStartAndMaxProgress();
@Override
public int getSwipeUpDestinationAndLength(DeviceProfile dp, Context context, Rect outRect) {
@@ -92,6 +98,11 @@
}
@Override
+ public Pair<Float, Float> getSwipeUpPullbackStartAndMaxProgress() {
+ return mSwipeUpPullbackStartAndMaxProgress;
+ }
+
+ @Override
public void onTransitionCancelled(boolean activityVisible) {
Launcher launcher = getCreatedActivity();
if (launcher == null) {
@@ -176,7 +187,8 @@
if (canUseWorkspaceView) {
return iconLocation;
} else {
- return HomeAnimationFactory.getDefaultWindowTargetRect(dp);
+ return HomeAnimationFactory
+ .getDefaultWindowTargetRect(recentsView.getPagedOrientationHandler(), dp);
}
}
@@ -234,6 +246,7 @@
public void adjustActivityControllerInterpolators() {
if (mAdjustInterpolatorsRunnable != null) {
mAdjustInterpolatorsRunnable.run();
+ mAdjustInterpolatorsRunnable = null;
}
}
@@ -267,23 +280,28 @@
float scrollOffsetX = recentsView.getScrollOffset();
float offscreenX = recentsView.getOffscreenTranslationX(currScale);
- float fromTranslationX = attached ? offscreenX - scrollOffsetX : 0;
- float toTranslationX = attached ? 0 : offscreenX - scrollOffsetX;
+ float fromTranslation = attached ? offscreenX - scrollOffsetX : 0;
+ float toTranslation = attached ? 0 : offscreenX - scrollOffsetX;
launcher.getStateManager()
.cancelStateElementAnimation(INDEX_RECENTS_TRANSLATE_X_ANIM);
+ PagedOrientationHandler pagedOrientationHandler =
+ recentsView.getPagedViewOrientedState().getOrientationHandler();
if (!recentsView.isShown() && animate) {
- recentsView.setTranslationX(fromTranslationX);
+ pagedOrientationHandler
+ .getPrimaryViewTranslate().set(recentsView, fromTranslation);
} else {
- fromTranslationX = recentsView.getTranslationX();
+ fromTranslation =
+ pagedOrientationHandler.getPrimaryViewTranslate().get(recentsView);
}
if (!animate) {
- recentsView.setTranslationX(toTranslationX);
+ pagedOrientationHandler
+ .getPrimaryViewTranslate().set(recentsView, toTranslation);
} else {
launcher.getStateManager().createStateElementAnimation(
INDEX_RECENTS_TRANSLATE_X_ANIM,
- fromTranslationX, toTranslationX).start();
+ fromTranslation, toTranslation).start();
}
fadeAnim.setInterpolator(attached ? INSTANT : ACCEL_2);
@@ -311,6 +329,16 @@
fromState.getVerticalProgress(activity),
endState.getVerticalProgress(activity)));
}
+
+ // Animate the blur and wallpaper zoom
+ DepthController depthController = getDepthController();
+ float fromDepthRatio = fromState.getDepth(activity);
+ float toDepthRatio = endState.getDepth(activity);
+ Animator depthAnimator = ObjectAnimator.ofFloat(depthController,
+ new ClampedDepthProperty(fromDepthRatio, toDepthRatio),
+ fromDepthRatio, toDepthRatio);
+ anim.play(depthAnimator);
+
playScaleDownAnim(anim, activity, fromState, endState);
anim.setDuration(transitionLength * 2);
@@ -376,6 +404,14 @@
return newT <= 1f ? newT : newT + normalizedTranslationY * (newT - 1);
});
};
+
+ // Start pulling back when RecentsView scale is 0.75f, and let it go down to 0.5f.
+ float pullbackStartProgress = (0.75f - fromScaleAndTranslation.scale)
+ / (endScaleAndTranslation.scale - fromScaleAndTranslation.scale);
+ float pullbackMaxProgress = (0.5f - fromScaleAndTranslation.scale)
+ / (endScaleAndTranslation.scale - fromScaleAndTranslation.scale);
+ mSwipeUpPullbackStartAndMaxProgress = new Pair<>(
+ pullbackStartProgress, pullbackMaxProgress);
}
@Override
@@ -518,4 +554,14 @@
PredictionUiStateManager.INSTANCE.get(launcher).switchClient(
PredictionUiStateManager.Client.OVERVIEW);
}
+
+ @Nullable
+ @Override
+ public DepthController getDepthController() {
+ BaseQuickstepLauncher launcher = getCreatedActivity();
+ if (launcher == null) {
+ return null;
+ }
+ return launcher.getDepthController();
+ }
}
\ No newline at end of file
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/LauncherSwipeHandler.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/LauncherSwipeHandler.java
index f0516ac..8574cf1 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/LauncherSwipeHandler.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/LauncherSwipeHandler.java
@@ -21,7 +21,7 @@
import static com.android.launcher3.anim.Interpolators.LINEAR;
import static com.android.launcher3.anim.Interpolators.OVERSHOOT_1_2;
import static com.android.launcher3.config.FeatureFlags.ENABLE_QUICKSTEP_LIVE_TILE;
-import static com.android.launcher3.config.FeatureFlags.QUICKSTEP_SPRINGS;
+import static com.android.launcher3.config.FeatureFlags.UNSTABLE_SPRINGS;
import static com.android.launcher3.util.DefaultDisplay.getSingleFrameMs;
import static com.android.launcher3.util.SystemUiController.UI_STATE_OVERVIEW;
import static com.android.quickstep.GestureState.GestureEndTarget.HOME;
@@ -29,6 +29,7 @@
import static com.android.quickstep.GestureState.GestureEndTarget.NEW_TASK;
import static com.android.quickstep.GestureState.GestureEndTarget.RECENTS;
import static com.android.quickstep.GestureState.STATE_END_TARGET_ANIMATION_FINISHED;
+import static com.android.quickstep.GestureState.STATE_RECENTS_SCROLLING_FINISHED;
import static com.android.quickstep.MultiStateCallback.DEBUG_STATES;
import static com.android.quickstep.SysUINavigationMode.Mode.TWO_BUTTONS;
import static com.android.quickstep.util.ShelfPeekAnim.ShelfAnimState.HIDE;
@@ -46,6 +47,7 @@
import android.graphics.RectF;
import android.os.Build;
import android.os.SystemClock;
+import android.util.Log;
import android.view.View;
import android.view.View.OnApplyWindowInsetsListener;
import android.view.ViewTreeObserver.OnDrawListener;
@@ -64,6 +66,7 @@
import com.android.launcher3.anim.AnimatorPlaybackController;
import com.android.launcher3.anim.Interpolators;
import com.android.launcher3.logging.UserEventDispatcher;
+import com.android.launcher3.testing.TestProtocol;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action.Direction;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action.Touch;
import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
@@ -244,7 +247,11 @@
| STATE_GESTURE_STARTED,
this::setupLauncherUiAfterSwipeUpToRecentsAnimation);
- mGestureState.runOnceAtState(STATE_END_TARGET_ANIMATION_FINISHED, this::onEndTargetSet);
+ mGestureState.runOnceAtState(STATE_END_TARGET_ANIMATION_FINISHED,
+ this::continueComputingRecentsScrollIfNecessary);
+ mGestureState.runOnceAtState(STATE_END_TARGET_ANIMATION_FINISHED
+ | STATE_RECENTS_SCROLLING_FINISHED,
+ this::onSettledOnEndTarget);
mStateCallback.runOnceAtState(STATE_HANDLER_INVALIDATED, this::invalidateHandler);
mStateCallback.runOnceAtState(STATE_LAUNCHER_PRESENT | STATE_HANDLER_INVALIDATED,
@@ -261,6 +268,7 @@
@Override
protected boolean onActivityInit(Boolean alreadyOnHome) {
+ super.onActivityInit(alreadyOnHome);
final T activity = mActivityInterface.getCreatedActivity();
if (mActivity == activity) {
return true;
@@ -282,6 +290,7 @@
}
mRecentsView = activity.getOverviewPanel();
+ mRecentsView.setOnPageTransitionEndCallback(null);
linkRecentsViewScroll();
addLiveTileOverlay();
@@ -504,16 +513,22 @@
}
private void buildAnimationController() {
- if (mGestureState.getEndTarget() == HOME || mHasLauncherTransitionControllerStarted) {
- // We don't want a new mLauncherTransitionController if
- // mGestureState.getEndTarget() == HOME (it has its own animation) or if we're already
- // animating the current controller.
+ if (!canCreateNewOrUpdateExistingLauncherTransitionController()) {
return;
}
initTransitionEndpoints(mActivity.getDeviceProfile());
mAnimationFactory.createActivityInterface(mTransitionDragLength);
}
+ /**
+ * We don't want to change mLauncherTransitionController if mGestureState.getEndTarget() == HOME
+ * (it has its own animation) or if we're already animating the current controller.
+ * @return Whether we can create the launcher controller or update its progress.
+ */
+ private boolean canCreateNewOrUpdateExistingLauncherTransitionController() {
+ return mGestureState.getEndTarget() != HOME && !mHasLauncherTransitionControllerStarted;
+ }
+
@Override
public WindowInsets onApplyWindowInsets(View view, WindowInsets windowInsets) {
WindowInsets result = view.onApplyWindowInsets(windowInsets);
@@ -557,15 +572,12 @@
}
}
- if (mLauncherTransitionController == null || mLauncherTransitionController
- .getAnimationPlayer().isStarted()) {
- return;
- }
updateLauncherTransitionProgress();
}
private void updateLauncherTransitionProgress() {
- if (mGestureState.getEndTarget() == HOME) {
+ if (mLauncherTransitionController == null
+ || !canCreateNewOrUpdateExistingLauncherTransitionController()) {
return;
}
// Normalize the progress to 0 to 1, as the animation controller will clamp it to that
@@ -586,7 +598,7 @@
// We will handle the sysui flags based on the centermost task view.
if (mRecentsAnimationController != null) {
mRecentsAnimationController.setWindowThresholdCrossed(centermostTaskFlags != 0
- || useHomeScreenFlags);
+ && useHomeScreenFlags);
}
int sysuiFlags = useHomeScreenFlags ? 0 : centermostTaskFlags;
mActivity.getSystemUiController().updateUiState(UI_STATE_OVERVIEW, sysuiFlags);
@@ -695,10 +707,12 @@
}
}
- private void onEndTargetSet() {
+ private void onSettledOnEndTarget() {
switch (mGestureState.getEndTarget()) {
case HOME:
mStateCallback.setState(STATE_SCALED_CONTROLLER_HOME | STATE_CAPTURE_SCREENSHOT);
+ // Notify swipe-to-home (recents animation) is finished
+ SystemUiProxy.INSTANCE.get(mContext).notifySwipeToHomeFinished();
break;
case RECENTS:
mStateCallback.setState(STATE_SCALED_CONTROLLER_RECENTS | STATE_CAPTURE_SCREENSHOT
@@ -768,6 +782,12 @@
}
}
+ if (endTarget == RECENTS || endTarget == HOME) {
+ // Since we're now done quickStepping, we want to only listen for touch events
+ // for the main orientation's nav bar, instead of multiple
+ mDeviceState.enableMultipleRegions(false);
+ }
+
if (mDeviceState.isOverviewDisabled() && (endTarget == RECENTS || endTarget == LAST_TASK)) {
return LAST_TASK;
}
@@ -846,13 +866,17 @@
if (mDeviceState.isFullyGesturalNavMode()) {
setShelfState(ShelfAnimState.OVERVIEW, interpolator, duration);
}
- } else if (endTarget == NEW_TASK || endTarget == LAST_TASK) {
- // Let RecentsView handle the scrolling to the task, which we launch in startNewTask()
- // or resumeLastTask().
- if (mRecentsView != null) {
- duration = Math.max(duration, mRecentsView.getScroller().getDuration());
- }
}
+
+ // Let RecentsView handle the scrolling to the task, which we launch in startNewTask()
+ // or resumeLastTask().
+ if (mRecentsView != null) {
+ mRecentsView.setOnPageTransitionEndCallback(
+ () -> mGestureState.setState(STATE_RECENTS_SCROLLING_FINISHED));
+ } else {
+ mGestureState.setState(STATE_RECENTS_SCROLLING_FINISHED);
+ }
+
animateToProgress(startShift, endShift, duration, interpolator, endTarget, velocityPxPerMs);
}
@@ -917,11 +941,18 @@
windowAnim.addAnimatorListener(new AnimationSuccessListener() {
@Override
public void onAnimationSuccess(Animator animator) {
+ if (mRecentsAnimationController == null) {
+ // If the recents animation is interrupted, we still end the running
+ // animation (not canceled) so this is still called. In that case, we can
+ // skip doing any future work here for the current gesture.
+ return;
+ }
// Finalize the state and notify of the change
mGestureState.setState(STATE_END_TARGET_ANIMATION_FINISHED);
}
});
- windowAnim.start(velocityPxPerMs);
+ getOrientationHandler().adjustFloatingIconStartVelocity(velocityPxPerMs);
+ windowAnim.start(mContext, velocityPxPerMs);
homeAnimFactory.playAtomicAnimation(velocityPxPerMs.y);
mRunningWindowAnim = RunningWindowAnim.wrap(windowAnim);
mLauncherTransitionController = null;
@@ -929,15 +960,17 @@
ValueAnimator windowAnim = mCurrentShift.animateToValue(start, end);
windowAnim.setDuration(duration).setInterpolator(interpolator);
windowAnim.addUpdateListener(valueAnimator -> {
- if (mRecentsView != null && mRecentsView.getVisibility() != View.VISIBLE) {
- // Views typically don't compute scroll when invisible as an optimization,
- // but in our case we need to since the window offset depends on the scroll.
- mRecentsView.computeScroll();
- }
+ computeRecentsScrollIfInvisible();
});
windowAnim.addListener(new AnimationSuccessListener() {
@Override
public void onAnimationSuccess(Animator animator) {
+ if (mRecentsAnimationController == null) {
+ // If the recents animation is interrupted, we still end the running
+ // animation (not canceled) so this is still called. In that case, we can
+ // skip doing any future work here for the current gesture.
+ return;
+ }
if (target == NEW_TASK && mRecentsView != null
&& mRecentsView.getNextPage() == mRecentsView.getRunningTaskIndex()) {
// We are about to launch the current running task, so use LAST_TASK state
@@ -972,13 +1005,28 @@
}
mLauncherTransitionController.getAnimationPlayer().setDuration(Math.max(0, duration));
- if (QUICKSTEP_SPRINGS.get()) {
- mLauncherTransitionController.dispatchOnStartWithVelocity(end, velocityPxPerMs.y);
+ if (UNSTABLE_SPRINGS.get()) {
+ mLauncherTransitionController.dispatchOnStart();
}
mLauncherTransitionController.getAnimationPlayer().start();
mHasLauncherTransitionControllerStarted = true;
}
+ private void computeRecentsScrollIfInvisible() {
+ if (mRecentsView != null && mRecentsView.getVisibility() != View.VISIBLE) {
+ // Views typically don't compute scroll when invisible as an optimization,
+ // but in our case we need to since the window offset depends on the scroll.
+ mRecentsView.computeScroll();
+ }
+ }
+
+ private void continueComputingRecentsScrollIfNecessary() {
+ if (!mGestureState.hasState(STATE_RECENTS_SCROLLING_FINISHED)) {
+ computeRecentsScrollIfInvisible();
+ mRecentsView.post(this::continueComputingRecentsScrollIfNecessary);
+ }
+ }
+
/**
* Creates an animation that transforms the current app window into the home app.
* @param startProgress The progress of {@link #mCurrentShift} to start the window from.
@@ -989,7 +1037,9 @@
HomeAnimationFactory homeAnimationFactory) {
RectFSpringAnim anim =
super.createWindowAnimationToHome(startProgress, homeAnimationFactory);
- anim.addOnUpdateListener((r, p) -> updateSysUiFlags(Math.max(p, mCurrentShift.value)));
+ anim.addOnUpdateListener((r, p) -> {
+ updateSysUiFlags(Math.max(p, mCurrentShift.value));
+ });
anim.addAnimatorListener(new AnimationSuccessListener() {
@Override
public void onAnimationStart(Animator animation) {
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/OverviewCommandHelper.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/OverviewCommandHelper.java
index fc50660..c6b719a 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/OverviewCommandHelper.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/OverviewCommandHelper.java
@@ -33,6 +33,7 @@
import com.android.launcher3.logging.UserEventDispatcher;
import com.android.launcher3.userevent.nano.LauncherLogProto;
import com.android.quickstep.util.ActivityInitListener;
+import com.android.quickstep.util.RemoteAnimationProvider;
import com.android.quickstep.views.RecentsView;
import com.android.quickstep.views.TaskView;
import com.android.systemui.shared.system.ActivityManagerWrapper;
@@ -187,7 +188,15 @@
// Otherwise, start overview.
mListener = mActivityInterface.createActivityInitListener(this::onActivityReady);
mListener.registerAndStartActivity(mOverviewComponentObserver.getOverviewIntent(),
- this::createWindowAnimation, mContext, MAIN_EXECUTOR.getHandler(),
+ new RemoteAnimationProvider() {
+ @Override
+ public AnimatorSet createWindowAnimation(
+ RemoteAnimationTargetCompat[] appTargets,
+ RemoteAnimationTargetCompat[] wallpaperTargets) {
+ return RecentsActivityCommand.this.createWindowAnimation(appTargets,
+ wallpaperTargets);
+ }
+ }, mContext, MAIN_EXECUTOR.getHandler(),
mAnimationProvider.getRecentsLaunchDuration());
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/QuickstepTestInformationHandler.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/QuickstepTestInformationHandler.java
index a538fff..d4c746f 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/QuickstepTestInformationHandler.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/QuickstepTestInformationHandler.java
@@ -3,8 +3,8 @@
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
-import android.util.Log;
+import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.testing.TestInformationHandler;
import com.android.launcher3.testing.TestProtocol;
import com.android.launcher3.uioverrides.touchcontrollers.PortraitStatesTouchController;
@@ -64,6 +64,12 @@
taskBaseIntentComponents);
return response;
}
+
+ case TestProtocol.REQUEST_OVERVIEW_ACTIONS_ENABLED: {
+ response.putBoolean(TestProtocol.TEST_INFO_RESPONSE_FIELD,
+ FeatureFlags.ENABLE_OVERVIEW_ACTIONS.get());
+ return response;
+ }
}
return super.call(method);
@@ -82,11 +88,6 @@
@Override
protected boolean isLauncherInitialized() {
- if (TestProtocol.sDebugTracing) {
- Log.d(TestProtocol.LAUNCHER_DIDNT_INITIALIZE,
- "isLauncherInitialized.TouchInteractionService.isInitialized=" +
- TouchInteractionService.isInitialized());
- }
return super.isLauncherInitialized() && TouchInteractionService.isInitialized();
}
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/RecentsActivity.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/RecentsActivity.java
index 3f5179f..42d944f 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/RecentsActivity.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/RecentsActivity.java
@@ -70,7 +70,7 @@
setContentView(R.layout.fallback_recents_activity);
mRecentsRootView = findViewById(R.id.drag_layer);
mFallbackRecentsView = findViewById(R.id.overview_panel);
- mRecentsRootView.setup();
+ mRecentsRootView.recreateControllers();
}
@Override
@@ -108,7 +108,7 @@
@Override
protected void onHandleConfigChanged() {
super.onHandleConfigChanged();
- mRecentsRootView.setup();
+ mRecentsRootView.recreateControllers();
}
@Override
@@ -183,9 +183,12 @@
RemoteAnimationTargetCompat[] wallpaperTargets) {
AnimatorSet target = new AnimatorSet();
boolean activityClosing = taskIsATargetWithMode(appTargets, getTaskId(), MODE_CLOSING);
- AppWindowAnimationHelper helper = new AppWindowAnimationHelper(this);
- target.play(getRecentsWindowAnimator(taskView, !activityClosing, appTargets,
- wallpaperTargets, helper).setDuration(RECENTS_LAUNCH_DURATION));
+ AppWindowAnimationHelper helper = new AppWindowAnimationHelper(
+ mFallbackRecentsView.getPagedViewOrientedState(), this);
+ Animator recentsAnimator = getRecentsWindowAnimator(taskView, !activityClosing, appTargets,
+ wallpaperTargets, null /* depthController */,
+ helper);
+ target.play(recentsAnimator.setDuration(RECENTS_LAUNCH_DURATION));
// Found a visible recents task that matches the opening app, lets launch the app from there
if (activityClosing) {
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/TaskOverlayFactory.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/TaskOverlayFactory.java
index ec7cddf..fbf29af 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/TaskOverlayFactory.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/TaskOverlayFactory.java
@@ -16,12 +16,13 @@
package com.android.quickstep;
+import static com.android.launcher3.config.FeatureFlags.ENABLE_OVERVIEW_ACTIONS;
import static com.android.launcher3.util.MainThreadInitializedObject.forOverride;
+import android.content.Context;
+import android.graphics.Insets;
import android.graphics.Matrix;
-import android.view.View;
-
-import androidx.annotation.Nullable;
+import android.graphics.Rect;
import com.android.launcher3.BaseActivity;
import com.android.launcher3.BaseDraggingActivity;
@@ -29,8 +30,10 @@
import com.android.launcher3.popup.SystemShortcut;
import com.android.launcher3.util.MainThreadInitializedObject;
import com.android.launcher3.util.ResourceBasedOverride;
+import com.android.quickstep.views.OverviewActionsView;
import com.android.quickstep.views.TaskThumbnailView;
import com.android.quickstep.views.TaskView;
+import com.android.systemui.plugins.OverscrollPlugin;
import com.android.systemui.shared.recents.model.Task;
import com.android.systemui.shared.recents.model.ThumbnailData;
@@ -42,16 +45,6 @@
*/
public class TaskOverlayFactory implements ResourceBasedOverride {
- /** Note that these will be shown in order from top to bottom, if available for the task. */
- private static final TaskShortcutFactory[] MENU_OPTIONS = new TaskShortcutFactory[]{
- TaskShortcutFactory.APP_INFO,
- TaskShortcutFactory.SPLIT_SCREEN,
- TaskShortcutFactory.PIN,
- TaskShortcutFactory.INSTALL,
- TaskShortcutFactory.FREE_FORM,
- TaskShortcutFactory.WELLBEING
- };
-
public static List<SystemShortcut> getEnabledShortcuts(TaskView taskView) {
final ArrayList<SystemShortcut> shortcuts = new ArrayList<>();
final BaseDraggingActivity activity = BaseActivity.fromContext(taskView.getContext());
@@ -67,25 +60,105 @@
public static final MainThreadInitializedObject<TaskOverlayFactory> INSTANCE =
forOverride(TaskOverlayFactory.class, R.string.task_overlay_factory_class);
- public TaskOverlay createOverlay(TaskThumbnailView thumbnailView) {
- return new TaskOverlay();
+ /**
+ * @return a launcher-provided OverscrollPlugin if available, otherwise null
+ */
+ public OverscrollPlugin getLocalOverscrollPlugin() {
+ return null;
}
+ public TaskOverlay createOverlay(TaskThumbnailView thumbnailView) {
+ return new TaskOverlay(thumbnailView);
+ }
+
+ /** Note that these will be shown in order from top to bottom, if available for the task. */
+ private static final TaskShortcutFactory[] MENU_OPTIONS = new TaskShortcutFactory[]{
+ TaskShortcutFactory.APP_INFO,
+ TaskShortcutFactory.SPLIT_SCREEN,
+ TaskShortcutFactory.PIN,
+ TaskShortcutFactory.INSTALL,
+ TaskShortcutFactory.FREE_FORM,
+ TaskShortcutFactory.WELLBEING
+ };
+
+ /**
+ * Overlay on each task handling Overview Action Buttons.
+ */
public static class TaskOverlay {
+ private final Context mApplicationContext;
+ private OverviewActionsView mActionsView;
+ private final TaskThumbnailView mThumbnailView;
+
+
+ protected TaskOverlay(TaskThumbnailView taskThumbnailView) {
+ mApplicationContext = taskThumbnailView.getContext().getApplicationContext();
+ mThumbnailView = taskThumbnailView;
+ }
+
/**
* Called when the current task is interactive for the user
*/
- public void initOverlay(Task task, ThumbnailData thumbnail, Matrix matrix) { }
+ public void initOverlay(Task task, ThumbnailData thumbnail, Matrix matrix) {
+ ImageActionsApi imageApi = new ImageActionsApi(
+ mApplicationContext, mThumbnailView::getThumbnail);
- @Nullable
- public View getActionsView() {
- return null;
+ if (mActionsView == null && ENABLE_OVERVIEW_ACTIONS.get()
+ && SysUINavigationMode.removeShelfFromOverview(mApplicationContext)) {
+ mActionsView = BaseActivity.fromContext(mThumbnailView.getContext()).findViewById(
+ R.id.overview_actions_view);
+ }
+ if (mActionsView != null) {
+ mActionsView.setListener(new OverviewActionsView.Listener() {
+ @Override
+ public void onShare() {
+ imageApi.startShareActivity();
+ }
+
+ @Override
+ public void onScreenshot() {
+ imageApi.saveScreenshot(mThumbnailView.getThumbnail(),
+ getTaskSnapshotBounds(), getTaskSnapshotInsets(), task.key.id);
+ }
+ });
+ }
+
}
/**
* Called when the overlay is no longer used.
*/
- public void reset() { }
+ public void reset() {
+ }
+
+ /**
+ * Whether the overlay is modal, which means only tapping is enabled, but no swiping.
+ */
+ public boolean isOverlayModal() {
+ return false;
+ }
+
+ /**
+ * Gets the task snapshot as it is displayed on the screen.
+ *
+ * @return the bounds of the snapshot in screen coordinates.
+ */
+ public Rect getTaskSnapshotBounds() {
+ int[] location = new int[2];
+ mThumbnailView.getLocationOnScreen(location);
+
+ return new Rect(location[0], location[1], mThumbnailView.getWidth() + location[0],
+ mThumbnailView.getHeight() + location[1]);
+ }
+
+ /**
+ * Gets the insets that the snapshot is drawn with.
+ *
+ * @return the insets in screen coordinates.
+ */
+ public Insets getTaskSnapshotInsets() {
+ // TODO: return the real insets
+ return Insets.of(0, 0, 0, 0);
+ }
}
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/TaskShortcutFactory.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/TaskShortcutFactory.java
index 9ba2e5a..021d39d 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/TaskShortcutFactory.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/TaskShortcutFactory.java
@@ -35,8 +35,8 @@
import com.android.launcher3.BaseDraggingActivity;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.R;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.model.WellbeingModel;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.popup.SystemShortcut;
import com.android.launcher3.popup.SystemShortcut.AppInfo;
import com.android.launcher3.userevent.nano.LauncherLogProto;
@@ -71,7 +71,7 @@
WorkspaceItemInfo dummyInfo = new WorkspaceItemInfo();
dummyInfo.intent = new Intent();
ComponentName component = task.getTopComponent();
- dummyInfo.intent.setComponent(component);
+ dummyInfo.getIntent().setComponent(component);
dummyInfo.user = UserHandle.of(task.key.userId);
dummyInfo.title = TaskUtils.getTitle(view.getContext(), task);
return dummyInfo;
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/TaskViewUtils.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/TaskViewUtils.java
index bfe5738..47c07af 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/TaskViewUtils.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/TaskViewUtils.java
@@ -15,13 +15,17 @@
*/
package com.android.quickstep;
+import static com.android.launcher3.LauncherState.BACKGROUND_APP;
import static com.android.launcher3.anim.Interpolators.LINEAR;
import static com.android.launcher3.anim.Interpolators.TOUCH_RESPONSE_INTERPOLATOR;
import static com.android.launcher3.config.FeatureFlags.ENABLE_QUICKSTEP_LIVE_TILE;
+import static com.android.launcher3.statehandlers.DepthController.DEPTH;
import static com.android.systemui.shared.system.RemoteAnimationTargetCompat.MODE_OPENING;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
+import android.animation.AnimatorSet;
+import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.ComponentName;
import android.graphics.RectF;
@@ -29,8 +33,9 @@
import com.android.launcher3.BaseActivity;
import com.android.launcher3.BaseDraggingActivity;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.Utilities;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.statehandlers.DepthController;
import com.android.quickstep.util.AppWindowAnimationHelper;
import com.android.quickstep.util.MultiValueUpdateListener;
import com.android.quickstep.views.RecentsView;
@@ -115,9 +120,11 @@
* @return Animator that controls the window of the opening targets for the recents launch
* animation.
*/
- public static ValueAnimator getRecentsWindowAnimator(TaskView v, boolean skipViewChanges,
+ public static Animator getRecentsWindowAnimator(TaskView v, boolean skipViewChanges,
RemoteAnimationTargetCompat[] appTargets,
- RemoteAnimationTargetCompat[] wallpaperTargets, final AppWindowAnimationHelper inOutHelper) {
+ RemoteAnimationTargetCompat[] wallpaperTargets,
+ DepthController depthController,
+ final AppWindowAnimationHelper inOutHelper) {
SyncRtSurfaceTransactionApplierCompat applier =
new SyncRtSurfaceTransactionApplierCompat(v);
final RemoteAnimationTargets targets =
@@ -129,6 +136,7 @@
.setTargetSet(targets)
.setLauncherOnTop(true);
+ AnimatorSet animatorSet = new AnimatorSet();
final RecentsView recentsView = v.getRecentsView();
final ValueAnimator appAnimator = ValueAnimator.ofFloat(0, 1);
appAnimator.setInterpolator(TOUCH_RESPONSE_INTERPOLATOR);
@@ -137,8 +145,6 @@
// Defer fading out the view until after the app window gets faded in
final FloatProp mViewAlpha = new FloatProp(1f, 0f, 75, 75, LINEAR);
final FloatProp mTaskAlpha = new FloatProp(0f, 1f, 0, 75, LINEAR);
-
-
final RectF mThumbnailRect;
{
@@ -163,7 +169,7 @@
if (ENABLE_QUICKSTEP_LIVE_TILE.get()) {
List<SurfaceParams> surfaceParamsList = new ArrayList<>();
// Append the surface transform params for the app that's being opened.
- Collections.addAll(surfaceParamsList, inOutHelper.getSurfaceParams(params));
+ Collections.addAll(surfaceParamsList, inOutHelper.computeSurfaceParams(params));
AppWindowAnimationHelper liveTileAnimationHelper =
v.getRecentsView().getClipAnimationHelper();
@@ -173,14 +179,14 @@
v.getRecentsView().getLiveTileParams(true /* mightNeedToRefill */);
if (liveTileParams != null) {
SurfaceParams[] liveTileSurfaceParams =
- liveTileAnimationHelper.getSurfaceParams(liveTileParams);
+ liveTileAnimationHelper.computeSurfaceParams(liveTileParams);
if (liveTileSurfaceParams != null) {
Collections.addAll(surfaceParamsList, liveTileSurfaceParams);
}
}
}
// Apply surface transform using the surface params list.
- AppWindowAnimationHelper.applySurfaceParams(params.syncTransactionApplier,
+ AppWindowAnimationHelper.applySurfaceParams(params.getSyncTransactionApplier(),
surfaceParamsList.toArray(new SurfaceParams[surfaceParamsList.size()]));
// Get the task bounds for the app that's being opened after surface transform
// update.
@@ -208,6 +214,14 @@
targets.release();
}
});
- return appAnimator;
+
+ if (depthController != null) {
+ ObjectAnimator backgroundRadiusAnim = ObjectAnimator.ofFloat(depthController,
+ DEPTH, BACKGROUND_APP.getDepth(v.getContext()));
+ animatorSet.playTogether(appAnimator, backgroundRadiusAnim);
+ } else {
+ animatorSet.play(appAnimator);
+ }
+ return animatorSet;
}
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/TouchInteractionService.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/TouchInteractionService.java
index edaef30..2c2feb2 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/TouchInteractionService.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/TouchInteractionService.java
@@ -15,24 +15,23 @@
*/
package com.android.quickstep;
+import static android.view.MotionEvent.ACTION_CANCEL;
import static android.view.MotionEvent.ACTION_DOWN;
+import static android.view.MotionEvent.ACTION_UP;
-import static com.android.launcher3.config.FeatureFlags.ADAPTIVE_ICON_WINDOW_ANIM;
-import static com.android.launcher3.config.FeatureFlags.APPLY_CONFIG_AT_RUNTIME;
-import static com.android.launcher3.config.FeatureFlags.ENABLE_HINTS_IN_OVERVIEW;
import static com.android.launcher3.config.FeatureFlags.ENABLE_QUICKSTEP_LIVE_TILE;
-import static com.android.launcher3.config.FeatureFlags.FAKE_LANDSCAPE_UI;
-import static com.android.launcher3.config.FeatureFlags.QUICKSTEP_SPRINGS;
-import static com.android.launcher3.config.FeatureFlags.UNSTABLE_SPRINGS;
import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
import static com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR;
+import static com.android.quickstep.GestureState.DEFAULT_STATE;
import static com.android.systemui.shared.system.QuickStepContract.KEY_EXTRA_INPUT_MONITOR;
import static com.android.systemui.shared.system.QuickStepContract.KEY_EXTRA_SYSUI_PROXY;
-import static com.android.systemui.shared.system.RemoteAnimationTargetCompat.ACTIVITY_TYPE_ASSISTANT;
+import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_TRACING_ENABLED;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
+import android.app.PendingIntent;
+import android.app.RemoteAction;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
@@ -40,6 +39,7 @@
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Region;
+import android.graphics.drawable.Icon;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
@@ -48,6 +48,7 @@
import android.view.Choreographer;
import android.view.InputEvent;
import android.view.MotionEvent;
+import android.view.accessibility.AccessibilityManager;
import androidx.annotation.BinderThread;
import androidx.annotation.Nullable;
@@ -55,15 +56,18 @@
import androidx.annotation.WorkerThread;
import com.android.launcher3.BaseDraggingActivity;
+import com.android.launcher3.R;
import com.android.launcher3.Utilities;
-import com.android.launcher3.allapps.DiscoveryBounce;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.logging.UserEventDispatcher;
import com.android.launcher3.model.AppLaunchTracker;
import com.android.launcher3.provider.RestoreDbTask;
import com.android.launcher3.testing.TestLogging;
import com.android.launcher3.testing.TestProtocol;
+import com.android.launcher3.tracing.nano.LauncherTraceProto;
+import com.android.launcher3.tracing.nano.TouchInteractionServiceProto;
import com.android.launcher3.uioverrides.plugins.PluginManagerWrapper;
+import com.android.launcher3.util.OnboardingPrefs;
import com.android.launcher3.util.TraceHelper;
import com.android.quickstep.inputconsumers.AccessibilityInputConsumer;
import com.android.quickstep.inputconsumers.AssistantInputConsumer;
@@ -76,6 +80,8 @@
import com.android.quickstep.inputconsumers.ScreenPinnedInputConsumer;
import com.android.quickstep.util.ActiveGestureLog;
import com.android.quickstep.util.AssistantUtilities;
+import com.android.quickstep.util.ProtoTracer;
+import com.android.quickstep.views.RecentsView;
import com.android.systemui.plugins.OverscrollPlugin;
import com.android.systemui.plugins.PluginListener;
import com.android.systemui.shared.recents.IOverviewProxy;
@@ -85,6 +91,7 @@
import com.android.systemui.shared.system.InputConsumerController;
import com.android.systemui.shared.system.InputMonitorCompat;
import com.android.systemui.shared.system.RecentsAnimationListener;
+import com.android.systemui.shared.tracing.ProtoTraceable;
import java.io.FileDescriptor;
import java.io.PrintWriter;
@@ -113,7 +120,8 @@
* Service connected by system-UI for handling touch interaction.
*/
@TargetApi(Build.VERSION_CODES.Q)
-public class TouchInteractionService extends Service implements PluginListener<OverscrollPlugin> {
+public class TouchInteractionService extends Service implements PluginListener<OverscrollPlugin>,
+ ProtoTraceable<LauncherTraceProto> {
private static final String TAG = "TouchInteractionService";
@@ -121,6 +129,13 @@
private static final String NOTIFY_ACTION_BACK = "com.android.quickstep.action.BACK_GESTURE";
private static final String HAS_ENABLED_QUICKSTEP_ONCE = "launcher.has_enabled_quickstep_once";
private static final int MAX_BACK_NOTIFICATION_COUNT = 3;
+
+ /**
+ * System Action ID to show all apps. This ID should follow the ones in
+ * com.android.systemui.accessibility.SystemActions.
+ */
+ private static final int SYSTEM_ACTION_ID_ALL_APPS = 100;
+
private int mBackGestureNotificationCounter = -1;
@Nullable
private OverscrollPlugin mOverscrollPlugin;
@@ -136,16 +151,13 @@
TouchInteractionService.this.initInputMonitor();
preloadOverview(true /* fromInit */);
});
- if (TestProtocol.sDebugTracing) {
- Log.d(TestProtocol.LAUNCHER_DIDNT_INITIALIZE, "TIS initialized");
- }
sIsInitialized = true;
}
@BinderThread
@Override
public void onOverviewToggle() {
- TestLogging.recordEvent("onOverviewToggle");
+ TestLogging.recordEvent(TestProtocol.SEQUENCE_MAIN, "onOverviewToggle");
mOverviewCommandHelper.onOverviewToggle();
}
@@ -263,7 +275,7 @@
private InputConsumer mConsumer = InputConsumer.NO_OP;
private Choreographer mMainChoreographer;
private InputConsumer mResetGestureInputConsumer;
- private GestureState mGestureState = new GestureState();
+ private GestureState mGestureState = DEFAULT_STATE;
private InputMonitorCompat mInputMonitorCompat;
private InputEventReceiver mInputEventReceiver;
@@ -278,6 +290,7 @@
mDeviceState = new RecentsAnimationDeviceState(this);
mDeviceState.addNavigationModeChangedCallback(this::onNavigationModeChanged);
mDeviceState.runOnUserUnlocked(this::onUserUnlocked);
+ ProtoTracer.INSTANCE.get(this).add(this);
sConnected = true;
}
@@ -348,17 +361,9 @@
PluginManagerWrapper.INSTANCE.get(getBaseContext()).addPluginListener(this,
OverscrollPlugin.class, false /* allowMultiple */);
- }
- private void onDeferredActivityLaunch() {
- if (ENABLE_QUICKSTEP_LIVE_TILE.get()) {
- mOverviewComponentObserver.getActivityInterface().switchRunningTaskViewToScreenshot(
- null, () -> {
- mTaskAnimationManager.finishRunningRecentsAnimation(true /* toHome */);
- });
- } else {
- mTaskAnimationManager.finishRunningRecentsAnimation(true /* toHome */);
- }
+ mOverviewComponentObserver.setOverviewChangeListener(this::onOverviewTargetChange);
+ onOverviewTargetChange(mOverviewComponentObserver.isHomeAndOverviewSame());
}
private void resetHomeBounceSeenOnQuickstepEnabledFirstTime() {
@@ -373,17 +378,42 @@
if (!sharedPrefs.getBoolean(HAS_ENABLED_QUICKSTEP_ONCE, true)) {
sharedPrefs.edit()
.putBoolean(HAS_ENABLED_QUICKSTEP_ONCE, true)
- .putBoolean(DiscoveryBounce.HOME_BOUNCE_SEEN, false)
+ .putBoolean(OnboardingPrefs.HOME_BOUNCE_SEEN, false)
.apply();
}
}
+ private void onOverviewTargetChange(boolean isHomeAndOverviewSame) {
+ AccessibilityManager am = getSystemService(AccessibilityManager.class);
+
+ if (isHomeAndOverviewSame) {
+ Intent intent = new Intent(mOverviewComponentObserver.getHomeIntent())
+ .setAction(Intent.ACTION_ALL_APPS);
+ RemoteAction allAppsAction = new RemoteAction(
+ Icon.createWithResource(this, R.drawable.ic_apps),
+ getString(R.string.all_apps_label),
+ getString(R.string.all_apps_label),
+ PendingIntent.getActivity(this, SYSTEM_ACTION_ID_ALL_APPS, intent,
+ PendingIntent.FLAG_UPDATE_CURRENT));
+ am.registerSystemAction(allAppsAction, SYSTEM_ACTION_ID_ALL_APPS);
+ } else {
+ am.unregisterSystemAction(SYSTEM_ACTION_ID_ALL_APPS);
+ }
+ }
+
@UiThread
private void onSystemUiFlagsChanged() {
if (mDeviceState.isUserUnlocked()) {
SystemUiProxy.INSTANCE.get(this).setLastSystemUiStateFlags(
mDeviceState.getSystemUiStateFlags());
mOverviewComponentObserver.onSystemUiStateChanged();
+
+ // Update the tracing state
+ if ((mDeviceState.getSystemUiStateFlags() & SYSUI_STATE_TRACING_ENABLED) != 0) {
+ ProtoTracer.INSTANCE.get(TouchInteractionService.this).start();
+ } else {
+ ProtoTracer.INSTANCE.get(TouchInteractionService.this).stop();
+ }
}
}
@@ -397,9 +427,6 @@
@Override
public void onDestroy() {
- if (TestProtocol.sDebugTracing) {
- Log.d(TestProtocol.LAUNCHER_DIDNT_INITIALIZE, "TIS destroyed");
- }
sIsInitialized = false;
if (mDeviceState.isUserUnlocked()) {
mInputConsumer.unregisterInputConsumer();
@@ -409,6 +436,11 @@
disposeEventHandlers();
mDeviceState.destroy();
SystemUiProxy.INSTANCE.get(this).setProxy(null);
+ ProtoTracer.INSTANCE.get(TouchInteractionService.this).stop();
+ ProtoTracer.INSTANCE.get(this).remove(this);
+
+ getSystemService(AccessibilityManager.class)
+ .unregisterSystemAction(SYSTEM_ACTION_ID_ALL_APPS);
sConnected = false;
super.onDestroy();
@@ -428,51 +460,87 @@
Log.e(TAG, "Unknown event " + ev);
return;
}
+ MotionEvent event = (MotionEvent) ev;
+
+ TestLogging.recordMotionEvent(
+ TestProtocol.SEQUENCE_TIS, "TouchInteractionService.onInputEvent", event);
+
if (!mDeviceState.isUserUnlocked()) {
return;
}
Object traceToken = TraceHelper.INSTANCE.beginFlagsOverride(
TraceHelper.FLAG_ALLOW_BINDER_TRACKING);
- MotionEvent event = (MotionEvent) ev;
- if (event.getAction() == ACTION_DOWN) {
- GestureState newGestureState = new GestureState(mOverviewComponentObserver,
- ActiveGestureLog.INSTANCE.generateAndSetLogId());
- newGestureState.updateRunningTask(TraceHelper.whitelistIpcs("getRunningTask.0",
- () -> mAM.getRunningTask(0)));
+
+ final int action = event.getAction();
+ if (action == ACTION_DOWN) {
+ mDeviceState.setOrientationTransformIfNeeded(event);
+ GestureState newGestureState;
if (mDeviceState.isInSwipeUpTouchRegion(event)) {
+ // Clone the previous gesture state since onConsumerAboutToBeSwitched might trigger
+ // onConsumerInactive and wipe the previous gesture state
+ GestureState prevGestureState = new GestureState(mGestureState);
+ newGestureState = createGestureState();
mConsumer.onConsumerAboutToBeSwitched();
- mConsumer = newConsumer(mGestureState, newGestureState, event);
+ mConsumer = newConsumer(prevGestureState, newGestureState, event);
- ActiveGestureLog.INSTANCE.addLog("setInputConsumer", mConsumer.getType());
+ ActiveGestureLog.INSTANCE.addLog("setInputConsumer: " + mConsumer.getName());
mUncheckedConsumer = mConsumer;
} else if (mDeviceState.isUserUnlocked()
&& mDeviceState.isFullyGesturalNavMode()
&& mDeviceState.canTriggerAssistantAction(event)) {
+ newGestureState = createGestureState();
// Do not change mConsumer as if there is an ongoing QuickSwitch gesture, we should
// not interrupt it. QuickSwitch assumes that interruption can only happen if the
// next gesture is also quick switch.
- mUncheckedConsumer = new AssistantInputConsumer(this, newGestureState,
- InputConsumer.NO_OP, mInputMonitorCompat);
+ mUncheckedConsumer = new AssistantInputConsumer(
+ this,
+ newGestureState,
+ InputConsumer.NO_OP, mInputMonitorCompat,
+ mOverviewComponentObserver.assistantGestureIsConstrained());
} else {
+ newGestureState = DEFAULT_STATE;
mUncheckedConsumer = InputConsumer.NO_OP;
}
// Save the current gesture state
mGestureState = newGestureState;
+ } else {
+ // Other events
+ if (mUncheckedConsumer != InputConsumer.NO_OP) {
+ // Only transform the event if we are handling it in a proper consumer
+ mDeviceState.setOrientationTransformIfNeeded(event);
+ }
}
ActiveGestureLog.INSTANCE.addLog("onMotionEvent", event.getActionMasked());
+ boolean cleanUpConsumer = (action == ACTION_UP || action == ACTION_CANCEL)
+ && mConsumer != null
+ && !mConsumer.getActiveConsumerInHierarchy().isConsumerDetachedFromGesture();
mUncheckedConsumer.onMotionEvent(event);
+
+ if (cleanUpConsumer) {
+ reset();
+ }
TraceHelper.INSTANCE.endFlagsOverride(traceToken);
}
+ private GestureState createGestureState() {
+ GestureState gestureState = new GestureState(mOverviewComponentObserver,
+ ActiveGestureLog.INSTANCE.generateAndSetLogId());
+ gestureState.updateRunningTask(TraceHelper.whitelistIpcs("getRunningTask.0",
+ () -> mAM.getRunningTask(false /* filterOnlyVisibleRecents */)));
+ return gestureState;
+ }
+
private InputConsumer newConsumer(GestureState previousGestureState,
GestureState newGestureState, MotionEvent event) {
boolean canStartSystemGesture = mDeviceState.canStartSystemGesture();
if (!mDeviceState.isUserUnlocked()) {
+ Log.d(TAG, "User locked. Can start system gesture? " + canStartSystemGesture
+ + " sysUiFlags: " + mDeviceState.getSystemUiStateFlags());
if (canStartSystemGesture) {
// This handles apps launched in direct boot mode (e.g. dialer) as well as apps
// launched while device is locked even after exiting direct boot mode (e.g. camera).
@@ -488,17 +556,39 @@
|| previousGestureState.isRecentsAnimationRunning()
? newBaseConsumer(previousGestureState, newGestureState, event)
: mResetGestureInputConsumer;
+ // TODO(b/149880412): 2 button landscape mode is wrecked. Fixit!
+ if (mDeviceState.isGesturalNavMode()) {
+ handleOrientationSetup(base);
+ }
if (mDeviceState.isFullyGesturalNavMode()) {
if (mDeviceState.canTriggerAssistantAction(event)) {
- base = new AssistantInputConsumer(this, newGestureState, base, mInputMonitorCompat);
+ base = new AssistantInputConsumer(
+ this,
+ newGestureState,
+ base,
+ mInputMonitorCompat,
+ mOverviewComponentObserver.assistantGestureIsConstrained());
}
- if (FeatureFlags.ENABLE_QUICK_CAPTURE_GESTURE.get()
- && (mOverscrollPlugin != null)
- && mOverscrollPlugin.isActive()) {
- // Put the overscroll gesture as higher priority than the Assistant or base gestures
- base = new OverscrollInputConsumer(this, newGestureState, base, mInputMonitorCompat,
- mOverscrollPlugin);
+ if (FeatureFlags.ENABLE_QUICK_CAPTURE_GESTURE.get()) {
+ OverscrollPlugin plugin = null;
+ if (FeatureFlags.FORCE_LOCAL_OVERSCROLL_PLUGIN.get()) {
+ TaskOverlayFactory factory =
+ TaskOverlayFactory.INSTANCE.get(getApplicationContext());
+ plugin = factory.getLocalOverscrollPlugin(); // may be null
+ }
+
+ // If not local plugin was forced, use the actual overscroll plugin if available.
+ if (plugin == null && mOverscrollPlugin != null && mOverscrollPlugin.isActive()) {
+ plugin = mOverscrollPlugin;
+ }
+
+ if (plugin != null) {
+ // Put the overscroll gesture as higher priority than the Assistant or base
+ // gestures
+ base = new OverscrollInputConsumer(this, newGestureState, base,
+ mInputMonitorCompat, plugin);
+ }
}
if (mDeviceState.isScreenPinningActive()) {
@@ -519,6 +609,22 @@
return base;
}
+ private void handleOrientationSetup(InputConsumer baseInputConsumer) {
+ if (!FeatureFlags.ENABLE_FIXED_ROTATION_TRANSFORM.get()) {
+ return;
+ }
+ mDeviceState.enableMultipleRegions(baseInputConsumer instanceof OtherActivityInputConsumer);
+ BaseDraggingActivity activity =
+ mOverviewComponentObserver.getActivityInterface().getCreatedActivity();
+ if (activity == null || !(activity.getOverviewPanel() instanceof RecentsView)) {
+ return;
+ }
+ ((RecentsView) activity.getOverviewPanel())
+ .setLayoutRotation(mDeviceState.getCurrentActiveRotation(),
+ mDeviceState.getDisplayRotation());
+ activity.getDragLayer().recreateControllers();
+ }
+
private InputConsumer newBaseConsumer(GestureState previousGestureState,
GestureState gestureState, MotionEvent event) {
if (mDeviceState.isKeyguardShowingOccluded()) {
@@ -531,7 +637,7 @@
// In the case where we are in the excluded assistant state, ignore it and treat the
// running activity as the task behind the assistant
gestureState.updateRunningTask(TraceHelper.whitelistIpcs("getRunningTask.assistant",
- () -> mAM.getRunningTask(ACTIVITY_TYPE_ASSISTANT /* ignoreActivityType */)));
+ () -> mAM.getRunningTask(true /* filterOnlyVisibleRecents */)));
ComponentName homeComponent = mOverviewComponentObserver.getHomeIntent().getComponent();
ComponentName runningComponent =
gestureState.getRunningTask().baseIntent.getComponent();
@@ -572,11 +678,7 @@
if (!mOverviewComponentObserver.isHomeAndOverviewSame()) {
shouldDefer = previousGestureState.getFinishingRecentsAnimationTaskId() < 0;
- if (mDeviceState.isFullyGesturalNavMode()) {
- factory = mFallbackSwipeHandlerFactory;
- } else {
- factory = this::determineFallbackTwoButtonSwipeHandler;
- }
+ factory = mFallbackSwipeHandlerFactory;
} else {
shouldDefer = gestureState.getActivityInterface().deferStartingActivity(mDeviceState,
event);
@@ -589,23 +691,6 @@
mInputMonitorCompat, disableHorizontalSwipe, factory);
}
- /**
- * Determines whether to use the LauncherSwipeHandler or FallbackSwipeHandler at runtime.
- * We need to use the FallbackSwipeHandler to handle quick switch from home, otherwise the
- * normal LauncherSwipeHandler works.
- */
- private BaseSwipeUpHandler determineFallbackTwoButtonSwipeHandler(GestureState gestureState,
- long touchTimeMs, boolean continuingLastGesture, boolean isLikelyToStartNewTask) {
- boolean runningOverHome = gestureState.getRunningTask() == null
- || ActivityManagerWrapper.isHomeTask(gestureState.getRunningTask());
- boolean isQuickSwitchMode = isLikelyToStartNewTask || continuingLastGesture;
- BaseSwipeUpHandler.Factory factory = runningOverHome && isQuickSwitchMode
- ? mFallbackSwipeHandlerFactory
- : mLauncherSwipeHandlerFactory;
- return factory.newHandler(gestureState, touchTimeMs, continuingLastGesture,
- isLikelyToStartNewTask);
- }
-
private InputConsumer createDeviceLockedInputConsumer(GestureState gestureState) {
if (mDeviceState.isFullyGesturalNavMode() && gestureState.getRunningTask() != null) {
return new DeviceLockedInputConsumer(this, mDeviceState, mTaskAnimationManager,
@@ -637,15 +722,21 @@
}
/**
- * To be called by the consumer when it's no longer active.
+ * To be called by the consumer when it's no longer active. This can be called by any consumer
+ * in the hierarchy at any point during the gesture (ie. if a delegate consumer starts
+ * intercepting touches, the base consumer can try to call this).
*/
private void onConsumerInactive(InputConsumer caller) {
- if (mConsumer == caller) {
- mConsumer = mResetGestureInputConsumer;
- mUncheckedConsumer = mConsumer;
+ if (mConsumer != null && mConsumer.getActiveConsumerInHierarchy() == caller) {
+ reset();
}
}
+ private void reset() {
+ mConsumer = mUncheckedConsumer = mResetGestureInputConsumer;
+ mGestureState = new GestureState();
+ }
+
private void preloadOverview(boolean fromInit) {
if (!mDeviceState.isUserUnlocked()) {
return;
@@ -715,21 +806,29 @@
}
} else {
// Dump everything
+ FeatureFlags.dump(pw);
+ if (mDeviceState.isUserUnlocked()) {
+ PluginManagerWrapper.INSTANCE.get(getBaseContext()).dump(pw);
+ }
mDeviceState.dump(pw);
+ if (mOverviewComponentObserver != null) {
+ mOverviewComponentObserver.dump(pw);
+ }
+ if (mGestureState != null) {
+ mGestureState.dump(pw);
+ }
pw.println("TouchState:");
+ BaseDraggingActivity createdOverviewActivity = mOverviewComponentObserver == null ? null
+ : mOverviewComponentObserver.getActivityInterface().getCreatedActivity();
boolean resumed = mOverviewComponentObserver != null
&& mOverviewComponentObserver.getActivityInterface().isResumed();
+ pw.println(" createdOverviewActivity=" + createdOverviewActivity);
pw.println(" resumed=" + resumed);
pw.println(" mConsumer=" + mConsumer.getName());
- pw.println("FeatureFlags:");
- pw.println(" APPLY_CONFIG_AT_RUNTIME=" + APPLY_CONFIG_AT_RUNTIME.get());
- pw.println(" QUICKSTEP_SPRINGS=" + QUICKSTEP_SPRINGS.get());
- pw.println(" UNSTABLE_SPRINGS=" + UNSTABLE_SPRINGS.get());
- pw.println(" ADAPTIVE_ICON_WINDOW_ANIM=" + ADAPTIVE_ICON_WINDOW_ANIM.get());
- pw.println(" ENABLE_QUICKSTEP_LIVE_TILE=" + ENABLE_QUICKSTEP_LIVE_TILE.get());
- pw.println(" ENABLE_HINTS_IN_OVERVIEW=" + ENABLE_HINTS_IN_OVERVIEW.get());
- pw.println(" FAKE_LANDSCAPE_UI=" + FAKE_LANDSCAPE_UI.get());
ActiveGestureLog.INSTANCE.dump("", pw);
+ pw.println("ProtoTrace:");
+ pw.println(" file="
+ + ProtoTracer.INSTANCE.get(TouchInteractionService.this).getTraceFile());
}
}
@@ -760,7 +859,7 @@
protected boolean shouldNotifyBackGesture() {
return mBackGestureNotificationCounter > 0 &&
- mDeviceState.getGestureBlockedActivityPackage() != null;
+ !mDeviceState.getGestureBlockedActivityPackages().isEmpty();
}
@WorkerThread
@@ -769,8 +868,8 @@
mBackGestureNotificationCounter--;
Utilities.getDevicePrefs(this).edit()
.putInt(KEY_BACK_NOTIFICATION_COUNT, mBackGestureNotificationCounter).apply();
- sendBroadcast(new Intent(NOTIFY_ACTION_BACK).setPackage(
- mDeviceState.getGestureBlockedActivityPackage()));
+ mDeviceState.getGestureBlockedActivityPackages().forEach(blockedPackage ->
+ sendBroadcast(new Intent(NOTIFY_ACTION_BACK).setPackage(blockedPackage)));
}
}
@@ -788,4 +887,13 @@
public void onPluginDisconnected(OverscrollPlugin overscrollPlugin) {
mOverscrollPlugin = null;
}
+
+ @Override
+ public void writeToProto(LauncherTraceProto proto) {
+ if (proto.touchInteractionService == null) {
+ proto.touchInteractionService = new TouchInteractionServiceProto();
+ }
+ proto.touchInteractionService.serviceConnected = true;
+ proto.touchInteractionService.serviceConnected = true;
+ }
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/fallback/FallbackRecentsView.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/fallback/FallbackRecentsView.java
index 79e71a1..dc0c194 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/fallback/FallbackRecentsView.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/fallback/FallbackRecentsView.java
@@ -195,4 +195,9 @@
}
super.applyLoadPlan(tasks);
}
+
+ @Override
+ protected boolean supportsVerticalLandscape() {
+ return false;
+ }
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/fallback/RecentsRootView.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/fallback/RecentsRootView.java
index de5fd7c..7f5ec9b 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/fallback/RecentsRootView.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/fallback/RecentsRootView.java
@@ -21,7 +21,6 @@
import android.graphics.Rect;
import android.util.AttributeSet;
-import com.android.launcher3.BaseActivity;
import com.android.launcher3.R;
import com.android.launcher3.util.Themes;
import com.android.launcher3.util.TouchController;
@@ -31,13 +30,11 @@
public class RecentsRootView extends BaseDragLayer<RecentsActivity> {
private static final int MIN_SIZE = 10;
- private final RecentsActivity mActivity;
private final Point mLastKnownSize = new Point(MIN_SIZE, MIN_SIZE);
public RecentsRootView(Context context, AttributeSet attrs) {
super(context, attrs, 1 /* alphaChannelCount */);
- mActivity = BaseActivity.fromContext(context);
setSystemUiVisibility(SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| SYSTEM_UI_FLAG_LAYOUT_STABLE);
@@ -47,7 +44,8 @@
return mLastKnownSize;
}
- public void setup() {
+ @Override
+ public void recreateControllers() {
mControllers = new TouchController[] {
new RecentsTaskController(mActivity),
new FallbackNavBarTouchController(mActivity),
@@ -83,7 +81,8 @@
if (!insets.equals(mInsets)) {
super.setInsets(insets);
}
- setBackground(insets.top == 0 ? null
+ setBackground(insets.top == 0 || !mAllowSysuiScrims
+ ? null
: Themes.getAttrDrawable(getContext(), R.attr.workspaceStatusBarScrim));
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/AccessibilityInputConsumer.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/AccessibilityInputConsumer.java
index d3765c5..5ad48eb 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/AccessibilityInputConsumer.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/AccessibilityInputConsumer.java
@@ -31,8 +31,8 @@
import com.android.launcher3.R;
import com.android.quickstep.InputConsumer;
import com.android.quickstep.RecentsAnimationDeviceState;
-import com.android.quickstep.util.MotionPauseDetector;
import com.android.quickstep.SystemUiProxy;
+import com.android.quickstep.util.MotionPauseDetector;
import com.android.systemui.shared.system.InputMonitorCompat;
/**
@@ -117,9 +117,7 @@
if (pointerIndex == -1) {
break;
}
-
- mMotionPauseDetector.addPosition(ev.getY(pointerIndex) - mDownY,
- ev.getEventTime());
+ mMotionPauseDetector.addPosition(ev, pointerIndex);
}
break;
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/AssistantInputConsumer.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/AssistantInputConsumer.java
index 94126ff..89e6931 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/AssistantInputConsumer.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/AssistantInputConsumer.java
@@ -90,12 +90,18 @@
private final float mSquaredSlop;
private final Context mContext;
private final GestureDetector mGestureDetector;
+ private final boolean mIsAssistGestureConstrained;
- public AssistantInputConsumer(Context context, GestureState gestureState,
- InputConsumer delegate, InputMonitorCompat inputMonitor) {
+ public AssistantInputConsumer(
+ Context context,
+ GestureState gestureState,
+ InputConsumer delegate,
+ InputMonitorCompat inputMonitor,
+ boolean isAssistGestureConstrained) {
super(delegate, inputMonitor);
final Resources res = context.getResources();
mContext = context;
+ mIsAssistGestureConstrained = isAssistGestureConstrained;
mDragDistThreshold = res.getDimension(R.dimen.gestures_assistant_drag_threshold);
mFlingDistThreshold = res.getDimension(R.dimen.gestures_assistant_fling_threshold);
mTimeThreshold = res.getInteger(R.integer.assistant_gesture_min_time_threshold);
@@ -258,7 +264,8 @@
private class AssistantGestureListener extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
- if (isValidAssistantGestureAngle(velocityX, -velocityY)
+ if (!mIsAssistGestureConstrained
+ && isValidAssistantGestureAngle(velocityX, -velocityY)
&& mDistance >= mFlingDistThreshold
&& !mLaunchedAssistant
&& mState != STATE_DELEGATE_ACTIVE) {
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/DelegateInputConsumer.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/DelegateInputConsumer.java
index 8ae4f06..67a15a7 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/DelegateInputConsumer.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/DelegateInputConsumer.java
@@ -3,6 +3,7 @@
import android.view.MotionEvent;
import com.android.launcher3.testing.TestLogging;
+import com.android.launcher3.testing.TestProtocol;
import com.android.quickstep.InputConsumer;
import com.android.systemui.shared.system.InputMonitorCompat;
@@ -24,6 +25,14 @@
}
@Override
+ public InputConsumer getActiveConsumerInHierarchy() {
+ if (mState == STATE_ACTIVE) {
+ return this;
+ }
+ return mDelegate.getActiveConsumerInHierarchy();
+ }
+
+ @Override
public boolean allowInterceptByParent() {
return mDelegate.allowInterceptByParent() && mState != STATE_ACTIVE;
}
@@ -35,7 +44,7 @@
protected void setActive(MotionEvent ev) {
mState = STATE_ACTIVE;
- TestLogging.recordEvent("pilferPointers");
+ TestLogging.recordEvent(TestProtocol.SEQUENCE_PILFER, "pilferPointers");
mInputMonitor.pilferPointers();
// Send cancel event
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/DeviceLockedInputConsumer.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/DeviceLockedInputConsumer.java
index d01e1a4..7b8d40c 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/DeviceLockedInputConsumer.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/DeviceLockedInputConsumer.java
@@ -38,6 +38,7 @@
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.testing.TestLogging;
+import com.android.launcher3.testing.TestProtocol;
import com.android.launcher3.util.DefaultDisplay;
import com.android.quickstep.GestureState;
import com.android.quickstep.InputConsumer;
@@ -203,7 +204,7 @@
private void startRecentsTransition() {
mThresholdCrossed = true;
- TestLogging.recordEvent("pilferPointers");
+ TestLogging.recordEvent(TestProtocol.SEQUENCE_PILFER, "pilferPointers");
mInputMonitorCompat.pilferPointers();
Intent intent = new Intent(Intent.ACTION_MAIN)
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/OtherActivityInputConsumer.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/OtherActivityInputConsumer.java
index 1b0e05a..fe9ef2b 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/OtherActivityInputConsumer.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/OtherActivityInputConsumer.java
@@ -45,6 +45,7 @@
import com.android.launcher3.R;
import com.android.launcher3.testing.TestLogging;
+import com.android.launcher3.testing.TestProtocol;
import com.android.launcher3.util.Preconditions;
import com.android.launcher3.util.TraceHelper;
import com.android.quickstep.BaseActivityInterface;
@@ -58,6 +59,7 @@
import com.android.quickstep.util.ActiveGestureLog;
import com.android.quickstep.util.CachedEventDispatcher;
import com.android.quickstep.util.MotionPauseDetector;
+import com.android.quickstep.util.NavBarPosition;
import com.android.systemui.shared.system.ActivityManagerWrapper;
import com.android.systemui.shared.system.InputMonitorCompat;
@@ -76,6 +78,7 @@
public static final float QUICKSTEP_TOUCH_SLOP_RATIO = 3;
private final RecentsAnimationDeviceState mDeviceState;
+ private final NavBarPosition mNavBarPosition;
private final TaskAnimationManager mTaskAnimationManager;
private final GestureState mGestureState;
private RecentsAnimationCallbacks mActiveCallbacks;
@@ -125,13 +128,16 @@
Factory handlerFactory) {
super(base);
mDeviceState = deviceState;
+ mNavBarPosition = mDeviceState.getNavBarPosition();
mTaskAnimationManager = taskAnimationManager;
mGestureState = gestureState;
mMainThreadHandler = new Handler(Looper.getMainLooper());
mHandlerFactory = handlerFactory;
mActivityInterface = mGestureState.getActivityInterface();
- mMotionPauseDetector = new MotionPauseDetector(base);
+ mMotionPauseDetector = new MotionPauseDetector(base, false,
+ mNavBarPosition.isLeftEdge() || mNavBarPosition.isRightEdge()
+ ? MotionEvent.AXIS_X : MotionEvent.AXIS_Y);
mMotionPauseMinDisplacement = base.getResources().getDimension(
R.dimen.motion_pause_detector_min_displacement_from_app);
mOnCompleteCallback = onCompleteCallback;
@@ -154,6 +160,11 @@
return TYPE_OTHER_ACTIVITY;
}
+ @Override
+ public boolean isConsumerDetachedFromGesture() {
+ return true;
+ }
+
private void forceCancelGesture(MotionEvent ev) {
int action = ev.getAction();
ev.setAction(ACTION_CANCEL);
@@ -170,8 +181,8 @@
// Proxy events to recents view
if (mPassedWindowMoveSlop && mInteractionHandler != null
&& !mRecentsViewDispatcher.hasConsumer()) {
- mRecentsViewDispatcher.setConsumer(mInteractionHandler.getRecentsViewDispatcher(
- mDeviceState.getNavBarPosition().getRotationMode()));
+ mRecentsViewDispatcher.setConsumer(mInteractionHandler
+ .getRecentsViewDispatcher(mNavBarPosition.getRotation()));
}
int edgeFlags = ev.getEdgeFlags();
ev.setEdgeFlags(edgeFlags | EDGE_NAV_BAR);
@@ -284,7 +295,7 @@
if (mDeviceState.isFullyGesturalNavMode()) {
mMotionPauseDetector.setDisallowPause(upDist < mMotionPauseMinDisplacement
|| isLikelyToStartNewTask);
- mMotionPauseDetector.addPosition(displacement, ev.getEventTime());
+ mMotionPauseDetector.addPosition(ev);
mInteractionHandler.setIsLikelyToStartNewTask(isLikelyToStartNewTask);
}
}
@@ -303,7 +314,7 @@
if (mInteractionHandler == null) {
return;
}
- TestLogging.recordEvent("pilferPointers");
+ TestLogging.recordEvent(TestProtocol.SEQUENCE_PILFER, "pilferPointers");
mInputMonitorCompat.pilferPointers();
mActivityInterface.closeOverlay();
@@ -353,12 +364,11 @@
ViewConfiguration.get(this).getScaledMaximumFlingVelocity());
float velocityX = mVelocityTracker.getXVelocity(mActivePointerId);
float velocityY = mVelocityTracker.getYVelocity(mActivePointerId);
- float velocity = mDeviceState.getNavBarPosition().isRightEdge()
+ float velocity = mNavBarPosition.isRightEdge()
? velocityX
- : mDeviceState.getNavBarPosition().isLeftEdge()
+ : mNavBarPosition.isLeftEdge()
? -velocityX
: velocityY;
-
mInteractionHandler.updateDisplacement(getDisplacement(ev) - mStartDisplacement);
mInteractionHandler.onGestureEnded(velocity, new PointF(velocityX, velocityY),
mDownPos);
@@ -409,9 +419,9 @@
}
private float getDisplacement(MotionEvent ev) {
- if (mDeviceState.getNavBarPosition().isRightEdge()) {
+ if (mNavBarPosition.isRightEdge()) {
return ev.getX() - mDownPos.x;
- } else if (mDeviceState.getNavBarPosition().isLeftEdge()) {
+ } else if (mNavBarPosition.isLeftEdge()) {
return mDownPos.x - ev.getX();
} else {
return ev.getY() - mDownPos.y;
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/OverviewInputConsumer.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/OverviewInputConsumer.java
index 32a67ca..6bfabcd 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/OverviewInputConsumer.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/OverviewInputConsumer.java
@@ -26,6 +26,7 @@
import com.android.launcher3.BaseDraggingActivity;
import com.android.launcher3.Utilities;
import com.android.launcher3.testing.TestLogging;
+import com.android.launcher3.testing.TestProtocol;
import com.android.launcher3.views.BaseDragLayer;
import com.android.quickstep.BaseActivityInterface;
import com.android.quickstep.GestureState;
@@ -107,7 +108,7 @@
ActiveGestureLog.INSTANCE.addLog("startQuickstep");
}
if (mInputMonitor != null) {
- TestLogging.recordEvent("pilferPointers");
+ TestLogging.recordEvent(TestProtocol.SEQUENCE_PILFER, "pilferPointers");
mInputMonitor.pilferPointers();
}
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/OverviewWithoutFocusInputConsumer.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/OverviewWithoutFocusInputConsumer.java
index 6bfc3fd..ac1c3a8 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/OverviewWithoutFocusInputConsumer.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/OverviewWithoutFocusInputConsumer.java
@@ -23,6 +23,7 @@
import com.android.launcher3.BaseDraggingActivity;
import com.android.launcher3.logging.StatsLogUtils;
import com.android.launcher3.testing.TestLogging;
+import com.android.launcher3.testing.TestProtocol;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action.Direction;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action.Touch;
import com.android.quickstep.GestureState;
@@ -64,7 +65,7 @@
private void onInterceptTouch() {
if (mInputMonitor != null) {
- TestLogging.recordEvent("pilferPointers");
+ TestLogging.recordEvent(TestProtocol.SEQUENCE_PILFER, "pilferPointers");
mInputMonitor.pilferPointers();
}
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/ScreenPinnedInputConsumer.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/ScreenPinnedInputConsumer.java
index d5ed321..b9827ff 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/ScreenPinnedInputConsumer.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/ScreenPinnedInputConsumer.java
@@ -23,8 +23,8 @@
import com.android.launcher3.R;
import com.android.quickstep.GestureState;
import com.android.quickstep.InputConsumer;
-import com.android.quickstep.util.MotionPauseDetector;
import com.android.quickstep.SystemUiProxy;
+import com.android.quickstep.util.MotionPauseDetector;
/**
* An input consumer that detects swipe up and hold to exit screen pinning mode.
@@ -72,7 +72,7 @@
case MotionEvent.ACTION_MOVE:
float displacement = mTouchDownY - y;
mMotionPauseDetector.setDisallowPause(displacement < mMotionPauseMinDisplacement);
- mMotionPauseDetector.addPosition(y, ev.getEventTime());
+ mMotionPauseDetector.addPosition(ev);
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/logging/UserEventDispatcherAppPredictionExtension.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/logging/UserEventDispatcherAppPredictionExtension.java
index b251f9e..e000803 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/logging/UserEventDispatcherAppPredictionExtension.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/logging/UserEventDispatcherAppPredictionExtension.java
@@ -19,10 +19,12 @@
import androidx.annotation.NonNull;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.appprediction.PredictionUiStateManager;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.userevent.nano.LauncherLogProto;
+import java.util.ArrayList;
+
/**
* This class handles AOSP MetricsLogger function calls and logging around
* quickstep interactions and app launches.
@@ -41,7 +43,7 @@
@Override
protected void onFillInLogContainerData(
@NonNull ItemInfo itemInfo, @NonNull LauncherLogProto.Target target,
- @NonNull LauncherLogProto.Target targetParent) {
+ @NonNull ArrayList<LauncherLogProto.Target> targets) {
PredictionUiStateManager.fillInPredictedRank(itemInfo, target);
}
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/util/AppWindowAnimationHelper.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/util/AppWindowAnimationHelper.java
index 9e29238..75a5976 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/util/AppWindowAnimationHelper.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/util/AppWindowAnimationHelper.java
@@ -18,16 +18,19 @@
import static com.android.launcher3.config.FeatureFlags.ENABLE_QUICKSTEP_LIVE_TILE;
import static com.android.systemui.shared.system.QuickStepContract.getWindowCornerRadius;
import static com.android.systemui.shared.system.QuickStepContract.supportsRoundedCornersOnWindows;
+import static com.android.systemui.shared.system.RemoteAnimationTargetCompat.ACTIVITY_TYPE_HOME;
import static com.android.systemui.shared.system.RemoteAnimationTargetCompat.MODE_CLOSING;
import static com.android.systemui.shared.system.RemoteAnimationTargetCompat.MODE_OPENING;
import android.annotation.TargetApi;
import android.content.Context;
+import android.content.res.Resources;
import android.graphics.Matrix;
import android.graphics.Matrix.ScaleToFit;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Build;
+import android.view.Surface;
import androidx.annotation.Nullable;
@@ -60,28 +63,29 @@
private final Rect mSourceStackBounds = new Rect();
// The insets of the source app
private final Rect mSourceInsets = new Rect();
- // The source app bounds with the source insets applied, in the source app window coordinates
+ // The source app bounds with the source insets applied, in the device coordinates
private final RectF mSourceRect = new RectF();
- // The bounds of the task view in launcher window coordinates
+ // The bounds of the task view in device coordinates
private final RectF mTargetRect = new RectF();
+ // The bounds of the app window (between mSourceRect and mTargetRect) in device coordinates
+ private final RectF mCurrentRect = new RectF();
// The insets to be used for clipping the app window, which can be larger than mSourceInsets
// if the aspect ratio of the target is smaller than the aspect ratio of the source rect. In
// app window coordinates.
private final RectF mSourceWindowClipInsets = new RectF();
- // The insets to be used for clipping the app window. For live tile, we don't transform the clip
- // relative to the target rect.
- private final RectF mSourceWindowClipInsetsForLiveTile = new RectF();
+ // The clip rect in source app window coordinates. The app window surface will only be drawn
+ // within these bounds. This clip rect starts at the full mSourceStackBounds, and insets by
+ // mSourceWindowClipInsets as the transform progress goes to 1.
+ private final RectF mCurrentClipRectF = new RectF();
// The bounds of launcher (not including insets) in device coordinates
public final Rect mHomeStackBounds = new Rect();
-
- // The clip rect in source app window coordinates
- private final RectF mClipRectF = new RectF();
private final RectFEvaluator mRectFEvaluator = new RectFEvaluator();
private final Matrix mTmpMatrix = new Matrix();
private final Rect mTmpRect = new Rect();
private final RectF mTmpRectF = new RectF();
private final RectF mCurrentRectWithInsets = new RectF();
+ private RecentsOrientedState mOrientedState;
// Corner radius of windows, in pixels
private final float mWindowCornerRadius;
// Corner radius of windows when they're in overview mode.
@@ -100,20 +104,25 @@
private TargetAlphaProvider mTaskAlphaCallback = (t, a) -> a;
private TargetAlphaProvider mBaseAlphaCallback = (t, a) -> 1;
- public AppWindowAnimationHelper(Context context) {
- mWindowCornerRadius = getWindowCornerRadius(context.getResources());
- mSupportsRoundedCornersOnWindows = supportsRoundedCornersOnWindows(context.getResources());
+ public AppWindowAnimationHelper(RecentsOrientedState orientedState, Context context) {
+ Resources res = context.getResources();
+ mOrientedState = orientedState;
+ mWindowCornerRadius = getWindowCornerRadius(res);
+ mSupportsRoundedCornersOnWindows = supportsRoundedCornersOnWindows(res);
mTaskCornerRadius = TaskCornerRadius.get(context);
mUseRoundedCornersOnWindows = mSupportsRoundedCornersOnWindows;
}
+ public AppWindowAnimationHelper(Context context) {
+ this(null, context);
+ }
+
private void updateSourceStack(RemoteAnimationTargetCompat target) {
mSourceInsets.set(target.contentInsets);
- mSourceStackBounds.set(target.sourceContainerBounds);
+ mSourceStackBounds.set(target.screenSpaceBounds);
// TODO: Should sourceContainerBounds already have this offset?
mSourceStackBounds.offsetTo(target.position.x, target.position.y);
-
}
public void updateSource(Rect homeStackBounds, RemoteAnimationTargetCompat target) {
@@ -138,61 +147,88 @@
// from the source rect. The difference between the target rect (scaled to the
// source rect) is the amount to clip on each edge.
RectF scaledTargetRect = new RectF(mTargetRect);
- Utilities.scaleRectFAboutCenter(scaledTargetRect,
- mSourceRect.width() / mTargetRect.width());
+ float scale = getSrcToTargetScale();
+ Utilities.scaleRectFAboutCenter(scaledTargetRect, scale);
+
scaledTargetRect.offsetTo(mSourceRect.left, mSourceRect.top);
mSourceWindowClipInsets.set(
Math.max(scaledTargetRect.left, 0),
Math.max(scaledTargetRect.top, 0),
Math.max(mSourceStackBounds.width() - scaledTargetRect.right, 0),
Math.max(mSourceStackBounds.height() - scaledTargetRect.bottom, 0));
- mSourceWindowClipInsetsForLiveTile.set(mSourceWindowClipInsets);
mSourceRect.set(scaledTargetRect);
}
+ private float getSrcToTargetScale() {
+ if (mOrientedState == null ||
+ (mOrientedState.getDisplayRotation() == Surface.ROTATION_0
+ || mOrientedState.getDisplayRotation() == Surface.ROTATION_180)) {
+ return mSourceRect.width() / mTargetRect.width();
+ } else {
+ return mSourceRect.height() / mTargetRect.height();
+ }
+ }
+
public void prepareAnimation(DeviceProfile dp, boolean isOpening) {
mBoostModeTargetLayers = isOpening ? MODE_OPENING : MODE_CLOSING;
mUseRoundedCornersOnWindows = mSupportsRoundedCornersOnWindows && !dp.isMultiWindowMode;
}
public RectF applyTransform(TransformParams params) {
- SurfaceParams[] surfaceParams = getSurfaceParams(params);
+ SurfaceParams[] surfaceParams = computeSurfaceParams(params);
if (surfaceParams == null) {
return null;
}
- applySurfaceParams(params.syncTransactionApplier, surfaceParams);
- return params.currentRect;
+ applySurfaceParams(params.mSyncTransactionApplier, surfaceParams);
+ return mCurrentRect;
}
- public SurfaceParams[] getSurfaceParams(TransformParams params) {
- if (params.targetSet == null) {
+ /**
+ * Updates this AppWindowAnimationHelper's state based on the given TransformParams, and returns
+ * the SurfaceParams to apply via {@link SyncRtSurfaceTransactionApplierCompat#applyParams}.
+ */
+ public SurfaceParams[] computeSurfaceParams(TransformParams params) {
+ if (params.mTargetSet == null) {
return null;
}
- float progress = Utilities.boundToRange(params.progress, 0, 1);
+ float progress = Utilities.boundToRange(params.mProgress, 0, 1);
updateCurrentRect(params);
- SurfaceParams[] surfaceParams = new SurfaceParams[params.targetSet.unfilteredApps.length];
- for (int i = 0; i < params.targetSet.unfilteredApps.length; i++) {
- RemoteAnimationTargetCompat app = params.targetSet.unfilteredApps[i];
- mTmpMatrix.setTranslate(app.position.x, app.position.y);
+ SurfaceParams[] surfaceParams = new SurfaceParams[params.mTargetSet.unfilteredApps.length];
+ for (int i = 0; i < params.mTargetSet.unfilteredApps.length; i++) {
+ RemoteAnimationTargetCompat app = params.mTargetSet.unfilteredApps[i];
+ SurfaceParams.Builder builder = new SurfaceParams.Builder(app.leash);
+ if (app.localBounds != null) {
+ mTmpMatrix.setTranslate(0, 0);
+ if (app.activityType == ACTIVITY_TYPE_HOME && app.mode == MODE_CLOSING) {
+ mTmpMatrix.setTranslate(app.localBounds.left, app.localBounds.top);
+ }
+ } else {
+ mTmpMatrix.setTranslate(app.position.x, app.position.y);
+ }
+
Rect crop = mTmpRect;
- crop.set(app.sourceContainerBounds);
+ crop.set(app.screenSpaceBounds);
crop.offsetTo(0, 0);
float alpha;
- int layer = RemoteAnimationProvider.getLayer(app, mBoostModeTargetLayers);
float cornerRadius = 0f;
- float scale = Math.max(params.currentRect.width(), mTargetRect.width()) / crop.width();
- if (app.mode == params.targetSet.targetMode) {
- alpha = mTaskAlphaCallback.getAlpha(app, params.targetAlpha);
+ float scale = Math.max(mCurrentRect.width(), mTargetRect.width()) / crop.width();
+ int layer = RemoteAnimationProvider.getLayer(app, mBoostModeTargetLayers);
+ if (app.mode == params.mTargetSet.targetMode) {
+ alpha = mTaskAlphaCallback.getAlpha(app, params.mTargetAlpha);
if (app.activityType != RemoteAnimationTargetCompat.ACTIVITY_TYPE_HOME) {
- mTmpMatrix.setRectToRect(mSourceRect, params.currentRect, ScaleToFit.FILL);
- mTmpMatrix.postTranslate(app.position.x, app.position.y);
- mClipRectF.roundOut(crop);
+ mTmpMatrix.setRectToRect(mSourceRect, mCurrentRect, ScaleToFit.FILL);
+ if (app.localBounds != null) {
+ mTmpMatrix.postTranslate(app.localBounds.left, app.localBounds.top);
+ } else {
+ mTmpMatrix.postTranslate(app.position.x, app.position.y);
+ }
+ mCurrentClipRectF.roundOut(crop);
if (mSupportsRoundedCornersOnWindows) {
- if (params.cornerRadius > -1) {
- cornerRadius = params.cornerRadius;
- scale = params.currentRect.width() / crop.width();
+ if (params.mCornerRadius > -1) {
+ cornerRadius = params.mCornerRadius;
+ scale = mCurrentRect.width() / crop.width();
} else {
float windowCornerRadius = mUseRoundedCornersOnWindows
? mWindowCornerRadius : 0;
@@ -206,53 +242,63 @@
&& app.isNotInRecents) {
alpha = 1 - Interpolators.DEACCEL_2_5.getInterpolation(progress);
}
- } else if (params.targetSet.hasRecents) {
+ } else if (params.mTargetSet.hasRecents) {
// If home has a different target then recents, reverse anim the
// home target.
- alpha = 1 - (progress * params.targetAlpha);
+ alpha = 1 - (progress * params.mTargetAlpha);
}
} else {
alpha = mBaseAlphaCallback.getAlpha(app, progress);
- if (ENABLE_QUICKSTEP_LIVE_TILE.get() && params.launcherOnTop) {
+ if (ENABLE_QUICKSTEP_LIVE_TILE.get() && params.mLauncherOnTop) {
crop = null;
layer = Integer.MAX_VALUE;
}
}
-
- // Since radius is in Surface space, but we draw the rounded corners in screen space, we
- // have to undo the scale.
- surfaceParams[i] = new SurfaceParams(app.leash, alpha, mTmpMatrix, crop, layer,
- cornerRadius / scale);
+ builder.withAlpha(alpha)
+ .withMatrix(mTmpMatrix)
+ .withWindowCrop(crop)
+ .withLayer(layer)
+ // Since radius is in Surface space, but we draw the rounded corners in screen
+ // space, we have to undo the scale
+ .withCornerRadius(cornerRadius / scale);
+ surfaceParams[i] = builder.build();
}
return surfaceParams;
}
public RectF updateCurrentRect(TransformParams params) {
- float progress = params.progress;
- if (params.currentRect == null) {
- RectF currentRect;
+ if (params.mCurrentRect != null) {
+ mCurrentRect.set(params.mCurrentRect);
+ } else {
mTmpRectF.set(mTargetRect);
- Utilities.scaleRectFAboutCenter(mTmpRectF, params.offsetScale);
- currentRect = mRectFEvaluator.evaluate(progress, mSourceRect, mTmpRectF);
- currentRect.offset(params.offsetX, 0);
-
- // Don't clip past progress > 1.
- progress = Math.min(1, progress);
- final RectF sourceWindowClipInsets = params.forLiveTile
- ? mSourceWindowClipInsetsForLiveTile : mSourceWindowClipInsets;
- mClipRectF.left = sourceWindowClipInsets.left * progress;
- mClipRectF.top = sourceWindowClipInsets.top * progress;
- mClipRectF.right =
- mSourceStackBounds.width() - (sourceWindowClipInsets.right * progress);
- mClipRectF.bottom =
- mSourceStackBounds.height() - (sourceWindowClipInsets.bottom * progress);
- params.setCurrentRectAndTargetAlpha(currentRect, 1);
+ Utilities.scaleRectFAboutCenter(mTmpRectF, params.mOffsetScale);
+ mCurrentRect.set(mRectFEvaluator.evaluate(params.mProgress, mSourceRect, mTmpRectF));
+ if (mOrientedState == null || mOrientedState.areMultipleLayoutOrientationsDisabled()) {
+ mCurrentRect.offset(params.mOffset, 0);
+ } else {
+ int displayRotation = mOrientedState.getDisplayRotation();
+ mOrientedState.getOrientationHandler().offsetTaskRect(mCurrentRect,
+ params.mOffset, displayRotation);
+ }
}
- return params.currentRect;
+
+ updateClipRect(params);
+ return mCurrentRect;
+ }
+
+ private void updateClipRect(TransformParams params) {
+ // Don't clip past progress > 1.
+ float progress = Math.min(1, params.mProgress);
+ mCurrentClipRectF.left = mSourceWindowClipInsets.left * progress;
+ mCurrentClipRectF.top = mSourceWindowClipInsets.top * progress;
+ mCurrentClipRectF.right =
+ mSourceStackBounds.width() - (mSourceWindowClipInsets.right * progress);
+ mCurrentClipRectF.bottom =
+ mSourceStackBounds.height() - (mSourceWindowClipInsets.bottom * progress);
}
public RectF getCurrentRectWithInsets() {
- mTmpMatrix.mapRect(mCurrentRectWithInsets, mClipRectF);
+ mTmpMatrix.mapRect(mCurrentRectWithInsets, mCurrentClipRectF);
return mCurrentRectWithInsets;
}
@@ -335,7 +381,7 @@
* @return The source rect's scale and translation relative to the target rect.
*/
public LauncherState.ScaleAndTranslation getScaleAndTranslation() {
- float scale = mSourceRect.width() / mTargetRect.width();
+ float scale = getSrcToTargetScale();
float translationY = mSourceRect.centerY() - mSourceRect.top - mTargetRect.centerY();
return new LauncherState.ScaleAndTranslation(scale, 0, translationY);
}
@@ -384,75 +430,152 @@
}
public static class TransformParams {
- float progress;
- public float offsetX;
- public float offsetScale;
- public @Nullable RectF currentRect;
- float targetAlpha;
- boolean forLiveTile;
- float cornerRadius;
- boolean launcherOnTop;
-
- public RemoteAnimationTargets targetSet;
- public SyncRtSurfaceTransactionApplierCompat syncTransactionApplier;
+ private float mProgress;
+ private float mOffset;
+ private float mOffsetScale;
+ private @Nullable RectF mCurrentRect;
+ private float mTargetAlpha;
+ private float mCornerRadius;
+ private boolean mLauncherOnTop;
+ private RemoteAnimationTargets mTargetSet;
+ private SyncRtSurfaceTransactionApplierCompat mSyncTransactionApplier;
public TransformParams() {
- progress = 0;
- offsetX = 0;
- offsetScale = 1;
- currentRect = null;
- targetAlpha = 0;
- forLiveTile = false;
- cornerRadius = -1;
- launcherOnTop = false;
+ mProgress = 0;
+ mOffset = 0;
+ mOffsetScale = 1;
+ mCurrentRect = null;
+ mTargetAlpha = 1;
+ mCornerRadius = -1;
+ mLauncherOnTop = false;
}
+ /**
+ * Sets the progress of the transformation, where 0 is the source and 1 is the target. We
+ * automatically adjust properties such as currentRect and cornerRadius based on this
+ * progress, unless they are manually overridden by setting them on this TransformParams.
+ */
public TransformParams setProgress(float progress) {
- this.progress = progress;
- this.currentRect = null;
+ mProgress = progress;
return this;
}
+ /**
+ * Sets the corner radius of the transformed window, in pixels. If unspecified (-1), we
+ * simply interpolate between the window's corner radius to the task view's corner radius,
+ * based on {@link #mProgress}.
+ */
public TransformParams setCornerRadius(float cornerRadius) {
- this.cornerRadius = cornerRadius;
+ mCornerRadius = cornerRadius;
return this;
}
- public TransformParams setCurrentRectAndTargetAlpha(RectF currentRect, float targetAlpha) {
- this.currentRect = currentRect;
- this.targetAlpha = targetAlpha;
+ /**
+ * Sets the current rect to show the transformed window, in device coordinates. This gives
+ * the caller manual control of where to show the window. If unspecified (null), we
+ * interpolate between {@link AppWindowAnimationHelper#mSourceRect} and
+ * {@link AppWindowAnimationHelper#mTargetRect}, based on {@link #mProgress}.
+ */
+ public TransformParams setCurrentRect(RectF currentRect) {
+ mCurrentRect = currentRect;
return this;
}
- public TransformParams setOffsetX(float offsetX) {
- this.offsetX = offsetX;
+ /**
+ * Specifies the alpha of the transformed window. Default is 1.
+ */
+ public TransformParams setTargetAlpha(float targetAlpha) {
+ mTargetAlpha = targetAlpha;
return this;
}
+ /**
+ * If {@link #mCurrentRect} is null (i.e. {@link #setCurrentRect(RectF)} hasn't overridden
+ * the default), then offset the current rect by this amount after computing the rect based
+ * on {@link #mProgress}.
+ */
+ public TransformParams setOffset(float offset) {
+ mOffset = offset;
+ return this;
+ }
+
+ /**
+ * If {@link #mCurrentRect} is null (i.e. {@link #setCurrentRect(RectF)} hasn't overridden
+ * the default), then scale the current rect by this amount after computing the rect based
+ * on {@link #mProgress}.
+ */
public TransformParams setOffsetScale(float offsetScale) {
- this.offsetScale = offsetScale;
+ mOffsetScale = offsetScale;
return this;
}
- public TransformParams setForLiveTile(boolean forLiveTile) {
- this.forLiveTile = forLiveTile;
- return this;
- }
-
+ /**
+ * If true, sets the crop = null and layer = Integer.MAX_VALUE for targets that don't match
+ * {@link #mTargetSet}.targetMode. (Currently only does this when live tiles are enabled.)
+ */
public TransformParams setLauncherOnTop(boolean launcherOnTop) {
- this.launcherOnTop = launcherOnTop;
+ mLauncherOnTop = launcherOnTop;
return this;
}
+ /**
+ * Specifies the set of RemoteAnimationTargetCompats that are included in the transformation
+ * that these TransformParams help compute. These TransformParams generally only apply to
+ * the targetSet.apps which match the targetSet.targetMode (e.g. the MODE_CLOSING app when
+ * swiping to home).
+ */
public TransformParams setTargetSet(RemoteAnimationTargets targetSet) {
- this.targetSet = targetSet;
+ mTargetSet = targetSet;
return this;
}
+ /**
+ * Sets the SyncRtSurfaceTransactionApplierCompat that will apply the SurfaceParams that
+ * are computed based on these TransformParams.
+ */
public TransformParams setSyncTransactionApplier(
SyncRtSurfaceTransactionApplierCompat applier) {
- this.syncTransactionApplier = applier;
+ mSyncTransactionApplier = applier;
return this;
}
+
+ // Pubic getters so outside packages can read the values.
+
+ public float getProgress() {
+ return mProgress;
+ }
+
+ public float getOffset() {
+ return mOffset;
+ }
+
+ public float getOffsetScale() {
+ return mOffsetScale;
+ }
+
+ @Nullable
+ public RectF getCurrentRect() {
+ return mCurrentRect;
+ }
+
+ public float getTargetAlpha() {
+ return mTargetAlpha;
+ }
+
+ public float getCornerRadius() {
+ return mCornerRadius;
+ }
+
+ public boolean isLauncherOnTop() {
+ return mLauncherOnTop;
+ }
+
+ public RemoteAnimationTargets getTargetSet() {
+ return mTargetSet;
+ }
+
+ public SyncRtSurfaceTransactionApplierCompat getSyncTransactionApplier() {
+ return mSyncTransactionApplier;
+ }
}
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/util/ProtoTracer.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/util/ProtoTracer.java
new file mode 100644
index 0000000..190763a
--- /dev/null
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/util/ProtoTracer.java
@@ -0,0 +1,127 @@
+/*
+ * 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.quickstep.util;
+
+import static com.android.launcher3.tracing.nano.LauncherTraceFileProto.MagicNumber.MAGIC_NUMBER_H;
+import static com.android.launcher3.tracing.nano.LauncherTraceFileProto.MagicNumber.MAGIC_NUMBER_L;
+
+import android.content.Context;
+import android.os.SystemClock;
+
+import com.android.launcher3.tracing.nano.LauncherTraceProto;
+import com.android.launcher3.tracing.nano.LauncherTraceEntryProto;
+import com.android.launcher3.tracing.nano.LauncherTraceFileProto;
+import com.android.launcher3.util.MainThreadInitializedObject;
+import com.android.systemui.shared.tracing.FrameProtoTracer;
+import com.android.systemui.shared.tracing.FrameProtoTracer.ProtoTraceParams;
+import com.android.systemui.shared.tracing.ProtoTraceable;
+import com.google.protobuf.nano.MessageNano;
+
+import java.io.File;
+import java.io.FileDescriptor;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.Queue;
+
+
+/**
+ * Controller for coordinating winscope proto tracing.
+ */
+public class ProtoTracer implements ProtoTraceParams<MessageNano,
+ LauncherTraceFileProto, LauncherTraceEntryProto, LauncherTraceProto> {
+
+ public static final MainThreadInitializedObject<ProtoTracer> INSTANCE =
+ new MainThreadInitializedObject<>(ProtoTracer::new);
+
+ private static final String TAG = "ProtoTracer";
+ private static final long MAGIC_NUMBER_VALUE = ((long) MAGIC_NUMBER_H << 32) | MAGIC_NUMBER_L;
+
+ private final Context mContext;
+ private final FrameProtoTracer<MessageNano,
+ LauncherTraceFileProto, LauncherTraceEntryProto, LauncherTraceProto> mProtoTracer;
+
+ public ProtoTracer(Context context) {
+ mContext = context;
+ mProtoTracer = new FrameProtoTracer<>(this);
+ }
+
+ @Override
+ public File getTraceFile() {
+ return new File(mContext.getFilesDir(), "launcher_trace.pb");
+ }
+
+ @Override
+ public LauncherTraceFileProto getEncapsulatingTraceProto() {
+ return new LauncherTraceFileProto();
+ }
+
+ @Override
+ public LauncherTraceEntryProto updateBufferProto(LauncherTraceEntryProto reuseObj,
+ ArrayList<ProtoTraceable<LauncherTraceProto>> traceables) {
+ LauncherTraceEntryProto proto = reuseObj != null
+ ? reuseObj
+ : new LauncherTraceEntryProto();
+ proto.elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos();
+ proto.launcher = proto.launcher != null ? proto.launcher : new LauncherTraceProto();
+ for (ProtoTraceable t : traceables) {
+ t.writeToProto(proto.launcher);
+ }
+ return proto;
+ }
+
+ @Override
+ public byte[] serializeEncapsulatingProto(LauncherTraceFileProto encapsulatingProto,
+ Queue<LauncherTraceEntryProto> buffer) {
+ encapsulatingProto.magicNumber = MAGIC_NUMBER_VALUE;
+ encapsulatingProto.entry = buffer.toArray(new LauncherTraceEntryProto[0]);
+ return MessageNano.toByteArray(encapsulatingProto);
+ }
+
+ @Override
+ public byte[] getProtoBytes(MessageNano proto) {
+ return MessageNano.toByteArray(proto);
+ }
+
+ @Override
+ public int getProtoSize(MessageNano proto) {
+ return proto.getCachedSize();
+ }
+
+ public void start() {
+ mProtoTracer.start();
+ }
+
+ public void stop() {
+ mProtoTracer.stop();
+ }
+
+ public void add(ProtoTraceable<LauncherTraceProto> traceable) {
+ mProtoTracer.add(traceable);
+ }
+
+ public void remove(ProtoTraceable<LauncherTraceProto> traceable) {
+ mProtoTracer.remove(traceable);
+ }
+
+ public void scheduleFrameUpdate() {
+ mProtoTracer.scheduleFrameUpdate();
+ }
+
+ public void update() {
+ mProtoTracer.update();
+ }
+}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/util/RectFSpringAnim.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/util/RectFSpringAnim.java
index c6eafe6..dde7605 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/util/RectFSpringAnim.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/util/RectFSpringAnim.java
@@ -16,7 +16,7 @@
package com.android.quickstep.util;
import android.animation.Animator;
-import android.content.res.Resources;
+import android.content.Context;
import android.graphics.PointF;
import android.graphics.RectF;
@@ -28,6 +28,8 @@
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.anim.FlingSpringAnim;
+import com.android.launcher3.util.DynamicResource;
+import com.android.systemui.plugins.ResourceProvider;
import java.util.ArrayList;
import java.util.List;
@@ -103,7 +105,7 @@
private float mMinVisChange;
private float mYOvershoot;
- public RectFSpringAnim(RectF startRect, RectF targetRect, Resources resources) {
+ public RectFSpringAnim(RectF startRect, RectF targetRect, Context context) {
mStartRect = startRect;
mTargetRect = targetRect;
mCurrentCenterX = mStartRect.centerX();
@@ -111,8 +113,9 @@
mTrackingBottomY = startRect.bottom < targetRect.bottom;
mCurrentY = mTrackingBottomY ? mStartRect.bottom : mStartRect.top;
- mMinVisChange = resources.getDimensionPixelSize(R.dimen.swipe_up_fling_min_visible_change);
- mYOvershoot = resources.getDimensionPixelSize(R.dimen.swipe_up_y_overshoot);
+ ResourceProvider rp = DynamicResource.provider(context);
+ mMinVisChange = rp.getDimension(R.dimen.swipe_up_fling_min_visible_change);
+ mYOvershoot = rp.getDimension(R.dimen.swipe_up_y_overshoot);
}
public void onTargetPositionChanged() {
@@ -137,7 +140,12 @@
mAnimatorListeners.add(animatorListener);
}
- public void start(PointF velocityPxPerMs) {
+ /**
+ * Starts the fling/spring animation.
+ * @param context The activity context.
+ * @param velocityPxPerMs Velocity of swipe in px/ms.
+ */
+ public void start(Context context, PointF velocityPxPerMs) {
// Only tell caller that we ended if both x and y animations have ended.
OnAnimationEndListener onXEndListener = ((animation, canceled, centerX, velocityX) -> {
mRectXAnimEnded = true;
@@ -152,7 +160,7 @@
float endX = mTargetRect.centerX();
float minXValue = Math.min(startX, endX);
float maxXValue = Math.max(startX, endX);
- mRectXAnim = new FlingSpringAnim(this, RECT_CENTER_X, startX, endX,
+ mRectXAnim = new FlingSpringAnim(this, context, RECT_CENTER_X, startX, endX,
velocityPxPerMs.x * 1000, mMinVisChange, minXValue, maxXValue, 1f, onXEndListener);
float startVelocityY = velocityPxPerMs.y * 1000;
@@ -162,14 +170,18 @@
float endY = mTrackingBottomY ? mTargetRect.bottom : mTargetRect.top;
float minYValue = Math.min(startY, endY - mYOvershoot);
float maxYValue = Math.max(startY, endY);
- mRectYAnim = new FlingSpringAnim(this, RECT_Y, startY, endY, startVelocityY,
+ mRectYAnim = new FlingSpringAnim(this, context, RECT_Y, startY, endY, startVelocityY,
mMinVisChange, minYValue, maxYValue, springVelocityFactor, onYEndListener);
- float minVisibleChange = 1f / mStartRect.height();
+ float minVisibleChange = Math.abs(1f / mStartRect.height());
+ ResourceProvider rp = DynamicResource.provider(context);
+ float damping = rp.getFloat(R.dimen.swipe_up_rect_scale_damping_ratio);
+ float stiffness = rp.getFloat(R.dimen.swipe_up_rect_scale_stiffness);
+
mRectScaleAnim = new SpringAnimation(this, RECT_SCALE_PROGRESS)
.setSpring(new SpringForce(1f)
- .setDampingRatio(SpringForce.DAMPING_RATIO_LOW_BOUNCY)
- .setStiffness(SpringForce.STIFFNESS_LOW))
+ .setDampingRatio(damping)
+ .setStiffness(stiffness))
.setStartVelocity(velocityPxPerMs.y * minVisibleChange)
.setMaxValue(1f)
.setMinimumVisibleChange(minVisibleChange)
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/util/StaggeredWorkspaceAnim.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/util/StaggeredWorkspaceAnim.java
index babf13e..9cf45b3 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/util/StaggeredWorkspaceAnim.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/util/StaggeredWorkspaceAnim.java
@@ -18,8 +18,10 @@
import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_Y;
import static com.android.launcher3.LauncherState.BACKGROUND_APP;
import static com.android.launcher3.LauncherState.NORMAL;
-import static com.android.launcher3.LauncherStateManager.ANIM_ALL;
+import static com.android.launcher3.anim.Interpolators.ACCEL_DEACCEL;
import static com.android.launcher3.anim.Interpolators.LINEAR;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_ALL_COMPONENTS;
+import static com.android.launcher3.states.StateAnimationConfig.SKIP_OVERVIEW;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
@@ -32,16 +34,16 @@
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherState;
-import com.android.launcher3.LauncherStateManager;
-import com.android.launcher3.LauncherStateManager.AnimationConfig;
import com.android.launcher3.R;
import com.android.launcher3.ShortcutAndWidgetContainer;
import com.android.launcher3.Workspace;
-import com.android.launcher3.anim.AnimatorSetBuilder;
-import com.android.launcher3.anim.PropertySetter;
+import com.android.launcher3.anim.PendingAnimation;
import com.android.launcher3.anim.SpringAnimationBuilder;
import com.android.launcher3.graphics.OverviewScrim;
+import com.android.launcher3.states.StateAnimationConfig;
+import com.android.launcher3.util.DynamicResource;
import com.android.quickstep.views.RecentsView;
+import com.android.systemui.plugins.ResourceProvider;
/**
* Creates an animation where all the workspace items are moved into their final location,
@@ -55,9 +57,6 @@
private static final float MAX_VELOCITY_PX_PER_S = 22f;
- private static final float DAMPING_RATIO = 0.7f;
- private static final float STIFFNESS = 150f;
-
private final float mVelocity;
private final float mSpringTransY;
@@ -127,6 +126,8 @@
addScrimAnimationForState(launcher, NORMAL, ALPHA_DURATION_MS);
}
+ mAnimators.play(launcher.getDragLayer().getScrim().createSysuiMultiplierAnim(0f, 1f)
+ .setDuration(ALPHA_DURATION_MS));
mAnimators.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
@@ -144,17 +145,20 @@
* Setup workspace with 0 duration to prepare for our staggered animation.
*/
private void prepareToAnimate(Launcher launcher) {
- LauncherStateManager stateManager = launcher.getStateManager();
- AnimatorSetBuilder builder = new AnimatorSetBuilder();
+ StateAnimationConfig config = new StateAnimationConfig();
+ config.animFlags = ANIM_ALL_COMPONENTS | SKIP_OVERVIEW;
+ config.duration = 0;
// setRecentsAttachedToAppWindow() will animate recents out.
- builder.addFlag(AnimatorSetBuilder.FLAG_DONT_ANIMATE_OVERVIEW);
- stateManager.createAtomicAnimation(BACKGROUND_APP, NORMAL, builder, ANIM_ALL, 0);
- builder.build().start();
+ launcher.getStateManager().createAtomicAnimation(BACKGROUND_APP, NORMAL, config).start();
// Stop scrolling so that it doesn't interfere with the translation offscreen.
launcher.<RecentsView>getOverviewPanel().getScroller().forceFinished(true);
}
+ public AnimatorSet getAnimators() {
+ return mAnimators;
+ }
+
/**
* Starts the animation.
*/
@@ -177,9 +181,12 @@
v.setTranslationY(mSpringTransY);
+ ResourceProvider rp = DynamicResource.provider(v.getContext());
+ float stiffness = rp.getFloat(R.dimen.staggered_stiffness);
+ float damping = rp.getFloat(R.dimen.staggered_damping_ratio);
ObjectAnimator springTransY = new SpringAnimationBuilder<>(v, VIEW_TRANSLATE_Y)
- .setStiffness(STIFFNESS)
- .setDampingRatio(DAMPING_RATIO)
+ .setStiffness(stiffness)
+ .setDampingRatio(damping)
.setMinimumVisibleChange(1f)
.setEndValue(0)
.setStartVelocity(mVelocity)
@@ -196,16 +203,12 @@
}
private void addScrimAnimationForState(Launcher launcher, LauncherState state, long duration) {
- AnimatorSetBuilder scrimAnimBuilder = new AnimatorSetBuilder();
- AnimationConfig scrimAnimConfig = new AnimationConfig();
- scrimAnimConfig.duration = duration;
- PropertySetter scrimPropertySetter = scrimAnimConfig.getPropertySetter(scrimAnimBuilder);
- launcher.getWorkspace().getStateTransitionAnimation().setScrim(scrimPropertySetter, state);
- mAnimators.play(scrimAnimBuilder.build());
- Animator fadeOverviewScrim = ObjectAnimator.ofFloat(
- launcher.getDragLayer().getOverviewScrim(), OverviewScrim.SCRIM_PROGRESS,
- state.getOverviewScrimAlpha(launcher));
- fadeOverviewScrim.setDuration(duration);
- mAnimators.play(fadeOverviewScrim);
+ PendingAnimation builder = new PendingAnimation(duration, mAnimators);
+ launcher.getWorkspace().getStateTransitionAnimation().setScrim(builder, state);
+ builder.setFloat(
+ launcher.getDragLayer().getOverviewScrim(),
+ OverviewScrim.SCRIM_PROGRESS,
+ state.getOverviewScrimAlpha(launcher),
+ ACCEL_DEACCEL);
}
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/views/ClearAllButton.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/views/ClearAllButton.java
index 9db0c09..e455939 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/views/ClearAllButton.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/views/ClearAllButton.java
@@ -18,25 +18,25 @@
import android.content.Context;
import android.util.AttributeSet;
-import android.util.Property;
+import android.util.FloatProperty;
import android.widget.Button;
-import com.android.launcher3.Utilities;
+import com.android.launcher3.touch.PagedOrientationHandler;
import com.android.quickstep.views.RecentsView.PageCallbacks;
import com.android.quickstep.views.RecentsView.ScrollState;
public class ClearAllButton extends Button implements PageCallbacks {
- public static final Property<ClearAllButton, Float> VISIBILITY_ALPHA =
- new Property<ClearAllButton, Float>(Float.class, "visibilityAlpha") {
+ public static final FloatProperty<ClearAllButton> VISIBILITY_ALPHA =
+ new FloatProperty<ClearAllButton>("visibilityAlpha") {
@Override
public Float get(ClearAllButton view) {
return view.mVisibilityAlpha;
}
@Override
- public void set(ClearAllButton view, Float visibilityAlpha) {
- view.setVisibilityAlpha(visibilityAlpha);
+ public void setValue(ClearAllButton view, float v) {
+ view.setVisibilityAlpha(v);
}
};
@@ -44,21 +44,26 @@
private float mContentAlpha = 1;
private float mVisibilityAlpha = 1;
- private final boolean mIsRtl;
+ private boolean mIsRtl;
private int mScrollOffset;
+ private RecentsView mParent;
public ClearAllButton(Context context, AttributeSet attrs) {
super(context, attrs);
- mIsRtl = Utilities.isRtl(context.getResources());
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
+ mScrollOffset = mIsRtl ? mParent.getPaddingRight() / 2 : - mParent.getPaddingLeft() / 2;
+ }
- RecentsView parent = (RecentsView) getParent();
- mScrollOffset = mIsRtl ? parent.getPaddingRight() / 2 : - parent.getPaddingLeft() / 2;
+ @Override
+ protected void onAttachedToWindow() {
+ super.onAttachedToWindow();
+ mParent = (RecentsView) getParent();
+ mIsRtl = !mParent.getPagedOrientationHandler().getRecentsRtlSetting(getResources());
}
@Override
@@ -82,14 +87,16 @@
@Override
public void onPageScroll(ScrollState scrollState) {
- float width = getWidth();
- if (width == 0) {
+ PagedOrientationHandler orientationHandler = mParent.getPagedOrientationHandler();
+ float orientationSize = orientationHandler.getPrimaryValue(getWidth(), getHeight());
+ if (orientationSize == 0) {
return;
}
- float shift = Math.min(scrollState.scrollFromEdge, width);
- setTranslationX(mIsRtl ? (mScrollOffset - shift) : (mScrollOffset + shift));
- mScrollAlpha = 1 - shift / width;
+ float shift = Math.min(scrollState.scrollFromEdge, orientationSize);
+ float translation = mIsRtl ? (mScrollOffset - shift) : (mScrollOffset + shift);
+ orientationHandler.setPrimaryAndResetSecondaryTranslate(this, translation);
+ mScrollAlpha = 1 - shift / orientationSize;
updateAlpha();
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/views/LauncherRecentsView.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/views/LauncherRecentsView.java
index 1bbb3f5..98eb29a 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/views/LauncherRecentsView.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/views/LauncherRecentsView.java
@@ -19,7 +19,7 @@
import static com.android.launcher3.LauncherState.ALL_APPS_HEADER_EXTRA;
import static com.android.launcher3.LauncherState.NORMAL;
import static com.android.launcher3.LauncherState.OVERVIEW;
-import static com.android.launcher3.LauncherState.RECENTS_CLEAR_ALL_BUTTON;
+import static com.android.launcher3.LauncherState.OVERVIEW_BUTTONS;
import static com.android.launcher3.LauncherState.SPRING_LOADED;
import static com.android.launcher3.QuickstepAppTransitionManagerImpl.ALL_APPS_PROGRESS_OFF_SCREEN;
import static com.android.launcher3.allapps.AllAppsTransitionController.ALL_APPS_PROGRESS;
@@ -37,15 +37,17 @@
import android.view.View;
import android.widget.FrameLayout;
+import com.android.launcher3.BaseQuickstepLauncher;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.Hotseat;
-import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherState;
import com.android.launcher3.LauncherStateManager.StateListener;
-import com.android.launcher3.R;
import com.android.launcher3.anim.Interpolators;
import com.android.launcher3.appprediction.PredictionUiStateManager;
import com.android.launcher3.appprediction.PredictionUiStateManager.Client;
+import com.android.launcher3.config.FeatureFlags;
+import com.android.launcher3.statehandlers.DepthController;
+import com.android.launcher3.states.RotationHelper;
import com.android.launcher3.uioverrides.plugins.PluginManagerWrapper;
import com.android.launcher3.util.TraceHelper;
import com.android.launcher3.views.ScrimView;
@@ -60,7 +62,8 @@
* {@link RecentsView} used in Launcher activity
*/
@TargetApi(Build.VERSION_CODES.O)
-public class LauncherRecentsView extends RecentsView<Launcher> implements StateListener {
+public class LauncherRecentsView extends RecentsView<BaseQuickstepLauncher>
+ implements StateListener {
private static final Rect sTempRect = new Rect();
@@ -85,6 +88,10 @@
}
};
+ private RotationHelper.ForcedRotationChangedListener mForcedRotationChangedListener =
+ isForcedRotation -> LauncherRecentsView.this
+ .disableMultipleLayoutRotations(!isForcedRotation);
+
public LauncherRecentsView(Context context) {
this(context, null);
}
@@ -164,7 +171,7 @@
mActivity.getAllAppsController(), ALL_APPS_PROGRESS, allAppsProgressOffscreen));
ObjectAnimator dragHandleAnim = ObjectAnimator.ofInt(
- mActivity.findViewById(R.id.scrim_view), ScrimView.DRAG_HANDLE_ALPHA, 0);
+ mActivity.getScrimView(), ScrimView.DRAG_HANDLE_ALPHA, 0);
dragHandleAnim.setInterpolator(Interpolators.ACCEL_2);
anim.play(dragHandleAnim);
@@ -180,19 +187,21 @@
* @return The translationX to apply to this view so that the first task is just offscreen.
*/
public float getOffscreenTranslationX(float recentsScale) {
- float offscreenX = NORMAL.getOverviewScaleAndTranslation(mActivity).translationX;
+ LauncherState.ScaleAndTranslation overviewScaleAndTranslation =
+ NORMAL.getOverviewScaleAndTranslation(mActivity);
+ float offscreen = mOrientationHandler.getTranslationValue(overviewScaleAndTranslation);
// Offset since scale pushes tasks outwards.
getTaskSize(sTempRect);
- int taskWidth = sTempRect.width();
- offscreenX += taskWidth * (recentsScale - 1) / 2;
+ int taskSize = mOrientationHandler.getPrimarySize(sTempRect);
+ offscreen += taskSize * (recentsScale - 1) / 2;
if (mRunningTaskTileHidden) {
// The first task is hidden, so offset by its width.
- offscreenX -= (taskWidth + getPageSpacing()) * recentsScale;
+ offscreen -= (taskSize + getPageSpacing()) * recentsScale;
}
if (isRtl()) {
- offscreenX = -offscreenX;
+ offscreen = -offscreen;
}
- return offscreenX;
+ return offscreen;
}
@Override
@@ -200,8 +209,8 @@
if (ENABLE_QUICKSTEP_LIVE_TILE.get()) {
if (tv.isRunningTask()) {
mTransformParams.setProgress(1 - progress)
- .setSyncTransactionApplier(mSyncTransactionApplier)
- .setForLiveTile(true);
+ .setCurrentRect(null)
+ .setSyncTransactionApplier(mSyncTransactionApplier);
mAppWindowAnimationHelper.applyTransform(mTransformParams);
} else {
redrawLiveTile(true);
@@ -267,7 +276,8 @@
}
mTempRectF.set(mTempRect);
mTransformParams.setProgress(1f)
- .setCurrentRectAndTargetAlpha(mTempRectF, taskView.getAlpha())
+ .setCurrentRect(mTempRectF)
+ .setTargetAlpha(taskView.getAlpha())
.setSyncTransactionApplier(mSyncTransactionApplier)
.setTargetSet(mRecentsAnimationTargets)
.setLauncherOnTop(true);
@@ -276,6 +286,12 @@
}
@Override
+ protected boolean supportsVerticalLandscape() {
+ return FeatureFlags.ENABLE_FIXED_ROTATION_TRANSFORM.get()
+ && !mOrientationState.areMultipleLayoutOrientationsDisabled();
+ }
+
+ @Override
public void reset() {
super.reset();
@@ -306,7 +322,7 @@
if (enabled) {
LauncherState state = mActivity.getStateManager().getState();
boolean hasClearAllButton = (state.getVisibleElements(mActivity)
- & RECENTS_CLEAR_ALL_BUTTON) != 0;
+ & OVERVIEW_BUTTONS) != 0;
setDisallowScrollToClearAll(!hasClearAllButton);
}
}
@@ -328,6 +344,7 @@
super.onAttachedToWindow();
PluginManagerWrapper.INSTANCE.get(getContext()).addPluginListener(
mRecentsExtraCardPluginListener, RecentsExtraCard.class);
+ mActivity.getRotationHelper().addForcedRotationCallback(mForcedRotationChangedListener);
}
@Override
@@ -335,22 +352,23 @@
super.onDetachedFromWindow();
PluginManagerWrapper.INSTANCE.get(getContext()).removePluginListener(
mRecentsExtraCardPluginListener);
+ mActivity.getRotationHelper().removeForcedRotationCallback(mForcedRotationChangedListener);
}
@Override
- protected int computeMinScrollX() {
+ protected int computeMinScroll() {
if (canComputeScrollX() && !mIsRtl) {
return computeScrollX();
}
- return super.computeMinScrollX();
+ return super.computeMinScroll();
}
@Override
- protected int computeMaxScrollX() {
+ protected int computeMaxScroll() {
if (canComputeScrollX() && mIsRtl) {
return computeScrollX();
}
- return super.computeMaxScrollX();
+ return super.computeMaxScroll();
}
private boolean canComputeScrollX() {
@@ -389,4 +407,9 @@
mRecentsExtraViewContainer.setAlpha(alpha);
}
}
+
+ @Override
+ protected DepthController getDepthController() {
+ return mActivity.getDepthController();
+ }
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/views/OverviewActionsView.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/views/OverviewActionsView.java
new file mode 100644
index 0000000..6a37e2b
--- /dev/null
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/views/OverviewActionsView.java
@@ -0,0 +1,79 @@
+/*
+ * 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.quickstep.views;
+
+import android.content.Context;
+import android.util.AttributeSet;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.widget.FrameLayout;
+
+import androidx.annotation.Nullable;
+
+import com.android.launcher3.R;
+
+/**
+ * View for showing action buttons in Overview
+ */
+public class OverviewActionsView extends FrameLayout {
+
+ private final View mScreenshotButton;
+ private final View mShareButton;
+
+ /**
+ * Listener for taps on the various actions.
+ */
+ public interface Listener {
+ /** User has initiated the share actions. */
+ void onShare();
+
+ /** User has initiated the screenshot action. */
+ void onScreenshot();
+ }
+
+ public OverviewActionsView(Context context) {
+ this(context, null);
+ }
+
+ public OverviewActionsView(Context context, @Nullable AttributeSet attrs) {
+ this(context, attrs, 0);
+ }
+
+ public OverviewActionsView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
+ this(context, attrs, defStyleAttr, 0);
+ }
+
+ public OverviewActionsView(Context context, AttributeSet attrs, int defStyleAttr,
+ int defStyleRes) {
+ super(context, attrs, defStyleAttr, defStyleRes);
+ LayoutInflater.from(context).inflate(R.layout.overview_actions, this, true);
+ mShareButton = findViewById(R.id.action_share);
+ mScreenshotButton = findViewById(R.id.action_screenshot);
+ }
+
+ /**
+ * Set listener for callbacks on action button taps.
+ *
+ * @param listener for callbacks, or {@code null} to clear the listener.
+ */
+ public void setListener(@Nullable OverviewActionsView.Listener listener) {
+ mShareButton.setOnClickListener(
+ listener == null ? null : view -> listener.onShare());
+ mScreenshotButton.setOnClickListener(
+ listener == null ? null : view -> listener.onScreenshot());
+ }
+}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/views/RecentsView.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/views/RecentsView.java
index 321af6c..a18f7ba 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/views/RecentsView.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/views/RecentsView.java
@@ -16,13 +16,11 @@
package com.android.quickstep.views;
-import static androidx.dynamicanimation.animation.DynamicAnimation.MIN_VISIBLE_CHANGE_PIXELS;
-
import static com.android.launcher3.BaseActivity.STATE_HANDLER_INVISIBILITY_FLAGS;
import static com.android.launcher3.InvariantDeviceProfile.CHANGE_FLAG_ICON_PARAMS;
import static com.android.launcher3.LauncherAnimUtils.SCALE_PROPERTY;
-import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_X;
-import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_Y;
+import static com.android.launcher3.LauncherAnimUtils.VIEW_ALPHA;
+import static com.android.launcher3.LauncherState.BACKGROUND_APP;
import static com.android.launcher3.Utilities.EDGE_NAV_BAR;
import static com.android.launcher3.Utilities.squaredHypot;
import static com.android.launcher3.Utilities.squaredTouchSlop;
@@ -30,8 +28,11 @@
import static com.android.launcher3.anim.Interpolators.ACCEL_2;
import static com.android.launcher3.anim.Interpolators.FAST_OUT_SLOW_IN;
import static com.android.launcher3.anim.Interpolators.LINEAR;
+import static com.android.launcher3.config.FeatureFlags.ENABLE_OVERVIEW_ACTIONS;
import static com.android.launcher3.config.FeatureFlags.ENABLE_QUICKSTEP_LIVE_TILE;
-import static com.android.launcher3.config.FeatureFlags.UNSTABLE_SPRINGS;
+import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.TASK_DISMISS_SWIPE_UP;
+import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.TASK_LAUNCH_SWIPE_DOWN;
+import static com.android.launcher3.statehandlers.DepthController.DEPTH;
import static com.android.launcher3.uioverrides.touchcontrollers.TaskViewTouchController.SUCCESS_TRANSITION_PROGRESS;
import static com.android.launcher3.userevent.nano.LauncherLogProto.Action.Touch.TAP;
import static com.android.launcher3.userevent.nano.LauncherLogProto.ControlType.CLEAR_ALL_BUTTON;
@@ -39,12 +40,10 @@
import static com.android.launcher3.util.SystemUiController.UI_STATE_OVERVIEW;
import static com.android.quickstep.TaskUtils.checkCurrentOrManagedUserId;
-import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.LayoutTransition;
import android.animation.LayoutTransition.TransitionListener;
import android.animation.ObjectAnimator;
-import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.app.ActivityManager;
@@ -52,7 +51,6 @@
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
-import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
@@ -66,51 +64,67 @@
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.FloatProperty;
+import android.util.Property;
import android.util.SparseBooleanArray;
+import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
+import android.view.OrientationEventListener;
import android.view.View;
import android.view.ViewDebug;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
+import android.view.animation.Interpolator;
import android.widget.ListView;
import androidx.annotation.Nullable;
-import androidx.dynamicanimation.animation.SpringForce;
import com.android.launcher3.BaseActivity;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.Insettable;
+import com.android.launcher3.InsettableFrameLayout;
import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.LauncherState;
import com.android.launcher3.PagedView;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
+import com.android.launcher3.anim.AnimationSuccessListener;
import com.android.launcher3.anim.AnimatorPlaybackController;
+import com.android.launcher3.anim.PendingAnimation;
+import com.android.launcher3.anim.PendingAnimation.EndState;
import com.android.launcher3.anim.PropertyListBuilder;
-import com.android.launcher3.anim.SpringObjectAnimator;
+import com.android.launcher3.anim.SpringProperty;
+import com.android.launcher3.compat.AccessibilityManagerCompat;
import com.android.launcher3.config.FeatureFlags;
-import com.android.launcher3.graphics.RotationMode;
+import com.android.launcher3.statehandlers.DepthController;
+import com.android.launcher3.testing.TestProtocol;
+import com.android.launcher3.touch.PagedOrientationHandler;
+import com.android.launcher3.touch.PagedOrientationHandler.CurveProperties;
import com.android.launcher3.userevent.nano.LauncherLogProto;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action.Direction;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action.Touch;
import com.android.launcher3.util.ComponentKey;
+import com.android.launcher3.util.DynamicResource;
import com.android.launcher3.util.OverScroller;
-import com.android.launcher3.util.PendingAnimation;
import com.android.launcher3.util.Themes;
import com.android.launcher3.util.ViewPool;
import com.android.quickstep.RecentsAnimationController;
import com.android.quickstep.RecentsAnimationTargets;
import com.android.quickstep.RecentsModel;
import com.android.quickstep.RecentsModel.TaskVisualsChangeListener;
+import com.android.quickstep.SysUINavigationMode;
+import com.android.quickstep.SystemUiProxy;
import com.android.quickstep.TaskThumbnailCache;
import com.android.quickstep.TaskUtils;
import com.android.quickstep.ViewUtils;
import com.android.quickstep.util.AppWindowAnimationHelper;
import com.android.quickstep.util.LayoutUtils;
+import com.android.quickstep.util.RecentsOrientedState;
+import com.android.systemui.plugins.ResourceProvider;
+import com.android.systemui.shared.recents.IPinnedStackAnimationListener;
import com.android.systemui.shared.recents.model.Task;
import com.android.systemui.shared.recents.model.ThumbnailData;
import com.android.systemui.shared.system.ActivityManagerWrapper;
@@ -158,6 +172,10 @@
}
};
+ protected final RecentsOrientedState mOrientationState = new RecentsOrientedState();
+
+ private OrientationEventListener mOrientationListener;
+ private int mPreviousRotation;
protected RecentsAnimationController mRecentsAnimationController;
protected RecentsAnimationTargets mRecentsAnimationTargets;
protected AppWindowAnimationHelper mAppWindowAnimationHelper;
@@ -194,7 +212,7 @@
private boolean mDwbToastShown;
protected boolean mDisallowScrollToClearAll;
private boolean mOverlayEnabled;
- private boolean mFreezeViewVisibility;
+ protected boolean mFreezeViewVisibility;
/**
* TODO: Call reloadIdNeeded in onTaskStackChanged.
@@ -262,15 +280,11 @@
}
});
}
-
- @Override
- public void onPinnedStackAnimationStarted() {
- // Needed for activities that auto-enter PiP, which will not trigger a remote
- // animation to be created
- mActivity.clearForceInvisibleFlag(STATE_HANDLER_INVISIBILITY_FLAGS);
- }
};
+ private final PinnedStackAnimationListener mIPinnedStackAnimationListener =
+ new PinnedStackAnimationListener();
+
// Used to keep track of the last requested task list id, so that we do not request to load the
// tasks again if we have already requested it and the task list has not changed
private int mTaskListChangeId = -1;
@@ -314,6 +328,8 @@
// Keeps track of the index where the first TaskView should be
private int mTaskViewStartIndex = 0;
+ private View mActionsView;
+ private boolean mGestureRunning = false;
private BaseActivity.MultiWindowModeChangedListener mMultiWindowModeChangedListener =
(inMultiWindowMode) -> {
@@ -333,7 +349,8 @@
mActivity = (T) BaseActivity.fromContext(context);
mModel = RecentsModel.INSTANCE.get(context);
mIdp = InvariantDeviceProfile.INSTANCE.get(context);
- mTempAppWindowAnimationHelper = new AppWindowAnimationHelper(context);
+ mTempAppWindowAnimationHelper =
+ new AppWindowAnimationHelper(getPagedViewOrientedState(), context);
mClearAllButton = (ClearAllButton) LayoutInflater.from(context)
.inflate(R.layout.overview_clear_all_button, this, false);
@@ -341,7 +358,7 @@
mTaskViewPool = new ViewPool<>(context, this, R.layout.task, 20 /* max size */,
10 /* initial size */);
- mIsRtl = !Utilities.isRtl(getResources());
+ mIsRtl = mOrientationHandler.getRecentsRtlSetting(getResources());
setLayoutDirection(mIsRtl ? View.LAYOUT_DIRECTION_RTL : View.LAYOUT_DIRECTION_LTR);
mTaskTopMargin = getResources()
.getDimensionPixelSize(R.dimen.task_thumbnail_top_margin);
@@ -361,9 +378,26 @@
.getDimensionPixelSize(R.dimen.recents_empty_message_text_padding);
setWillNotDraw(false);
updateEmptyMessage();
+ disableMultipleLayoutRotations(!supportsVerticalLandscape());
// Initialize quickstep specific cache params here, as this is constructed only once
mActivity.getViewCache().setCacheSize(R.layout.digital_wellbeing_toast, 5);
+
+ mOrientationListener = new OrientationEventListener(getContext()) {
+ @Override
+ public void onOrientationChanged(int i) {
+ int rotation = RecentsOrientedState.getRotationForUserDegreesRotated(i);
+ if (mPreviousRotation != rotation) {
+ animateRecentsRotationInPlace(rotation);
+ if (rotation == 0) {
+ showActionsView();
+ } else {
+ hideActionsView();
+ }
+ mPreviousRotation = rotation;
+ }
+ }
+ };
}
public OverScroller getScroller() {
@@ -444,6 +478,10 @@
mSyncTransactionApplier = new SyncRtSurfaceTransactionApplierCompat(this);
RecentsModel.INSTANCE.get(getContext()).addThumbnailChangeListener(this);
mIdp.addOnChangeListener(this);
+ mIPinnedStackAnimationListener.setActivity(mActivity);
+ SystemUiProxy.INSTANCE.get(getContext()).setPinnedStackAnimationListener(
+ mIPinnedStackAnimationListener);
+ setActionsView();
}
@Override
@@ -456,6 +494,8 @@
mSyncTransactionApplier = null;
RecentsModel.INSTANCE.get(getContext()).removeThumbnailChangeListener(this);
mIdp.removeOnChangeListener(this);
+ SystemUiProxy.INSTANCE.get(getContext()).setPinnedStackAnimationListener(null);
+ mIPinnedStackAnimationListener.setActivity(null);
}
@Override
@@ -468,6 +508,29 @@
mHasVisibleTaskData.delete(taskView.getTask().key.id);
mTaskViewPool.recycle(taskView);
}
+ updateTaskStartIndex(child);
+ }
+
+ @Override
+ public void onViewAdded(View child) {
+ super.onViewAdded(child);
+ child.setAlpha(mContentAlpha);
+ // RecentsView is set to RTL in the constructor when system is using LTR. Here we set the
+ // child direction back to match system settings.
+ child.setLayoutDirection(mIsRtl ? View.LAYOUT_DIRECTION_LTR : View.LAYOUT_DIRECTION_RTL);
+ updateTaskStartIndex(child);
+ }
+
+ private void updateTaskStartIndex(View affectingView) {
+ if (!(affectingView instanceof TaskView) && !(affectingView instanceof ClearAllButton)) {
+ int childCount = getChildCount();
+
+ mTaskViewStartIndex = 0;
+ while (mTaskViewStartIndex < childCount
+ && !(getChildAt(mTaskViewStartIndex) instanceof TaskView)) {
+ mTaskViewStartIndex++;
+ }
+ }
}
public boolean isTaskViewVisible(TaskView tv) {
@@ -486,6 +549,15 @@
}
public void setOverviewStateEnabled(boolean enabled) {
+ if (supportsVerticalLandscape()
+ && !TestProtocol.sDisableSensorRotation // Ignore hardware dependency for tests
+ && mOrientationListener.canDetectOrientation()) {
+ if (enabled) {
+ mOrientationListener.enable();
+ } else {
+ mOrientationListener.disable();
+ }
+ }
mOverviewStateEnabled = enabled;
updateTaskStackListenerState();
if (!enabled) {
@@ -563,13 +635,20 @@
return isHandlingTouch() || shouldStealTouchFromSiblingsBelow(ev);
}
+ @Override
+ protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
+ // Enables swiping to the left or right only if the task overlay is not modal.
+ if (getCurrentPageTaskView() == null || !getCurrentPageTaskView().isTaskOverlayModal()) {
+ super.determineScrollingStart(ev, touchSlopScale);
+ }
+ }
protected boolean shouldStealTouchFromSiblingsBelow(MotionEvent ev) {
return true;
}
protected void applyLoadPlan(ArrayList<Task> tasks) {
if (mPendingAnimation != null) {
- mPendingAnimation.addEndListener((onEndListener) -> applyLoadPlan(tasks));
+ mPendingAnimation.addEndListener((endState) -> applyLoadPlan(tasks));
return;
}
@@ -589,6 +668,7 @@
if (getTaskViewCount() != requiredTaskCount) {
if (indexOfChild(mClearAllButton) != -1) {
removeView(mClearAllButton);
+ hideActionsView();
}
for (int i = getTaskViewCount(); i < requiredTaskCount; i++) {
addView(mTaskViewPool.getView());
@@ -598,6 +678,7 @@
}
if (requiredTaskCount > 0) {
addView(mClearAllButton);
+ showActionsView();
}
}
@@ -606,7 +687,7 @@
final int pageIndex = requiredTaskCount - i - 1 + mTaskViewStartIndex;
final Task task = tasks.get(i);
final TaskView taskView = (TaskView) getChildAt(pageIndex);
- taskView.bind(task);
+ taskView.bind(task, mOrientationState);
}
if (mNextPage == INVALID_PAGE) {
@@ -637,6 +718,7 @@
if (indexOfChild(mClearAllButton) != -1) {
removeView(mClearAllButton);
}
+ hideActionsView();
}
public int getTaskViewCount() {
@@ -647,6 +729,25 @@
return taskViewCount;
}
+ /**
+ * Updates UI for a modal task, including hiding other tasks.
+ */
+ public void updateUiForModalTask(TaskView taskView, boolean isTaskOverlayModal) {
+ int currentIndex = indexOfChild(taskView);
+ TaskView previousTask = getTaskViewAt(currentIndex - 1);
+ TaskView nextTask = getTaskViewAt(currentIndex + 1);
+ float alpha = isTaskOverlayModal ? 0.0f : 1.0f;
+ if (previousTask != null) {
+ previousTask.animate().alpha(alpha)
+ .translationX(isTaskOverlayModal ? previousTask.getWidth() / 2 : 0);
+ }
+ if (nextTask != null) {
+ nextTask.animate().alpha(alpha)
+ .translationX(isTaskOverlayModal ? -nextTask.getWidth() / 2 : 0);
+
+ }
+ }
+
protected void onTaskStackUpdated() { }
public void resetTaskVisuals() {
@@ -677,6 +778,9 @@
for (int i = 0; i < taskCount; i++) {
getTaskViewAt(i).setFullscreenProgress(mFullscreenProgress);
}
+ if (mActionsView != null) {
+ mActionsView.setVisibility(fullscreenProgress == 0 ? VISIBLE : INVISIBLE);
+ }
}
private void updateTaskStackListenerState() {
@@ -738,21 +842,15 @@
if (getPageCount() == 0 || getPageAt(0).getMeasuredWidth() == 0) {
return;
}
- int scrollX = getScrollX();
- final int halfPageWidth = getNormalChildWidth() / 2;
- final int screenCenter = mInsets.left + getPaddingLeft() + scrollX + halfPageWidth;
- final int halfScreenWidth = getMeasuredWidth() / 2;
- final int pageSpacing = mPageSpacing;
- mScrollState.scrollFromEdge = mIsRtl ? scrollX : (mMaxScrollX - scrollX);
+ mOrientationHandler.getCurveProperties(this, mInsets, mScrollState);
+ mScrollState.scrollFromEdge =
+ mIsRtl ? mScrollState.scroll : (mMaxScroll - mScrollState.scroll);
final int pageCount = getPageCount();
for (int i = 0; i < pageCount; i++) {
View page = getPageAt(i);
- float pageCenter = page.getLeft() + page.getTranslationX() + halfPageWidth;
- float distanceFromScreenCenter = screenCenter - pageCenter;
- float distanceToReachEdge = halfScreenWidth + halfPageWidth + pageSpacing;
- mScrollState.linearInterpolation = Math.min(1,
- Math.abs(distanceFromScreenCenter) / distanceToReachEdge);
+ mScrollState.updateInterpolation(mOrientationHandler.getChildStartWithTranslation(page),
+ mPageSpacing);
((PageCallbacks) page).onPageScroll(mScrollState);
}
}
@@ -882,6 +980,7 @@
setEnableDrawingLiveTile(false);
setRunningTaskHidden(true);
setRunningTaskIconScaledDown(true);
+ mGestureRunning = true;
}
/**
@@ -898,6 +997,43 @@
setSwipeDownShouldLaunchApp(true);
}
+ private void animateRecentsRotationInPlace(int newRotation) {
+ if (!supportsVerticalLandscape()) {
+ return;
+ }
+
+ AnimatorSet pa = setRecentsChangedOrientation(true);
+ pa.addListener(AnimationSuccessListener.forRunnable(() -> {
+ setLayoutRotation(newRotation, mOrientationState.getDisplayRotation());
+ mActivity.getDragLayer().recreateControllers();
+ rotateAllChildTasks();
+ setRecentsChangedOrientation(false).start();
+ }));
+ pa.start();
+ }
+
+ public AnimatorSet setRecentsChangedOrientation(boolean fadeInChildren) {
+ getRunningTaskIndex();
+ int runningIndex = getCurrentPage();
+ AnimatorSet as = new AnimatorSet();
+ for (int i = 0; i < getTaskViewCount(); i++) {
+ if (runningIndex == i) {
+ continue;
+ }
+ View taskView = getTaskViewAt(i);
+ as.play(ObjectAnimator.ofFloat(taskView, View.ALPHA, fadeInChildren ? 0 : 1));
+ }
+ return as;
+ }
+
+ abstract protected boolean supportsVerticalLandscape();
+
+ private void rotateAllChildTasks() {
+ for (int i = 0; i < getTaskViewCount(); i++) {
+ getTaskViewAt(i).setOrientationState(mOrientationState);
+ }
+ }
+
/**
* Called when a gesture from an app has finished.
*/
@@ -910,6 +1046,7 @@
}
setRunningTaskHidden(false);
animateUpRunningTaskIconScale();
+ mGestureRunning = false;
}
/**
@@ -926,6 +1063,7 @@
addView(taskView, mTaskViewStartIndex);
if (wasEmpty) {
addView(mClearAllButton);
+ showActionsView();
}
// The temporary running task is only used for the duration between the start of the
// gesture and the task list is loaded and applied
@@ -933,7 +1071,7 @@
new ComponentName(getContext(), getClass()), 0, 0), null, null, "", "", 0, 0,
false, true, false, false, new ActivityManager.TaskDescription(), 0,
new ComponentName("", ""), false);
- taskView.bind(mTmpRunningTask);
+ taskView.bind(mTmpRunningTask, mOrientationState);
}
boolean runningTaskTileHidden = mRunningTaskTileHidden;
@@ -972,6 +1110,10 @@
TaskView runningTask = getRunningTaskView();
if (runningTask != null) {
runningTask.setStableAlpha(isHidden ? 0 : mContentAlpha);
+ if (!isHidden) {
+ AccessibilityManagerCompat.sendCustomAccessibilityEvent(runningTask,
+ AccessibilityEvent.TYPE_VIEW_FOCUSED, null);
+ }
}
}
@@ -1079,7 +1221,7 @@
default void onPageScroll(ScrollState scrollState) {}
}
- public static class ScrollState {
+ public static class ScrollState extends CurveProperties {
/**
* The progress from 0 to 1, where 0 is the center
@@ -1091,6 +1233,17 @@
* The amount by which all the content is scrolled relative to the end of the list.
*/
public float scrollFromEdge;
+
+ /**
+ * Updates linearInterpolation for the provided child position
+ */
+ public void updateInterpolation(float childStart, int pageSpacing) {
+ float pageCenter = childStart + halfPageSize;
+ float distanceFromScreenCenter = screenCenter - pageCenter;
+ float distanceToReachEdge = halfScreenSize + halfPageSize + pageSpacing;
+ linearInterpolation = Math.min(1,
+ Math.abs(distanceFromScreenCenter) / distanceToReachEdge);
+ }
}
public void setIgnoreResetTask(int taskId) {
@@ -1103,30 +1256,31 @@
}
}
- private void addDismissedTaskAnimations(View taskView, AnimatorSet anim, long duration) {
- addAnim(ObjectAnimator.ofFloat(taskView, ALPHA, 0), duration, ACCEL_2, anim);
- if (UNSTABLE_SPRINGS.get() && taskView instanceof TaskView) {
- addAnim(new SpringObjectAnimator<>(taskView, VIEW_TRANSLATE_Y,
- MIN_VISIBLE_CHANGE_PIXELS, SpringForce.DAMPING_RATIO_MEDIUM_BOUNCY,
- SpringForce.STIFFNESS_MEDIUM,
- 0, -taskView.getHeight()),
- duration, LINEAR, anim);
- } else {
- addAnim(ObjectAnimator.ofFloat(taskView, TRANSLATION_Y, -taskView.getHeight()),
- duration, LINEAR, anim);
- }
+ private void addDismissedTaskAnimations(View taskView, long duration, PendingAnimation anim) {
+ // Use setFloat instead of setViewAlpha as we want to keep the view visible even when it's
+ // alpha is set to 0 so that it can be recycled in the view pool properly
+ anim.setFloat(taskView, VIEW_ALPHA, 0, ACCEL_2);
+ FloatProperty<View> secondaryViewTranslate =
+ mOrientationHandler.getSecondaryViewTranslate();
+ int secondaryTaskDimension = mOrientationHandler.getSecondaryDimension(taskView);
+ int verticalFactor = mOrientationHandler.getTaskDismissDirectionFactor();
+
+ ResourceProvider rp = DynamicResource.provider(mActivity);
+ SpringProperty sp = new SpringProperty(SpringProperty.FLAG_CAN_SPRING_ON_START)
+ .setDampingRatio(rp.getFloat(R.dimen.dismiss_task_trans_y_damping_ratio))
+ .setStiffness(rp.getFloat(R.dimen.dismiss_task_trans_y_stiffness));
+
+ anim.add(ObjectAnimator.ofFloat(taskView, secondaryViewTranslate,
+ verticalFactor * secondaryTaskDimension).setDuration(duration), LINEAR, sp);
}
- private void removeTask(Task task, int index, PendingAnimation.OnEndListener onEndListener,
- boolean shouldLog) {
- if (task != null) {
- ActivityManagerWrapper.getInstance().removeTask(task.key.id);
- if (shouldLog) {
- ComponentKey componentKey = TaskUtils.getLaunchComponentKeyForTask(task.key);
- mActivity.getUserEventDispatcher().logTaskLaunchOrDismiss(
- onEndListener.logAction, Direction.UP, index, componentKey);
- mActivity.getStatsLogManager().logTaskDismiss(this, componentKey);
- }
+ private void removeTask(TaskView taskView, int index, EndState endState) {
+ if (taskView.getTask() != null) {
+ ActivityManagerWrapper.getInstance().removeTask(taskView.getTask().key.id);
+ ComponentKey compKey = TaskUtils.getLaunchComponentKeyForTask(taskView.getTask().key);
+ mActivity.getUserEventDispatcher().logTaskLaunchOrDismiss(
+ endState.logAction, Direction.UP, index, compKey);
+ mActivity.getStatsLogManager().log(TASK_DISMISS_SWIPE_UP, taskView.buildProto());
}
}
@@ -1135,20 +1289,17 @@
if (mPendingAnimation != null) {
mPendingAnimation.finish(false, Touch.SWIPE);
}
- AnimatorSet anim = new AnimatorSet();
- PendingAnimation pendingAnimation = new PendingAnimation(anim);
+ PendingAnimation anim = new PendingAnimation(duration);
int count = getPageCount();
if (count == 0) {
- return pendingAnimation;
+ return anim;
}
int[] oldScroll = new int[count];
- getPageScrolls(oldScroll, false, SIMPLE_SCROLL_LOGIC);
-
int[] newScroll = new int[count];
+ getPageScrolls(oldScroll, false, SIMPLE_SCROLL_LOGIC);
getPageScrolls(newScroll, false, (v) -> v.getVisibility() != GONE && v != taskView);
-
int taskCount = getTaskViewCount();
int scrollDiffPerPage = 0;
if (count > 1) {
@@ -1161,7 +1312,7 @@
View child = getChildAt(i);
if (child == taskView) {
if (animateTaskView) {
- addDismissedTaskAnimations(taskView, anim, duration);
+ addDismissedTaskAnimations(taskView, duration, anim);
}
} else {
// If we just take newScroll - oldScroll, everything to the right of dragged task
@@ -1185,25 +1336,22 @@
}
int scrollDiff = newScroll[i] - oldScroll[i] + offset;
if (scrollDiff != 0) {
- if (UNSTABLE_SPRINGS.get() && child instanceof TaskView) {
- addAnim(new SpringObjectAnimator<>(child, VIEW_TRANSLATE_X,
- MIN_VISIBLE_CHANGE_PIXELS, SpringForce.DAMPING_RATIO_MEDIUM_BOUNCY,
- SpringForce.STIFFNESS_MEDIUM,
- 0, scrollDiff), duration, ACCEL, anim);
- } else {
- addAnim(ObjectAnimator.ofFloat(child, TRANSLATION_X, scrollDiff), duration,
- ACCEL, anim);
- }
+ Property translationProperty = mOrientationHandler.getPrimaryViewTranslate();
+ ResourceProvider rp = DynamicResource.provider(mActivity);
+ SpringProperty sp = new SpringProperty(SpringProperty.FLAG_CAN_SPRING_ON_END)
+ .setDampingRatio(
+ rp.getFloat(R.dimen.dismiss_task_trans_x_damping_ratio))
+ .setStiffness(rp.getFloat(R.dimen.dismiss_task_trans_x_stiffness));
+ anim.add(ObjectAnimator.ofFloat(child, translationProperty, scrollDiff)
+ .setDuration(duration), ACCEL, sp);
needsCurveUpdates = true;
}
}
}
if (needsCurveUpdates) {
- ValueAnimator va = ValueAnimator.ofFloat(0, 1);
- va.addUpdateListener((a) -> updateCurveProperties());
- anim.play(va);
+ anim.addOnFrameCallback(this::updateCurveProperties);
}
// Add a tiny bit of translation Z, so that it draws on top of other views
@@ -1211,22 +1359,23 @@
taskView.setTranslationZ(0.1f);
}
- mPendingAnimation = pendingAnimation;
- mPendingAnimation.addEndListener(new Consumer<PendingAnimation.OnEndListener>() {
+ mPendingAnimation = anim;
+ mPendingAnimation.addEndListener(new Consumer<EndState>() {
@Override
- public void accept(PendingAnimation.OnEndListener onEndListener) {
+ public void accept(EndState endState) {
if (ENABLE_QUICKSTEP_LIVE_TILE.get() &&
- taskView.isRunningTask() && onEndListener.isSuccess) {
- finishRecentsAnimation(true /* toHome */, () -> onEnd(onEndListener));
+ taskView.isRunningTask() && endState.isSuccess) {
+ finishRecentsAnimation(true /* toHome */, () -> onEnd(endState));
} else {
- onEnd(onEndListener);
+ onEnd(endState);
}
}
- private void onEnd(PendingAnimation.OnEndListener onEndListener) {
- if (onEndListener.isSuccess) {
+ @SuppressWarnings("WrongCall")
+ private void onEnd(EndState endState) {
+ if (endState.isSuccess) {
if (shouldRemoveTask) {
- removeTask(taskView.getTask(), draggedIndex, onEndListener, true);
+ removeTask(taskView, draggedIndex, endState);
}
int pageToSnapTo = mCurrentPage;
@@ -1234,37 +1383,40 @@
pageToSnapTo == (getTaskViewCount() - 1)) {
pageToSnapTo -= 1;
}
- removeView(taskView);
+ removeViewInLayout(taskView);
if (getTaskViewCount() == 0) {
- removeView(mClearAllButton);
+ removeViewInLayout(mClearAllButton);
+ hideActionsView();
startHome();
} else {
snapToPageImmediately(pageToSnapTo);
}
+ // Update the layout synchronously so that the position of next view is
+ // immediately available.
+ onLayout(false /* changed */, getLeft(), getTop(), getRight(), getBottom());
}
resetTaskVisuals();
mPendingAnimation = null;
}
});
- return pendingAnimation;
+ return anim;
}
public PendingAnimation createAllTasksDismissAnimation(long duration) {
- if (FeatureFlags.IS_DOGFOOD_BUILD && mPendingAnimation != null) {
+ if (FeatureFlags.IS_STUDIO_BUILD && mPendingAnimation != null) {
throw new IllegalStateException("Another pending animation is still running");
}
- AnimatorSet anim = new AnimatorSet();
- PendingAnimation pendingAnimation = new PendingAnimation(anim);
+ PendingAnimation anim = new PendingAnimation(duration);
int count = getTaskViewCount();
for (int i = 0; i < count; i++) {
- addDismissedTaskAnimations(getTaskViewAt(i), anim, duration);
+ addDismissedTaskAnimations(getTaskViewAt(i), duration, anim);
}
- mPendingAnimation = pendingAnimation;
- mPendingAnimation.addEndListener((onEndListener) -> {
- if (onEndListener.isSuccess) {
+ mPendingAnimation = anim;
+ mPendingAnimation.addEndListener((endState) -> {
+ if (endState.isSuccess) {
// Remove all the task views now
ActivityManagerWrapper.getInstance().removeAllRecentTasks();
removeTasksViewsAndClearAllButton();
@@ -1272,13 +1424,7 @@
}
mPendingAnimation = null;
});
- return pendingAnimation;
- }
-
- private static void addAnim(Animator anim, long duration,
- TimeInterpolator interpolator, AnimatorSet set) {
- anim.setDuration(duration).setInterpolator(interpolator);
- set.play(anim);
+ return anim;
}
private boolean snapToPageRelative(int pageCount, int delta, boolean cycle) {
@@ -1295,8 +1441,7 @@
}
private void runDismissAnimation(PendingAnimation pendingAnim) {
- AnimatorPlaybackController controller = AnimatorPlaybackController.wrap(
- pendingAnim.anim, DISMISS_TASK_DURATION);
+ AnimatorPlaybackController controller = pendingAnim.createPlaybackController();
controller.dispatchOnStart();
controller.setEndAction(() -> pendingAnim.finish(true, Touch.SWIPE));
controller.getAnimationPlayer().setInterpolator(FAST_OUT_SLOW_IN);
@@ -1382,15 +1527,17 @@
}
}
mClearAllButton.setContentAlpha(mContentAlpha);
-
int alphaInt = Math.round(alpha * 255);
mEmptyMessagePaint.setAlpha(alphaInt);
mEmptyIcon.setAlpha(alphaInt);
-
if (alpha > 0) {
setVisibility(VISIBLE);
+ if (!mGestureRunning) {
+ showActionsView();
+ }
} else if (!mFreezeViewVisibility) {
setVisibility(GONE);
+ hideActionsView();
}
}
@@ -1404,14 +1551,37 @@
if (!mFreezeViewVisibility) {
setVisibility(mContentAlpha > 0 ? VISIBLE : GONE);
+ if (mContentAlpha > 0) {
+ showActionsView();
+ } else {
+ hideActionsView();
+ }
}
}
}
- @Override
- public void onViewAdded(View child) {
- super.onViewAdded(child);
- child.setAlpha(mContentAlpha);
+ public void setLayoutRotation(int touchRotation, int displayRotation) {
+ if (mOrientationState.update(touchRotation, displayRotation)) {
+ mOrientationHandler = mOrientationState.getOrientationHandler();
+ mIsRtl = mOrientationHandler.getRecentsRtlSetting(getResources());
+ setLayoutDirection(mIsRtl ? View.LAYOUT_DIRECTION_RTL : View.LAYOUT_DIRECTION_LTR);
+ mClearAllButton.setRotation(mOrientationHandler.getDegreesRotated());
+ requestLayout();
+ }
+ }
+
+ public void disableMultipleLayoutRotations(boolean disable) {
+ mOrientationState.disableMultipleOrientations(disable);
+ mOrientationHandler = mOrientationState.getOrientationHandler();
+ requestLayout();
+ }
+
+ public RecentsOrientedState getPagedViewOrientedState() {
+ return mOrientationState;
+ }
+
+ public PagedOrientationHandler getPagedOrientationHandler() {
+ return mOrientationHandler;
}
@Nullable
@@ -1480,6 +1650,7 @@
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
+
updateEmptyStateUi(changed);
// Set the pivot points to match the task preview center
@@ -1594,20 +1765,20 @@
return anim;
}
- public PendingAnimation createTaskLauncherAnimation(TaskView tv, long duration) {
- if (FeatureFlags.IS_DOGFOOD_BUILD && mPendingAnimation != null) {
+ public PendingAnimation createTaskLaunchAnimation(
+ TaskView tv, long duration, Interpolator interpolator) {
+ if (FeatureFlags.IS_STUDIO_BUILD && mPendingAnimation != null) {
throw new IllegalStateException("Another pending animation is still running");
}
int count = getTaskViewCount();
if (count == 0) {
- return new PendingAnimation(new AnimatorSet());
+ return new PendingAnimation(duration);
}
int targetSysUiFlags = tv.getThumbnail().getSysUiStatusNavFlags();
final boolean[] passedOverviewThreshold = new boolean[] {false};
ValueAnimator progressAnim = ValueAnimator.ofFloat(0, 1);
- progressAnim.setInterpolator(LINEAR);
progressAnim.addUpdateListener(animator -> {
// Once we pass a certain threshold, update the sysui flags to match the target
// tasks' flags
@@ -1628,20 +1799,27 @@
}
});
- AppWindowAnimationHelper appWindowAnimationHelper = new AppWindowAnimationHelper(mActivity);
+ AppWindowAnimationHelper appWindowAnimationHelper = new AppWindowAnimationHelper(
+ getPagedViewOrientedState(), mActivity);
appWindowAnimationHelper.fromTaskThumbnailView(tv.getThumbnail(), this);
appWindowAnimationHelper.prepareAnimation(mActivity.getDeviceProfile(), true /* isOpening */);
AnimatorSet anim = createAdjacentPageAnimForTaskLaunch(tv, appWindowAnimationHelper);
+
+ DepthController depthController = getDepthController();
+ if (depthController != null) {
+ ObjectAnimator depthAnimator = ObjectAnimator.ofFloat(depthController, DEPTH,
+ BACKGROUND_APP.getDepth(mActivity));
+ anim.play(depthAnimator);
+ }
anim.play(progressAnim);
- anim.setDuration(duration);
+ anim.setDuration(duration).setInterpolator(interpolator);
- Consumer<Boolean> onTaskLaunchFinish = this::onTaskLaunched;
-
- mPendingAnimation = new PendingAnimation(anim);
- mPendingAnimation.addEndListener((onEndListener) -> {
- if (onEndListener.isSuccess) {
+ mPendingAnimation = new PendingAnimation(duration);
+ mPendingAnimation.add(anim);
+ mPendingAnimation.addEndListener((endState) -> {
+ if (endState.isSuccess) {
Consumer<Boolean> onLaunchResult = (result) -> {
- onTaskLaunchFinish.accept(result);
+ onTaskLaunched(result);
if (!result) {
tv.notifyTaskLaunchFailed(TAG);
}
@@ -1650,11 +1828,13 @@
Task task = tv.getTask();
if (task != null) {
mActivity.getUserEventDispatcher().logTaskLaunchOrDismiss(
- onEndListener.logAction, Direction.DOWN, indexOfChild(tv),
+ endState.logAction, Direction.DOWN, indexOfChild(tv),
TaskUtils.getLaunchComponentKeyForTask(task.key));
+ mActivity.getStatsLogManager().log(TASK_LAUNCH_SWIPE_DOWN, tv.buildProto()
+ );
}
} else {
- onTaskLaunchFinish.accept(false);
+ onTaskLaunched(false);
}
mPendingAnimation = null;
});
@@ -1785,7 +1965,7 @@
}
@Override
- protected int computeMinScrollX() {
+ protected int computeMinScroll() {
if (getTaskViewCount() > 0) {
if (mDisallowScrollToClearAll) {
// We aren't showing the clear all button,
@@ -1800,11 +1980,11 @@
}
return getScrollForPage(mTaskViewStartIndex);
}
- return super.computeMinScrollX();
+ return super.computeMinScroll();
}
@Override
- protected int computeMaxScrollX() {
+ protected int computeMaxScroll() {
if (getTaskViewCount() > 0) {
if (mDisallowScrollToClearAll) {
// We aren't showing the clear all button,
@@ -1819,7 +1999,7 @@
}
return getScrollForPage(indexOfChild(getTaskViewAt(getTaskViewCount() - 1)) + 1);
}
- return super.computeMaxScrollX();
+ return super.computeMaxScroll();
}
public ClearAllButton getClearAllButton() {
@@ -1834,31 +2014,37 @@
return 0;
}
int startScroll = getScrollForPage(getRunningTaskIndex());
- int offsetX = startScroll - getScrollX();
- offsetX *= getScaleX();
+ int offsetX = startScroll - mOrientationHandler.getPrimaryScroll(this);
+ offsetX *= mOrientationHandler.getPrimaryScale(this);
return offsetX;
}
- public Consumer<MotionEvent> getEventDispatcher(RotationMode rotationMode) {
- if (rotationMode.isTransposed) {
- Matrix transform = new Matrix();
- transform.setRotate(-rotationMode.surfaceRotation);
-
- if (getWidth() > 0 && getHeight() > 0) {
- float scale = ((float) getWidth()) / getHeight();
- transform.postScale(scale, 1 / scale);
- }
-
- Matrix inverse = new Matrix();
- transform.invert(inverse);
- return e -> {
- e.transform(transform);
- super.onTouchEvent(e);
- e.transform(inverse);
- };
+ public Consumer<MotionEvent> getEventDispatcher(float navbarRotation) {
+ float degreesRotated;
+ if (navbarRotation == 0) {
+ degreesRotated = mOrientationState.getTouchRotationDegrees();
} else {
+ degreesRotated = -navbarRotation;
+ }
+ if (degreesRotated == 0) {
return super::onTouchEvent;
}
+
+ // At this point the event coordinates have already been transformed, so we need to
+ // undo that transformation since PagedView also accommodates for the transformation via
+ // PagedOrientationHandler
+ return e -> {
+ if (navbarRotation != 0
+ && !mOrientationState.areMultipleLayoutOrientationsDisabled()) {
+ mOrientationState.flipVertical(e);
+ super.onTouchEvent(e);
+ mOrientationState.flipVertical(e);
+ return;
+ }
+ mOrientationState.transformEvent(-degreesRotated, e, true);
+ super.onTouchEvent(e);
+ mOrientationState.transformEvent(-degreesRotated, e, false);
+ };
}
public AppWindowAnimationHelper getClipAnimationHelper() {
@@ -1905,30 +2091,9 @@
}
}
- @Override
- public void addView(View child, int index) {
- // RecentsView is set to RTL in the constructor when system is using LTR. Here we set the
- // child direction back to match system settings.
- child.setLayoutDirection(
- Utilities.isRtl(getResources())
- ? View.LAYOUT_DIRECTION_RTL : View.LAYOUT_DIRECTION_LTR);
- super.addView(child, index);
- if (isExtraCardView(child, index)) {
- mTaskViewStartIndex++;
- }
- }
-
- @Override
- public void removeView(View view) {
- if (isExtraCardView(view, indexOfChild(view))) {
- mTaskViewStartIndex--;
- }
- super.removeView(view);
- }
-
- private boolean isExtraCardView(View view, int index) {
- return !(view instanceof TaskView) && !(view instanceof ClearAllButton)
- && index <= mTaskViewStartIndex;
+ @Nullable
+ protected DepthController getDepthController() {
+ return null;
}
/**
@@ -1941,4 +2106,52 @@
/** @param isEmpty Whether RecentsView is empty (i.e. has no children) */
void onEmptyMessageUpdated(boolean isEmpty);
}
+
+ private static class PinnedStackAnimationListener<T extends BaseActivity> extends
+ IPinnedStackAnimationListener.Stub {
+ private T mActivity;
+
+ public void setActivity(T activity) {
+ mActivity = activity;
+ }
+
+ @Override
+ public void onPinnedStackAnimationStarted() {
+ // Needed for activities that auto-enter PiP, which will not trigger a remote
+ // animation to be created
+ mActivity.clearForceInvisibleFlag(STATE_HANDLER_INVISIBILITY_FLAGS);
+ }
+ }
+
+ private void showActionsView() {
+ if (mActionsView != null && getTaskViewCount() > 0) {
+ mActionsView.setVisibility(VISIBLE);
+ }
+ }
+
+ private void hideActionsView() {
+ if (mActionsView != null) {
+ mActionsView.setVisibility(GONE);
+ }
+ }
+
+ private void setActionsView() {
+ if (mActionsView == null && ENABLE_OVERVIEW_ACTIONS.get()
+ && SysUINavigationMode.removeShelfFromOverview(mActivity)) {
+ mActionsView = ((ViewGroup) getParent()).findViewById(R.id.overview_actions_view);
+ if (mActionsView != null) {
+ InsettableFrameLayout.LayoutParams layoutParams =
+ new InsettableFrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,
+ getResources().getDimensionPixelSize(
+ R.dimen.overview_actions_height));
+ layoutParams.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
+ int margin = getResources().getDimensionPixelSize(
+ R.dimen.overview_actions_horizontal_margin);
+ layoutParams.setMarginStart(margin);
+ layoutParams.setMarginEnd(margin);
+ mActionsView.setLayoutParams(layoutParams);
+ showActionsView();
+ }
+ }
+ }
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/views/TaskThumbnailView.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/views/TaskThumbnailView.java
index 49f667e..178ff32 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/views/TaskThumbnailView.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/views/TaskThumbnailView.java
@@ -36,6 +36,7 @@
import android.graphics.Shader;
import android.util.AttributeSet;
import android.util.FloatProperty;
+import android.util.Log;
import android.util.Property;
import android.view.Surface;
import android.view.View;
@@ -54,6 +55,7 @@
import com.android.systemui.plugins.PluginListener;
import com.android.systemui.shared.recents.model.Task;
import com.android.systemui.shared.recents.model.ThumbnailData;
+import com.android.systemui.shared.system.ConfigurationCompat;
/**
* A task in the Recents view.
@@ -357,7 +359,8 @@
final float thumbnailScale;
int thumbnailRotation = mThumbnailData.rotation;
- int currentRotation = getDisplay() != null ? getDisplay().getRotation() : 0;
+ int currentRotation = ConfigurationCompat.getWindowConfigurationRotation(
+ getResources().getConfiguration());
int deltaRotate = getRotationDelta(currentRotation, thumbnailRotation);
// Landscape vs portrait change
boolean windowingModeSupportsRotation = !mActivity.isInMultiWindowMode()
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/views/TaskView.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/views/TaskView.java
index 294bb7b..470b720 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/views/TaskView.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/views/TaskView.java
@@ -16,13 +16,20 @@
package com.android.quickstep.views;
+import static android.view.Gravity.BOTTOM;
+import static android.view.Gravity.CENTER_HORIZONTAL;
+import static android.view.Gravity.CENTER_VERTICAL;
+import static android.view.Gravity.END;
+import static android.view.Gravity.START;
+import static android.view.Gravity.TOP;
import static android.widget.Toast.LENGTH_SHORT;
import static com.android.launcher3.QuickstepAppTransitionManagerImpl.RECENTS_LAUNCH_DURATION;
import static com.android.launcher3.anim.Interpolators.FAST_OUT_SLOW_IN;
import static com.android.launcher3.anim.Interpolators.LINEAR;
+import static com.android.launcher3.anim.Interpolators.TOUCH_RESPONSE_INTERPOLATOR;
import static com.android.launcher3.config.FeatureFlags.ENABLE_QUICKSTEP_LIVE_TILE;
-import static com.android.quickstep.SysUINavigationMode.removeShelfFromOverview;
+import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.TASK_LAUNCH_TAP;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
@@ -37,31 +44,33 @@
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
+import android.os.Process;
import android.util.AttributeSet;
import android.util.FloatProperty;
import android.util.Log;
-import android.view.Gravity;
+import android.view.Surface;
import android.view.View;
import android.view.ViewOutlineProvider;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.FrameLayout;
import android.widget.Toast;
-import androidx.annotation.Nullable;
-
import com.android.launcher3.BaseDraggingActivity;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.anim.AnimatorPlaybackController;
import com.android.launcher3.anim.Interpolators;
-import com.android.launcher3.config.FeatureFlags;
+import com.android.launcher3.anim.PendingAnimation;
+import com.android.launcher3.logger.LauncherAtom;
import com.android.launcher3.logging.UserEventDispatcher;
import com.android.launcher3.popup.SystemShortcut;
import com.android.launcher3.testing.TestLogging;
+import com.android.launcher3.testing.TestProtocol;
+import com.android.launcher3.touch.PagedOrientationHandler;
import com.android.launcher3.userevent.nano.LauncherLogProto;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action.Direction;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action.Touch;
-import com.android.launcher3.util.PendingAnimation;
+import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.ViewPool.Reusable;
import com.android.quickstep.RecentsModel;
import com.android.quickstep.TaskIconCache;
@@ -69,6 +78,7 @@
import com.android.quickstep.TaskThumbnailCache;
import com.android.quickstep.TaskUtils;
import com.android.quickstep.util.LayoutUtils;
+import com.android.quickstep.util.RecentsOrientedState;
import com.android.quickstep.util.TaskCornerRadius;
import com.android.quickstep.views.RecentsView.PageCallbacks;
import com.android.quickstep.views.RecentsView.ScrollState;
@@ -109,19 +119,6 @@
private static final List<Rect> SYSTEM_GESTURE_EXCLUSION_RECT =
Collections.singletonList(new Rect());
- public static final FloatProperty<TaskView> FULLSCREEN_PROGRESS =
- new FloatProperty<TaskView>("fullscreenProgress") {
- @Override
- public void setValue(TaskView taskView, float v) {
- taskView.setFullscreenProgress(v);
- }
-
- @Override
- public Float get(TaskView taskView) {
- return taskView.mFullscreenProgress;
- }
- };
-
private static final FloatProperty<TaskView> FOCUS_TRANSITION =
new FloatProperty<TaskView>("focusTransition") {
@Override
@@ -164,14 +161,13 @@
private final float mWindowCornerRadius;
private final BaseDraggingActivity mActivity;
- @Nullable private View mActionsView;
-
private ObjectAnimator mIconAndDimAnimator;
private float mIconScaleAnimStartProgress = 0;
private float mFocusTransitionProgress = 1;
private float mStableAlpha = 1;
private boolean mShowScreenshot;
+ private boolean mRunningModalAnimation = false;
// The current background requests to load the task thumbnail and icon
private TaskThumbnailCache.ThumbnailLoadRequest mThumbnailLoadRequest;
@@ -213,8 +209,7 @@
mActivity.getUserEventDispatcher().logTaskLaunchOrDismiss(
Touch.TAP, Direction.NONE, getRecentsView().indexOfChild(this),
TaskUtils.getLaunchComponentKeyForTask(getTask().key));
- mActivity.getStatsLogManager().logTaskLaunch(getRecentsView(),
- TaskUtils.getLaunchComponentKeyForTask(getTask().key));
+ mActivity.getStatsLogManager().log(TASK_LAUNCH_TAP, buildProto());
});
mCornerRadius = TaskCornerRadius.get(context);
mWindowCornerRadius = QuickStepContract.getWindowCornerRadius(context.getResources());
@@ -225,6 +220,17 @@
setOutlineProvider(mOutlineProvider);
}
+ /* Builds proto for logging */
+ protected LauncherAtom.ItemInfo buildProto() {
+ ComponentKey componentKey = TaskUtils.getLaunchComponentKeyForTask(getTask().key);
+ LauncherAtom.ItemInfo.Builder itemBuilder = LauncherAtom.ItemInfo.newBuilder();
+ itemBuilder.setIsWork(componentKey.user != Process.myUserHandle());
+ itemBuilder.setTask(LauncherAtom.Task.newBuilder()
+ .setComponentName(componentKey.componentName.flattenToShortString())
+ .setIndex(getRecentsView().indexOfChild(this)));
+ return itemBuilder.build();
+ }
+
@Override
protected void onFinishInflate() {
super.onFinishInflate();
@@ -235,18 +241,48 @@
TaskView.LayoutParams thumbnailParams = (LayoutParams) mSnapshotView.getLayoutParams();
thumbnailParams.bottomMargin = LayoutUtils.thumbnailBottomMargin(context);
mSnapshotView.setLayoutParams(thumbnailParams);
+ }
+ public boolean isTaskOverlayModal() {
+ return mSnapshotView.getTaskOverlay().isOverlayModal();
+ }
- if (FeatureFlags.ENABLE_OVERVIEW_ACTIONS.get() && removeShelfFromOverview(context)) {
- mActionsView = mSnapshotView.getTaskOverlay().getActionsView();
- if (mActionsView != null) {
- TaskView.LayoutParams params = new TaskView.LayoutParams(LayoutParams.MATCH_PARENT,
- getResources().getDimensionPixelSize(R.dimen.overview_actions_height),
- Gravity.BOTTOM);
- addView(mActionsView, params);
- mActionsView.setAlpha(0);
- }
+ /** Updates UI based on whether the task is modal. */
+ public void updateUiForModalTask() {
+ boolean isOverlayModal = isTaskOverlayModal();
+ mRunningModalAnimation = true;
+ if (getRecentsView() != null) {
+ getRecentsView().updateUiForModalTask(this, isOverlayModal);
}
+
+ // Hides footers and icon when overlay is modal.
+ if (isOverlayModal) {
+ for (FooterWrapper footer : mFooters) {
+ if (footer != null) {
+ footer.animateHide();
+ }
+ }
+ mIconView.animate().alpha(0.0f);
+ } else {
+ mIconView.animate().alpha(1.0f);
+ }
+
+ // Sets animations for modal UI. We will remove the margins to zoom in the snapshot.
+ float topMargin = getResources().getDimension(R.dimen.task_thumbnail_top_margin);
+ float bottomMargin =
+ getResources().getDimension(R.dimen.task_thumbnail_bottom_margin_with_actions);
+ float newHeight = mSnapshotView.getHeight() + topMargin + bottomMargin;
+ float scale = isOverlayModal ? newHeight / mSnapshotView.getHeight() : 1.0f;
+ float centerDifference = (bottomMargin - topMargin) / 2;
+ float translationY = isOverlayModal ? centerDifference : 0;
+ this.animate().scaleX(scale).scaleY(scale).translationY(translationY)
+ .withEndAction(new Runnable() {
+ @Override
+ public void run() {
+ setCurveScale(scale);
+ mRunningModalAnimation = false;
+ }
+ });
}
public TaskMenuView getMenuView() {
@@ -260,10 +296,11 @@
/**
* Updates this task view to the given {@param task}.
*/
- public void bind(Task task) {
+ public void bind(Task task, RecentsOrientedState orientedState) {
cancelPendingLoadTasks();
mTask = task;
mSnapshotView.bind(task);
+ setOrientationState(orientedState);
}
public Task getTask() {
@@ -279,11 +316,9 @@
}
public AnimatorPlaybackController createLaunchAnimationForRunningTask() {
- final PendingAnimation pendingAnimation =
- getRecentsView().createTaskLauncherAnimation(this, RECENTS_LAUNCH_DURATION);
- pendingAnimation.anim.setInterpolator(Interpolators.TOUCH_RESPONSE_INTERPOLATOR);
- AnimatorPlaybackController currentAnimation = AnimatorPlaybackController
- .wrap(pendingAnimation.anim, RECENTS_LAUNCH_DURATION, null);
+ final PendingAnimation pendingAnimation = getRecentsView().createTaskLaunchAnimation(
+ this, RECENTS_LAUNCH_DURATION, TOUCH_RESPONSE_INTERPOLATOR);
+ AnimatorPlaybackController currentAnimation = pendingAnimation.createPlaybackController();
currentAnimation.setEndAction(() -> {
pendingAnimation.finish(true, Touch.SWIPE);
launchTask(false);
@@ -334,9 +369,8 @@
Consumer<Boolean> resultCallback, Handler resultCallbackHandler) {
if (mTask != null) {
final ActivityOptions opts;
- if (Utilities.IS_RUNNING_IN_TEST_HARNESS) {
- TestLogging.recordEvent("startActivityFromRecentsAsync:" + mTask);
- }
+ TestLogging.recordEvent(
+ TestProtocol.SEQUENCE_MAIN, "startActivityFromRecentsAsync", mTask);
if (animate) {
opts = mActivity.getActivityLaunchOptions(this);
if (freezeTaskList) {
@@ -435,6 +469,43 @@
}
}
+ public void setOrientationState(RecentsOrientedState orientationState) {
+ int iconRotation = orientationState.getTouchRotation();
+ PagedOrientationHandler orientationHandler = orientationState.getOrientationHandler();
+ boolean isRtl = orientationHandler.getRecentsRtlSetting(getResources());
+ LayoutParams snapshotParams = (LayoutParams) mSnapshotView.getLayoutParams();
+ snapshotParams.bottomMargin = LayoutUtils.thumbnailBottomMargin(getContext());
+ int thumbnailPadding = (int) getResources().getDimension(R.dimen.task_thumbnail_top_margin);
+ LayoutParams iconParams = (LayoutParams) mIconView.getLayoutParams();
+ int rotation = orientationState.getTouchRotationDegrees();
+ switch (iconRotation) {
+ case Surface.ROTATION_90:
+ iconParams.gravity = (isRtl ? END : START) | CENTER_VERTICAL;
+ iconParams.rightMargin = -thumbnailPadding;
+ iconParams.leftMargin = iconParams.topMargin = iconParams.bottomMargin = 0;
+ break;
+ case Surface.ROTATION_180:
+ iconParams.gravity = BOTTOM | CENTER_HORIZONTAL;
+ iconParams.bottomMargin = -thumbnailPadding;
+ iconParams.leftMargin = iconParams.topMargin = iconParams.rightMargin = 0;
+ break;
+ case Surface.ROTATION_270:
+ iconParams.gravity = (isRtl ? END : START) | CENTER_VERTICAL;
+ iconParams.leftMargin = -thumbnailPadding;
+ iconParams.rightMargin = iconParams.topMargin = iconParams.bottomMargin = 0;
+ break;
+ case Surface.ROTATION_0:
+ default:
+ iconParams.gravity = TOP | CENTER_HORIZONTAL;
+ iconParams.leftMargin = iconParams.topMargin = iconParams.rightMargin =
+ iconParams.bottomMargin = 0;
+ break;
+ }
+ mSnapshotView.setLayoutParams(snapshotParams);
+ mIconView.setLayoutParams(iconParams);
+ mIconView.setRotation(rotation);
+ }
+
private void setIconAndDimTransitionProgress(float progress, boolean invert) {
if (invert) {
progress = 1 - progress;
@@ -449,11 +520,6 @@
mIconView.setScaleX(scale);
mIconView.setScaleY(scale);
-
- if (mActionsView != null && isRunningTask()) {
- mActionsView.setAlpha(scale);
- }
-
mFooterVerticalOffset = 1.0f - scale;
for (FooterWrapper footer : mFooters) {
if (footer != null) {
@@ -524,11 +590,15 @@
@Override
public void onPageScroll(ScrollState scrollState) {
+ // Don't do anything if it's modal.
+ if (mRunningModalAnimation || isTaskOverlayModal()) {
+ return;
+ }
+
float curveInterpolation =
CURVE_INTERPOLATOR.getInterpolation(scrollState.linearInterpolation);
float curveScaleForCurveInterpolation = getCurveScaleForCurveInterpolation(
curveInterpolation);
-
mSnapshotView.setDimAlpha(curveInterpolation * MAX_PAGE_SCRIM_ALPHA);
setCurveScale(curveScaleForCurveInterpolation);
@@ -544,31 +614,8 @@
mMenuView.setScaleX(getScaleX());
mMenuView.setScaleY(getScaleY());
}
-
- // This is not the proper implementation and will be replaced with a proper layout.
- if (mActionsView != null) {
- if (mFocusTransitionProgress == 1f) {
- mActionsView.setAlpha(1 - curveInterpolation / MAX_PAGE_SCRIM_ALPHA);
- }
- maintainActionViewPosition(curveScaleForCurveInterpolation);
- }
-
}
- private void maintainActionViewPosition(float curveScaleForCurveInterpolation) {
- float inverseCurveScaleFactor = curveScaleForCurveInterpolation == 0 ? 0 :
- (1f / curveScaleForCurveInterpolation);
- mActionsView.setScaleX(inverseCurveScaleFactor);
- mActionsView.setScaleY(inverseCurveScaleFactor);
- mActionsView.setTranslationX(inverseCurveScaleFactor * (-getX()
- + getRecentsView().getScrollX() + getRecentsView().scrollOffsetLeft()));
- mActionsView.setTranslationY(
- (1f - curveScaleForCurveInterpolation) * (mSnapshotView.getHeight()
- + mActionsView.getHeight()) / 2f
- + inverseCurveScaleFactor * (-getTranslationY()));
- }
-
-
/**
* Sets the footer at the specific index and returns the previously set footer.
*/
@@ -597,8 +644,7 @@
addView(view, indexToAdd);
LayoutParams layoutParams = (LayoutParams) view.getLayoutParams();
- layoutParams.gravity =
- Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
+ layoutParams.gravity = BOTTOM | CENTER_HORIZONTAL;
layoutParams.bottomMargin =
((MarginLayoutParams) mSnapshotView.getLayoutParams()).bottomMargin;
view.setAlpha(mFooterAlpha);
@@ -772,6 +818,22 @@
animator.setDuration(100);
animator.start();
}
+
+ void animateHide() {
+ ValueAnimator animator = ValueAnimator.ofFloat(0.0f, 1.0f);
+ animator.addUpdateListener(anim -> {
+ mFooterVerticalOffset = anim.getAnimatedFraction();
+ updateFooterOffset();
+ });
+ animator.addListener(new AnimatorListenerAdapter() {
+ @Override
+ public void onAnimationEnd(Animator animation) {
+ removeView(mView);
+ }
+ });
+ animator.setDuration(100);
+ animator.start();
+ }
}
@Override
@@ -779,8 +841,8 @@
super.onInitializeAccessibilityNodeInfo(info);
info.addAction(
- new AccessibilityNodeInfo.AccessibilityAction(R.string.accessibility_close_task,
- getContext().getText(R.string.accessibility_close_task)));
+ new AccessibilityNodeInfo.AccessibilityAction(R.string.accessibility_close,
+ getContext().getText(R.string.accessibility_close)));
final Context context = getContext();
for (SystemShortcut s : TaskOverlayFactory.getEnabledShortcuts(this)) {
@@ -804,7 +866,7 @@
@Override
public boolean performAccessibilityAction(int action, Bundle arguments) {
- if (action == R.string.accessibility_close_task) {
+ if (action == R.string.accessibility_close) {
getRecentsView().dismissTask(this, true /*animateTaskView*/,
true /*removeTask*/);
return true;
@@ -851,9 +913,6 @@
mFullscreenProgress = progress;
boolean isFullscreen = mFullscreenProgress > 0;
mIconView.setVisibility(progress < 1 ? VISIBLE : INVISIBLE);
- if (mActionsView != null) {
- mActionsView.setVisibility(progress < 1 ? VISIBLE : INVISIBLE);
- }
setClipChildren(!isFullscreen);
setClipToPadding(!isFullscreen);
@@ -934,5 +993,4 @@
mScale = scale;
}
}
-
}
diff --git a/quickstep/res/drawable/ic_screenshot.xml b/quickstep/res/drawable/ic_screenshot.xml
new file mode 100644
index 0000000..d97eae1
--- /dev/null
+++ b/quickstep/res/drawable/ic_screenshot.xml
@@ -0,0 +1,23 @@
+<!-- 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.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FF000000"
+ android:pathData="M17,1.01L7,1c-1.1,0 -2,0.9 -2,2v18c0,1.1 0.9,2 2,2h10c1.1,0 2,-0.9 2,-2L19,3c0,-1.1 -0.9,-1.99 -2,-1.99zM17,21L7,21v-1h10v1zM17,18L7,18L7,6h10v12zM17,4L7,4L7,3h10v1zM9.5,8.5L12,8.5L12,7L8,7v4h1.5zM12,17h4v-4h-1.5v2.5L12,15.5z"/>
+</vector>
diff --git a/quickstep/res/drawable/ic_share.xml b/quickstep/res/drawable/ic_share.xml
new file mode 100644
index 0000000..ff4baec
--- /dev/null
+++ b/quickstep/res/drawable/ic_share.xml
@@ -0,0 +1,23 @@
+<!-- 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.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FF000000"
+ android:pathData="M18,16c-0.79,0 -1.5,0.31 -2.03,0.81L8.91,12.7c0.05,-0.23 0.09,-0.46 0.09,-0.7s-0.04,-0.47 -0.09,-0.7l7.05,-4.11c0.53,0.5 1.25,0.81 2.04,0.81 1.66,0 3,-1.34 3,-3s-1.34,-3 -3,-3 -3,1.34 -3,3c0,0.24 0.04,0.48 0.09,0.7L8.04,9.81C7.5,9.31 6.79,9 6,9c-1.66,0 -3,1.34 -3,3s1.34,3 3,3c0.79,0 1.5,-0.31 2.04,-0.81l7.05,4.12c-0.05,0.22 -0.09,0.45 -0.09,0.69 0,1.66 1.34,3 3,3s3,-1.34 3,-3 -1.34,-3 -3,-3zM18,4c0.55,0 1,0.45 1,1s-0.45,1 -1,1 -1,-0.45 -1,-1 0.45,-1 1,-1zM6,13c-0.55,0 -1,-0.45 -1,-1s0.45,-1 1,-1 1,0.45 1,1 -0.45,1 -1,1zM18,20c-0.55,0 -1,-0.45 -1,-1s0.45,-1 1,-1 1,0.45 1,1 -0.45,1 -1,1z"/>
+</vector>
diff --git a/quickstep/res/layout/back_gesture_tutorial_fragment.xml b/quickstep/res/layout/back_gesture_tutorial_fragment.xml
index 294e46e..d8c25bd 100644
--- a/quickstep/res/layout/back_gesture_tutorial_fragment.xml
+++ b/quickstep/res/layout/back_gesture_tutorial_fragment.xml
@@ -16,9 +16,7 @@
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
- android:layerType="software"
android:background="@color/back_gesture_tutorial_background_color">
- <!--The layout is rendered on the software layer to avoid b/136158117-->
<ImageView
android:id="@+id/back_gesture_tutorial_fragment_hand_coaching"
diff --git a/quickstep/res/layout/overview_actions.xml b/quickstep/res/layout/overview_actions.xml
new file mode 100644
index 0000000..ad5efb6
--- /dev/null
+++ b/quickstep/res/layout/overview_actions.xml
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?>
+<merge xmlns:android="http://schemas.android.com/apk/res/android">
+ <LinearLayout
+ android:id="@+id/action_buttons"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center"
+ android:orientation="horizontal">
+ <Space
+ android:layout_width="0dp"
+ android:layout_height="1dp"
+ android:layout_weight="1" >
+ </Space>
+ <Button
+ android:id="@+id/action_screenshot"
+ style="@style/OverviewActionButton"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:drawableTop="@drawable/ic_screenshot"
+ android:text="@string/action_screenshot" />
+ <Space
+ android:layout_width="0dp"
+ android:layout_height="1dp"
+ android:layout_weight="1" >
+ </Space>
+
+ <Button
+ android:id="@+id/action_share"
+ style="@style/OverviewActionButton"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:drawableTop="@drawable/ic_share"
+ android:text="@string/action_share" />
+ <Space
+ android:layout_width="0dp"
+ android:layout_height="1dp"
+ android:layout_weight="1" >
+ </Space>
+ </LinearLayout>
+
+</merge>
diff --git a/iconloaderlib/res/drawable-v26/adaptive_icon_drawable_wrapper.xml b/quickstep/res/layout/overview_actions_container.xml
similarity index 64%
rename from iconloaderlib/res/drawable-v26/adaptive_icon_drawable_wrapper.xml
rename to quickstep/res/layout/overview_actions_container.xml
index 9f13cf5..328c20b 100644
--- a/iconloaderlib/res/drawable-v26/adaptive_icon_drawable_wrapper.xml
+++ b/quickstep/res/layout/overview_actions_container.xml
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
- Copyright (C) 2017 The Android Open Source Project
+ 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.
@@ -14,9 +14,10 @@
See the License for the specific language governing permissions and
limitations under the License.
-->
-<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
- <background android:drawable="@color/legacy_icon_background"/>
- <foreground>
- <com.android.launcher3.icons.FixedScaleDrawable />
- </foreground>
-</adaptive-icon>
+<com.android.quickstep.views.OverviewActionsView
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:visibility="gone">
+
+</com.android.quickstep.views.OverviewActionsView>
\ No newline at end of file
diff --git a/quickstep/res/layout/task.xml b/quickstep/res/layout/task.xml
index 60cfa0c..f9bb2f2 100644
--- a/quickstep/res/layout/task.xml
+++ b/quickstep/res/layout/task.xml
@@ -31,7 +31,6 @@
android:id="@+id/icon"
android:layout_width="@dimen/task_thumbnail_icon_size"
android:layout_height="@dimen/task_thumbnail_icon_size"
- android:layout_gravity="top|center_horizontal"
android:focusable="false"
android:importantForAccessibility="no"/>
</com.android.quickstep.views.TaskView>
\ No newline at end of file
diff --git a/iconloaderlib/res/values/dimens.xml b/quickstep/res/values/colors.xml
similarity index 77%
copy from iconloaderlib/res/values/dimens.xml
copy to quickstep/res/values/colors.xml
index e8c0c44..3583676 100644
--- a/iconloaderlib/res/values/dimens.xml
+++ b/quickstep/res/values/colors.xml
@@ -1,11 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2018 The Android Open Source Project
+<!-- 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
+ http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
@@ -13,7 +13,6 @@
See the License for the specific language governing permissions and
limitations under the License.
-->
-
<resources>
- <dimen name="profile_badge_size">24dp</dimen>
-</resources>
+ <color name="back_arrow_color_dark">#99000000</color>
+</resources>
\ No newline at end of file
diff --git a/quickstep/res/values/config.xml b/quickstep/res/values/config.xml
index 327bb14..a688f9a 100644
--- a/quickstep/res/values/config.xml
+++ b/quickstep/res/values/config.xml
@@ -13,11 +13,13 @@
See the License for the specific language governing permissions and
limitations under the License.
-->
-<resources>
- <string name="task_overlay_factory_class" translatable="false"></string>
+<resources xmlns:tools="http://schemas.android.com/tools">
+ <string name="task_overlay_factory_class" translatable="false"/>
- <!-- Activity which blocks home gesture -->
- <string name="gesture_blocking_activity" translatable="false"></string>
+ <!-- Activities which block home gesture -->
+ <string-array name="gesture_blocking_activities" tools:ignore="InconsistentArrays">
+ <item>com.android.launcher3/com.android.quickstep.interaction.GestureSandboxActivity</item>
+ </string-array>
<string name="stats_log_manager_class" translatable="false">com.android.quickstep.logging.StatsLogCompatManager</string>
@@ -32,5 +34,5 @@
<integer name="assistant_gesture_min_time_threshold">200</integer>
<integer name="assistant_gesture_corner_deg_threshold">20</integer>
- <string name="wellbeing_provider_pkg" translatable="false"></string>
+ <string name="wellbeing_provider_pkg" translatable="false"/>
</resources>
diff --git a/quickstep/res/values/dimens.xml b/quickstep/res/values/dimens.xml
index 988c78d..9a61165 100644
--- a/quickstep/res/values/dimens.xml
+++ b/quickstep/res/values/dimens.xml
@@ -17,13 +17,15 @@
<resources>
<dimen name="task_thumbnail_top_margin">24dp</dimen>
+ <dimen name="task_thumbnail_bottom_margin_with_actions">44dp</dimen>
<dimen name="task_thumbnail_half_top_margin">12dp</dimen>
<dimen name="task_thumbnail_icon_size">48dp</dimen>
<!-- For screens without rounded corners -->
<dimen name="task_corner_radius_small">2dp</dimen>
<!-- Overrideable in overlay that provides the Overview Actions. -->
- <dimen name="overview_actions_height">0dp</dimen>
+ <dimen name="overview_actions_height">110dp</dimen>
+ <dimen name="overview_actions_horizontal_margin">16dp</dimen>
<dimen name="recents_page_spacing">10dp</dimen>
<dimen name="recents_clear_all_deadzone_vertical_margin">70dp</dimen>
@@ -66,9 +68,6 @@
docked_stack_divider_thickness - 2 * docked_stack_divider_insets -->
<dimen name="multi_window_task_divider_size">10dp</dimen>
- <!-- same as vertical_drag_handle_size -->
- <dimen name="shelf_surface_offset">24dp</dimen>
-
<!-- Assistant Gestures -->
<!-- Distance from the vertical edges of the screen in which assist gestures are recognized -->
<dimen name="gestures_assistant_width">48dp</dimen>
diff --git a/quickstep/res/values/strings.xml b/quickstep/res/values/strings.xml
index 5f81e1f..c6b1477 100644
--- a/quickstep/res/values/strings.xml
+++ b/quickstep/res/values/strings.xml
@@ -32,9 +32,6 @@
<!-- Recents: The empty recents string. [CHAR LIMIT=NONE] -->
<string name="recents_empty_message">No recent items</string>
- <!-- Content description for the recent apps's accessibility option that closes it. [CHAR LIMIT=NONE] -->
- <string name="accessibility_close_task">Close</string>
-
<!-- Content description for the recent apps's accessibility option that opens its usage settings. [CHAR LIMIT=NONE] -->
<string name="accessibility_app_usage_settings">App usage settings</string>
@@ -66,27 +63,35 @@
<!-- Content description for a close button. [CHAR LIMIT=NONE] -->
<string name="back_gesture_tutorial_close_button_content_description" translatable="false">Close</string>
- <!-- Hotseat migration notification title -->
- <string translatable="false" name="hotseat_migrate_prompt_title">Get suggested apps on the home screen</string>
- <!-- Hotseat migration notification content -->
- <string translatable="false" name="hotseat_migrate_prompt_content">Tap to set up</string>
- <!-- Hotseat migration wizard title -->
- <string translatable="false" name="hotseat_migrate_title">Suggested apps replace the bottom row of apps</string>
- <!-- Hotseat migration wizard message -->
- <string translatable="false" name="hotseat_migrate_message">To pin a favorite app, drag it over a suggested app. To hide a suggested app, touch & hold it.</string>
- <!-- Toast message user sees after opting into fully predicted hybrid hotseat -->
- <string translatable="false" name="hotseat_items_migrated">Bottom row of apps moved to last screen</string>
- <!-- Toast message user sees after opting into fully predicted hybrid hotseat -->
- <string translatable="false" name="hotseat_no_migration">Bottom row won\'t be replaced. Manually drag apps for predictions.</string>
- <!-- Button text to opt in for fully predicted hotseat -->
- <string translatable="false" name="hotseat_migrate_accept">Turn On</string>
- <!-- Button text to dismiss opt in for fully predicted hotseat -->
- <string translatable="false" name="hotseat_migrate_dismiss">No thanks</string>
- <!-- Hotseat onboard notification title -->
- <string translatable="false" name="hotseat_onboard_notification_title">Your hotseat just got smarter</string>
- <!-- Hotseat onboard notification detail -->
- <string translatable="false" name="hotseat_onboard_notification_detail">Tap here to set it up</string>
+ <!-- Hotseat migration notification title -->
+ <string name="hotseat_edu_prompt_title">Easily access your most-used apps</string>
+ <!-- Hotseat migration notification content -->
+ <string name="hotseat_edu_prompt_content">Pixel predicts apps you\’ll need next, right on your Home screen. Tap to set up.</string>
+
+ <!-- Hotseat educational strings for users who don't qualify for migration -->
+ <string name="hotseat_edu_title_migrate">Get app suggestions on the bottom row of your Home screen</string>
+
+ <string name="hotseat_edu_message_migrate">Easily access your most-used apps right on the Home screen. Suggestions will change based on your routines. Apps on the bottom row will move up to your Home screen. </string>
+ <string name="hotseat_edu_message_migrate_alt">Easily access your most-used apps, right on the Home screen. Suggestions will change based on your routines. Apps on the bottom row will move to a new folder.</string>
+
+ <!-- Button text to opt in for fully predicted hotseat -->
+ <string name="hotseat_edu_accept">Get app suggestions</string>
+ <!-- Button text to dismiss opt in for fully predicted hotseat -->
+ <string name="hotseat_edu_dismiss">No thanks</string>
+
+ <!-- action shown to turn off predictions after onboarding -->
+ <string name="hotseat_turn_off">Settings</string>
+
+ <!-- tip shown if user has no items in hotseat to migrate -->
+ <string name="hotseat_auto_enrolled">Most-used apps appear here, and change based on routines</string>
+ <!-- tip shown if user declines migration and has no open spots for prediction -->
+ <string name="hotseat_tip_no_empty_slots">Drag apps off the bottom row to get app suggestions</string>
+ <!-- tip shown if user declines migration and has some open spots for prediction -->
+ <string name="hotseat_tip_gaps_filled">App suggestions added to empty space</string>
+
+ <!-- content description for hotseat items -->
+ <string name="hotseat_prediction_content_description">Predicted app: <xliff:g id="title" example="Chrome">%1$s</xliff:g></string>
<!-- Title shown during interactive part of Back gesture tutorial for right edge. [CHAR LIMIT=30] -->
@@ -108,4 +113,10 @@
<string name="back_gesture_tutorial_action_button_label" translatable="false">Done</string>
<!-- Button text shown on a text button on the confirm screen. [CHAR LIMIT=14] -->
<string name="back_gesture_tutorial_action_text_button_label" translatable="false">Settings</string>
+
+ <!-- ******* Overview ******* -->
+ <!-- Label for a button that causes the current overview app to be shared. [CHAR_LIMIT=40] -->
+ <string name="action_share">Share</string>
+ <!-- Label for a button that causes a screen shot of the current app to be taken. [CHAR_LIMIT=40] -->
+ <string name="action_screenshot">Screenshot</string>
</resources>
\ No newline at end of file
diff --git a/quickstep/res/values/styles.xml b/quickstep/res/values/styles.xml
index c8d7777..bf107fb 100644
--- a/quickstep/res/values/styles.xml
+++ b/quickstep/res/values/styles.xml
@@ -60,4 +60,13 @@
parent="TextAppearance.BackGestureTutorial.ButtonLabel">
<item name="android:textColor">@color/back_gesture_tutorial_primary_color</item>
</style>
+
+ <style name="OverviewActionButton"
+ parent="@android:style/Widget.DeviceDefault.Button.Borderless">
+ <item name="android:textColor">?attr/workspaceTextColor</item>
+ <item name="android:drawableTint">?attr/workspaceTextColor</item>
+ <item name="android:tint">?attr/workspaceTextColor</item>
+ <item name="android:drawablePadding">4dp</item>
+ <item name="android:textAllCaps">false</item>
+ </style>
</resources>
\ No newline at end of file
diff --git a/quickstep/res/xml/overview_file_provider_paths.xml b/quickstep/res/xml/overview_file_provider_paths.xml
new file mode 100644
index 0000000..14d7459
--- /dev/null
+++ b/quickstep/res/xml/overview_file_provider_paths.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<paths xmlns:android="http://schemas.android.com/apk/res/android">
+ <cache-path name="shared_images" path="/" />
+ <files-path name="log_files" path="/" />
+</paths>
\ No newline at end of file
diff --git a/quickstep/robolectric_tests/src/com/android/quickstep/OrientationTouchTransformerTest.java b/quickstep/robolectric_tests/src/com/android/quickstep/OrientationTouchTransformerTest.java
new file mode 100644
index 0000000..53f37c1
--- /dev/null
+++ b/quickstep/robolectric_tests/src/com/android/quickstep/OrientationTouchTransformerTest.java
@@ -0,0 +1,194 @@
+/*
+ * 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.quickstep;
+
+import static com.android.quickstep.SysUINavigationMode.Mode.NO_BUTTON;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import android.content.res.Resources;
+import android.graphics.Point;
+import android.util.DisplayMetrics;
+import android.view.MotionEvent;
+import android.view.Surface;
+
+import com.android.launcher3.ResourceUtils;
+import com.android.launcher3.util.DefaultDisplay;
+
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RobolectricTestRunner;
+
+@RunWith(RobolectricTestRunner.class)
+public class OrientationTouchTransformerTest {
+ private static final int SIZE_WIDTH = 1080;
+ private static final int SIZE_HEIGHT = 2280;
+ private static final float DENSITY_DISPLAY_METRICS = 3.0f;
+
+ private OrientationTouchTransformer mTouchTransformer;
+
+ Resources mResources;
+ private DefaultDisplay.Info mInfo;
+
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+ mResources = mock(Resources.class);
+ when(mResources.getBoolean(anyInt())).thenReturn(true);
+ when(mResources.getDimension(anyInt())).thenReturn(10.0f);
+ DisplayMetrics mockDisplayMetrics = new DisplayMetrics();
+ mockDisplayMetrics.density = DENSITY_DISPLAY_METRICS;
+ when(mResources.getDisplayMetrics()).thenReturn(mockDisplayMetrics);
+ mInfo = createDisplayInfo(Surface.ROTATION_0);
+ mTouchTransformer = new OrientationTouchTransformer(mResources, NO_BUTTON, () -> 0);
+ }
+
+ @Test
+ public void disabledMultipeRegions_shouldOverrideFirstRegion() {
+ mTouchTransformer.createOrAddTouchRegion(mInfo);
+ DefaultDisplay.Info info2 = createDisplayInfo(Surface.ROTATION_90);
+ mTouchTransformer.createOrAddTouchRegion(info2);
+
+ float y = generateTouchRegionHeight(Surface.ROTATION_0) + 1;
+ MotionEvent inOldRegion = generateMotionEvent(MotionEvent.ACTION_DOWN, 100, y);
+ mTouchTransformer.transform(inOldRegion);
+ assertFalse(mTouchTransformer.touchInValidSwipeRegions(inOldRegion.getX(), inOldRegion.getY()));
+
+ // Override region
+ mTouchTransformer.createOrAddTouchRegion(mInfo);
+ inOldRegion = generateMotionEvent(MotionEvent.ACTION_DOWN, 100, y);
+ mTouchTransformer.transform(inOldRegion);
+ assertTrue(mTouchTransformer.touchInValidSwipeRegions(inOldRegion.getX(), inOldRegion.getY()));
+ }
+
+ @Test
+ public void allowMultipeRegions_shouldOverrideFirstRegion() {
+ DefaultDisplay.Info info2 = createDisplayInfo(Surface.ROTATION_90);
+ mTouchTransformer.createOrAddTouchRegion(info2);
+ // We have to add 0 rotation second so that gets set as the current rotation, otherwise
+ // matrix transform will fail (tests only work in Portrait at the moment)
+ mTouchTransformer.enableMultipleRegions(true, mInfo);
+ mTouchTransformer.createOrAddTouchRegion(mInfo);
+
+ float y = generateTouchRegionHeight(Surface.ROTATION_0) + 1;
+ MotionEvent inNewRegion = generateMotionEvent(MotionEvent.ACTION_DOWN, 100, y);
+ mTouchTransformer.transform(inNewRegion);
+ assertTrue(mTouchTransformer.touchInValidSwipeRegions(inNewRegion.getX(), inNewRegion.getY()));
+ }
+
+ @Test
+ public void applyTransform_taskNotFrozen_notInRegion() {
+ mTouchTransformer.createOrAddTouchRegion(mInfo);
+ MotionEvent outOfRegion = generateMotionEvent(MotionEvent.ACTION_DOWN, 100, 100);
+ mTouchTransformer.transform(outOfRegion);
+ assertFalse(mTouchTransformer.touchInValidSwipeRegions(outOfRegion.getX(), outOfRegion.getY()));
+ }
+
+ @Test
+ public void applyTransform_taskFrozen_noRotate_outOfRegion() {
+ mTouchTransformer.createOrAddTouchRegion(mInfo);
+ mTouchTransformer.enableMultipleRegions(true, mInfo);
+ MotionEvent outOfRegion = generateMotionEvent(MotionEvent.ACTION_DOWN, 100, 100);
+ mTouchTransformer.transform(outOfRegion);
+ assertFalse(mTouchTransformer.touchInValidSwipeRegions(outOfRegion.getX(), outOfRegion.getY()));
+ }
+
+ @Test
+ public void applyTransform_taskFrozen_noRotate_inRegion() {
+ mTouchTransformer.createOrAddTouchRegion(mInfo);
+ mTouchTransformer.enableMultipleRegions(true, mInfo);
+ float y = generateTouchRegionHeight(Surface.ROTATION_0) + 1;
+ MotionEvent inRegion = generateMotionEvent(MotionEvent.ACTION_DOWN, 100, y);
+ mTouchTransformer.transform(inRegion);
+ assertTrue(mTouchTransformer.touchInValidSwipeRegions(inRegion.getX(), inRegion.getY()));
+ }
+
+ @Test
+ public void applyTransform_taskNotFrozen_noRotate_inDefaultRegion() {
+ mTouchTransformer.createOrAddTouchRegion(mInfo);
+ float y = generateTouchRegionHeight(Surface.ROTATION_0) + 1;
+ MotionEvent inRegion = generateMotionEvent(MotionEvent.ACTION_DOWN, 100, y);
+ mTouchTransformer.transform(inRegion);
+ assertTrue(mTouchTransformer.touchInValidSwipeRegions(inRegion.getX(), inRegion.getY()));
+ }
+
+ @Test
+ public void applyTransform_taskNotFrozen_90Rotate_inRegion() {
+ mTouchTransformer.createOrAddTouchRegion(createDisplayInfo(Surface.ROTATION_90));
+ float y = generateTouchRegionHeight(Surface.ROTATION_90) + 1;
+ MotionEvent inRegion = generateMotionEvent(MotionEvent.ACTION_DOWN, 100, y);
+ mTouchTransformer.transform(inRegion);
+ assertTrue(mTouchTransformer.touchInValidSwipeRegions(inRegion.getX(), inRegion.getY()));
+ }
+
+ @Test
+ @Ignore("There's too much that goes into needing to mock a real motion event so the "
+ + "transforms in native code get applied correctly. Once that happens then maybe we can"
+ + " write slightly more complex unit tests")
+ public void applyTransform_taskNotFrozen_90Rotate_inTwoRegions() {
+ mTouchTransformer.createOrAddTouchRegion(mInfo);
+ mTouchTransformer.enableMultipleRegions(true, mInfo);
+ mTouchTransformer.createOrAddTouchRegion(createDisplayInfo(Surface.ROTATION_90));
+ // Landscape point
+ float y1 = generateTouchRegionHeight(Surface.ROTATION_90) + 1;
+ MotionEvent inRegion1_down = generateMotionEvent(MotionEvent.ACTION_DOWN, 10, y1);
+ MotionEvent inRegion1_up = generateMotionEvent(MotionEvent.ACTION_UP, 10, y1);
+ // Portrait point in landscape orientation axis
+ MotionEvent inRegion2 = generateMotionEvent(MotionEvent.ACTION_DOWN, 10, 10);
+ mTouchTransformer.transform(inRegion1_down);
+ mTouchTransformer.transform(inRegion2);
+ assertTrue(mTouchTransformer.touchInValidSwipeRegions(inRegion1_down.getX(), inRegion1_down.getY()));
+ // We only process one gesture region until we see a MotionEvent.ACTION_UP
+ assertFalse(mTouchTransformer.touchInValidSwipeRegions(inRegion2.getX(), inRegion2.getY()));
+
+ mTouchTransformer.transform(inRegion1_up);
+
+ // Set the new region with this MotionEvent.ACTION_DOWN
+ inRegion2 = generateMotionEvent(MotionEvent.ACTION_DOWN, 10, 370);
+ mTouchTransformer.transform(inRegion2);
+ assertTrue(mTouchTransformer.touchInValidSwipeRegions(inRegion2.getX(), inRegion2.getY()));
+ }
+
+ private DefaultDisplay.Info createDisplayInfo(int rotation) {
+ Point p = new Point(SIZE_WIDTH, SIZE_HEIGHT);
+ if (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) {
+ p = new Point(SIZE_HEIGHT, SIZE_WIDTH);
+ }
+ return new DefaultDisplay.Info(0, rotation, 0, p, p, p, null);
+ }
+
+ private float generateTouchRegionHeight(int rotation) {
+ float height = SIZE_HEIGHT;
+ if (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) {
+ height = SIZE_WIDTH;
+ }
+ return height - ResourceUtils.DEFAULT_NAVBAR_VALUE * DENSITY_DISPLAY_METRICS;
+ }
+
+ private MotionEvent generateMotionEvent(int motionAction, float x, float y) {
+ return MotionEvent.obtain(0, 0, motionAction, x, y, 0);
+ }
+}
diff --git a/quickstep/src/com/android/launcher3/BaseQuickstepLauncher.java b/quickstep/src/com/android/launcher3/BaseQuickstepLauncher.java
index 94ff63b..48e25bd 100644
--- a/quickstep/src/com/android/launcher3/BaseQuickstepLauncher.java
+++ b/quickstep/src/com/android/launcher3/BaseQuickstepLauncher.java
@@ -17,22 +17,18 @@
import static com.android.launcher3.AbstractFloatingView.TYPE_ALL;
import static com.android.launcher3.AbstractFloatingView.TYPE_HIDE_BACK_BUTTON;
-import static com.android.launcher3.LauncherState.ALL_APPS;
import static com.android.launcher3.LauncherState.NORMAL;
-import static com.android.launcher3.LauncherState.OVERVIEW;
-import static com.android.launcher3.allapps.DiscoveryBounce.BOUNCE_MAX_COUNT;
-import static com.android.launcher3.allapps.DiscoveryBounce.HOME_BOUNCE_COUNT;
-import static com.android.launcher3.allapps.DiscoveryBounce.HOME_BOUNCE_SEEN;
-import static com.android.launcher3.allapps.DiscoveryBounce.SHELF_BOUNCE_COUNT;
-import static com.android.launcher3.allapps.DiscoveryBounce.SHELF_BOUNCE_SEEN;
import static com.android.quickstep.SysUINavigationMode.removeShelfFromOverview;
+import static com.android.systemui.shared.system.ActivityManagerWrapper.CLOSE_SYSTEM_WINDOWS_REASON_HOME_KEY;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.content.IntentSender;
+import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CancellationSignal;
+import android.view.View;
import com.android.launcher3.LauncherState.ScaleAndTranslation;
import com.android.launcher3.LauncherStateManager.StateHandler;
@@ -41,16 +37,24 @@
import com.android.launcher3.popup.SystemShortcut;
import com.android.launcher3.proxy.ProxyActivityStarter;
import com.android.launcher3.proxy.StartActivityParams;
-import com.android.launcher3.uioverrides.BackButtonAlphaHandler;
+import com.android.launcher3.statehandlers.BackButtonAlphaHandler;
+import com.android.launcher3.statehandlers.DepthController;
+import com.android.launcher3.touch.PagedOrientationHandler;
import com.android.launcher3.uioverrides.RecentsViewStateController;
+import com.android.launcher3.util.OnboardingPrefs;
import com.android.launcher3.util.UiThreadHelper;
import com.android.quickstep.RecentsModel;
import com.android.quickstep.SysUINavigationMode;
import com.android.quickstep.SysUINavigationMode.Mode;
import com.android.quickstep.SysUINavigationMode.NavigationModeChangeListener;
import com.android.quickstep.SystemUiProxy;
+import com.android.quickstep.util.QuickstepOnboardingPrefs;
+import com.android.quickstep.util.RemoteAnimationProvider;
import com.android.quickstep.util.RemoteFadeOutAnimationListener;
import com.android.quickstep.util.ShelfPeekAnim;
+import com.android.quickstep.views.RecentsView;
+import com.android.systemui.shared.system.ActivityManagerWrapper;
+import com.android.systemui.shared.system.RemoteAnimationTargetCompat;
import java.util.stream.Stream;
@@ -60,6 +64,8 @@
public abstract class BaseQuickstepLauncher extends Launcher
implements NavigationModeChangeListener {
+ private DepthController mDepthController = new DepthController(this);
+
/**
* Reusable command for applying the back button alpha on the background thread.
*/
@@ -69,52 +75,13 @@
private final ShelfPeekAnim mShelfPeekAnim = new ShelfPeekAnim(this);
+ private View mActionsView;
+
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
- SysUINavigationMode.Mode mode = SysUINavigationMode.INSTANCE.get(this)
- .addModeChangeListener(this);
- getRotationHelper().setRotationHadDifferentUI(mode != Mode.NO_BUTTON);
-
- if (!getSharedPrefs().getBoolean(HOME_BOUNCE_SEEN, false)) {
- getStateManager().addStateListener(new LauncherStateManager.StateListener() {
- @Override
- public void onStateTransitionStart(LauncherState toState) { }
-
- @Override
- public void onStateTransitionComplete(LauncherState finalState) {
- boolean swipeUpEnabled = SysUINavigationMode.INSTANCE
- .get(BaseQuickstepLauncher.this).getMode().hasGestures;
- LauncherState prevState = getStateManager().getLastState();
-
- if (((swipeUpEnabled && finalState == OVERVIEW) || (!swipeUpEnabled
- && finalState == ALL_APPS && prevState == NORMAL) || BOUNCE_MAX_COUNT
- <= getSharedPrefs().getInt(HOME_BOUNCE_COUNT, 0))) {
- getSharedPrefs().edit().putBoolean(HOME_BOUNCE_SEEN, true).apply();
- getStateManager().removeStateListener(this);
- }
- }
- });
- }
-
- if (!getSharedPrefs().getBoolean(SHELF_BOUNCE_SEEN, false)) {
- getStateManager().addStateListener(new LauncherStateManager.StateListener() {
- @Override
- public void onStateTransitionStart(LauncherState toState) { }
-
- @Override
- public void onStateTransitionComplete(LauncherState finalState) {
- LauncherState prevState = getStateManager().getLastState();
-
- if ((finalState == ALL_APPS && prevState == OVERVIEW) || BOUNCE_MAX_COUNT
- <= getSharedPrefs().getInt(SHELF_BOUNCE_COUNT, 0)) {
- getSharedPrefs().edit().putBoolean(SHELF_BOUNCE_SEEN, true).apply();
- getStateManager().removeStateListener(this);
- }
- }
- });
- }
+ SysUINavigationMode.INSTANCE.get(this).addModeChangeListener(this);
}
@Override
@@ -126,7 +93,6 @@
@Override
public void onNavigationModeChanged(Mode newMode) {
getDragLayer().recreateControllers();
- getRotationHelper().setRotationHadDifferentUI(newMode != Mode.NO_BUTTON);
}
@Override
@@ -146,6 +112,12 @@
}
@Override
+ protected void onUiChangedWhileSleeping() {
+ // Remove the snapshot because the content view may have obvious changes.
+ ActivityManagerWrapper.getInstance().invalidateHomeTaskSnapshot(this);
+ }
+
+ @Override
public void startIntentSenderForResult(IntentSender intent, int requestCode,
Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options) {
if (requestCode != -1) {
@@ -167,7 +139,7 @@
@Override
public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
if (requestCode != -1) {
- mPendingActivityRequestCode = -1;
+ mPendingActivityRequestCode = requestCode;
StartActivityParams params = new StartActivityParams(this, requestCode);
params.intent = intent;
params.options = options;
@@ -191,28 +163,56 @@
@Override
protected void setupViews() {
super.setupViews();
+ mActionsView = findViewById(R.id.overview_actions_view);
+
if (FeatureFlags.ENABLE_OVERVIEW_ACTIONS.get() && removeShelfFromOverview(this)) {
// Overview is above all other launcher elements, including qsb, so move it to the top.
getOverviewPanel().bringToFront();
+ if (mActionsView != null) {
+ mActionsView.bringToFront();
+ }
}
}
+ public View getActionsView() {
+ return mActionsView;
+ }
+
+ @Override
+ protected void closeOpenViews(boolean animate) {
+ super.closeOpenViews(animate);
+ ActivityManagerWrapper.getInstance()
+ .closeSystemWindows(CLOSE_SYSTEM_WINDOWS_REASON_HOME_KEY);
+ }
+
@Override
protected StateHandler[] createStateHandlers() {
return new StateHandler[] {
getAllAppsController(),
getWorkspace(),
+ getDepthController(),
new RecentsViewStateController(this),
new BackButtonAlphaHandler(this)};
}
+ public DepthController getDepthController() {
+ return mDepthController;
+ }
+
+ @Override
+ protected OnboardingPrefs createOnboardingPrefs(SharedPreferences sharedPrefs,
+ LauncherStateManager stateManager) {
+ return new QuickstepOnboardingPrefs(this, sharedPrefs, stateManager);
+ }
+
@Override
protected ScaleAndTranslation getOverviewScaleAndTranslationForNormalState() {
if (SysUINavigationMode.getMode(this) == Mode.NO_BUTTON) {
- float offscreenTranslationX = getDeviceProfile().widthPx
- - getOverviewPanel().getPaddingStart();
- return new ScaleAndTranslation(1f, offscreenTranslationX, 0f);
+ PagedOrientationHandler layoutVertical =
+ ((RecentsView)getOverviewPanel()).getPagedViewOrientedState().getOrientationHandler();
+ return layoutVertical.getScaleAndTranslation(getDeviceProfile(),
+ getOverviewPanel());
}
return super.getOverviewScaleAndTranslationForNormalState();
}
@@ -221,17 +221,21 @@
public void useFadeOutAnimationForLauncherStart(CancellationSignal signal) {
QuickstepAppTransitionManagerImpl appTransitionManager =
(QuickstepAppTransitionManagerImpl) getAppTransitionManager();
- appTransitionManager.setRemoteAnimationProvider((appTargets, wallpaperTargets) -> {
+ appTransitionManager.setRemoteAnimationProvider(new RemoteAnimationProvider() {
+ @Override
+ public AnimatorSet createWindowAnimation(RemoteAnimationTargetCompat[] appTargets,
+ RemoteAnimationTargetCompat[] wallpaperTargets) {
- // On the first call clear the reference.
- signal.cancel();
+ // On the first call clear the reference.
+ signal.cancel();
- ValueAnimator fadeAnimation = ValueAnimator.ofFloat(1, 0);
- fadeAnimation.addUpdateListener(new RemoteFadeOutAnimationListener(appTargets,
- wallpaperTargets));
- AnimatorSet anim = new AnimatorSet();
- anim.play(fadeAnimation);
- return anim;
+ ValueAnimator fadeAnimation = ValueAnimator.ofFloat(1, 0);
+ fadeAnimation.addUpdateListener(new RemoteFadeOutAnimationListener(appTargets,
+ wallpaperTargets));
+ AnimatorSet anim = new AnimatorSet();
+ anim.play(fadeAnimation);
+ return anim;
+ }
}, signal);
}
@@ -247,6 +251,10 @@
onLauncherStateOrFocusChanged();
}
+ if ((changeBits & ACTIVITY_STATE_STARTED) != 0) {
+ mDepthController.setActivityStarted(isStarted());
+ }
+
super.onActivityFlagsChanged(changeBits);
}
diff --git a/quickstep/src/com/android/launcher3/LauncherAnimationRunner.java b/quickstep/src/com/android/launcher3/LauncherAnimationRunner.java
index 31c1acf..2cb23f1 100644
--- a/quickstep/src/com/android/launcher3/LauncherAnimationRunner.java
+++ b/quickstep/src/com/android/launcher3/LauncherAnimationRunner.java
@@ -34,7 +34,8 @@
import com.android.systemui.shared.system.RemoteAnimationTargetCompat;
@TargetApi(Build.VERSION_CODES.P)
-public abstract class LauncherAnimationRunner implements RemoteAnimationRunnerCompat {
+public abstract class LauncherAnimationRunner implements RemoteAnimationRunnerCompat,
+ WrappedAnimationRunnerImpl {
private final Handler mHandler;
private final boolean mStartAtFrontOfQueue;
@@ -49,6 +50,10 @@
mStartAtFrontOfQueue = startAtFrontOfQueue;
}
+ public Handler getHandler() {
+ return mHandler;
+ }
+
// Called only in R+ platform
@BinderThread
public void onAnimationStart(RemoteAnimationTargetCompat[] appTargets,
diff --git a/quickstep/src/com/android/launcher3/LauncherInitListener.java b/quickstep/src/com/android/launcher3/LauncherInitListener.java
index 96340b2..fbd7a8a 100644
--- a/quickstep/src/com/android/launcher3/LauncherInitListener.java
+++ b/quickstep/src/com/android/launcher3/LauncherInitListener.java
@@ -15,6 +15,7 @@
*/
package com.android.launcher3;
+import android.animation.AnimatorSet;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
@@ -25,6 +26,7 @@
import com.android.launcher3.util.ActivityTracker;
import com.android.quickstep.util.ActivityInitListener;
import com.android.quickstep.util.RemoteAnimationProvider;
+import com.android.systemui.shared.system.RemoteAnimationTargetCompat;
import java.util.function.BiPredicate;
@@ -51,17 +53,21 @@
// Set a one-time animation provider. After the first call, this will get cleared.
// TODO: Probably also check the intended target id.
CancellationSignal cancellationSignal = new CancellationSignal();
- appTransitionManager.setRemoteAnimationProvider((appTargets, wallpaperTargets) -> {
+ appTransitionManager.setRemoteAnimationProvider(new RemoteAnimationProvider() {
+ @Override
+ public AnimatorSet createWindowAnimation(RemoteAnimationTargetCompat[] appTargets,
+ RemoteAnimationTargetCompat[] wallpaperTargets) {
- // On the first call clear the reference.
- cancellationSignal.cancel();
- RemoteAnimationProvider provider = mRemoteAnimationProvider;
- mRemoteAnimationProvider = null;
+ // On the first call clear the reference.
+ cancellationSignal.cancel();
+ RemoteAnimationProvider provider = mRemoteAnimationProvider;
+ mRemoteAnimationProvider = null;
- if (provider != null && launcher.getStateManager().getState().overviewUi) {
- return provider.createWindowAnimation(appTargets, wallpaperTargets);
+ if (provider != null && launcher.getStateManager().getState().overviewUi) {
+ return provider.createWindowAnimation(appTargets, wallpaperTargets);
+ }
+ return null;
}
- return null;
}, cancellationSignal);
}
launcher.deferOverlayCallbacksUntilNextResumeOrStop();
diff --git a/quickstep/src/com/android/launcher3/QuickstepAppTransitionManagerImpl.java b/quickstep/src/com/android/launcher3/QuickstepAppTransitionManagerImpl.java
index 2df490e..a30e102 100644
--- a/quickstep/src/com/android/launcher3/QuickstepAppTransitionManagerImpl.java
+++ b/quickstep/src/com/android/launcher3/QuickstepAppTransitionManagerImpl.java
@@ -16,11 +16,14 @@
package com.android.launcher3;
+import static android.util.TypedValue.COMPLEX_UNIT_DIP;
+
import static com.android.launcher3.BaseActivity.INVISIBLE_ALL;
import static com.android.launcher3.BaseActivity.INVISIBLE_BY_APP_TRANSITIONS;
import static com.android.launcher3.BaseActivity.INVISIBLE_BY_PENDING_FLAGS;
import static com.android.launcher3.BaseActivity.PENDING_INVISIBLE_BY_WALLPAPER_ANIMATION;
import static com.android.launcher3.LauncherState.ALL_APPS;
+import static com.android.launcher3.LauncherState.BACKGROUND_APP;
import static com.android.launcher3.LauncherState.OVERVIEW;
import static com.android.launcher3.Utilities.postAsyncCallback;
import static com.android.launcher3.allapps.AllAppsTransitionController.ALL_APPS_PROGRESS;
@@ -28,7 +31,9 @@
import static com.android.launcher3.anim.Interpolators.DEACCEL_1_7;
import static com.android.launcher3.anim.Interpolators.EXAGGERATED_EASE;
import static com.android.launcher3.anim.Interpolators.LINEAR;
+import static com.android.launcher3.config.FeatureFlags.KEYGUARD_ANIMATION;
import static com.android.launcher3.dragndrop.DragLayer.ALPHA_INDEX_TRANSITIONS;
+import static com.android.launcher3.statehandlers.DepthController.DEPTH;
import static com.android.launcher3.views.FloatingIconView.SHAPE_PROGRESS_DURATION;
import static com.android.quickstep.TaskUtils.taskIsATargetWithMode;
import static com.android.systemui.shared.system.QuickStepContract.getWindowCornerRadius;
@@ -47,6 +52,7 @@
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Matrix;
+import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
@@ -55,6 +61,7 @@
import android.os.Handler;
import android.os.Looper;
import android.util.Pair;
+import android.util.TypedValue;
import android.view.View;
import androidx.annotation.NonNull;
@@ -62,16 +69,18 @@
import com.android.launcher3.DeviceProfile.OnDeviceProfileChangeListener;
import com.android.launcher3.allapps.AllAppsTransitionController;
-import com.android.launcher3.anim.Interpolators;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.dragndrop.DragLayer;
import com.android.launcher3.shortcuts.DeepShortcutView;
+import com.android.launcher3.statehandlers.DepthController;
+import com.android.launcher3.util.DynamicResource;
import com.android.launcher3.util.MultiValueAlpha;
import com.android.launcher3.util.MultiValueAlpha.AlphaProperty;
import com.android.launcher3.views.FloatingIconView;
import com.android.quickstep.RemoteAnimationTargets;
import com.android.quickstep.util.MultiValueUpdateListener;
import com.android.quickstep.util.RemoteAnimationProvider;
+import com.android.quickstep.util.StaggeredWorkspaceAnim;
import com.android.systemui.shared.system.ActivityCompat;
import com.android.systemui.shared.system.ActivityOptionsCompat;
import com.android.systemui.shared.system.QuickStepContract;
@@ -83,11 +92,9 @@
import com.android.systemui.shared.system.SyncRtSurfaceTransactionApplierCompat.SurfaceParams;
import com.android.systemui.shared.system.WindowManagerWrapper;
-import java.lang.ref.WeakReference;
-
/**
* {@link LauncherAppTransitionManager} with Quickstep-specific app transitions for launching from
- * home and/or all-apps.
+ * home and/or all-apps. Not used for 3p launchers.
*/
@TargetApi(Build.VERSION_CODES.O)
@SuppressWarnings("unused")
@@ -136,7 +143,7 @@
// Progress = 0: All apps is fully pulled up, Progress = 1: All apps is fully pulled down.
public static final float ALL_APPS_PROGRESS_OFF_SCREEN = 1.3059858f;
- protected final Launcher mLauncher;
+ protected final BaseQuickstepLauncher mLauncher;
private final DragLayer mDragLayer;
private final AlphaProperty mDragLayerAlpha;
@@ -154,6 +161,7 @@
// Strong refs to runners which are cleared when the launcher activity is destroyed
private WrappedAnimationRunnerImpl mWallpaperOpenRunner;
private WrappedAnimationRunnerImpl mAppLaunchRunner;
+ private WrappedAnimationRunnerImpl mKeyguardGoingAwayRunner;
private final AnimatorListenerAdapter mForceInvisibleListener = new AnimatorListenerAdapter() {
@Override
@@ -168,7 +176,7 @@
};
public QuickstepAppTransitionManagerImpl(Context context) {
- mLauncher = Launcher.getLauncher(context);
+ mLauncher = Launcher.cast(Launcher.getLauncher(context));
mDragLayer = mLauncher.getDragLayer();
mDragLayerAlpha = mDragLayer.getAlphaProperty(ALPHA_INDEX_TRANSITIONS);
mHandler = new Handler(Looper.getMainLooper());
@@ -296,8 +304,12 @@
if (mLauncher.isInMultiWindowMode()) {
for (RemoteAnimationTargetCompat target : appTargets) {
if (target.mode == MODE_OPENING) {
- bounds.set(target.sourceContainerBounds);
- bounds.offsetTo(target.position.x, target.position.y);
+ bounds.set(target.screenSpaceBounds);
+ if (target.localBounds != null) {
+ bounds.set(target.localBounds);
+ } else {
+ bounds.offsetTo(target.position.x, target.position.y);
+ }
return bounds;
}
}
@@ -374,18 +386,35 @@
alpha.setInterpolator(LINEAR);
launcherAnimator.play(alpha);
- mDragLayer.setTranslationY(trans[0]);
- ObjectAnimator transY = ObjectAnimator.ofFloat(mDragLayer, View.TRANSLATION_Y, trans);
- transY.setInterpolator(AGGRESSIVE_EASE);
- transY.setDuration(CONTENT_TRANSLATION_DURATION);
- launcherAnimator.play(transY);
+ Workspace workspace = mLauncher.getWorkspace();
+ View currentPage = ((CellLayout) workspace.getChildAt(workspace.getCurrentPage()))
+ .getShortcutsAndWidgets();
+ View hotseat = mLauncher.getHotseat();
+ View qsb = mLauncher.findViewById(R.id.search_container_all_apps);
- mDragLayer.getScrim().hideSysUiScrim(true);
+ currentPage.setLayerType(View.LAYER_TYPE_HARDWARE, null);
+ hotseat.setLayerType(View.LAYER_TYPE_HARDWARE, null);
+ qsb.setLayerType(View.LAYER_TYPE_HARDWARE, null);
+
+ launcherAnimator.play(ObjectAnimator.ofFloat(currentPage, View.TRANSLATION_Y, trans));
+ launcherAnimator.play(ObjectAnimator.ofFloat(hotseat, View.TRANSLATION_Y, trans));
+ launcherAnimator.play(ObjectAnimator.ofFloat(qsb, View.TRANSLATION_Y, trans));
+
// Pause page indicator animations as they lead to layer trashing.
mLauncher.getWorkspace().getPageIndicator().pauseAnimations();
- mDragLayer.setLayerType(View.LAYER_TYPE_HARDWARE, null);
- endListener = this::resetContentView;
+ endListener = () -> {
+ currentPage.setTranslationY(0);
+ hotseat.setTranslationY(0);
+ qsb.setTranslationY(0);
+
+ currentPage.setLayerType(View.LAYER_TYPE_NONE, null);
+ hotseat.setLayerType(View.LAYER_TYPE_NONE, null);
+ qsb.setLayerType(View.LAYER_TYPE_NONE, null);
+
+ mDragLayerAlpha.setValue(1f);
+ mLauncher.getWorkspace().getPageIndicator().skipAnimationsToEnd();
+ };
}
return new Pair<>(launcherAnimator, endListener);
}
@@ -402,9 +431,9 @@
float[] alphas, float[] trans);
/**
- * @return Animator that controls the window of the opening targets.
+ * @return Animator that controls the window of the opening targets from app icons.
*/
- private ValueAnimator getOpeningWindowAnimators(View v,
+ private Animator getOpeningWindowAnimators(View v,
RemoteAnimationTargetCompat[] appTargets,
RemoteAnimationTargetCompat[] wallpaperTargets,
Rect windowTargetBounds, boolean toggleVisibility) {
@@ -457,7 +486,9 @@
RectF targetBounds = new RectF(windowTargetBounds);
RectF currentBounds = new RectF();
RectF temp = new RectF();
+ Point tmpPos = new Point();
+ AnimatorSet animatorSet = new AnimatorSet();
ValueAnimator appAnimator = ValueAnimator.ofFloat(0, 1);
appAnimator.setDuration(APP_LAUNCH_DURATION);
appAnimator.setInterpolator(LINEAR);
@@ -542,15 +573,17 @@
SurfaceParams[] params = new SurfaceParams[appTargets.length];
for (int i = appTargets.length - 1; i >= 0; i--) {
RemoteAnimationTargetCompat target = appTargets[i];
- Rect targetCrop;
- final float alpha;
- final float cornerRadius;
+ SurfaceParams.Builder builder = new SurfaceParams.Builder(target.leash);
+
+ tmpPos.set(target.position.x, target.position.y);
+ if (target.localBounds != null) {
+ final Rect localBounds = target.localBounds;
+ tmpPos.set(target.localBounds.left, target.localBounds.top);
+ }
+
if (target.mode == MODE_OPENING) {
matrix.setScale(scale, scale);
matrix.postTranslate(transX0, transY0);
- targetCrop = crop;
- alpha = 1f - mIconAlpha.value;
- cornerRadius = mWindowRadius.value;
matrix.mapRect(currentBounds, targetBounds);
if (mDeviceProfile.isVerticalBarLayout()) {
currentBounds.right -= croppedWidth;
@@ -558,22 +591,44 @@
currentBounds.bottom -= croppedHeight;
}
floatingView.update(currentBounds, mIconAlpha.value, percent, 0f,
- cornerRadius * scale, true /* isOpening */);
+ mWindowRadius.value * scale, true /* isOpening */);
+ builder.withMatrix(matrix)
+ .withWindowCrop(crop)
+ .withAlpha(1f - mIconAlpha.value)
+ .withCornerRadius(mWindowRadius.value);
} else {
- matrix.setTranslate(target.position.x, target.position.y);
- targetCrop = target.sourceContainerBounds;
- alpha = 1f;
- cornerRadius = 0;
+ matrix.setTranslate(tmpPos.x, tmpPos.y);
+ builder.withMatrix(matrix)
+ .withWindowCrop(target.screenSpaceBounds)
+ .withAlpha(1f);
}
-
- params[i] = new SurfaceParams(target.leash, alpha, matrix, targetCrop,
- RemoteAnimationProvider.getLayer(target, MODE_OPENING),
- cornerRadius);
+ builder.withLayer(RemoteAnimationProvider.getLayer(target, MODE_OPENING));
+ params[i] = builder.build();
}
surfaceApplier.scheduleApply(params);
}
});
- return appAnimator;
+
+ // When launching an app from overview that doesn't map to a task, we still want to just
+ // blur the wallpaper instead of the launcher surface as well
+ boolean allowBlurringLauncher = mLauncher.getStateManager().getState() != OVERVIEW;
+ DepthController depthController = mLauncher.getDepthController();
+ ObjectAnimator backgroundRadiusAnim = ObjectAnimator.ofFloat(depthController, DEPTH,
+ BACKGROUND_APP.getDepth(mLauncher))
+ .setDuration(APP_LAUNCH_DURATION);
+ if (allowBlurringLauncher) {
+ depthController.setSurfaceToApp(RemoteAnimationProvider.findLowestOpaqueLayerTarget(
+ appTargets, MODE_OPENING));
+ backgroundRadiusAnim.addListener(new AnimatorListenerAdapter() {
+ @Override
+ public void onAnimationEnd(Animator animation) {
+ depthController.setSurfaceToApp(null);
+ }
+ });
+ }
+
+ animatorSet.playTogether(appAnimator, backgroundRadiusAnim);
+ return animatorSet;
}
/**
@@ -591,6 +646,17 @@
new WrappedLauncherAnimationRunner<>(mWallpaperOpenRunner,
false /* startAtFrontOfQueue */),
CLOSING_TRANSITION_DURATION_MS, 0 /* statusBarTransitionDelay */));
+
+ if (KEYGUARD_ANIMATION.get()) {
+ mKeyguardGoingAwayRunner = createWallpaperOpenRunner(true /* fromUnlock */);
+ definition.addRemoteAnimation(
+ WindowManagerWrapper.TRANSIT_KEYGUARD_GOING_AWAY_ON_WALLPAPER,
+ new RemoteAnimationAdapterCompat(
+ new WrappedLauncherAnimationRunner<>(mKeyguardGoingAwayRunner,
+ true /* startAtFrontOfQueue */),
+ CLOSING_TRANSITION_DURATION_MS, 0 /* statusBarTransitionDelay */));
+ }
+
new ActivityCompat(mLauncher).registerRemoteAnimations(definition);
}
}
@@ -607,6 +673,7 @@
// definition so we don't have to wait for the system gc
mWallpaperOpenRunner = null;
mAppLaunchRunner = null;
+ mKeyguardGoingAwayRunner = null;
}
}
@@ -639,9 +706,12 @@
SurfaceParams[] params = new SurfaceParams[appTargets.length];
for (int i = appTargets.length - 1; i >= 0; i--) {
RemoteAnimationTargetCompat target = appTargets[i];
- params[i] = new SurfaceParams(target.leash, 1f, null,
- target.sourceContainerBounds,
- RemoteAnimationProvider.getLayer(target, MODE_OPENING), cornerRadius);
+ params[i] = new SurfaceParams.Builder(target.leash)
+ .withAlpha(1f)
+ .withWindowCrop(target.screenSpaceBounds)
+ .withLayer(RemoteAnimationProvider.getLayer(target, MODE_OPENING))
+ .withCornerRadius(cornerRadius)
+ .build();
}
surfaceApplier.scheduleApply(params);
}
@@ -657,6 +727,7 @@
SyncRtSurfaceTransactionApplierCompat surfaceApplier =
new SyncRtSurfaceTransactionApplierCompat(mDragLayer);
Matrix matrix = new Matrix();
+ Point tmpPos = new Point();
ValueAnimator closingAnimator = ValueAnimator.ofFloat(0, 1);
int duration = CLOSING_TRANSITION_DURATION_MS;
float windowCornerRadius = mDeviceProfile.isMultiWindowMode
@@ -672,25 +743,31 @@
SurfaceParams[] params = new SurfaceParams[appTargets.length];
for (int i = appTargets.length - 1; i >= 0; i--) {
RemoteAnimationTargetCompat target = appTargets[i];
- final float alpha;
- final float cornerRadius;
+ SurfaceParams.Builder builder = new SurfaceParams.Builder(target.leash);
+
+ tmpPos.set(target.position.x, target.position.y);
+ if (target.localBounds != null) {
+ tmpPos.set(target.localBounds.left, target.localBounds.top);
+ }
+
if (target.mode == MODE_CLOSING) {
matrix.setScale(mScale.value, mScale.value,
- target.sourceContainerBounds.centerX(),
- target.sourceContainerBounds.centerY());
+ target.screenSpaceBounds.centerX(),
+ target.screenSpaceBounds.centerY());
matrix.postTranslate(0, mDy.value);
- matrix.postTranslate(target.position.x, target.position.y);
- alpha = mAlpha.value;
- cornerRadius = windowCornerRadius;
+ matrix.postTranslate(tmpPos.x, tmpPos.y);
+ builder.withMatrix(matrix)
+ .withAlpha(mAlpha.value)
+ .withCornerRadius(windowCornerRadius);
} else {
- matrix.setTranslate(target.position.x, target.position.y);
- alpha = 1f;
- cornerRadius = 0f;
+ matrix.setTranslate(tmpPos.x, tmpPos.y);
+ builder.withMatrix(matrix)
+ .withAlpha(1f);
}
- params[i] = new SurfaceParams(target.leash, alpha, matrix,
- target.sourceContainerBounds,
- RemoteAnimationProvider.getLayer(target, MODE_CLOSING),
- cornerRadius);
+ params[i] = builder
+ .withWindowCrop(target.screenSpaceBounds)
+ .withLayer(RemoteAnimationProvider.getLayer(target, MODE_CLOSING))
+ .build();
}
surfaceApplier.scheduleApply(params);
}
@@ -699,114 +776,12 @@
return closingAnimator;
}
- /**
- * Creates an animator that modifies Launcher as a result from
- * {@link #createWallpaperOpenRunner}.
- */
- private void createLauncherResumeAnimation(AnimatorSet anim) {
- if (mLauncher.isInState(LauncherState.ALL_APPS)) {
- Pair<AnimatorSet, Runnable> contentAnimator =
- getLauncherContentAnimator(false /* isAppOpening */,
- new float[] {-mContentTransY, 0});
- contentAnimator.first.setStartDelay(LAUNCHER_RESUME_START_DELAY);
- anim.play(contentAnimator.first);
- anim.addListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationEnd(Animator animation) {
- contentAnimator.second.run();
- }
- });
- } else {
- AnimatorSet workspaceAnimator = new AnimatorSet();
-
- mDragLayer.setTranslationY(-mWorkspaceTransY);;
- workspaceAnimator.play(ObjectAnimator.ofFloat(mDragLayer, View.TRANSLATION_Y,
- -mWorkspaceTransY, 0));
-
- mDragLayerAlpha.setValue(0);
- workspaceAnimator.play(ObjectAnimator.ofFloat(
- mDragLayerAlpha, MultiValueAlpha.VALUE, 0, 1f));
-
- workspaceAnimator.setStartDelay(LAUNCHER_RESUME_START_DELAY);
- workspaceAnimator.setDuration(333);
- workspaceAnimator.setInterpolator(Interpolators.DEACCEL_1_7);
-
- mDragLayer.getScrim().hideSysUiScrim(true);
-
- // Pause page indicator animations as they lead to layer trashing.
- mLauncher.getWorkspace().getPageIndicator().pauseAnimations();
- mDragLayer.setLayerType(View.LAYER_TYPE_HARDWARE, null);
-
- workspaceAnimator.addListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationEnd(Animator animation) {
- resetContentView();
- }
- });
- anim.play(workspaceAnimator);
- }
- }
-
- private void resetContentView() {
- mLauncher.getWorkspace().getPageIndicator().skipAnimationsToEnd();
- mDragLayerAlpha.setValue(1f);
- mDragLayer.setLayerType(View.LAYER_TYPE_NONE, null);
- mDragLayer.setTranslationY(0f);
- mDragLayer.getScrim().hideSysUiScrim(false);
- }
-
private boolean hasControlRemoteAppTransitionPermission() {
return mLauncher.checkSelfPermission(CONTROL_REMOTE_APP_TRANSITION_PERMISSION)
== PackageManager.PERMISSION_GRANTED;
}
/**
- * Used with WrappedLauncherAnimationRunner as an interface for the runner to call back to the
- * implementation.
- */
- protected interface WrappedAnimationRunnerImpl {
- Handler getHandler();
- void onCreateAnimation(RemoteAnimationTargetCompat[] appTargets,
- RemoteAnimationTargetCompat[] wallpaperTargets,
- LauncherAnimationRunner.AnimationResult result);
- }
-
- /**
- * This class is needed to wrap any animation runner that is a part of the
- * RemoteAnimationDefinition:
- * - Launcher creates a new instance of the LauncherAppTransitionManagerImpl whenever it is
- * created, which in turn registers a new definition
- * - When the definition is registered, window manager retains a strong binder reference to the
- * runner passed in
- * - If the Launcher activity is recreated, the new definition registered will replace the old
- * reference in the system's activity record, but until the system server is GC'd, the binder
- * reference will still exist, which references the runner in the Launcher process, which
- * references the (old) Launcher activity through this class
- *
- * Instead we make the runner provided to the definition static only holding a weak reference to
- * the runner implementation. When this animation manager is destroyed, we remove the Launcher
- * reference to the runner, leaving only the weak ref from the runner.
- */
- protected static class WrappedLauncherAnimationRunner<R extends WrappedAnimationRunnerImpl>
- extends LauncherAnimationRunner {
- private WeakReference<R> mImpl;
-
- public WrappedLauncherAnimationRunner(R animationRunnerImpl, boolean startAtFrontOfQueue) {
- super(animationRunnerImpl.getHandler(), startAtFrontOfQueue);
- mImpl = new WeakReference<>(animationRunnerImpl);
- }
-
- @Override
- public void onCreateAnimation(RemoteAnimationTargetCompat[] appTargets,
- RemoteAnimationTargetCompat[] wallpaperTargets, AnimationResult result) {
- R animationRunnerImpl = mImpl.get();
- if (animationRunnerImpl != null) {
- animationRunnerImpl.onCreateAnimation(appTargets, wallpaperTargets, result);
- }
- }
- }
-
- /**
* Remote animation runner for animation from the app to Launcher, including recents.
*/
protected class WallpaperOpenLauncherAnimationRunner implements WrappedAnimationRunnerImpl {
@@ -872,11 +847,12 @@
|| mLauncher.isForceInvisible()) {
// Only register the content animation for cancellation when state changes
mLauncher.getStateManager().setCurrentAnimation(anim);
- if (mFromUnlock) {
+
+ if (mLauncher.isInState(LauncherState.ALL_APPS)) {
Pair<AnimatorSet, Runnable> contentAnimator =
getLauncherContentAnimator(false /* isAppOpening */,
- new float[] {mContentTransY, 0});
- contentAnimator.first.setStartDelay(0);
+ new float[] {-mContentTransY, 0});
+ contentAnimator.first.setStartDelay(LAUNCHER_RESUME_START_DELAY);
anim.play(contentAnimator.first);
anim.addListener(new AnimatorListenerAdapter() {
@Override
@@ -885,7 +861,12 @@
}
});
} else {
- createLauncherResumeAnimation(anim);
+ float velocityDpPerS = DynamicResource.provider(mLauncher)
+ .getDimension(R.dimen.unlock_staggered_velocity_dp_per_s);
+ float velocityPxPerS = TypedValue.applyDimension(COMPLEX_UNIT_DIP,
+ velocityDpPerS, mLauncher.getResources().getDisplayMetrics());
+ anim.play(new StaggeredWorkspaceAnim(mLauncher, velocityPxPerS, false)
+ .getAnimators());
}
}
}
diff --git a/quickstep/src/com/android/launcher3/WrappedAnimationRunnerImpl.java b/quickstep/src/com/android/launcher3/WrappedAnimationRunnerImpl.java
new file mode 100644
index 0000000..da2aee4
--- /dev/null
+++ b/quickstep/src/com/android/launcher3/WrappedAnimationRunnerImpl.java
@@ -0,0 +1,32 @@
+/*
+ * 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.launcher3;
+
+import android.os.Handler;
+
+import com.android.systemui.shared.system.RemoteAnimationTargetCompat;
+
+/**
+ * Used with WrappedLauncherAnimationRunner as an interface for the runner to call back to the
+ * implementation.
+ */
+public interface WrappedAnimationRunnerImpl {
+ Handler getHandler();
+ void onCreateAnimation(RemoteAnimationTargetCompat[] appTargets,
+ RemoteAnimationTargetCompat[] wallpaperTargets,
+ LauncherAnimationRunner.AnimationResult result);
+}
diff --git a/quickstep/src/com/android/launcher3/WrappedLauncherAnimationRunner.java b/quickstep/src/com/android/launcher3/WrappedLauncherAnimationRunner.java
new file mode 100644
index 0000000..1753b62
--- /dev/null
+++ b/quickstep/src/com/android/launcher3/WrappedLauncherAnimationRunner.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.launcher3;
+
+import com.android.systemui.shared.system.RemoteAnimationTargetCompat;
+
+import java.lang.ref.WeakReference;
+
+/**
+ * This class is needed to wrap any animation runner that is a part of the
+ * RemoteAnimationDefinition:
+ * - Launcher creates a new instance of the LauncherAppTransitionManagerImpl whenever it is
+ * created, which in turn registers a new definition
+ * - When the definition is registered, window manager retains a strong binder reference to the
+ * runner passed in
+ * - If the Launcher activity is recreated, the new definition registered will replace the old
+ * reference in the system's activity record, but until the system server is GC'd, the binder
+ * reference will still exist, which references the runner in the Launcher process, which
+ * references the (old) Launcher activity through this class
+ *
+ * Instead we make the runner provided to the definition static only holding a weak reference to
+ * the runner implementation. When this animation manager is destroyed, we remove the Launcher
+ * reference to the runner, leaving only the weak ref from the runner.
+ */
+public class WrappedLauncherAnimationRunner<R extends WrappedAnimationRunnerImpl>
+ extends LauncherAnimationRunner {
+ private WeakReference<R> mImpl;
+
+ public WrappedLauncherAnimationRunner(R animationRunnerImpl, boolean startAtFrontOfQueue) {
+ super(animationRunnerImpl.getHandler(), startAtFrontOfQueue);
+ mImpl = new WeakReference<>(animationRunnerImpl);
+ }
+
+ @Override
+ public void onCreateAnimation(RemoteAnimationTargetCompat[] appTargets,
+ RemoteAnimationTargetCompat[] wallpaperTargets, AnimationResult result) {
+ R animationRunnerImpl = mImpl.get();
+ if (animationRunnerImpl != null) {
+ animationRunnerImpl.onCreateAnimation(appTargets, wallpaperTargets, result);
+ }
+ }
+}
diff --git a/quickstep/src/com/android/launcher3/model/WellbeingModel.java b/quickstep/src/com/android/launcher3/model/WellbeingModel.java
index 92c8573..2181aa8 100644
--- a/quickstep/src/com/android/launcher3/model/WellbeingModel.java
+++ b/quickstep/src/com/android/launcher3/model/WellbeingModel.java
@@ -45,8 +45,8 @@
import androidx.annotation.MainThread;
import com.android.launcher3.BaseDraggingActivity;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.R;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.popup.RemoteActionShortcut;
import com.android.launcher3.popup.SystemShortcut;
import com.android.launcher3.util.MainThreadInitializedObject;
diff --git a/quickstep/src/com/android/launcher3/uioverrides/BackButtonAlphaHandler.java b/quickstep/src/com/android/launcher3/statehandlers/BackButtonAlphaHandler.java
similarity index 61%
rename from quickstep/src/com/android/launcher3/uioverrides/BackButtonAlphaHandler.java
rename to quickstep/src/com/android/launcher3/statehandlers/BackButtonAlphaHandler.java
index 43dc882..983702a 100644
--- a/quickstep/src/com/android/launcher3/uioverrides/BackButtonAlphaHandler.java
+++ b/quickstep/src/com/android/launcher3/statehandlers/BackButtonAlphaHandler.java
@@ -14,21 +14,28 @@
* limitations under the License.
*/
-package com.android.launcher3.uioverrides;
+package com.android.launcher3.statehandlers;
-import android.animation.ValueAnimator;
+import static com.android.launcher3.anim.Interpolators.LINEAR;
+import static com.android.quickstep.AnimatedFloat.VALUE;
import com.android.launcher3.BaseQuickstepLauncher;
import com.android.launcher3.LauncherState;
import com.android.launcher3.LauncherStateManager;
-import com.android.launcher3.anim.AnimatorSetBuilder;
+import com.android.launcher3.anim.PendingAnimation;
+import com.android.launcher3.states.StateAnimationConfig;
import com.android.launcher3.util.UiThreadHelper;
+import com.android.quickstep.AnimatedFloat;
import com.android.quickstep.SysUINavigationMode;
import com.android.quickstep.SystemUiProxy;
+/**
+ * State handler for animating back button alpha
+ */
public class BackButtonAlphaHandler implements LauncherStateManager.StateHandler {
private final BaseQuickstepLauncher mLauncher;
+ private final AnimatedFloat mBackAlpha = new AnimatedFloat(this::updateBackAlpha);
public BackButtonAlphaHandler(BaseQuickstepLauncher launcher) {
mLauncher = launcher;
@@ -38,9 +45,9 @@
public void setState(LauncherState state) { }
@Override
- public void setStateWithAnimation(LauncherState toState,
- AnimatorSetBuilder builder, LauncherStateManager.AnimationConfig config) {
- if (!config.playNonAtomicComponent()) {
+ public void setStateWithAnimation(LauncherState toState, StateAnimationConfig config,
+ PendingAnimation animation) {
+ if (config.onlyPlayAtomicComponent()) {
return;
}
@@ -51,17 +58,12 @@
return;
}
- float fromAlpha = SystemUiProxy.INSTANCE.get(mLauncher).getLastBackButtonAlpha();
- float toAlpha = toState.hideBackButton ? 0 : 1;
- if (Float.compare(fromAlpha, toAlpha) != 0) {
- ValueAnimator anim = ValueAnimator.ofFloat(fromAlpha, toAlpha);
- anim.setDuration(config.duration);
- anim.addUpdateListener(valueAnimator -> {
- final float alpha = (float) valueAnimator.getAnimatedValue();
- UiThreadHelper.setBackButtonAlphaAsync(mLauncher,
- BaseQuickstepLauncher.SET_BACK_BUTTON_ALPHA, alpha, false /* animate */);
- });
- builder.play(anim);
- }
+ mBackAlpha.value = SystemUiProxy.INSTANCE.get(mLauncher).getLastBackButtonAlpha();
+ animation.setFloat(mBackAlpha, VALUE, toState.hideBackButton ? 0 : 1, LINEAR);
+ }
+
+ private void updateBackAlpha() {
+ UiThreadHelper.setBackButtonAlphaAsync(mLauncher,
+ BaseQuickstepLauncher.SET_BACK_BUTTON_ALPHA, mBackAlpha.value, false /* animate */);
}
}
diff --git a/quickstep/src/com/android/launcher3/statehandlers/DepthController.java b/quickstep/src/com/android/launcher3/statehandlers/DepthController.java
new file mode 100644
index 0000000..24ba89a
--- /dev/null
+++ b/quickstep/src/com/android/launcher3/statehandlers/DepthController.java
@@ -0,0 +1,190 @@
+/*
+ * 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.launcher3.statehandlers;
+
+import static com.android.launcher3.anim.Interpolators.LINEAR;
+
+import android.os.IBinder;
+import android.util.FloatProperty;
+import android.view.View;
+import android.view.ViewTreeObserver;
+
+import com.android.launcher3.Launcher;
+import com.android.launcher3.LauncherState;
+import com.android.launcher3.LauncherStateManager;
+import com.android.launcher3.R;
+import com.android.launcher3.Utilities;
+import com.android.launcher3.anim.PendingAnimation;
+import com.android.launcher3.states.StateAnimationConfig;
+import com.android.systemui.shared.system.RemoteAnimationTargetCompat;
+import com.android.systemui.shared.system.SurfaceControlCompat;
+import com.android.systemui.shared.system.TransactionCompat;
+import com.android.systemui.shared.system.WallpaperManagerCompat;
+
+/**
+ * Controls blur and wallpaper zoom, for the Launcher surface only.
+ */
+public class DepthController implements LauncherStateManager.StateHandler {
+
+ public static final FloatProperty<DepthController> DEPTH =
+ new FloatProperty<DepthController>("depth") {
+ @Override
+ public void setValue(DepthController depthController, float depth) {
+ depthController.setDepth(depth);
+ }
+
+ @Override
+ public Float get(DepthController depthController) {
+ return depthController.mDepth;
+ }
+ };
+
+ /**
+ * A property that updates the background blur within a given range of values (ie. even if the
+ * animator goes beyond 0..1, the interpolated value will still be bounded).
+ */
+ public static class ClampedDepthProperty extends FloatProperty<DepthController> {
+ private final float mMinValue;
+ private final float mMaxValue;
+
+ public ClampedDepthProperty(float minValue, float maxValue) {
+ super("depthClamped");
+ mMinValue = minValue;
+ mMaxValue = maxValue;
+ }
+
+ @Override
+ public void setValue(DepthController depthController, float depth) {
+ depthController.setDepth(Utilities.boundToRange(depth, mMinValue, mMaxValue));
+ }
+
+ @Override
+ public Float get(DepthController depthController) {
+ return depthController.mDepth;
+ }
+ }
+
+ private final ViewTreeObserver.OnDrawListener mOnDrawListener =
+ new ViewTreeObserver.OnDrawListener() {
+ @Override
+ public void onDraw() {
+ View view = mLauncher.getDragLayer();
+ setSurface(new SurfaceControlCompat(view));
+ view.post(() -> view.getViewTreeObserver().removeOnDrawListener(this));
+ }
+ };
+
+ private final Launcher mLauncher;
+ /**
+ * Blur radius when completely zoomed out, in pixels.
+ */
+ private int mMaxBlurRadius;
+ private WallpaperManagerCompat mWallpaperManager;
+ private SurfaceControlCompat mSurface;
+ /**
+ * Ratio from 0 to 1, where 0 is fully zoomed out, and 1 is zoomed in.
+ * @see android.service.wallpaper.WallpaperService.Engine#onZoomChanged(float)
+ */
+ private float mDepth;
+
+ public DepthController(Launcher l) {
+ mLauncher = l;
+ }
+
+ private void ensureDependencies() {
+ if (mWallpaperManager != null) {
+ return;
+ }
+ mMaxBlurRadius = mLauncher.getResources().getInteger(R.integer.max_depth_blur_radius);
+ mWallpaperManager = new WallpaperManagerCompat(mLauncher);
+ }
+
+ /**
+ * Sets if the underlying activity is started or not
+ */
+ public void setActivityStarted(boolean isStarted) {
+ if (isStarted) {
+ mLauncher.getDragLayer().getViewTreeObserver().addOnDrawListener(mOnDrawListener);
+ } else {
+ mLauncher.getDragLayer().getViewTreeObserver().removeOnDrawListener(mOnDrawListener);
+ setSurface(null);
+ }
+ }
+
+ /**
+ * Sets the specified app target surface to apply the blur to.
+ */
+ public void setSurfaceToApp(RemoteAnimationTargetCompat target) {
+ if (target != null) {
+ setSurface(target.leash);
+ } else {
+ setActivityStarted(mLauncher.isStarted());
+ }
+ }
+
+ private void setSurface(SurfaceControlCompat surface) {
+ if (mSurface != surface) {
+ mSurface = surface;
+ if (surface != null) {
+ setDepth(mDepth);
+ } else {
+ // If there is no surface, then reset the ratio
+ setDepth(0f);
+ }
+ }
+ }
+
+ @Override
+ public void setState(LauncherState toState) {
+ if (mSurface == null) {
+ return;
+ }
+
+ float toDepth = toState.getDepth(mLauncher);
+ if (Float.compare(mDepth, toDepth) != 0) {
+ setDepth(toDepth);
+ }
+ }
+
+ @Override
+ public void setStateWithAnimation(LauncherState toState, StateAnimationConfig config,
+ PendingAnimation animation) {
+ if (mSurface == null || config.onlyPlayAtomicComponent()) {
+ return;
+ }
+
+ float toDepth = toState.getDepth(mLauncher);
+ if (Float.compare(mDepth, toDepth) != 0) {
+ animation.setFloat(this, DEPTH, toDepth, LINEAR);
+ }
+ }
+
+ private void setDepth(float depth) {
+ mDepth = depth;
+ if (mSurface == null || !mSurface.isValid()) {
+ return;
+ }
+ ensureDependencies();
+ IBinder windowToken = mLauncher.getRootView().getWindowToken();
+ if (windowToken != null) {
+ mWallpaperManager.setWallpaperZoomOut(windowToken, mDepth);
+ }
+ new TransactionCompat()
+ .setBackgroundBlurRadius(mSurface, (int) (mDepth * mMaxBlurRadius))
+ .apply();
+ }
+}
diff --git a/quickstep/src/com/android/launcher3/uioverrides/BaseRecentsViewStateController.java b/quickstep/src/com/android/launcher3/uioverrides/BaseRecentsViewStateController.java
index 174e49b..123c988 100644
--- a/quickstep/src/com/android/launcher3/uioverrides/BaseRecentsViewStateController.java
+++ b/quickstep/src/com/android/launcher3/uioverrides/BaseRecentsViewStateController.java
@@ -17,30 +17,32 @@
package com.android.launcher3.uioverrides;
import static com.android.launcher3.LauncherAnimUtils.SCALE_PROPERTY;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_FADE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_SCALE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_SCRIM_FADE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_TRANSLATE_X;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_TRANSLATE_Y;
-import static com.android.launcher3.anim.AnimatorSetBuilder.FLAG_DONT_ANIMATE_OVERVIEW;
+import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_X;
+import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_Y;
import static com.android.launcher3.anim.Interpolators.AGGRESSIVE_EASE_IN_OUT;
import static com.android.launcher3.anim.Interpolators.LINEAR;
import static com.android.launcher3.graphics.Scrim.SCRIM_PROGRESS;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_FADE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_SCALE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_SCRIM_FADE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_TRANSLATE_X;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_TRANSLATE_Y;
+import static com.android.launcher3.states.StateAnimationConfig.PLAY_ATOMIC_OVERVIEW_PEEK;
+import static com.android.launcher3.states.StateAnimationConfig.PLAY_ATOMIC_OVERVIEW_SCALE;
+import static com.android.launcher3.states.StateAnimationConfig.SKIP_OVERVIEW;
import android.util.FloatProperty;
import android.view.View;
-import android.view.animation.Interpolator;
import androidx.annotation.NonNull;
-import com.android.launcher3.Launcher;
+import com.android.launcher3.BaseQuickstepLauncher;
import com.android.launcher3.LauncherState;
import com.android.launcher3.LauncherState.ScaleAndTranslation;
-import com.android.launcher3.LauncherStateManager.AnimationConfig;
import com.android.launcher3.LauncherStateManager.StateHandler;
-import com.android.launcher3.anim.AnimatorSetBuilder;
-import com.android.launcher3.anim.PropertySetter;
+import com.android.launcher3.anim.PendingAnimation;
import com.android.launcher3.graphics.OverviewScrim;
+import com.android.launcher3.states.StateAnimationConfig;
/**
* State handler for recents view. Manages UI changes and animations for recents view based off the
@@ -51,9 +53,9 @@
public abstract class BaseRecentsViewStateController<T extends View>
implements StateHandler {
protected final T mRecentsView;
- protected final Launcher mLauncher;
+ protected final BaseQuickstepLauncher mLauncher;
- public BaseRecentsViewStateController(@NonNull Launcher launcher) {
+ public BaseRecentsViewStateController(@NonNull BaseQuickstepLauncher launcher) {
mLauncher = launcher;
mRecentsView = launcher.getOverviewPanel();
}
@@ -63,61 +65,49 @@
ScaleAndTranslation scaleAndTranslation = state
.getOverviewScaleAndTranslation(mLauncher);
SCALE_PROPERTY.set(mRecentsView, scaleAndTranslation.scale);
- float translationX = scaleAndTranslation.translationX;
- if (mRecentsView.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL) {
- translationX = -translationX;
- }
- mRecentsView.setTranslationX(translationX);
+ mRecentsView.setTranslationX(scaleAndTranslation.translationX);
mRecentsView.setTranslationY(scaleAndTranslation.translationY);
+
getContentAlphaProperty().set(mRecentsView, state.overviewUi ? 1f : 0);
OverviewScrim scrim = mLauncher.getDragLayer().getOverviewScrim();
SCRIM_PROGRESS.set(scrim, state.getOverviewScrimAlpha(mLauncher));
}
@Override
- public final void setStateWithAnimation(@NonNull final LauncherState toState,
- @NonNull AnimatorSetBuilder builder, @NonNull AnimationConfig config) {
- boolean playAtomicOverviewComponent = config.playAtomicOverviewScaleComponent()
- || config.playAtomicOverviewPeekComponent();
- if (!playAtomicOverviewComponent) {
+ public void setStateWithAnimation(LauncherState toState, StateAnimationConfig config,
+ PendingAnimation builder) {
+ if (!config.hasAnimationFlag(PLAY_ATOMIC_OVERVIEW_PEEK | PLAY_ATOMIC_OVERVIEW_SCALE)) {
// The entire recents animation is played atomically.
return;
}
- if (builder.hasFlag(FLAG_DONT_ANIMATE_OVERVIEW)) {
+ if (config.hasAnimationFlag(SKIP_OVERVIEW)) {
return;
}
- setStateWithAnimationInternal(toState, builder, config);
+ setStateWithAnimationInternal(toState, config, builder);
}
/**
* Core logic for animating the recents view UI.
*
* @param toState state to animate to
- * @param builder animator set builder
* @param config current animation config
+ * @param setter animator set builder
*/
void setStateWithAnimationInternal(@NonNull final LauncherState toState,
- @NonNull AnimatorSetBuilder builder, @NonNull AnimationConfig config) {
- PropertySetter setter = config.getPropertySetter(builder);
+ @NonNull StateAnimationConfig config, @NonNull PendingAnimation setter) {
ScaleAndTranslation scaleAndTranslation = toState.getOverviewScaleAndTranslation(mLauncher);
- Interpolator scaleInterpolator = builder.getInterpolator(ANIM_OVERVIEW_SCALE, LINEAR);
- setter.setFloat(mRecentsView, SCALE_PROPERTY, scaleAndTranslation.scale, scaleInterpolator);
- Interpolator translateXInterpolator = builder.getInterpolator(
- ANIM_OVERVIEW_TRANSLATE_X, LINEAR);
- Interpolator translateYInterpolator = builder.getInterpolator(
- ANIM_OVERVIEW_TRANSLATE_Y, LINEAR);
- float translationX = scaleAndTranslation.translationX;
- if (mRecentsView.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL) {
- translationX = -translationX;
- }
- setter.setFloat(mRecentsView, View.TRANSLATION_X, translationX, translateXInterpolator);
- setter.setFloat(mRecentsView, View.TRANSLATION_Y, scaleAndTranslation.translationY,
- translateYInterpolator);
+ setter.setFloat(mRecentsView, SCALE_PROPERTY, scaleAndTranslation.scale,
+ config.getInterpolator(ANIM_OVERVIEW_SCALE, LINEAR));
+ setter.setFloat(mRecentsView, VIEW_TRANSLATE_X, scaleAndTranslation.translationX,
+ config.getInterpolator(ANIM_OVERVIEW_TRANSLATE_X, LINEAR));
+ setter.setFloat(mRecentsView, VIEW_TRANSLATE_Y, scaleAndTranslation.translationY,
+ config.getInterpolator(ANIM_OVERVIEW_TRANSLATE_Y, LINEAR));
+
setter.setFloat(mRecentsView, getContentAlphaProperty(), toState.overviewUi ? 1 : 0,
- builder.getInterpolator(ANIM_OVERVIEW_FADE, AGGRESSIVE_EASE_IN_OUT));
+ config.getInterpolator(ANIM_OVERVIEW_FADE, AGGRESSIVE_EASE_IN_OUT));
OverviewScrim scrim = mLauncher.getDragLayer().getOverviewScrim();
setter.setFloat(scrim, SCRIM_PROGRESS, toState.getOverviewScrimAlpha(mLauncher),
- builder.getInterpolator(ANIM_OVERVIEW_SCRIM_FADE, LINEAR));
+ config.getInterpolator(ANIM_OVERVIEW_SCRIM_FADE, LINEAR));
}
/**
diff --git a/quickstep/src/com/android/launcher3/uioverrides/DeviceFlag.java b/quickstep/src/com/android/launcher3/uioverrides/DeviceFlag.java
index 3c3f397..010694b 100644
--- a/quickstep/src/com/android/launcher3/uioverrides/DeviceFlag.java
+++ b/quickstep/src/com/android/launcher3/uioverrides/DeviceFlag.java
@@ -23,12 +23,15 @@
import com.android.launcher3.config.FeatureFlags.DebugFlag;
+import java.util.ArrayList;
+
@TargetApi(Build.VERSION_CODES.P)
public class DeviceFlag extends DebugFlag {
public static final String NAMESPACE_LAUNCHER = "launcher";
private final boolean mDefaultValueInCode;
+ ArrayList<Runnable> mListeners;
public DeviceFlag(String key, boolean defaultValue, String description) {
super(key, getDeviceValue(key, defaultValue), description);
@@ -41,17 +44,36 @@
}
@Override
+ public void initialize(Context context) {
+ super.initialize(context);
+ if (mListeners == null) {
+ mListeners = new ArrayList<>();
+ registerDeviceConfigChangedListener(context);
+ }
+ }
+
+ @Override
public void addChangeListener(Context context, Runnable r) {
+ if (mListeners == null) {
+ initialize(context);
+ }
+ mListeners.add(r);
+ }
+
+ private void registerDeviceConfigChangedListener(Context context) {
DeviceConfig.addOnPropertiesChangedListener(
NAMESPACE_LAUNCHER,
context.getMainExecutor(),
properties -> {
- if (!NAMESPACE_LAUNCHER.equals(properties.getNamespace())) {
+ if (!NAMESPACE_LAUNCHER.equals(properties.getNamespace())
+ || !properties.getKeyset().contains(key)) {
return;
}
defaultValue = getDeviceValue(key, mDefaultValueInCode);
initialize(context);
- r.run();
+ for (Runnable r: mListeners) {
+ r.run();
+ }
});
}
diff --git a/quickstep/src/com/android/launcher3/uioverrides/DisplayRotationListener.java b/quickstep/src/com/android/launcher3/uioverrides/DisplayRotationListener.java
deleted file mode 100644
index 2d9a161..0000000
--- a/quickstep/src/com/android/launcher3/uioverrides/DisplayRotationListener.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * 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.launcher3.uioverrides;
-
-import android.content.Context;
-import android.os.Handler;
-
-import com.android.systemui.shared.system.RotationWatcher;
-
-/**
- * Utility class for listening for rotation changes
- */
-public class DisplayRotationListener extends RotationWatcher {
-
- private final Runnable mCallback;
- private Handler mHandler;
-
- public DisplayRotationListener(Context context, Runnable callback) {
- super(context);
- mCallback = callback;
- }
-
- @Override
- public void enable() {
- if (mHandler == null) {
- mHandler = new Handler();
- }
- super.enable();
- }
-
- @Override
- protected void onRotationChanged(int i) {
- mHandler.post(mCallback);
- }
-}
diff --git a/quickstep/src/com/android/launcher3/uioverrides/plugins/PluginManagerWrapper.java b/quickstep/src/com/android/launcher3/uioverrides/plugins/PluginManagerWrapper.java
index 6e7c087..2e422b7 100644
--- a/quickstep/src/com/android/launcher3/uioverrides/plugins/PluginManagerWrapper.java
+++ b/quickstep/src/com/android/launcher3/uioverrides/plugins/PluginManagerWrapper.java
@@ -14,8 +14,12 @@
package com.android.launcher3.uioverrides.plugins;
+import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
+
import android.content.ComponentName;
import android.content.Context;
+import android.content.Intent;
+import android.content.pm.ResolveInfo;
import com.android.launcher3.util.MainThreadInitializedObject;
import com.android.systemui.plugins.Plugin;
@@ -24,6 +28,9 @@
import com.android.systemui.shared.plugins.PluginManagerImpl;
import com.android.systemui.shared.plugins.PluginPrefs;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.List;
import java.util.Set;
public class PluginManagerWrapper {
@@ -75,4 +82,27 @@
public static boolean hasPlugins(Context context) {
return PluginPrefs.hasPlugins(context);
}
+
+ public void dump(PrintWriter pw) {
+ final List<ComponentName> enabledPlugins = new ArrayList<>();
+ final List<ComponentName> disabledPlugins = new ArrayList<>();
+ for (String action : getPluginActions()) {
+ for (ResolveInfo resolveInfo : mContext.getPackageManager().queryIntentServices(
+ new Intent(action), MATCH_DISABLED_COMPONENTS)) {
+ ComponentName installedPlugin = new ComponentName(
+ resolveInfo.serviceInfo.packageName, resolveInfo.serviceInfo.name);
+ if (mPluginEnabler.isEnabled(installedPlugin)) {
+ enabledPlugins.add(installedPlugin);
+ } else {
+ disabledPlugins.add(installedPlugin);
+ }
+ }
+ }
+
+ pw.println("PluginManager:");
+ pw.println(" numEnabledPlugins=" + enabledPlugins.size());
+ pw.println(" numDisabledPlugins=" + disabledPlugins.size());
+ pw.println(" enabledPlugins=" + enabledPlugins);
+ pw.println(" disabledPlugins=" + disabledPlugins);
+ }
}
diff --git a/quickstep/src/com/android/launcher3/uioverrides/states/AllAppsState.java b/quickstep/src/com/android/launcher3/uioverrides/states/AllAppsState.java
index e88a8a4..93e02a1 100644
--- a/quickstep/src/com/android/launcher3/uioverrides/states/AllAppsState.java
+++ b/quickstep/src/com/android/launcher3/uioverrides/states/AllAppsState.java
@@ -17,6 +17,8 @@
import static com.android.launcher3.anim.Interpolators.DEACCEL_2;
+import android.content.Context;
+
import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherState;
@@ -54,6 +56,12 @@
}
@Override
+ public void onStateDisabled(Launcher launcher) {
+ super.onStateDisabled(launcher);
+ AbstractFloatingView.closeAllOpenViews(launcher);
+ }
+
+ @Override
public String getDescription(Launcher launcher) {
AllAppsContainerView appsView = launcher.getAppsView();
return appsView.getDescription();
@@ -79,6 +87,11 @@
}
@Override
+ public float getDepth(Context context) {
+ return 1f;
+ }
+
+ @Override
public PageAlphaProvider getWorkspacePageAlphaProvider(Launcher launcher) {
return PAGE_ALPHA_PROVIDER;
}
diff --git a/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/LandscapeEdgeSwipeController.java b/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/LandscapeEdgeSwipeController.java
index 3cb0088..bef191e 100644
--- a/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/LandscapeEdgeSwipeController.java
+++ b/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/LandscapeEdgeSwipeController.java
@@ -9,7 +9,7 @@
import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherState;
-import com.android.launcher3.LauncherStateManager.AnimationComponents;
+import com.android.launcher3.states.StateAnimationConfig.AnimationFlags;
import com.android.launcher3.touch.AbstractStateChangeTouchController;
import com.android.launcher3.touch.SingleAxisSwipeDetector;
import com.android.launcher3.userevent.nano.LauncherLogProto;
@@ -56,7 +56,7 @@
}
@Override
- protected float initCurrentAnimation(@AnimationComponents int animComponent) {
+ protected float initCurrentAnimation(@AnimationFlags int animComponent) {
float range = getShiftRange();
long maxAccuracy = (long) (2 * range);
mCurrentAnimation = mLauncher.getStateManager().createAnimationToNewWorkspace(mToState,
diff --git a/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/PortraitStatesTouchController.java b/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/PortraitStatesTouchController.java
index 99b2a81..cc3fd97 100644
--- a/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/PortraitStatesTouchController.java
+++ b/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/PortraitStatesTouchController.java
@@ -19,13 +19,13 @@
import static com.android.launcher3.LauncherState.ALL_APPS;
import static com.android.launcher3.LauncherState.NORMAL;
import static com.android.launcher3.LauncherState.OVERVIEW;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_ALL_APPS_FADE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_FADE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_VERTICAL_PROGRESS;
import static com.android.launcher3.anim.Interpolators.ACCEL;
import static com.android.launcher3.anim.Interpolators.DEACCEL;
import static com.android.launcher3.anim.Interpolators.LINEAR;
-import static com.android.launcher3.config.FeatureFlags.QUICKSTEP_SPRINGS;
+import static com.android.launcher3.config.FeatureFlags.UNSTABLE_SPRINGS;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_ALL_APPS_FADE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_FADE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_VERTICAL_PROGRESS;
import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_OVERVIEW_DISABLED;
import android.animation.TimeInterpolator;
@@ -37,11 +37,10 @@
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherState;
-import com.android.launcher3.LauncherStateManager.AnimationComponents;
import com.android.launcher3.allapps.AllAppsTransitionController;
-import com.android.launcher3.anim.AnimatorPlaybackController;
-import com.android.launcher3.anim.AnimatorSetBuilder;
import com.android.launcher3.anim.Interpolators;
+import com.android.launcher3.states.StateAnimationConfig;
+import com.android.launcher3.states.StateAnimationConfig.AnimationFlags;
import com.android.launcher3.touch.AbstractStateChangeTouchController;
import com.android.launcher3.touch.SingleAxisSwipeDetector;
import com.android.launcher3.uioverrides.states.OverviewState;
@@ -87,8 +86,7 @@
protected boolean canInterceptTouch(MotionEvent ev) {
if (mCurrentAnimation != null) {
if (mFinishFastOnSecondTouch) {
- // TODO: Animate to finish instead.
- mCurrentAnimation.skipToEnd();
+ mCurrentAnimation.getAnimationPlayer().end();
}
AllAppsTransitionController allAppsController = mLauncher.getAllAppsController();
@@ -149,16 +147,16 @@
return isTouchOverHotseat(mLauncher, ev) ? ContainerType.HOTSEAT : ContainerType.WORKSPACE;
}
- private AnimatorSetBuilder getNormalToOverviewAnimation() {
+ private StateAnimationConfig getNormalToOverviewAnimation() {
mAllAppsInterpolatorWrapper.baseInterpolator = LINEAR;
- AnimatorSetBuilder builder = new AnimatorSetBuilder();
+ StateAnimationConfig builder = new StateAnimationConfig();
builder.setInterpolator(ANIM_VERTICAL_PROGRESS, mAllAppsInterpolatorWrapper);
return builder;
}
- public static AnimatorSetBuilder getOverviewToAllAppsAnimation() {
- AnimatorSetBuilder builder = new AnimatorSetBuilder();
+ private static StateAnimationConfig getOverviewToAllAppsAnimation() {
+ StateAnimationConfig builder = new StateAnimationConfig();
builder.setInterpolator(ANIM_ALL_APPS_FADE, Interpolators.clampToProgress(ACCEL,
0, ALL_APPS_CONTENT_FADE_THRESHOLD));
builder.setInterpolator(ANIM_OVERVIEW_FADE, Interpolators.clampToProgress(DEACCEL,
@@ -166,8 +164,8 @@
return builder;
}
- private AnimatorSetBuilder getAllAppsToOverviewAnimation() {
- AnimatorSetBuilder builder = new AnimatorSetBuilder();
+ private StateAnimationConfig getAllAppsToOverviewAnimation() {
+ StateAnimationConfig builder = new StateAnimationConfig();
builder.setInterpolator(ANIM_ALL_APPS_FADE, Interpolators.clampToProgress(DEACCEL,
1 - ALL_APPS_CONTENT_FADE_THRESHOLD, 1));
builder.setInterpolator(ANIM_OVERVIEW_FADE, Interpolators.clampToProgress(ACCEL,
@@ -175,40 +173,42 @@
return builder;
}
- private AnimatorSetBuilder getNormalToAllAppsAnimation() {
- AnimatorSetBuilder builder = new AnimatorSetBuilder();
+ private StateAnimationConfig getNormalToAllAppsAnimation() {
+ StateAnimationConfig builder = new StateAnimationConfig();
builder.setInterpolator(ANIM_ALL_APPS_FADE, Interpolators.clampToProgress(ACCEL,
0, ALL_APPS_CONTENT_FADE_THRESHOLD));
return builder;
}
- private AnimatorSetBuilder getAllAppsToNormalAnimation() {
- AnimatorSetBuilder builder = new AnimatorSetBuilder();
+ private StateAnimationConfig getAllAppsToNormalAnimation() {
+ StateAnimationConfig builder = new StateAnimationConfig();
builder.setInterpolator(ANIM_ALL_APPS_FADE, Interpolators.clampToProgress(DEACCEL,
1 - ALL_APPS_CONTENT_FADE_THRESHOLD, 1));
return builder;
}
@Override
- protected AnimatorSetBuilder getAnimatorSetBuilderForStates(LauncherState fromState,
- LauncherState toState) {
- AnimatorSetBuilder builder = new AnimatorSetBuilder();
+ protected StateAnimationConfig getConfigForStates(
+ LauncherState fromState, LauncherState toState) {
+ final StateAnimationConfig config;
if (fromState == NORMAL && toState == OVERVIEW) {
- builder = getNormalToOverviewAnimation();
+ config = getNormalToOverviewAnimation();
} else if (fromState == OVERVIEW && toState == ALL_APPS) {
- builder = getOverviewToAllAppsAnimation();
+ config = getOverviewToAllAppsAnimation();
} else if (fromState == ALL_APPS && toState == OVERVIEW) {
- builder = getAllAppsToOverviewAnimation();
+ config = getAllAppsToOverviewAnimation();
} else if (fromState == NORMAL && toState == ALL_APPS) {
- builder = getNormalToAllAppsAnimation();
+ config = getNormalToAllAppsAnimation();
} else if (fromState == ALL_APPS && toState == NORMAL) {
- builder = getAllAppsToNormalAnimation();
+ config = getAllAppsToNormalAnimation();
+ } else {
+ config = new StateAnimationConfig();
}
- return builder;
+ return config;
}
@Override
- protected float initCurrentAnimation(@AnimationComponents int animComponents) {
+ protected float initCurrentAnimation(@AnimationFlags int animFlags) {
float range = getShiftRange();
long maxAccuracy = (long) (2 * range);
@@ -217,9 +217,10 @@
float totalShift = endVerticalShift - startVerticalShift;
- final AnimatorSetBuilder builder = totalShift == 0 ? new AnimatorSetBuilder()
- : getAnimatorSetBuilderForStates(mFromState, mToState);
- updateAnimatorBuilderOnReinit(builder);
+ final StateAnimationConfig config = totalShift == 0 ? new StateAnimationConfig()
+ : getConfigForStates(mFromState, mToState);
+ config.animFlags = updateAnimComponentsOnReinit(animFlags);
+ config.duration = maxAccuracy;
cancelPendingAnim();
@@ -228,22 +229,20 @@
// Reset the state manager, when changing the interaction mode
mLauncher.getStateManager().goToState(OVERVIEW, false /* animate */);
mPendingAnimation = mOverviewPortraitStateTouchHelper
- .createSwipeDownToTaskAppAnimation(maxAccuracy);
- mPendingAnimation.anim.setInterpolator(Interpolators.LINEAR);
-
+ .createSwipeDownToTaskAppAnimation(maxAccuracy, Interpolators.LINEAR);
Runnable onCancelRunnable = () -> {
cancelPendingAnim();
clearState();
};
- mCurrentAnimation = AnimatorPlaybackController.wrap(mPendingAnimation.anim, maxAccuracy,
- onCancelRunnable);
+ mCurrentAnimation = mPendingAnimation.createPlaybackController()
+ .setOnCancelRunnable(onCancelRunnable);
mLauncher.getStateManager().setCurrentUserControlledAnimation(mCurrentAnimation);
totalShift = LayoutUtils.getShelfTrackingDistance(mLauncher,
mLauncher.getDeviceProfile());
} else {
mCurrentAnimation = mLauncher.getStateManager()
- .createAnimationToNewWorkspace(mToState, builder, maxAccuracy, this::clearState,
- animComponents);
+ .createAnimationToNewWorkspace(mToState, config)
+ .setOnCancelRunnable(this::clearState);
}
if (totalShift == 0) {
@@ -256,7 +255,9 @@
/**
* Give subclasses the chance to update the animation when we re-initialize towards a new state.
*/
- protected void updateAnimatorBuilderOnReinit(AnimatorSetBuilder builder) {
+ @AnimationFlags
+ protected int updateAnimComponentsOnReinit(@AnimationFlags int animComponents) {
+ return animComponents;
}
private void cancelPendingAnim() {
@@ -277,7 +278,7 @@
private void handleFirstSwipeToOverview(final ValueAnimator animator,
final long expectedDuration, final LauncherState targetState, final float velocity,
final boolean isFling) {
- if (QUICKSTEP_SPRINGS.get() && mFromState == OVERVIEW && mToState == ALL_APPS
+ if (UNSTABLE_SPRINGS.get() && mFromState == OVERVIEW && mToState == ALL_APPS
&& targetState == OVERVIEW) {
mFinishFastOnSecondTouch = true;
} else if (mFromState == NORMAL && mToState == OVERVIEW && targetState == OVERVIEW) {
diff --git a/quickstep/src/com/android/quickstep/BaseActivityInterface.java b/quickstep/src/com/android/quickstep/BaseActivityInterface.java
index fd55e07..94ef15a 100644
--- a/quickstep/src/com/android/quickstep/BaseActivityInterface.java
+++ b/quickstep/src/com/android/quickstep/BaseActivityInterface.java
@@ -20,6 +20,7 @@
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Build;
+import android.util.Pair;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Interpolator;
@@ -31,6 +32,8 @@
import com.android.launcher3.BaseDraggingActivity;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.anim.AnimatorPlaybackController;
+import com.android.launcher3.statehandlers.DepthController;
+import com.android.launcher3.touch.PagedOrientationHandler;
import com.android.quickstep.util.ActivityInitListener;
import com.android.quickstep.util.ShelfPeekAnim;
import com.android.systemui.shared.recents.model.ThumbnailData;
@@ -49,6 +52,15 @@
int getSwipeUpDestinationAndLength(DeviceProfile dp, Context context, Rect outRect);
+ /**
+ * @return The progress of the swipe where we start resisting the user, where 0 is fullscreen
+ * and 1 is recents. These values should probably be greater than 1 to let the user swipe past
+ * recents before we start resisting them.
+ */
+ default Pair<Float, Float> getSwipeUpPullbackStartAndMaxProgress() {
+ return new Pair<>(1.4f, 1.8f);
+ }
+
void onSwipeUpToRecentsComplete();
default void onSwipeUpToHomeComplete() { }
@@ -69,6 +81,11 @@
@Nullable
T getCreatedActivity();
+ @Nullable
+ default DepthController getDepthController() {
+ return null;
+ }
+
default boolean isResumed() {
BaseDraggingActivity activity = getCreatedActivity();
return activity != null && activity.hasBeenResumed();
@@ -148,13 +165,18 @@
// No-op
}
- static RectF getDefaultWindowTargetRect(DeviceProfile dp) {
+ static RectF getDefaultWindowTargetRect(PagedOrientationHandler orientationHandler,
+ DeviceProfile dp) {
final int halfIconSize = dp.iconSizePx / 2;
- final float targetCenterX = dp.availableWidthPx / 2f;
- final float targetCenterY = dp.availableHeightPx - dp.hotseatBarSizePx;
+ float primaryDimension = orientationHandler
+ .getPrimaryValue(dp.availableWidthPx, dp.availableHeightPx);
+ float secondaryDimension = orientationHandler
+ .getSecondaryValue(dp.availableWidthPx, dp.availableHeightPx);
+ final float targetX = primaryDimension / 2f;
+ final float targetY = secondaryDimension - dp.hotseatBarSizePx;
// Fallback to animate to center of screen.
- return new RectF(targetCenterX - halfIconSize, targetCenterY - halfIconSize,
- targetCenterX + halfIconSize, targetCenterY + halfIconSize);
+ return new RectF(targetX - halfIconSize, targetY - halfIconSize,
+ targetX + halfIconSize, targetY + halfIconSize);
}
}
diff --git a/quickstep/src/com/android/quickstep/GestureState.java b/quickstep/src/com/android/quickstep/GestureState.java
index ae0886b..5118906 100644
--- a/quickstep/src/com/android/quickstep/GestureState.java
+++ b/quickstep/src/com/android/quickstep/GestureState.java
@@ -19,10 +19,12 @@
import android.app.ActivityManager;
import android.content.Intent;
+
import com.android.launcher3.BaseDraggingActivity;
-import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
import com.android.systemui.shared.recents.model.ThumbnailData;
+
+import java.io.PrintWriter;
import java.util.ArrayList;
/**
@@ -62,6 +64,8 @@
private static final String TAG = "GestureState";
private static final ArrayList<String> STATE_NAMES = new ArrayList<>();
+ public static final GestureState DEFAULT_STATE = new GestureState();
+
private static int FLAG_COUNT = 0;
private static int getFlagForIndex(String name) {
if (DEBUG_STATES) {
@@ -101,6 +105,10 @@
public static final int STATE_RECENTS_ANIMATION_ENDED =
getFlagForIndex("STATE_RECENTS_ANIMATION_ENDED");
+ // Called when RecentsView stops scrolling and settles on a TaskView.
+ public static final int STATE_RECENTS_SCROLLING_FINISHED =
+ getFlagForIndex("STATE_RECENTS_SCROLLING_FINISHED");
+
// Needed to interact with the current activity
private final Intent mHomeIntent;
@@ -122,6 +130,17 @@
mGestureId = gestureId;
}
+ public GestureState(GestureState other) {
+ mHomeIntent = other.mHomeIntent;
+ mOverviewIntent = other.mOverviewIntent;
+ mActivityInterface = other.mActivityInterface;
+ mStateCallback = other.mStateCallback;
+ mGestureId = other.mGestureId;
+ mRunningTask = other.mRunningTask;
+ mEndTarget = other.mEndTarget;
+ mFinishingRecentsAnimationTaskId = other.mFinishingRecentsAnimationTaskId;
+ }
+
public GestureState() {
// Do nothing, only used for initializing the gesture state prior to user unlock
mHomeIntent = new Intent();
@@ -281,4 +300,13 @@
mStateCallback.setState(STATE_RECENTS_ANIMATION_FINISHED);
mStateCallback.setState(STATE_RECENTS_ANIMATION_ENDED);
}
+
+ public void dump(PrintWriter pw) {
+ pw.println("GestureState:");
+ pw.println(" gestureID=" + mGestureId);
+ pw.println(" runningTask=" + mRunningTask);
+ pw.println(" endTarget=" + mEndTarget);
+ pw.println(" finishingRecentsAnimationTaskId=" + mFinishingRecentsAnimationTaskId);
+ pw.println(" isRecentsAnimationRunning=" + isRecentsAnimationRunning());
+ }
}
diff --git a/quickstep/src/com/android/quickstep/InputConsumer.java b/quickstep/src/com/android/quickstep/InputConsumer.java
index 3e84e7d..a4861dc 100644
--- a/quickstep/src/com/android/quickstep/InputConsumer.java
+++ b/quickstep/src/com/android/quickstep/InputConsumer.java
@@ -60,6 +60,23 @@
}
/**
+ * Returns true if the lifecycle of this input consumer is detached from the normal gesture
+ * down/up flow. If so, it is the responsibility of the input consumer to call back to
+ * {@link TouchInteractionService#onConsumerInactive(InputConsumer)} after the consumer is
+ * finished.
+ */
+ default boolean isConsumerDetachedFromGesture() {
+ return false;
+ }
+
+ /**
+ * Returns the active input consumer is in the hierarchy of this input consumer.
+ */
+ default InputConsumer getActiveConsumerInHierarchy() {
+ return this;
+ }
+
+ /**
* Called by the event queue when the consumer is about to be switched to a new consumer.
* Consumers should update the state accordingly here before the state is passed to the new
* consumer.
@@ -79,15 +96,15 @@
}
default String getName() {
- String name = "";
+ StringBuilder name = new StringBuilder();
for (int i = 0; i < NAMES.length; i++) {
if ((getType() & (1 << i)) != 0) {
if (name.length() > 0) {
- name += ":";
+ name.append(":");
}
- name += NAMES[i];
+ name.append(NAMES[i]);
}
}
- return name;
+ return name.toString();
}
}
diff --git a/quickstep/src/com/android/quickstep/InstantAppResolverImpl.java b/quickstep/src/com/android/quickstep/InstantAppResolverImpl.java
index 3e9872a..7638541 100644
--- a/quickstep/src/com/android/quickstep/InstantAppResolverImpl.java
+++ b/quickstep/src/com/android/quickstep/InstantAppResolverImpl.java
@@ -21,7 +21,7 @@
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
-import com.android.launcher3.AppInfo;
+import com.android.launcher3.model.data.AppInfo;
import com.android.launcher3.util.InstantAppResolver;
/**
diff --git a/quickstep/src/com/android/quickstep/MultiStateCallback.java b/quickstep/src/com/android/quickstep/MultiStateCallback.java
index 6c65e01..b3875ae 100644
--- a/quickstep/src/com/android/quickstep/MultiStateCallback.java
+++ b/quickstep/src/com/android/quickstep/MultiStateCallback.java
@@ -130,7 +130,7 @@
final LinkedList<Runnable> callbacks;
if (mCallbacks.indexOfKey(stateMask) >= 0) {
callbacks = mCallbacks.get(stateMask);
- if (FeatureFlags.IS_DOGFOOD_BUILD && callbacks.contains(callback)) {
+ if (FeatureFlags.IS_STUDIO_BUILD && callbacks.contains(callback)) {
throw new IllegalStateException("Existing callback for state found");
}
} else {
diff --git a/quickstep/src/com/android/quickstep/OrientationTouchTransformer.java b/quickstep/src/com/android/quickstep/OrientationTouchTransformer.java
new file mode 100644
index 0000000..495c092
--- /dev/null
+++ b/quickstep/src/com/android/quickstep/OrientationTouchTransformer.java
@@ -0,0 +1,379 @@
+/*
+ * 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.quickstep;
+
+import static android.view.MotionEvent.ACTION_CANCEL;
+import static android.view.MotionEvent.ACTION_DOWN;
+import static android.view.MotionEvent.ACTION_MOVE;
+import static android.view.MotionEvent.ACTION_POINTER_DOWN;
+import static android.view.MotionEvent.ACTION_UP;
+
+import static com.android.quickstep.util.RecentsOrientedState.postDisplayRotation;
+
+import android.content.res.Resources;
+import android.graphics.Matrix;
+import android.graphics.Point;
+import android.graphics.RectF;
+import android.util.Log;
+import android.util.SparseArray;
+import android.view.MotionEvent;
+import android.view.Surface;
+
+import com.android.launcher3.R;
+import com.android.launcher3.ResourceUtils;
+import com.android.launcher3.util.DefaultDisplay;
+import com.android.quickstep.util.RecentsOrientedState.SurfaceRotation;
+
+import java.io.PrintWriter;
+
+/**
+ * Maintains state for supporting nav bars and tracking their gestures in multiple orientations.
+ * See {@link OrientationRectF#applyTransform(MotionEvent, boolean)} for transformation of
+ * MotionEvents from one orientation's coordinate space to another's.
+ *
+ * This class only supports single touch/pointer gesture tracking for touches started in a supported
+ * nav bar region.
+ */
+class OrientationTouchTransformer {
+
+ private static final String TAG = "OrientationTouchTransformer";
+ private static final boolean DEBUG = false;
+ private static final int MAX_ORIENTATIONS = 4;
+
+ private final Matrix mTmpMatrix = new Matrix();
+ private final float[] mTmpPoint = new float[2];
+
+ private SparseArray<OrientationRectF> mSwipeTouchRegions = new SparseArray<>(MAX_ORIENTATIONS);
+ private final RectF mAssistantLeftRegion = new RectF();
+ private final RectF mAssistantRightRegion = new RectF();
+ private int mCurrentDisplayRotation;
+ private boolean mEnableMultipleRegions;
+ private Resources mResources;
+ private OrientationRectF mLastRectTouched;
+ private SysUINavigationMode.Mode mMode;
+ private QuickStepContractInfo mContractInfo;
+
+ /**
+ * Represents if we're currently in a swipe "session" of sorts. If value is -1, then user
+ * has not tapped on an active nav region. Otherwise it will be the rotation of the display
+ * when the user first interacted with the active nav bar region.
+ * The "session" ends when {@link #enableMultipleRegions(boolean, DefaultDisplay.Info)} is
+ * called - usually from a timeout or if user starts interacting w/ the foreground app.
+ *
+ * This is different than {@link #mLastRectTouched} as it can get reset by the system whereas
+ * the rect is purely used for tracking touch interactions and usually this "session" will
+ * outlast the touch interaction.
+ */
+ private int mQuickStepStartingRotation = -1;
+
+ /** For testability */
+ interface QuickStepContractInfo {
+ float getWindowCornerRadius();
+ }
+
+
+ OrientationTouchTransformer(Resources resources, SysUINavigationMode.Mode mode,
+ QuickStepContractInfo contractInfo) {
+ mResources = resources;
+ mMode = mode;
+ mContractInfo = contractInfo;
+ }
+
+ void setNavigationMode(SysUINavigationMode.Mode newMode, DefaultDisplay.Info info) {
+ if (mMode == newMode) {
+ return;
+ }
+ this.mMode = newMode;
+ resetSwipeRegions(info);
+ }
+
+ /**
+ * Sets the current nav bar region to listen to events for as determined by
+ * {@param info}. If multiple nav bar regions are enabled, then this region will be added
+ * alongside other regions.
+ * Ok to call multiple times
+ *
+ * @see #enableMultipleRegions(boolean, DefaultDisplay.Info)
+ */
+ void createOrAddTouchRegion(DefaultDisplay.Info info) {
+ mCurrentDisplayRotation = info.rotation;
+ if (mQuickStepStartingRotation > -1
+ && mCurrentDisplayRotation == mQuickStepStartingRotation) {
+ // User already was swiping and the current screen is same rotation as the starting one
+ // Remove active nav bars in other rotations except for the one we started out in
+ resetSwipeRegions(info);
+ return;
+ }
+ OrientationRectF region = mSwipeTouchRegions.get(mCurrentDisplayRotation);
+ if (region != null) {
+ return;
+ }
+
+ if (mEnableMultipleRegions) {
+ mSwipeTouchRegions.put(mCurrentDisplayRotation, createRegionForDisplay(info));
+ } else {
+ resetSwipeRegions(info);
+ }
+ }
+
+ /**
+ * Call when we want to start tracking nav bar touch regions in multiple orientations.
+ * ALSO, you BETTER call this with {@param enableMultipleRegions} set to false once you're done.
+ *
+ * @param enableMultipleRegions Set to true to start tracking multiple nav bar regions
+ * @param info The current displayInfo
+ */
+ void enableMultipleRegions(boolean enableMultipleRegions, DefaultDisplay.Info info) {
+ mEnableMultipleRegions = enableMultipleRegions;
+ if (!enableMultipleRegions) {
+ mQuickStepStartingRotation = -1;
+ resetSwipeRegions(info);
+ }
+ }
+
+ /**
+ * Only saves the swipe region represented by {@param region}, clears the
+ * rest from {@link #mSwipeTouchRegions}
+ * To be called whenever we want to stop tracking more than one swipe region.
+ * Ok to call multiple times.
+ */
+ private void resetSwipeRegions(DefaultDisplay.Info region) {
+ if (DEBUG) {
+ Log.d(TAG, "clearing all regions except rotation: " + mCurrentDisplayRotation);
+ }
+
+ mCurrentDisplayRotation = region.rotation;
+ OrientationRectF regionToKeep = mSwipeTouchRegions.get(mCurrentDisplayRotation);
+ mSwipeTouchRegions.clear();
+ mSwipeTouchRegions.put(mCurrentDisplayRotation,
+ regionToKeep != null ? regionToKeep : createRegionForDisplay(region));
+ }
+
+ private void resetSwipeRegions() {
+ OrientationRectF regionToKeep = mSwipeTouchRegions.get(mCurrentDisplayRotation);
+ mSwipeTouchRegions.clear();
+ mSwipeTouchRegions.put(mCurrentDisplayRotation, regionToKeep);
+ }
+
+ private OrientationRectF createRegionForDisplay(DefaultDisplay.Info display) {
+ if (DEBUG) {
+ Log.d(TAG, "creating rotation region for: " + mCurrentDisplayRotation);
+ }
+
+ Point size = display.realSize;
+ int rotation = display.rotation;
+ OrientationRectF orientationRectF =
+ new OrientationRectF(0, 0, size.x, size.y, rotation);
+ if (mMode == SysUINavigationMode.Mode.NO_BUTTON) {
+ int touchHeight = getNavbarSize(ResourceUtils.NAVBAR_BOTTOM_GESTURE_SIZE);
+ orientationRectF.top = orientationRectF.bottom - touchHeight;
+
+ final int assistantWidth = mResources
+ .getDimensionPixelSize(R.dimen.gestures_assistant_width);
+ final float assistantHeight = Math.max(touchHeight,
+ mContractInfo.getWindowCornerRadius());
+ mAssistantLeftRegion.bottom = mAssistantRightRegion.bottom = orientationRectF.bottom;
+ mAssistantLeftRegion.top = mAssistantRightRegion.top =
+ orientationRectF.bottom - assistantHeight;
+
+ mAssistantLeftRegion.left = 0;
+ mAssistantLeftRegion.right = assistantWidth;
+
+ mAssistantRightRegion.right = orientationRectF.right;
+ mAssistantRightRegion.left = orientationRectF.right - assistantWidth;
+ } else {
+ mAssistantLeftRegion.setEmpty();
+ mAssistantRightRegion.setEmpty();
+ switch (rotation) {
+ case Surface.ROTATION_90:
+ orientationRectF.left = orientationRectF.right
+ - getNavbarSize(ResourceUtils.NAVBAR_LANDSCAPE_LEFT_RIGHT_SIZE);
+ break;
+ case Surface.ROTATION_270:
+ orientationRectF.right = orientationRectF.left
+ + getNavbarSize(ResourceUtils.NAVBAR_LANDSCAPE_LEFT_RIGHT_SIZE);
+ break;
+ default:
+ orientationRectF.top = orientationRectF.bottom
+ - getNavbarSize(ResourceUtils.NAVBAR_BOTTOM_GESTURE_SIZE);
+ }
+ }
+
+ return orientationRectF;
+ }
+
+ boolean touchInAssistantRegion(MotionEvent ev) {
+ return mAssistantLeftRegion.contains(ev.getX(), ev.getY())
+ || mAssistantRightRegion.contains(ev.getX(), ev.getY());
+
+ }
+
+ private int getNavbarSize(String resName) {
+ return ResourceUtils.getNavbarSize(resName, mResources);
+ }
+
+ boolean touchInValidSwipeRegions(float x, float y) {
+ if (mLastRectTouched != null) {
+ return mLastRectTouched.contains(x, y);
+ }
+ return false;
+ }
+
+ int getCurrentActiveRotation() {
+ if (mLastRectTouched == null) {
+ return 0;
+ } else {
+ return mLastRectTouched.mRotation;
+ }
+ }
+
+ int getQuickStepStartingRotation() {
+ return mQuickStepStartingRotation;
+ }
+
+ public void transform(MotionEvent event) {
+ int eventAction = event.getActionMasked();
+ switch (eventAction) {
+ case ACTION_MOVE: {
+ if (mLastRectTouched == null) {
+ return;
+ }
+ mLastRectTouched.applyTransform(event, true);
+ break;
+ }
+ case ACTION_CANCEL:
+ case ACTION_UP: {
+ if (mLastRectTouched == null) {
+ return;
+ }
+ mLastRectTouched.applyTransform(event, true);
+ mLastRectTouched = null;
+ break;
+ }
+ case ACTION_POINTER_DOWN:
+ case ACTION_DOWN: {
+ if (mLastRectTouched != null) {
+ return;
+ }
+
+ for (int i = 0; i < MAX_ORIENTATIONS; i++) {
+ OrientationRectF rect = mSwipeTouchRegions.get(i);
+ if (rect == null) {
+ continue;
+ }
+ if (rect.applyTransform(event, false)) {
+ mLastRectTouched = rect;
+ if (mCurrentDisplayRotation == mLastRectTouched.mRotation) {
+ // Start a touch session for the default nav region for the display
+ mQuickStepStartingRotation = mLastRectTouched.mRotation;
+ resetSwipeRegions();
+ }
+ if (DEBUG) {
+ Log.d(TAG, "set active region: " + rect);
+ }
+ return;
+ }
+ }
+ break;
+ }
+ }
+ }
+
+ public void dump(PrintWriter pw) {
+ pw.println("OrientationTouchTransformerState: ");
+ pw.println(" currentActiveRotation=" + getCurrentActiveRotation());
+ pw.println(" lastTouchedRegion=" + mLastRectTouched);
+ pw.println(" multipleRegionsEnabled=" + mEnableMultipleRegions);
+ StringBuilder regions = new StringBuilder(" currentTouchableRotations=");
+ for(int i = 0; i < mSwipeTouchRegions.size(); i++) {
+ OrientationRectF rectF = mSwipeTouchRegions.get(mSwipeTouchRegions.keyAt(i));
+ regions.append(rectF.mRotation).append(" ");
+ }
+ pw.println(regions.toString());
+ }
+
+ private class OrientationRectF extends RectF {
+
+ /**
+ * Delta to subtract width and height by because if we report the translated touch
+ * bounds as the width and height, calling {@link RectF#contains(float, float)} will
+ * be false
+ */
+ private float maxDelta = 0.001f;
+
+ private int mRotation;
+ private float mHeight;
+ private float mWidth;
+
+ OrientationRectF(float left, float top, float right, float bottom, int rotation) {
+ super(left, top, right, bottom);
+ this.mRotation = rotation;
+ mHeight = bottom - maxDelta;
+ mWidth = right - maxDelta;
+ }
+
+ @Override
+ public String toString() {
+ String s = super.toString();
+ s += " rotation: " + mRotation;
+ return s;
+ }
+
+ boolean applyTransform(MotionEvent event, boolean forceTransform) {
+ mTmpMatrix.reset();
+ postDisplayRotation(deltaRotation(mCurrentDisplayRotation, mRotation),
+ mHeight, mWidth, mTmpMatrix);
+ if (forceTransform) {
+ if (DEBUG) {
+ Log.d(TAG, "Transforming rotation due to forceTransform, "
+ + "mCurrentRotation: " + mCurrentDisplayRotation
+ + "mRotation: " + mRotation);
+ }
+ event.transform(mTmpMatrix);
+ return true;
+ }
+ mTmpPoint[0] = event.getX();
+ mTmpPoint[1] = event.getY();
+ mTmpMatrix.mapPoints(mTmpPoint);
+
+ if (DEBUG) {
+ Log.d(TAG, "original: " + event.getX() + ", " + event.getY()
+ + " new: " + mTmpPoint[0] + ", " + mTmpPoint[1]
+ + " rect: " + this + " forceTransform: " + forceTransform
+ + " contains: " + contains(mTmpPoint[0], mTmpPoint[1]));
+ }
+
+ if (contains(mTmpPoint[0], mTmpPoint[1])) {
+ event.transform(mTmpMatrix);
+ return true;
+ }
+ return false;
+ }
+ }
+
+ /**
+ * @return how many factors {@param newRotation} is rotated 90 degrees clockwise.
+ * E.g. 1->Rotated by 90 degrees clockwise, 2->Rotated 180 clockwise...
+ * A value of 0 means no rotation has been applied
+ */
+ @SurfaceRotation
+ private static int deltaRotation(int oldRotation, int newRotation) {
+ int delta = newRotation - oldRotation;
+ if (delta < 0) delta += 4;
+ return delta;
+ }
+}
diff --git a/quickstep/src/com/android/quickstep/OverviewComponentObserver.java b/quickstep/src/com/android/quickstep/OverviewComponentObserver.java
index 73b78db..231ee72 100644
--- a/quickstep/src/com/android/quickstep/OverviewComponentObserver.java
+++ b/quickstep/src/com/android/quickstep/OverviewComponentObserver.java
@@ -22,6 +22,7 @@
import static com.android.launcher3.util.PackageManagerHelper.getPackageFilter;
import static com.android.systemui.shared.system.PackageManagerWrapper.ACTION_PREFERRED_ACTIVITY_CHANGED;
+import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_ASSIST_GESTURE_CONSTRAINED;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
@@ -33,34 +34,33 @@
import android.content.pm.ResolveInfo;
import android.util.SparseIntArray;
+import com.android.launcher3.util.SimpleBroadcastReceiver;
import com.android.systemui.shared.system.PackageManagerWrapper;
+import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Objects;
+import java.util.function.Consumer;
/**
* Class to keep track of the current overview component based off user preferences and app updates
* and provide callers the relevant classes.
*/
public final class OverviewComponentObserver {
- private final BroadcastReceiver mUserPreferenceChangeReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- updateOverviewTargets();
- }
- };
- private final BroadcastReceiver mOtherHomeAppUpdateReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- updateOverviewTargets();
- }
- };
+ private final BroadcastReceiver mUserPreferenceChangeReceiver =
+ new SimpleBroadcastReceiver(this::updateOverviewTargets);
+ private final BroadcastReceiver mOtherHomeAppUpdateReceiver =
+ new SimpleBroadcastReceiver(this::updateOverviewTargets);
+
private final Context mContext;
private final RecentsAnimationDeviceState mDeviceState;
private final Intent mCurrentHomeIntent;
private final Intent mMyHomeIntent;
private final Intent mFallbackIntent;
private final SparseIntArray mConfigChangesMap = new SparseIntArray();
+
+ private Consumer<Boolean> mOverviewChangeListener = b -> { };
+
private String mUpdateRegisteredPackage;
private BaseActivityInterface mActivityInterface;
private Intent mOverviewIntent;
@@ -68,10 +68,10 @@
private boolean mIsDefaultHome;
private boolean mIsHomeDisabled;
+
public OverviewComponentObserver(Context context, RecentsAnimationDeviceState deviceState) {
mContext = context;
mDeviceState = deviceState;
-
mCurrentHomeIntent = new Intent(Intent.ACTION_MAIN)
.addCategory(Intent.CATEGORY_HOME)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
@@ -99,12 +99,27 @@
updateOverviewTargets();
}
+ /**
+ * Sets a listener for changes in {@link #isHomeAndOverviewSame()}
+ */
+ public void setOverviewChangeListener(Consumer<Boolean> overviewChangeListener) {
+ mOverviewChangeListener = overviewChangeListener;
+ }
+
public void onSystemUiStateChanged() {
if (mDeviceState.isHomeDisabled() != mIsHomeDisabled) {
updateOverviewTargets();
}
}
+ private void updateOverviewTargets(Intent unused) {
+ updateOverviewTargets();
+ }
+
+ public boolean assistantGestureIsConstrained() {
+ return (mDeviceState.getSystemUiStateFlags() & SYSUI_STATE_ASSIST_GESTURE_CONSTRAINED) != 0;
+ }
+
/**
* Update overview intent and {@link BaseActivityInterface} based off the current launcher home
* component.
@@ -130,11 +145,8 @@
mOverviewIntent = mMyHomeIntent;
mCurrentHomeIntent.setComponent(mMyHomeIntent.getComponent());
- if (mUpdateRegisteredPackage != null) {
- // Remove any update listener as we don't care about other packages.
- mContext.unregisterReceiver(mOtherHomeAppUpdateReceiver);
- mUpdateRegisteredPackage = null;
- }
+ // Remove any update listener as we don't care about other packages.
+ unregisterOtherHomeAppUpdateReceiver();
} else {
// The default home app is a different launcher. Use the fallback Overview instead.
@@ -148,13 +160,9 @@
// Listen for package updates of this app (and remove any previously attached
// package listener).
if (defaultHome == null) {
- if (mUpdateRegisteredPackage != null) {
- mContext.unregisterReceiver(mOtherHomeAppUpdateReceiver);
- }
+ unregisterOtherHomeAppUpdateReceiver();
} else if (!defaultHome.getPackageName().equals(mUpdateRegisteredPackage)) {
- if (mUpdateRegisteredPackage != null) {
- mContext.unregisterReceiver(mOtherHomeAppUpdateReceiver);
- }
+ unregisterOtherHomeAppUpdateReceiver();
mUpdateRegisteredPackage = defaultHome.getPackageName();
mContext.registerReceiver(mOtherHomeAppUpdateReceiver, getPackageFilter(
@@ -162,6 +170,7 @@
ACTION_PACKAGE_REMOVED));
}
}
+ mOverviewChangeListener.accept(mIsHomeAndOverviewSame);
}
/**
@@ -169,7 +178,10 @@
*/
public void onDestroy() {
mContext.unregisterReceiver(mUserPreferenceChangeReceiver);
+ unregisterOtherHomeAppUpdateReceiver();
+ }
+ private void unregisterOtherHomeAppUpdateReceiver() {
if (mUpdateRegisteredPackage != null) {
mContext.unregisterReceiver(mOtherHomeAppUpdateReceiver);
mUpdateRegisteredPackage = null;
@@ -233,4 +245,13 @@
public BaseActivityInterface getActivityInterface() {
return mActivityInterface;
}
+
+ public void dump(PrintWriter pw) {
+ pw.println("OverviewComponentObserver:");
+ pw.println(" isDefaultHome=" + mIsDefaultHome);
+ pw.println(" isHomeDisabled=" + mIsHomeDisabled);
+ pw.println(" homeAndOverviewSame=" + mIsHomeAndOverviewSame);
+ pw.println(" overviewIntent=" + mOverviewIntent);
+ pw.println(" homeIntent=" + mCurrentHomeIntent);
+ }
}
diff --git a/quickstep/src/com/android/quickstep/RecentsAnimationCallbacks.java b/quickstep/src/com/android/quickstep/RecentsAnimationCallbacks.java
index acf61b4..d1dbcfb 100644
--- a/quickstep/src/com/android/quickstep/RecentsAnimationCallbacks.java
+++ b/quickstep/src/com/android/quickstep/RecentsAnimationCallbacks.java
@@ -19,11 +19,13 @@
import android.graphics.Rect;
import android.util.ArraySet;
+import android.util.Log;
import androidx.annotation.BinderThread;
import androidx.annotation.UiThread;
import com.android.launcher3.Utilities;
+import com.android.launcher3.testing.TestProtocol;
import com.android.launcher3.util.Preconditions;
import com.android.systemui.shared.recents.model.ThumbnailData;
import com.android.systemui.shared.system.RecentsAnimationControllerCompat;
@@ -62,6 +64,12 @@
mListeners.remove(listener);
}
+ @UiThread
+ public void removeAllListeners() {
+ Preconditions.assertUIThread();
+ mListeners.clear();
+ }
+
public void notifyAnimationCanceled() {
mCancelled = true;
onAnimationCanceled(null);
diff --git a/quickstep/src/com/android/quickstep/RecentsAnimationController.java b/quickstep/src/com/android/quickstep/RecentsAnimationController.java
index 46af8bf..8dd4aa4 100644
--- a/quickstep/src/com/android/quickstep/RecentsAnimationController.java
+++ b/quickstep/src/com/android/quickstep/RecentsAnimationController.java
@@ -39,7 +39,7 @@
import java.util.function.Supplier;
/**
- * Wrapper around RecentsAnimationController to help with some synchronization
+ * Wrapper around RecentsAnimationControllerCompat to help with some synchronization
*/
public class RecentsAnimationController {
@@ -81,12 +81,9 @@
mWindowThresholdCrossed = windowThresholdCrossed;
UI_HELPER_EXECUTOR.execute(() -> {
mController.setAnimationTargetsBehindSystemBars(!windowThresholdCrossed);
- if (mShouldMinimizeSplitScreen && windowThresholdCrossed) {
- // NOTE: As a workaround for conflicting animations (Launcher animating the task
- // leash, and SystemUI resizing the docked stack, which resizes the task), we
- // currently only set the minimized mode, and not the inverse.
- // TODO: Synchronize the minimize animation with the launcher animation
- mController.setSplitScreenMinimized(windowThresholdCrossed);
+ SystemUiProxy p = SystemUiProxy.INSTANCE.getNoCreate();
+ if (p != null && mShouldMinimizeSplitScreen) {
+ p.setSplitScreenMinimized(windowThresholdCrossed);
}
});
}
@@ -201,6 +198,7 @@
if (mInputConsumerController != null) {
mInputConsumerController.setInputListener(null);
}
+ mInputProxySupplier = null;
}
private boolean onInputConsumerEvent(InputEvent ev) {
diff --git a/quickstep/src/com/android/quickstep/RecentsAnimationDeviceState.java b/quickstep/src/com/android/quickstep/RecentsAnimationDeviceState.java
index d0afb21..6dbf2b0 100644
--- a/quickstep/src/com/android/quickstep/RecentsAnimationDeviceState.java
+++ b/quickstep/src/com/android/quickstep/RecentsAnimationDeviceState.java
@@ -17,13 +17,13 @@
import static android.content.Intent.ACTION_USER_UNLOCKED;
-import static com.android.launcher3.ResourceUtils.NAVBAR_BOTTOM_GESTURE_SIZE;
-import static com.android.launcher3.ResourceUtils.NAVBAR_LANDSCAPE_LEFT_RIGHT_SIZE;
+import static com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR;
import static com.android.quickstep.SysUINavigationMode.Mode.NO_BUTTON;
import static com.android.quickstep.SysUINavigationMode.Mode.THREE_BUTTONS;
import static com.android.quickstep.SysUINavigationMode.Mode.TWO_BUTTONS;
import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_A11Y_BUTTON_CLICKABLE;
import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_A11Y_BUTTON_LONG_CLICKABLE;
+import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_BUBBLES_EXPANDED;
import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_HOME_DISABLED;
import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_NAV_BAR_HIDDEN;
import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_NOTIFICATION_PANEL_EXPANDED;
@@ -40,21 +40,18 @@
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
-import android.graphics.Point;
-import android.graphics.RectF;
import android.graphics.Region;
import android.os.Process;
import android.os.UserManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
-import android.view.Surface;
import androidx.annotation.BinderThread;
import com.android.launcher3.R;
-import com.android.launcher3.ResourceUtils;
import com.android.launcher3.Utilities;
+import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.testing.TestProtocol;
import com.android.launcher3.util.DefaultDisplay;
import com.android.quickstep.SysUINavigationMode.NavigationModeChangeListener;
@@ -63,9 +60,12 @@
import com.android.systemui.shared.system.QuickStepContract;
import com.android.systemui.shared.system.QuickStepContract.SystemUiStateFlags;
import com.android.systemui.shared.system.SystemGestureExclusionListenerCompat;
+import com.android.systemui.shared.system.TaskStackChangeListener;
import java.io.PrintWriter;
import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
/**
* Manages the state of the system during a swipe up gesture.
@@ -74,10 +74,13 @@
NavigationModeChangeListener,
DefaultDisplay.DisplayInfoChangeListener {
+ private static final String TAG = "RecentsAnimationDeviceState";
+
private final Context mContext;
private final SysUINavigationMode mSysUiNavMode;
private final DefaultDisplay mDefaultDisplay;
private final int mDisplayId;
+ private int mDisplayRotation;
private final ArrayList<Runnable> mOnDestroyActions = new ArrayList<>();
@@ -85,10 +88,7 @@
private SysUINavigationMode.Mode mMode = THREE_BUTTONS;
private NavBarPosition mNavBarPosition;
- private final RectF mSwipeUpTouchRegion = new RectF();
private final Region mDeferredGestureRegion = new Region();
- private final RectF mAssistantLeftRegion = new RectF();
- private final RectF mAssistantRightRegion = new RectF();
private boolean mAssistantAvailable;
private float mAssistantVisibility;
@@ -98,19 +98,32 @@
@Override
public void onReceive(Context context, Intent intent) {
if (ACTION_USER_UNLOCKED.equals(intent.getAction())) {
+ Log.d(TAG, "User Unlocked Broadcast Received");
mIsUserUnlocked = true;
notifyUserUnlocked();
}
}
};
+ private TaskStackChangeListener mFrozenTaskListener = new TaskStackChangeListener() {
+ @Override
+ public void onRecentTaskListFrozenChanged(boolean frozen) {
+ if (frozen) {
+ return;
+ }
+ mOrientationTouchTransformer.enableMultipleRegions(false, mDefaultDisplay.getInfo());
+ }
+ };
+
+ private OrientationTouchTransformer mOrientationTouchTransformer;
+
private Region mExclusionRegion;
private SystemGestureExclusionListenerCompat mExclusionListener;
- private ComponentName mGestureBlockedActivity;
+ private final List<ComponentName> mGestureBlockedActivities;
+ private Runnable mOnDestroyFrozenTaskRunnable;
public RecentsAnimationDeviceState(Context context) {
- final ContentResolver resolver = context.getContentResolver();
mContext = context;
mSysUiNavMode = SysUINavigationMode.INSTANCE.get(context);
mDefaultDisplay = DefaultDisplay.INSTANCE.get(context);
@@ -137,15 +150,45 @@
};
runOnDestroy(mExclusionListener::unregister);
+ Resources resources = mContext.getResources();
+ mOrientationTouchTransformer = new OrientationTouchTransformer(resources, mMode,
+ () -> QuickStepContract.getWindowCornerRadius(resources));
+
// Register for navigation mode changes
onNavigationModeChanged(mSysUiNavMode.addModeChangeListener(this));
runOnDestroy(() -> mSysUiNavMode.removeModeChangeListener(this));
// Add any blocked activities
- String blockingActivity = context.getString(R.string.gesture_blocking_activity);
- if (!TextUtils.isEmpty(blockingActivity)) {
- mGestureBlockedActivity = ComponentName.unflattenFromString(blockingActivity);
+ String[] blockingActivities;
+ try {
+ blockingActivities =
+ context.getResources().getStringArray(R.array.gesture_blocking_activities);
+ } catch (Resources.NotFoundException e) {
+ blockingActivities = new String[0];
}
+ mGestureBlockedActivities = new ArrayList<>(blockingActivities.length);
+ for (String blockingActivity : blockingActivities) {
+ if (!TextUtils.isEmpty(blockingActivity)) {
+ mGestureBlockedActivities.add(
+ ComponentName.unflattenFromString(blockingActivity));
+ }
+ }
+ }
+
+ private void setupOrientationSwipeHandler() {
+ if (!FeatureFlags.ENABLE_FIXED_ROTATION_TRANSFORM.get()) {
+ return;
+ }
+
+ ActivityManagerWrapper.getInstance().registerTaskStackListener(mFrozenTaskListener);
+ mOnDestroyFrozenTaskRunnable = () -> ActivityManagerWrapper.getInstance()
+ .unregisterTaskStackListener(mFrozenTaskListener);
+ runOnDestroy(mOnDestroyFrozenTaskRunnable);
+ }
+
+ private void destroyOrientationSwipeHandlerCallback() {
+ ActivityManagerWrapper.getInstance().unregisterTaskStackListener(mFrozenTaskListener);
+ mOnDestroyActions.remove(mOnDestroyFrozenTaskRunnable);
}
private void runOnDestroy(Runnable action) {
@@ -180,13 +223,22 @@
mDefaultDisplay.addChangeListener(this);
}
- if (mMode == NO_BUTTON) {
+ if (newMode == NO_BUTTON) {
mExclusionListener.register();
} else {
mExclusionListener.unregister();
}
+
+ mNavBarPosition = new NavBarPosition(newMode, mDefaultDisplay.getInfo());
+
+ mOrientationTouchTransformer.setNavigationMode(newMode, mDefaultDisplay.getInfo());
+ if (!mMode.hasGestures && newMode.hasGestures) {
+ setupOrientationSwipeHandler();
+ } else if (mMode.hasGestures && !newMode.hasGestures){
+ destroyOrientationSwipeHandlerCallback();
+ }
+
mMode = newMode;
- mNavBarPosition = new NavBarPosition(mMode, mDefaultDisplay.getInfo());
}
@Override
@@ -195,8 +247,10 @@
return;
}
+ mDisplayRotation = info.rotation;
mNavBarPosition = new NavBarPosition(mMode, info);
updateGestureTouchRegions();
+ mOrientationTouchTransformer.createOrAddTouchRegion(info);
}
/**
@@ -272,17 +326,16 @@
* @return whether the given running task info matches the gesture-blocked activity.
*/
public boolean isGestureBlockedActivity(ActivityManager.RunningTaskInfo runningTaskInfo) {
- return runningTaskInfo != null && mGestureBlockedActivity != null
- && mGestureBlockedActivity.equals(runningTaskInfo.topActivity);
+ return runningTaskInfo != null
+ && mGestureBlockedActivities.contains(runningTaskInfo.topActivity);
}
/**
- * @return the package of the gesture-blocked activity or {@code null} if there is none.
+ * @return the packages of gesture-blocked activities.
*/
- public String getGestureBlockedActivityPackage() {
- return (mGestureBlockedActivity != null)
- ? mGestureBlockedActivity.getPackageName()
- : null;
+ public List<String> getGestureBlockedActivityPackages() {
+ return mGestureBlockedActivities.stream().map(ComponentName::getPackageName)
+ .collect(Collectors.toList());
}
/**
@@ -307,6 +360,7 @@
return (mSystemUiStateFlags & SYSUI_STATE_NAV_BAR_HIDDEN) == 0
&& (mSystemUiStateFlags & SYSUI_STATE_NOTIFICATION_PANEL_EXPANDED) == 0
&& (mSystemUiStateFlags & SYSUI_STATE_QUICK_SETTINGS_EXPANDED) == 0
+ && (mSystemUiStateFlags & SYSUI_STATE_BUBBLES_EXPANDED) == 0
&& ((mSystemUiStateFlags & SYSUI_STATE_HOME_DISABLED) == 0
|| (mSystemUiStateFlags & SYSUI_STATE_OVERVIEW_DISABLED) == 0);
}
@@ -369,50 +423,14 @@
return;
}
- Resources res = mContext.getResources();
- DefaultDisplay.Info displayInfo = mDefaultDisplay.getInfo();
- Point realSize = new Point(displayInfo.realSize);
- mSwipeUpTouchRegion.set(0, 0, realSize.x, realSize.y);
- if (mMode == NO_BUTTON) {
- int touchHeight = ResourceUtils.getNavbarSize(NAVBAR_BOTTOM_GESTURE_SIZE, res);
- mSwipeUpTouchRegion.top = mSwipeUpTouchRegion.bottom - touchHeight;
-
- final int assistantWidth = res.getDimensionPixelSize(R.dimen.gestures_assistant_width);
- final float assistantHeight = Math.max(touchHeight,
- QuickStepContract.getWindowCornerRadius(res));
- mAssistantLeftRegion.bottom = mAssistantRightRegion.bottom = mSwipeUpTouchRegion.bottom;
- mAssistantLeftRegion.top = mAssistantRightRegion.top =
- mSwipeUpTouchRegion.bottom - assistantHeight;
-
- mAssistantLeftRegion.left = 0;
- mAssistantLeftRegion.right = assistantWidth;
-
- mAssistantRightRegion.right = mSwipeUpTouchRegion.right;
- mAssistantRightRegion.left = mSwipeUpTouchRegion.right - assistantWidth;
- } else {
- mAssistantLeftRegion.setEmpty();
- mAssistantRightRegion.setEmpty();
- switch (displayInfo.rotation) {
- case Surface.ROTATION_90:
- mSwipeUpTouchRegion.left = mSwipeUpTouchRegion.right
- - ResourceUtils.getNavbarSize(NAVBAR_LANDSCAPE_LEFT_RIGHT_SIZE, res);
- break;
- case Surface.ROTATION_270:
- mSwipeUpTouchRegion.right = mSwipeUpTouchRegion.left
- + ResourceUtils.getNavbarSize(NAVBAR_LANDSCAPE_LEFT_RIGHT_SIZE, res);
- break;
- default:
- mSwipeUpTouchRegion.top = mSwipeUpTouchRegion.bottom
- - ResourceUtils.getNavbarSize(NAVBAR_BOTTOM_GESTURE_SIZE, res);
- }
- }
+ mOrientationTouchTransformer.createOrAddTouchRegion(mDefaultDisplay.getInfo());
}
/**
* @return whether the coordinates of the {@param event} is in the swipe up gesture region.
*/
public boolean isInSwipeUpTouchRegion(MotionEvent event) {
- return mSwipeUpTouchRegion.contains(event.getX(), event.getY());
+ return mOrientationTouchTransformer.touchInValidSwipeRegions(event.getX(), event.getY());
}
/**
@@ -420,7 +438,8 @@
* is in the swipe up gesture region.
*/
public boolean isInSwipeUpTouchRegion(MotionEvent event, int pointerIndex) {
- return mSwipeUpTouchRegion.contains(event.getX(pointerIndex), event.getY(pointerIndex));
+ return mOrientationTouchTransformer.touchInValidSwipeRegions(event.getX(pointerIndex),
+ event.getY(pointerIndex));
}
/**
@@ -479,11 +498,42 @@
public boolean canTriggerAssistantAction(MotionEvent ev) {
return mAssistantAvailable
&& !QuickStepContract.isAssistantGestureDisabled(mSystemUiStateFlags)
- && (mAssistantLeftRegion.contains(ev.getX(), ev.getY())
- || mAssistantRightRegion.contains(ev.getX(), ev.getY()))
+ && mOrientationTouchTransformer.touchInAssistantRegion(ev)
&& !isLockToAppActive();
}
+ /**
+ * *May* apply a transform on the motion event if it lies in the nav bar region for another
+ * orientation that is currently being tracked as a part of quickstep
+ */
+ public void setOrientationTransformIfNeeded(MotionEvent event) {
+ // negative coordinates bug b/143901881
+ if (event.getX() < 0 || event.getY() < 0) {
+ event.setLocation(Math.max(0, event.getX()), Math.max(0, event.getY()));
+ }
+ mOrientationTouchTransformer.transform(event);
+ }
+
+ void enableMultipleRegions(boolean enable) {
+ mOrientationTouchTransformer.enableMultipleRegions(enable, mDefaultDisplay.getInfo());
+ if (enable) {
+ UI_HELPER_EXECUTOR.execute(() -> {
+ int quickStepStartingRotation =
+ mOrientationTouchTransformer.getQuickStepStartingRotation();
+ SystemUiProxy.INSTANCE.get(mContext)
+ .onQuickSwitchToNewTask(quickStepStartingRotation);
+ });
+ }
+ }
+
+ public int getCurrentActiveRotation() {
+ return mOrientationTouchTransformer.getCurrentActiveRotation();
+ }
+
+ public int getDisplayRotation() {
+ return mDisplayRotation;
+ }
+
public void dump(PrintWriter pw) {
pw.println("DeviceState:");
pw.println(" canStartSystemGesture=" + canStartSystemGesture());
@@ -493,5 +543,9 @@
pw.println(" assistantAvailable=" + mAssistantAvailable);
pw.println(" assistantDisabled="
+ QuickStepContract.isAssistantGestureDisabled(mSystemUiStateFlags));
+ pw.println(" currentActiveRotation=" + getCurrentActiveRotation());
+ pw.println(" displayRotation=" + getDisplayRotation());
+ pw.println(" isUserUnlocked=" + mIsUserUnlocked);
+ mOrientationTouchTransformer.dump(pw);
}
}
diff --git a/quickstep/src/com/android/quickstep/SystemUiProxy.java b/quickstep/src/com/android/quickstep/SystemUiProxy.java
index 101bb07..20d133c 100644
--- a/quickstep/src/com/android/quickstep/SystemUiProxy.java
+++ b/quickstep/src/com/android/quickstep/SystemUiProxy.java
@@ -29,6 +29,7 @@
import android.view.MotionEvent;
import com.android.launcher3.util.MainThreadInitializedObject;
+import com.android.systemui.shared.recents.IPinnedStackAnimationListener;
import com.android.systemui.shared.recents.ISystemUiProxy;
/**
@@ -268,9 +269,7 @@
}
}
- /**
- * See SharedApiCompat#setShelfHeight()
- */
+ @Override
public void setShelfHeight(boolean visible, int shelfHeight) {
boolean changed = visible != mLastShelfVisible || shelfHeight != mLastShelfHeight;
if (mSystemUiProxy != null && changed) {
@@ -295,4 +294,54 @@
}
}
}
+
+ @Override
+ public void setSplitScreenMinimized(boolean minimized) {
+ if (mSystemUiProxy != null) {
+ try {
+ mSystemUiProxy.setSplitScreenMinimized(minimized);
+ } catch (RemoteException e) {
+ Log.w(TAG, "Failed call stopScreenPinning", e);
+ }
+ }
+ }
+
+ /**
+ * Notifies that swipe-to-home action is finished.
+ */
+ @Override
+ public void notifySwipeToHomeFinished() {
+ if (mSystemUiProxy != null) {
+ try {
+ mSystemUiProxy.notifySwipeToHomeFinished();
+ } catch (RemoteException e) {
+ Log.w(TAG, "Failed call setPinnedStackAnimationType", e);
+ }
+ }
+ }
+
+ /**
+ * Sets listener to get pinned stack animation callbacks.
+ */
+ @Override
+ public void setPinnedStackAnimationListener(IPinnedStackAnimationListener listener) {
+ if (mSystemUiProxy != null) {
+ try {
+ mSystemUiProxy.setPinnedStackAnimationListener(listener);
+ } catch (RemoteException e) {
+ Log.w(TAG, "Failed call setPinnedStackAnimationListener", e);
+ }
+ }
+ }
+
+ @Override
+ public void onQuickSwitchToNewTask(int rotation) {
+ if (mSystemUiProxy != null) {
+ try {
+ mSystemUiProxy.onQuickSwitchToNewTask(rotation);
+ } catch (RemoteException e) {
+ Log.w(TAG, "Failed call onQuickSwitchToNewTask with arg: " + rotation, e);
+ }
+ }
+ }
}
diff --git a/quickstep/src/com/android/quickstep/TaskAnimationManager.java b/quickstep/src/com/android/quickstep/TaskAnimationManager.java
index e3e8ace..bbca568 100644
--- a/quickstep/src/com/android/quickstep/TaskAnimationManager.java
+++ b/quickstep/src/com/android/quickstep/TaskAnimationManager.java
@@ -26,6 +26,7 @@
import com.android.launcher3.Utilities;
import com.android.launcher3.config.FeatureFlags;
+import com.android.launcher3.testing.TestProtocol;
import com.android.systemui.shared.recents.model.ThumbnailData;
import com.android.systemui.shared.system.ActivityManagerWrapper;
@@ -55,7 +56,7 @@
// Notify if recents animation is still running
if (mController != null) {
String msg = "New recents animation started before old animation completed";
- if (FeatureFlags.IS_DOGFOOD_BUILD) {
+ if (FeatureFlags.IS_STUDIO_BUILD) {
throw new IllegalArgumentException(msg);
} else {
Log.e("TaskAnimationManager", msg, new Exception());
@@ -156,9 +157,9 @@
mTargets.release();
}
- // Remove gesture state from callbacks
- if (mCallbacks != null && mLastGestureState != null) {
- mCallbacks.removeListener(mLastGestureState);
+ // Clean up all listeners to ensure we don't get subsequent callbacks
+ if (mCallbacks != null) {
+ mCallbacks.removeAllListeners();
}
mController = null;
diff --git a/quickstep/src/com/android/quickstep/TaskThumbnailCache.java b/quickstep/src/com/android/quickstep/TaskThumbnailCache.java
index e47df6c..ace6743 100644
--- a/quickstep/src/com/android/quickstep/TaskThumbnailCache.java
+++ b/quickstep/src/com/android/quickstep/TaskThumbnailCache.java
@@ -17,7 +17,6 @@
import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
-import android.app.ActivityManager;
import android.content.Context;
import android.content.res.Resources;
import android.os.Handler;
@@ -43,9 +42,10 @@
private final int mCacheSize;
private final TaskKeyLruCache<ThumbnailData> mCache;
private final HighResLoadingState mHighResLoadingState;
+ private final boolean mEnableTaskSnapshotPreloading;
public static class HighResLoadingState {
- private boolean mIsLowRamDevice;
+ private boolean mForceHighResThumbnails;
private boolean mVisible;
private boolean mFlingingFast;
private boolean mHighResLoadingEnabled;
@@ -56,9 +56,9 @@
}
private HighResLoadingState(Context context) {
- ActivityManager activityManager =
- (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
- mIsLowRamDevice = activityManager.isLowRamDevice();
+ // If the device does not support low-res thumbnails, only attempt to load high-res
+ // thumbnails
+ mForceHighResThumbnails = !supportsLowResThumbnails();
}
public void addCallback(HighResLoadingStateChangedCallback callback) {
@@ -85,7 +85,7 @@
private void updateState() {
boolean prevState = mHighResLoadingEnabled;
- mHighResLoadingEnabled = !mIsLowRamDevice && mVisible && !mFlingingFast;
+ mHighResLoadingEnabled = mForceHighResThumbnails || (mVisible && !mFlingingFast);
if (prevState != mHighResLoadingEnabled) {
for (int i = mCallbacks.size() - 1; i >= 0; i--) {
mCallbacks.get(i).onHighResLoadingStateChanged(mHighResLoadingEnabled);
@@ -100,6 +100,7 @@
Resources res = context.getResources();
mCacheSize = res.getInteger(R.integer.recentsThumbnailCacheSize);
+ mEnableTaskSnapshotPreloading = res.getBoolean(R.bool.config_enableTaskSnapshotPreloading);
mCache = new TaskKeyLruCache<>(mCacheSize);
}
@@ -110,7 +111,7 @@
Preconditions.assertUIThread();
// Fetch the thumbnail for this task and put it in the cache
if (task.thumbnail == null) {
- updateThumbnailInBackground(task.key, true /* reducedResolution */,
+ updateThumbnailInBackground(task.key, true /* lowResolution */,
t -> task.thumbnail = t);
}
}
@@ -133,8 +134,8 @@
Task task, Consumer<ThumbnailData> callback) {
Preconditions.assertUIThread();
- boolean reducedResolution = !mHighResLoadingState.isEnabled();
- if (task.thumbnail != null && (!task.thumbnail.reducedResolution || reducedResolution)) {
+ boolean lowResolution = !mHighResLoadingState.isEnabled();
+ if (task.thumbnail != null && (!task.thumbnail.reducedResolution || lowResolution)) {
// Nothing to load, the thumbnail is already high-resolution or matches what the
// request, so just callback
callback.accept(task.thumbnail);
@@ -148,23 +149,23 @@
});
}
- private ThumbnailLoadRequest updateThumbnailInBackground(TaskKey key, boolean reducedResolution,
+ private ThumbnailLoadRequest updateThumbnailInBackground(TaskKey key, boolean lowResolution,
Consumer<ThumbnailData> callback) {
Preconditions.assertUIThread();
ThumbnailData cachedThumbnail = mCache.getAndInvalidateIfModified(key);
- if (cachedThumbnail != null && (!cachedThumbnail.reducedResolution || reducedResolution)) {
+ if (cachedThumbnail != null && (!cachedThumbnail.reducedResolution || lowResolution)) {
// Already cached, lets use that thumbnail
callback.accept(cachedThumbnail);
return null;
}
ThumbnailLoadRequest request = new ThumbnailLoadRequest(mBackgroundHandler,
- reducedResolution) {
+ lowResolution) {
@Override
public void run() {
ThumbnailData thumbnail = ActivityManagerWrapper.getInstance().getTaskThumbnail(
- key.id, reducedResolution);
+ key.id, lowResolution);
if (isCanceled()) {
// We don't call back to the provided callback in this case
return;
@@ -212,15 +213,31 @@
* @return Whether to enable background preloading of task thumbnails.
*/
public boolean isPreloadingEnabled() {
- return !mHighResLoadingState.mIsLowRamDevice && mHighResLoadingState.mVisible;
+ return mEnableTaskSnapshotPreloading && mHighResLoadingState.mVisible;
}
public static abstract class ThumbnailLoadRequest extends HandlerRunnable {
- public final boolean reducedResolution;
+ public final boolean mLowResolution;
- ThumbnailLoadRequest(Handler handler, boolean reducedResolution) {
+ ThumbnailLoadRequest(Handler handler, boolean lowResolution) {
super(handler, null);
- this.reducedResolution = reducedResolution;
+ mLowResolution = lowResolution;
}
}
+
+ /**
+ * @return Whether device supports low-res thumbnails. Low-res files are an optimization
+ * for faster load times of snapshots. Devices can optionally disable low-res files so that
+ * they only store snapshots at high-res scale. The actual scale can be configured in
+ * frameworks/base config overlay.
+ */
+ private static boolean supportsLowResThumbnails() {
+ Resources res = Resources.getSystem();
+ int resId = res.getIdentifier("config_lowResTaskSnapshotScale", "dimen", "android");
+ if (resId != 0) {
+ return 0 < res.getFloat(resId);
+ }
+ return true;
+ }
+
}
diff --git a/quickstep/src/com/android/quickstep/interaction/BackGestureTutorialController.java b/quickstep/src/com/android/quickstep/interaction/BackGestureTutorialController.java
index 3fe91a3..5c2e992 100644
--- a/quickstep/src/com/android/quickstep/interaction/BackGestureTutorialController.java
+++ b/quickstep/src/com/android/quickstep/interaction/BackGestureTutorialController.java
@@ -25,6 +25,7 @@
import com.android.launcher3.R;
import com.android.quickstep.interaction.BackGestureTutorialFragment.TutorialStep;
import com.android.quickstep.interaction.BackGestureTutorialFragment.TutorialType;
+import com.android.quickstep.interaction.EdgeBackGestureHandler.BackGestureResult;
import java.util.Optional;
@@ -79,21 +80,33 @@
mHandCoachingAnimation.stop();
}
- void onGestureDetected() {
- hideHandCoachingAnimation();
-
- if (mTutorialStep == TutorialStep.CONFIRM) {
+ void onGestureAttempted(BackGestureResult result) {
+ if (mTutorialStep == TutorialStep.CONFIRM
+ && (result == BackGestureResult.BACK_COMPLETED_FROM_LEFT
+ || result == BackGestureResult.BACK_COMPLETED_FROM_RIGHT)) {
mFragment.closeTutorial();
return;
}
- if (mTutorialTypeInfo.get().getTutorialType() == TutorialType.RIGHT_EDGE_BACK_NAVIGATION) {
- mFragment.changeController(TutorialStep.ENGAGED,
- TutorialType.LEFT_EDGE_BACK_NAVIGATION);
+ if (!mTutorialTypeInfo.isPresent()) {
return;
}
- mFragment.changeController(TutorialStep.CONFIRM);
+ switch (mTutorialTypeInfo.get().getTutorialType()) {
+ case RIGHT_EDGE_BACK_NAVIGATION:
+ if (result == BackGestureResult.BACK_COMPLETED_FROM_RIGHT) {
+ hideHandCoachingAnimation();
+ mFragment.changeController(
+ TutorialStep.ENGAGED, TutorialType.LEFT_EDGE_BACK_NAVIGATION);
+ }
+ break;
+ case LEFT_EDGE_BACK_NAVIGATION:
+ if (result == BackGestureResult.BACK_COMPLETED_FROM_LEFT) {
+ hideHandCoachingAnimation();
+ mFragment.changeController(TutorialStep.CONFIRM);
+ }
+ break;
+ }
}
abstract Optional<Integer> getTitleStringId();
diff --git a/quickstep/src/com/android/quickstep/interaction/BackGestureTutorialEngagedController.java b/quickstep/src/com/android/quickstep/interaction/BackGestureTutorialEngagedController.java
index c9ee1e2..297c287 100644
--- a/quickstep/src/com/android/quickstep/interaction/BackGestureTutorialEngagedController.java
+++ b/quickstep/src/com/android/quickstep/interaction/BackGestureTutorialEngagedController.java
@@ -35,7 +35,7 @@
@Override
void transitToController() {
super.transitToController();
- mHandCoachingAnimation.maybeStartLoopedAnimation(mTutorialTypeInfo.get().getTutorialType());
+ mHandCoachingAnimation.startLoopedAnimation(mTutorialTypeInfo.get().getTutorialType());
}
@Override
diff --git a/quickstep/src/com/android/quickstep/interaction/BackGestureTutorialFragment.java b/quickstep/src/com/android/quickstep/interaction/BackGestureTutorialFragment.java
index 54408ce..aeb718d 100644
--- a/quickstep/src/com/android/quickstep/interaction/BackGestureTutorialFragment.java
+++ b/quickstep/src/com/android/quickstep/interaction/BackGestureTutorialFragment.java
@@ -17,21 +17,26 @@
import android.content.ActivityNotFoundException;
import android.content.Intent;
+import android.graphics.Insets;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
+import android.view.WindowInsets;
+import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import com.android.launcher3.R;
+import com.android.quickstep.interaction.EdgeBackGestureHandler.BackGestureAttemptCallback;
+import com.android.quickstep.interaction.EdgeBackGestureHandler.BackGestureResult;
import java.net.URISyntaxException;
import java.util.Optional;
/** Shows the Back gesture interactive tutorial. */
-public class BackGestureTutorialFragment extends Fragment {
+public class BackGestureTutorialFragment extends Fragment implements BackGestureAttemptCallback {
private static final String LOG_TAG = "TutorialFragment";
private static final String KEY_TUTORIAL_STEP = "tutorialStep";
@@ -47,6 +52,7 @@
private Optional<BackGestureTutorialController> mTutorialController = Optional.empty();
private View mRootView;
private BackGestureTutorialHandAnimation mHandCoachingAnimation;
+ private EdgeBackGestureHandler mEdgeBackGestureHandler;
public static BackGestureTutorialFragment newInstance(
TutorialStep tutorialStep, TutorialType tutorialType) {
@@ -64,17 +70,25 @@
Bundle args = savedInstanceState != null ? savedInstanceState : getArguments();
mTutorialStep = (TutorialStep) args.getSerializable(KEY_TUTORIAL_STEP);
mTutorialType = (TutorialType) args.getSerializable(KEY_TUTORIAL_TYPE);
+ mEdgeBackGestureHandler = new EdgeBackGestureHandler(getContext());
+ mEdgeBackGestureHandler.registerBackGestureAttemptCallback(this);
}
@Override
public View onCreateView(
- LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ @NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
mRootView = inflater.inflate(R.layout.back_gesture_tutorial_fragment,
container, /* attachToRoot= */ false);
mRootView.findViewById(R.id.back_gesture_tutorial_fragment_close_button)
.setOnClickListener(this::onCloseButtonClicked);
+ mRootView.setOnApplyWindowInsetsListener((view, insets) -> {
+ Insets systemInsets = insets.getInsets(WindowInsets.Type.systemBars());
+ mEdgeBackGestureHandler.setInsets(systemInsets.left, systemInsets.right);
+ return insets;
+ });
+ mRootView.setOnTouchListener(mEdgeBackGestureHandler);
mHandCoachingAnimation = new BackGestureTutorialHandAnimation(getContext(), mRootView);
return mRootView;
@@ -92,6 +106,14 @@
mHandCoachingAnimation.stop();
}
+ void onAttachedToWindow() {
+ mEdgeBackGestureHandler.setViewGroupParent((ViewGroup) getRootView());
+ }
+
+ void onDetachedFromWindow() {
+ mEdgeBackGestureHandler.setViewGroupParent(null);
+ }
+
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putSerializable(KEY_TUTORIAL_STEP, mTutorialStep);
@@ -125,10 +147,9 @@
this.mTutorialType = tutorialType;
}
- void onBackPressed() {
- if (mTutorialController.isPresent()) {
- mTutorialController.get().onGestureDetected();
- }
+ @Override
+ public void onBackGestureAttempted(BackGestureResult result) {
+ mTutorialController.ifPresent(controller -> controller.onGestureAttempted(result));
}
void closeTutorial() {
diff --git a/quickstep/src/com/android/quickstep/interaction/BackGestureTutorialHandAnimation.java b/quickstep/src/com/android/quickstep/interaction/BackGestureTutorialHandAnimation.java
index d03811d..d7c10b0 100644
--- a/quickstep/src/com/android/quickstep/interaction/BackGestureTutorialHandAnimation.java
+++ b/quickstep/src/com/android/quickstep/interaction/BackGestureTutorialHandAnimation.java
@@ -38,8 +38,6 @@
private final ImageView mHandCoachingView;
private final AnimatedVectorDrawable mGestureAnimation;
- private boolean mIsAnimationPlayed = false;
-
BackGestureTutorialHandAnimation(Context context, View rootView) {
mHandCoachingView = rootView.findViewById(
R.id.back_gesture_tutorial_fragment_hand_coaching);
@@ -47,20 +45,15 @@
R.drawable.back_gesture);
}
- boolean isRunning() {
- return mGestureAnimation.isRunning();
- }
-
/**
- * Starts animation if the playground is launched for the first time.
+ * [Re]starts animation for the given tutorial.
*/
- void maybeStartLoopedAnimation(TutorialType tutorialType) {
- if (isRunning() || mIsAnimationPlayed) {
- return;
+ void startLoopedAnimation(TutorialType tutorialType) {
+ if (mGestureAnimation.isRunning()) {
+ stop();
}
- mIsAnimationPlayed = true;
- clearAnimationCallbacks();
+ mGestureAnimation.clearAnimationCallbacks();
mGestureAnimation.registerAnimationCallback(
new Animatable2.AnimationCallback() {
@Override
@@ -78,17 +71,11 @@
float rotationY = tutorialType == TutorialType.LEFT_EDGE_BACK_NAVIGATION ? 180f : 0f;
mHandCoachingView.setRotationY(rotationY);
mHandCoachingView.setImageDrawable(mGestureAnimation);
- mHandCoachingView.postDelayed(() -> mGestureAnimation.start(),
- ANIMATION_START_DELAY.toMillis());
- }
-
- private void clearAnimationCallbacks() {
- mGestureAnimation.clearAnimationCallbacks();
+ mHandCoachingView.postDelayed(mGestureAnimation::start, ANIMATION_START_DELAY.toMillis());
}
void stop() {
- mIsAnimationPlayed = false;
- clearAnimationCallbacks();
+ mGestureAnimation.clearAnimationCallbacks();
mGestureAnimation.stop();
}
}
diff --git a/quickstep/src/com/android/quickstep/interaction/EdgeBackGestureHandler.java b/quickstep/src/com/android/quickstep/interaction/EdgeBackGestureHandler.java
new file mode 100644
index 0000000..f34530e
--- /dev/null
+++ b/quickstep/src/com/android/quickstep/interaction/EdgeBackGestureHandler.java
@@ -0,0 +1,234 @@
+/*
+ * 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.quickstep.interaction;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.graphics.Point;
+import android.graphics.PointF;
+import android.os.SystemProperties;
+import android.view.Display;
+import android.view.MotionEvent;
+import android.view.View;
+import android.view.View.OnTouchListener;
+import android.view.ViewConfiguration;
+import android.view.ViewGroup;
+import android.view.ViewGroup.LayoutParams;
+
+import androidx.annotation.Nullable;
+
+import com.android.launcher3.ResourceUtils;
+
+/**
+ * Utility class to handle edge swipes for back gestures.
+ *
+ * Forked from platform/frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/phone/EdgeBackGestureHandler.java.
+ */
+public class EdgeBackGestureHandler implements OnTouchListener {
+
+ private static final String TAG = "EdgeBackGestureHandler";
+ private static final int MAX_LONG_PRESS_TIMEOUT = SystemProperties.getInt(
+ "gestures.back_timeout", 250);
+
+ private final Context mContext;
+
+ private final Point mDisplaySize = new Point();
+ private final int mDisplayId;
+
+ // The edge width where touch down is allowed
+ private int mEdgeWidth;
+ // The bottom gesture area height
+ private int mBottomGestureHeight;
+ // The slop to distinguish between horizontal and vertical motion
+ private final float mTouchSlop;
+ // Duration after which we consider the event as longpress.
+ private final int mLongPressTimeout;
+
+ private final PointF mDownPoint = new PointF();
+ private boolean mThresholdCrossed = false;
+ private boolean mAllowGesture = false;
+ private boolean mIsEnabled;
+ private int mLeftInset;
+ private int mRightInset;
+
+ private EdgeBackGesturePanel mEdgeBackPanel;
+ private BackGestureAttemptCallback mGestureCallback;
+
+ private final EdgeBackGesturePanel.BackCallback mBackCallback =
+ new EdgeBackGesturePanel.BackCallback() {
+ @Override
+ public void triggerBack() {
+ if (mGestureCallback != null) {
+ mGestureCallback.onBackGestureAttempted(mEdgeBackPanel.getIsLeftPanel()
+ ? BackGestureResult.BACK_COMPLETED_FROM_LEFT
+ : BackGestureResult.BACK_COMPLETED_FROM_RIGHT);
+ }
+ }
+
+ @Override
+ public void cancelBack() {
+ if (mGestureCallback != null) {
+ mGestureCallback.onBackGestureAttempted(mEdgeBackPanel.getIsLeftPanel()
+ ? BackGestureResult.BACK_CANCELLED_FROM_LEFT
+ : BackGestureResult.BACK_CANCELLED_FROM_RIGHT);
+ }
+ }
+ };
+
+ EdgeBackGestureHandler(Context context) {
+ final Resources res = context.getResources();
+ mContext = context;
+ mDisplayId = context.getDisplay() == null
+ ? Display.DEFAULT_DISPLAY : context.getDisplay().getDisplayId();
+
+ mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
+ mLongPressTimeout = Math.min(MAX_LONG_PRESS_TIMEOUT,
+ ViewConfiguration.getLongPressTimeout());
+
+ mBottomGestureHeight =
+ ResourceUtils.getNavbarSize(ResourceUtils.NAVBAR_BOTTOM_GESTURE_SIZE, res);
+ mEdgeWidth = ResourceUtils.getNavbarSize("config_backGestureInset", res);
+ }
+
+ void setViewGroupParent(@Nullable ViewGroup parent) {
+ mIsEnabled = parent != null;
+
+ if (mEdgeBackPanel != null) {
+ mEdgeBackPanel.onDestroy();
+ mEdgeBackPanel = null;
+ }
+
+ if (mIsEnabled) {
+ // Add a nav bar panel window.
+ mEdgeBackPanel = new EdgeBackGesturePanel(mContext, parent, createLayoutParams());
+ mEdgeBackPanel.setBackCallback(mBackCallback);
+ if (mContext.getDisplay() != null) {
+ mContext.getDisplay().getRealSize(mDisplaySize);
+ mEdgeBackPanel.setDisplaySize(mDisplaySize);
+ }
+ }
+ }
+
+ void registerBackGestureAttemptCallback(BackGestureAttemptCallback callback) {
+ mGestureCallback = callback;
+ }
+
+ private LayoutParams createLayoutParams() {
+ Resources resources = mContext.getResources();
+ return new LayoutParams(
+ ResourceUtils.getNavbarSize("navigation_edge_panel_width", resources),
+ ResourceUtils.getNavbarSize("navigation_edge_panel_height", resources));
+ }
+
+ @Override
+ public boolean onTouch(View view, MotionEvent motionEvent) {
+ if (mIsEnabled) {
+ onMotionEvent(motionEvent);
+ return true;
+ }
+ return false;
+ }
+
+ private boolean isWithinTouchRegion(int x, int y) {
+ // Disallow if too far from the edge
+ if (x > mEdgeWidth + mLeftInset && x < (mDisplaySize.x - mEdgeWidth - mRightInset)) {
+ return false;
+ }
+
+ // Disallow if we are in the bottom gesture area
+ if (y >= (mDisplaySize.y - mBottomGestureHeight)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ private void cancelGesture(MotionEvent ev) {
+ // Send action cancel to reset all the touch events
+ mAllowGesture = false;
+ MotionEvent cancelEv = MotionEvent.obtain(ev);
+ cancelEv.setAction(MotionEvent.ACTION_CANCEL);
+ mEdgeBackPanel.onMotionEvent(cancelEv);
+ cancelEv.recycle();
+ }
+
+ private void onMotionEvent(MotionEvent ev) {
+ int action = ev.getActionMasked();
+ if (action == MotionEvent.ACTION_DOWN) {
+ boolean isOnLeftEdge = ev.getX() <= mEdgeWidth + mLeftInset;
+ mAllowGesture = isWithinTouchRegion((int) ev.getX(), (int) ev.getY());
+ if (mAllowGesture) {
+ mEdgeBackPanel.setIsLeftPanel(isOnLeftEdge);
+ mEdgeBackPanel.onMotionEvent(ev);
+
+ mDownPoint.set(ev.getX(), ev.getY());
+ mThresholdCrossed = false;
+ }
+ } else if (mAllowGesture) {
+ if (!mThresholdCrossed) {
+ if (action == MotionEvent.ACTION_POINTER_DOWN) {
+ // We do not support multi touch for back gesture
+ cancelGesture(ev);
+ return;
+ } else if (action == MotionEvent.ACTION_MOVE) {
+ if ((ev.getEventTime() - ev.getDownTime()) > mLongPressTimeout) {
+ cancelGesture(ev);
+ return;
+ }
+ float dx = Math.abs(ev.getX() - mDownPoint.x);
+ float dy = Math.abs(ev.getY() - mDownPoint.y);
+ if (dy > dx && dy > mTouchSlop) {
+ cancelGesture(ev);
+ return;
+
+ } else if (dx > dy && dx > mTouchSlop) {
+ mThresholdCrossed = true;
+ }
+ }
+
+ }
+
+ // forward touch
+ mEdgeBackPanel.onMotionEvent(ev);
+ }
+
+ if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
+ if (!mAllowGesture && mGestureCallback != null) {
+ mGestureCallback.onBackGestureAttempted(BackGestureResult.BACK_NOT_STARTED);
+ }
+ }
+ }
+
+ void setInsets(int leftInset, int rightInset) {
+ mLeftInset = leftInset;
+ mRightInset = rightInset;
+ }
+
+ enum BackGestureResult {
+ UNKNOWN,
+ BACK_COMPLETED_FROM_LEFT,
+ BACK_COMPLETED_FROM_RIGHT,
+ BACK_CANCELLED_FROM_LEFT,
+ BACK_CANCELLED_FROM_RIGHT,
+ BACK_NOT_STARTED,
+ }
+
+ /** Callback to let the UI react to attempted back gestures. */
+ interface BackGestureAttemptCallback {
+ /** Called whenever any touch is completed. */
+ void onBackGestureAttempted(BackGestureResult result);
+ }
+}
diff --git a/quickstep/src/com/android/quickstep/interaction/EdgeBackGesturePanel.java b/quickstep/src/com/android/quickstep/interaction/EdgeBackGesturePanel.java
new file mode 100644
index 0000000..5bf5026
--- /dev/null
+++ b/quickstep/src/com/android/quickstep/interaction/EdgeBackGesturePanel.java
@@ -0,0 +1,693 @@
+/*
+ * 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.quickstep.interaction;
+
+import android.animation.ValueAnimator;
+import android.annotation.SuppressLint;
+import android.content.Context;
+import android.content.res.Configuration;
+import android.content.res.Resources;
+import android.graphics.Canvas;
+import android.graphics.Paint;
+import android.graphics.Path;
+import android.graphics.Point;
+import android.os.SystemClock;
+import android.view.MotionEvent;
+import android.view.VelocityTracker;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.ViewGroup.LayoutParams;
+import android.view.animation.Interpolator;
+import android.view.animation.PathInterpolator;
+
+import androidx.core.math.MathUtils;
+import androidx.dynamicanimation.animation.DynamicAnimation;
+import androidx.dynamicanimation.animation.FloatPropertyCompat;
+import androidx.dynamicanimation.animation.SpringAnimation;
+import androidx.dynamicanimation.animation.SpringForce;
+
+import com.android.launcher3.R;
+import com.android.launcher3.ResourceUtils;
+import com.android.launcher3.anim.Interpolators;
+import com.android.launcher3.util.VibratorWrapper;
+
+/** Forked from platform/frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarEdgePanel.java. */
+public class EdgeBackGesturePanel extends View {
+
+ private static final String LOG_TAG = "EdgeBackGesturePanel";
+
+ private static final long DISAPPEAR_FADE_ANIMATION_DURATION_MS = 80;
+ private static final long DISAPPEAR_ARROW_ANIMATION_DURATION_MS = 100;
+
+ /**
+ * The time required since the first vibration effect to automatically trigger a click
+ */
+ private static final int GESTURE_DURATION_FOR_CLICK_MS = 400;
+
+ /**
+ * The basic translation in dp where the arrow resides
+ */
+ private static final int BASE_TRANSLATION_DP = 32;
+
+ /**
+ * The length of the arrow leg measured from the center to the end
+ */
+ private static final int ARROW_LENGTH_DP = 18;
+
+ /**
+ * The angle measured from the xAxis, where the leg is when the arrow rests
+ */
+ private static final int ARROW_ANGLE_WHEN_EXTENDED_DEGREES = 56;
+
+ /**
+ * The angle that is added per 1000 px speed to the angle of the leg
+ */
+ private static final int ARROW_ANGLE_ADDED_PER_1000_SPEED = 4;
+
+ /**
+ * The maximum angle offset allowed due to speed
+ */
+ private static final int ARROW_MAX_ANGLE_SPEED_OFFSET_DEGREES = 4;
+
+ /**
+ * The thickness of the arrow. Adjusted to match the home handle (approximately)
+ */
+ private static final float ARROW_THICKNESS_DP = 2.5f;
+
+ /**
+ * The amount of rubber banding we do for the vertical translation
+ */
+ private static final int RUBBER_BAND_AMOUNT = 15;
+
+ /**
+ * The interpolator used to rubberband
+ */
+ private static final Interpolator RUBBER_BAND_INTERPOLATOR =
+ new PathInterpolator(1.0f / 5.0f, 1.0f, 1.0f, 1.0f);
+
+ /**
+ * The amount of rubber banding we do for the translation before base translation
+ */
+ private static final int RUBBER_BAND_AMOUNT_APPEAR = 4;
+
+ /**
+ * The interpolator used to rubberband the appearing of the arrow.
+ */
+ private static final Interpolator RUBBER_BAND_INTERPOLATOR_APPEAR =
+ new PathInterpolator(1.0f / RUBBER_BAND_AMOUNT_APPEAR, 1.0f, 1.0f, 1.0f);
+
+ private BackCallback mBackCallback;
+
+ /**
+ * The paint the arrow is drawn with
+ */
+ private final Paint mPaint = new Paint();
+
+ private final float mDensity;
+ private final float mBaseTranslation;
+ private final float mArrowLength;
+ private final float mArrowThickness;
+
+ /**
+ * The minimum delta needed in movement for the arrow to change direction / stop triggering back
+ */
+ private final float mMinDeltaForSwitch;
+ // The closest to y = 0 that the arrow will be displayed.
+ private int mMinArrowPosition;
+ // The amount the arrow is shifted to avoid the finger.
+ private int mFingerOffset;
+
+ private final float mSwipeThreshold;
+ private final Path mArrowPath = new Path();
+ private final Point mDisplaySize = new Point();
+
+ private final SpringAnimation mAngleAnimation;
+ private final SpringAnimation mTranslationAnimation;
+ private final SpringAnimation mVerticalTranslationAnimation;
+ private final SpringForce mAngleAppearForce;
+ private final SpringForce mAngleDisappearForce;
+ private final ValueAnimator mArrowDisappearAnimation;
+ private final SpringForce mRegularTranslationSpring;
+ private final SpringForce mTriggerBackSpring;
+
+ private VelocityTracker mVelocityTracker;
+ private int mArrowPaddingEnd;
+
+ /**
+ * True if the panel is currently on the left of the screen
+ */
+ private boolean mIsLeftPanel;
+
+ private float mStartX;
+ private float mStartY;
+ private float mCurrentAngle;
+ /**
+ * The current translation of the arrow
+ */
+ private float mCurrentTranslation;
+ /**
+ * Where the arrow will be in the resting position.
+ */
+ private float mDesiredTranslation;
+
+ private boolean mDragSlopPassed;
+ private boolean mArrowsPointLeft;
+ private float mMaxTranslation;
+ private boolean mTriggerBack;
+ private float mPreviousTouchTranslation;
+ private float mTotalTouchDelta;
+ private float mVerticalTranslation;
+ private float mDesiredVerticalTranslation;
+ private float mDesiredAngle;
+ private float mAngleOffset;
+ private float mDisappearAmount;
+ private long mVibrationTime;
+ private int mScreenSize;
+
+ private final DynamicAnimation.OnAnimationEndListener mSetGoneEndListener =
+ new DynamicAnimation.OnAnimationEndListener() {
+ @Override
+ public void onAnimationEnd(
+ DynamicAnimation animation, boolean canceled, float value, float velocity) {
+ animation.removeEndListener(this);
+ if (!canceled) {
+ setVisibility(GONE);
+ }
+ }
+ };
+
+ private static final FloatPropertyCompat<EdgeBackGesturePanel> CURRENT_ANGLE =
+ new FloatPropertyCompat<EdgeBackGesturePanel>("currentAngle") {
+ @Override
+ public void setValue(EdgeBackGesturePanel object, float value) {
+ object.setCurrentAngle(value);
+ }
+
+ @Override
+ public float getValue(EdgeBackGesturePanel object) {
+ return object.getCurrentAngle();
+ }
+ };
+
+ private static final FloatPropertyCompat<EdgeBackGesturePanel> CURRENT_TRANSLATION =
+ new FloatPropertyCompat<EdgeBackGesturePanel>("currentTranslation") {
+ @Override
+ public void setValue(EdgeBackGesturePanel object, float value) {
+ object.setCurrentTranslation(value);
+ }
+
+ @Override
+ public float getValue(EdgeBackGesturePanel object) {
+ return object.getCurrentTranslation();
+ }
+ };
+
+ private static final FloatPropertyCompat<EdgeBackGesturePanel> CURRENT_VERTICAL_TRANSLATION =
+ new FloatPropertyCompat<EdgeBackGesturePanel>("verticalTranslation") {
+
+ @Override
+ public void setValue(EdgeBackGesturePanel object, float value) {
+ object.setVerticalTranslation(value);
+ }
+
+ @Override
+ public float getValue(EdgeBackGesturePanel object) {
+ return object.getVerticalTranslation();
+ }
+ };
+
+ public EdgeBackGesturePanel(Context context, ViewGroup parent, LayoutParams layoutParams) {
+ super(context);
+
+ mDensity = context.getResources().getDisplayMetrics().density;
+
+ mBaseTranslation = dp(BASE_TRANSLATION_DP);
+ mArrowLength = dp(ARROW_LENGTH_DP);
+ mArrowThickness = dp(ARROW_THICKNESS_DP);
+ mMinDeltaForSwitch = dp(32);
+
+ mPaint.setStrokeWidth(mArrowThickness);
+ mPaint.setStrokeCap(Paint.Cap.ROUND);
+ mPaint.setAntiAlias(true);
+ mPaint.setStyle(Paint.Style.STROKE);
+ mPaint.setStrokeJoin(Paint.Join.ROUND);
+
+ mArrowDisappearAnimation = ValueAnimator.ofFloat(0.0f, 1.0f);
+ mArrowDisappearAnimation.setDuration(DISAPPEAR_ARROW_ANIMATION_DURATION_MS);
+ mArrowDisappearAnimation.setInterpolator(Interpolators.FAST_OUT_SLOW_IN);
+ mArrowDisappearAnimation.addUpdateListener(animation -> {
+ mDisappearAmount = (float) animation.getAnimatedValue();
+ invalidate();
+ });
+
+ mAngleAnimation =
+ new SpringAnimation(this, CURRENT_ANGLE);
+ mAngleAppearForce = new SpringForce()
+ .setStiffness(500)
+ .setDampingRatio(0.5f);
+ mAngleDisappearForce = new SpringForce()
+ .setStiffness(SpringForce.STIFFNESS_MEDIUM)
+ .setDampingRatio(SpringForce.DAMPING_RATIO_MEDIUM_BOUNCY)
+ .setFinalPosition(90);
+ mAngleAnimation.setSpring(mAngleAppearForce).setMaxValue(90);
+
+ mTranslationAnimation =
+ new SpringAnimation(this, CURRENT_TRANSLATION);
+ mRegularTranslationSpring = new SpringForce()
+ .setStiffness(SpringForce.STIFFNESS_MEDIUM)
+ .setDampingRatio(SpringForce.DAMPING_RATIO_LOW_BOUNCY);
+ mTriggerBackSpring = new SpringForce()
+ .setStiffness(450)
+ .setDampingRatio(SpringForce.DAMPING_RATIO_LOW_BOUNCY);
+ mTranslationAnimation.setSpring(mRegularTranslationSpring);
+ mVerticalTranslationAnimation =
+ new SpringAnimation(this, CURRENT_VERTICAL_TRANSLATION);
+ mVerticalTranslationAnimation.setSpring(
+ new SpringForce()
+ .setStiffness(SpringForce.STIFFNESS_MEDIUM)
+ .setDampingRatio(SpringForce.DAMPING_RATIO_LOW_BOUNCY));
+ mPaint.setColor(context.getColor(R.color.back_arrow_color_dark));
+ loadDimens();
+ updateArrowDirection();
+
+ mSwipeThreshold = ResourceUtils.getDimenByName(
+ "navigation_edge_action_drag_threshold", context.getResources(), 16 /* defaultValue */);
+ parent.addView(this, layoutParams);
+ setVisibility(GONE);
+ }
+
+ void onDestroy() {
+ ViewGroup parent = (ViewGroup) getParent();
+ if (parent != null) {
+ parent.removeView(this);
+ }
+ }
+
+ @Override
+ public boolean hasOverlappingRendering() {
+ return false;
+ }
+
+ @SuppressLint("RtlHardcoded")
+ void setIsLeftPanel(boolean isLeftPanel) {
+ mIsLeftPanel = isLeftPanel;
+ }
+
+ boolean getIsLeftPanel() {
+ return mIsLeftPanel;
+ }
+
+ void setDisplaySize(Point displaySize) {
+ mDisplaySize.set(displaySize.x, displaySize.y);
+ mScreenSize = Math.min(mDisplaySize.x, mDisplaySize.y);
+ }
+
+ void setBackCallback(BackCallback callback) {
+ mBackCallback = callback;
+ }
+
+ private float getCurrentAngle() {
+ return mCurrentAngle;
+ }
+
+ private float getCurrentTranslation() {
+ return mCurrentTranslation;
+ }
+
+ void onMotionEvent(MotionEvent event) {
+ if (mVelocityTracker == null) {
+ mVelocityTracker = VelocityTracker.obtain();
+ }
+ mVelocityTracker.addMovement(event);
+ switch (event.getActionMasked()) {
+ case MotionEvent.ACTION_DOWN:
+ mDragSlopPassed = false;
+ resetOnDown();
+ mStartX = event.getX();
+ mStartY = event.getY();
+ setVisibility(VISIBLE);
+ updatePosition(event.getY());
+ break;
+ case MotionEvent.ACTION_MOVE:
+ handleMoveEvent(event);
+ break;
+ case MotionEvent.ACTION_UP:
+ if (mTriggerBack) {
+ triggerBack();
+ } else {
+ cancelBack();
+ }
+ mVelocityTracker.recycle();
+ mVelocityTracker = null;
+ break;
+ case MotionEvent.ACTION_CANCEL:
+ cancelBack();
+ mVelocityTracker.recycle();
+ mVelocityTracker = null;
+ break;
+ }
+ }
+
+ @Override
+ protected void onConfigurationChanged(Configuration newConfig) {
+ super.onConfigurationChanged(newConfig);
+ updateArrowDirection();
+ loadDimens();
+ }
+
+ @Override
+ protected void onDraw(Canvas canvas) {
+ float pointerPosition = mCurrentTranslation - mArrowThickness / 2.0f;
+ canvas.save();
+ canvas.translate(
+ mIsLeftPanel ? pointerPosition : getWidth() - pointerPosition,
+ (getHeight() * 0.5f) + mVerticalTranslation);
+
+ // Let's calculate the position of the end based on the angle
+ float x = (polarToCartX(mCurrentAngle) * mArrowLength);
+ float y = (polarToCartY(mCurrentAngle) * mArrowLength);
+ Path arrowPath = calculatePath(x, y);
+
+ canvas.drawPath(arrowPath, mPaint);
+ canvas.restore();
+ }
+
+ @Override
+ protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
+ super.onLayout(changed, left, top, right, bottom);
+ mMaxTranslation = getWidth() - mArrowPaddingEnd;
+ }
+
+ private void loadDimens() {
+ Resources res = getResources();
+ mArrowPaddingEnd = ResourceUtils.getDimenByName("navigation_edge_panel_padding", res, 8);
+ mMinArrowPosition = ResourceUtils.getDimenByName("navigation_edge_arrow_min_y", res, 64);
+ mFingerOffset = ResourceUtils.getDimenByName("navigation_edge_finger_offset", res, 48);
+ }
+
+ private void updateArrowDirection() {
+ // Both panels arrow point the same way
+ mArrowsPointLeft = getLayoutDirection() == LAYOUT_DIRECTION_LTR;
+ invalidate();
+ }
+
+ private float getStaticArrowWidth() {
+ return polarToCartX(ARROW_ANGLE_WHEN_EXTENDED_DEGREES) * mArrowLength;
+ }
+
+ private float polarToCartX(float angleInDegrees) {
+ return (float) Math.cos(Math.toRadians(angleInDegrees));
+ }
+
+ private float polarToCartY(float angleInDegrees) {
+ return (float) Math.sin(Math.toRadians(angleInDegrees));
+ }
+
+ private Path calculatePath(float x, float y) {
+ if (!mArrowsPointLeft) {
+ x = -x;
+ }
+ float extent = lerp(1.0f, 0.75f, mDisappearAmount);
+ x = x * extent;
+ y = y * extent;
+ mArrowPath.reset();
+ mArrowPath.moveTo(x, y);
+ mArrowPath.lineTo(0, 0);
+ mArrowPath.lineTo(x, -y);
+ return mArrowPath;
+ }
+
+ private static float lerp(float start, float stop, float amount) {
+ return start + (stop - start) * amount;
+ }
+
+ private void triggerBack() {
+ if (mBackCallback != null) {
+ mBackCallback.triggerBack();
+ }
+
+ if (mVelocityTracker == null) {
+ mVelocityTracker = VelocityTracker.obtain();
+ }
+ mVelocityTracker.computeCurrentVelocity(1000);
+ // Only do the extra translation if we're not already flinging
+ boolean isSlow = Math.abs(mVelocityTracker.getXVelocity()) < 500;
+ if (isSlow
+ || SystemClock.uptimeMillis() - mVibrationTime >= GESTURE_DURATION_FOR_CLICK_MS) {
+ VibratorWrapper.INSTANCE.get(getContext()).vibrate(VibratorWrapper.EFFECT_CLICK);
+ }
+
+ // Let's also snap the angle a bit
+ if (mAngleOffset > -4) {
+ mAngleOffset = Math.max(-8, mAngleOffset - 8);
+ updateAngle(true /* animated */);
+ }
+
+ // Finally, after the translation, animate back and disappear the arrow
+ Runnable translationEnd = () -> {
+ // let's snap it back
+ mAngleOffset = Math.max(0, mAngleOffset + 8);
+ updateAngle(true /* animated */);
+
+ mTranslationAnimation.setSpring(mTriggerBackSpring);
+ // Translate the arrow back a bit to make for a nice transition
+ setDesiredTranslation(mDesiredTranslation - dp(32), true /* animated */);
+ animate().alpha(0f).setDuration(DISAPPEAR_FADE_ANIMATION_DURATION_MS)
+ .withEndAction(() -> setVisibility(GONE));
+ mArrowDisappearAnimation.start();
+ };
+ if (mTranslationAnimation.isRunning()) {
+ mTranslationAnimation.addEndListener(new DynamicAnimation.OnAnimationEndListener() {
+ @Override
+ public void onAnimationEnd(DynamicAnimation animation, boolean canceled,
+ float value,
+ float velocity) {
+ animation.removeEndListener(this);
+ if (!canceled) {
+ translationEnd.run();
+ }
+ }
+ });
+ } else {
+ translationEnd.run();
+ }
+ }
+
+ private void cancelBack() {
+ if (mBackCallback != null) {
+ mBackCallback.cancelBack();
+ }
+
+ if (mTranslationAnimation.isRunning()) {
+ mTranslationAnimation.addEndListener(mSetGoneEndListener);
+ } else {
+ setVisibility(GONE);
+ }
+ }
+
+ private void resetOnDown() {
+ animate().cancel();
+ mAngleAnimation.cancel();
+ mTranslationAnimation.cancel();
+ mVerticalTranslationAnimation.cancel();
+ mArrowDisappearAnimation.cancel();
+ mAngleOffset = 0;
+ mTranslationAnimation.setSpring(mRegularTranslationSpring);
+ // Reset the arrow to the side
+ setTriggerBack(false /* triggerBack */, false /* animated */);
+ setDesiredTranslation(0, false /* animated */);
+ setCurrentTranslation(0);
+ updateAngle(false /* animate */);
+ mPreviousTouchTranslation = 0;
+ mTotalTouchDelta = 0;
+ mVibrationTime = 0;
+ setDesiredVerticalTransition(0, false /* animated */);
+ }
+
+ private void handleMoveEvent(MotionEvent event) {
+ float x = event.getX();
+ float y = event.getY();
+ float touchTranslation = Math.abs(x - mStartX);
+ float yOffset = y - mStartY;
+ float delta = touchTranslation - mPreviousTouchTranslation;
+ if (Math.abs(delta) > 0) {
+ if (Math.signum(delta) == Math.signum(mTotalTouchDelta)) {
+ mTotalTouchDelta += delta;
+ } else {
+ mTotalTouchDelta = delta;
+ }
+ }
+ mPreviousTouchTranslation = touchTranslation;
+
+ // Apply a haptic on drag slop passed
+ if (!mDragSlopPassed && touchTranslation > mSwipeThreshold) {
+ mDragSlopPassed = true;
+ VibratorWrapper.INSTANCE.get(getContext()).vibrate(VibratorWrapper.EFFECT_CLICK);
+ mVibrationTime = SystemClock.uptimeMillis();
+
+ // Let's show the arrow and animate it in!
+ mDisappearAmount = 0.0f;
+ setAlpha(1f);
+ // And animate it go to back by default!
+ setTriggerBack(true /* triggerBack */, true /* animated */);
+ }
+
+ // Let's make sure we only go to the baseextend and apply rubberbanding afterwards
+ if (touchTranslation > mBaseTranslation) {
+ float diff = touchTranslation - mBaseTranslation;
+ float progress = MathUtils.clamp(diff / (mScreenSize - mBaseTranslation), 0, 1);
+ progress = RUBBER_BAND_INTERPOLATOR.getInterpolation(progress)
+ * (mMaxTranslation - mBaseTranslation);
+ touchTranslation = mBaseTranslation + progress;
+ } else {
+ float diff = mBaseTranslation - touchTranslation;
+ float progress = MathUtils.clamp(diff / mBaseTranslation, 0, 1);
+ progress = RUBBER_BAND_INTERPOLATOR_APPEAR.getInterpolation(progress)
+ * (mBaseTranslation / RUBBER_BAND_AMOUNT_APPEAR);
+ touchTranslation = mBaseTranslation - progress;
+ }
+ // By default we just assume the current direction is kept
+ boolean triggerBack = mTriggerBack;
+
+ // First lets see if we had continuous motion in one direction for a while
+ if (Math.abs(mTotalTouchDelta) > mMinDeltaForSwitch) {
+ triggerBack = mTotalTouchDelta > 0;
+ }
+
+ // Then, let's see if our velocity tells us to change direction
+ mVelocityTracker.computeCurrentVelocity(1000);
+ float xVelocity = mVelocityTracker.getXVelocity();
+ float yVelocity = mVelocityTracker.getYVelocity();
+ float velocity = (float) Math.hypot(xVelocity, yVelocity);
+ mAngleOffset = Math.min(velocity / 1000 * ARROW_ANGLE_ADDED_PER_1000_SPEED,
+ ARROW_MAX_ANGLE_SPEED_OFFSET_DEGREES) * Math.signum(xVelocity);
+ if (mIsLeftPanel && mArrowsPointLeft || !mIsLeftPanel && !mArrowsPointLeft) {
+ mAngleOffset *= -1;
+ }
+
+ // Last if the direction in Y is bigger than X * 2 we also abort
+ if (Math.abs(yOffset) > Math.abs(x - mStartX) * 2) {
+ triggerBack = false;
+ }
+ setTriggerBack(triggerBack, true /* animated */);
+
+ if (!mTriggerBack) {
+ touchTranslation = 0;
+ } else if (mIsLeftPanel && mArrowsPointLeft
+ || (!mIsLeftPanel && !mArrowsPointLeft)) {
+ // If we're on the left we should move less, because the arrow is facing the other
+ // direction
+ touchTranslation -= getStaticArrowWidth();
+ }
+ setDesiredTranslation(touchTranslation, true /* animated */);
+ updateAngle(true /* animated */);
+
+ float maxYOffset = getHeight() / 2.0f - mArrowLength;
+ float progress =
+ MathUtils.clamp(Math.abs(yOffset) / (maxYOffset * RUBBER_BAND_AMOUNT), 0, 1);
+ float verticalTranslation = RUBBER_BAND_INTERPOLATOR.getInterpolation(progress)
+ * maxYOffset * Math.signum(yOffset);
+ setDesiredVerticalTransition(verticalTranslation, true /* animated */);
+ }
+
+ private void updatePosition(float touchY) {
+ float positionY = touchY - mFingerOffset;
+ positionY = Math.max(positionY, mMinArrowPosition);
+ positionY -= getLayoutParams().height / 2.0f;
+ setX(mIsLeftPanel ? 0 : mDisplaySize.x - getLayoutParams().width);
+ setY(MathUtils.clamp((int) positionY, 0, mDisplaySize.y));
+ }
+
+ private void setDesiredVerticalTransition(float verticalTranslation, boolean animated) {
+ if (mDesiredVerticalTranslation != verticalTranslation) {
+ mDesiredVerticalTranslation = verticalTranslation;
+ if (!animated) {
+ setVerticalTranslation(verticalTranslation);
+ } else {
+ mVerticalTranslationAnimation.animateToFinalPosition(verticalTranslation);
+ }
+ invalidate();
+ }
+ }
+
+ private void setVerticalTranslation(float verticalTranslation) {
+ mVerticalTranslation = verticalTranslation;
+ invalidate();
+ }
+
+ private float getVerticalTranslation() {
+ return mVerticalTranslation;
+ }
+
+ private void setDesiredTranslation(float desiredTranslation, boolean animated) {
+ if (mDesiredTranslation != desiredTranslation) {
+ mDesiredTranslation = desiredTranslation;
+ if (!animated) {
+ setCurrentTranslation(desiredTranslation);
+ } else {
+ mTranslationAnimation.animateToFinalPosition(desiredTranslation);
+ }
+ }
+ }
+
+ private void setCurrentTranslation(float currentTranslation) {
+ mCurrentTranslation = currentTranslation;
+ invalidate();
+ }
+
+ private void setTriggerBack(boolean triggerBack, boolean animated) {
+ if (mTriggerBack != triggerBack) {
+ mTriggerBack = triggerBack;
+ mAngleAnimation.cancel();
+ updateAngle(animated);
+ // Whenever the trigger back state changes the existing translation animation should be
+ // cancelled
+ mTranslationAnimation.cancel();
+ }
+ }
+
+ private void updateAngle(boolean animated) {
+ float newAngle = mTriggerBack ? ARROW_ANGLE_WHEN_EXTENDED_DEGREES + mAngleOffset : 90;
+ if (newAngle != mDesiredAngle) {
+ if (!animated) {
+ setCurrentAngle(newAngle);
+ } else {
+ mAngleAnimation.setSpring(mTriggerBack ? mAngleAppearForce : mAngleDisappearForce);
+ mAngleAnimation.animateToFinalPosition(newAngle);
+ }
+ mDesiredAngle = newAngle;
+ }
+ }
+
+ private void setCurrentAngle(float currentAngle) {
+ mCurrentAngle = currentAngle;
+ invalidate();
+ }
+
+ private float dp(float dp) {
+ return mDensity * dp;
+ }
+
+ /** Callback to let the gesture handler react to the detected back gestures. */
+ interface BackCallback {
+ /** Indicates that a Back gesture was recognized. */
+ void triggerBack();
+
+ /** Indicates that the gesture was cancelled. */
+ void cancelBack();
+ }
+}
diff --git a/quickstep/src/com/android/quickstep/interaction/BackGestureTutorialActivity.java b/quickstep/src/com/android/quickstep/interaction/GestureSandboxActivity.java
similarity index 65%
rename from quickstep/src/com/android/quickstep/interaction/BackGestureTutorialActivity.java
rename to quickstep/src/com/android/quickstep/interaction/GestureSandboxActivity.java
index 295ab48..4815366 100644
--- a/quickstep/src/com/android/quickstep/interaction/BackGestureTutorialActivity.java
+++ b/quickstep/src/com/android/quickstep/interaction/GestureSandboxActivity.java
@@ -16,7 +16,10 @@
package com.android.quickstep.interaction;
import android.graphics.Color;
+import android.graphics.Rect;
import android.os.Bundle;
+import android.util.DisplayMetrics;
+import android.view.Display;
import android.view.View;
import android.view.Window;
@@ -26,12 +29,12 @@
import com.android.quickstep.interaction.BackGestureTutorialFragment.TutorialStep;
import com.android.quickstep.interaction.BackGestureTutorialFragment.TutorialType;
-import java.util.Optional;
+import java.util.List;
-/** Shows the Back gesture interactive tutorial in full screen mode. */
-public class BackGestureTutorialActivity extends FragmentActivity {
+/** Shows the gesture interactive sandbox in full screen mode. */
+public class GestureSandboxActivity extends FragmentActivity {
- Optional<BackGestureTutorialFragment> mFragment = Optional.empty();
+ private BackGestureTutorialFragment mFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
@@ -39,14 +42,27 @@
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.back_gesture_tutorial_activity);
- mFragment = Optional.of(BackGestureTutorialFragment.newInstance(TutorialStep.ENGAGED,
- TutorialType.RIGHT_EDGE_BACK_NAVIGATION));
+ mFragment = BackGestureTutorialFragment.newInstance(
+ TutorialStep.ENGAGED, TutorialType.RIGHT_EDGE_BACK_NAVIGATION);
getSupportFragmentManager().beginTransaction()
- .add(R.id.back_gesture_tutorial_fragment_container, mFragment.get())
+ .add(R.id.back_gesture_tutorial_fragment_container, mFragment)
.commit();
}
@Override
+ public void onAttachedToWindow() {
+ super.onAttachedToWindow();
+ disableSystemGestures();
+ mFragment.onAttachedToWindow();
+ }
+
+ @Override
+ public void onDetachedFromWindow() {
+ super.onDetachedFromWindow();
+ mFragment.onDetachedFromWindow();
+ }
+
+ @Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
@@ -54,13 +70,6 @@
}
}
- @Override
- public void onBackPressed() {
- if (mFragment.isPresent()) {
- mFragment.get().onBackPressed();
- }
- }
-
private void hideSystemUI() {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
@@ -70,4 +79,14 @@
| View.SYSTEM_UI_FLAG_FULLSCREEN);
getWindow().setNavigationBarColor(Color.TRANSPARENT);
}
+
+ private void disableSystemGestures() {
+ Display display = getDisplay();
+ if (display != null) {
+ DisplayMetrics metrics = new DisplayMetrics();
+ display.getMetrics(metrics);
+ getWindow().setSystemGestureExclusionRects(
+ List.of(new Rect(0, 0, metrics.widthPixels, metrics.heightPixels)));
+ }
+ }
}
diff --git a/quickstep/src/com/android/quickstep/logging/StatsLogCompatManager.java b/quickstep/src/com/android/quickstep/logging/StatsLogCompatManager.java
index 53859ad..ac2200d 100644
--- a/quickstep/src/com/android/quickstep/logging/StatsLogCompatManager.java
+++ b/quickstep/src/com/android/quickstep/logging/StatsLogCompatManager.java
@@ -18,34 +18,24 @@
import static android.stats.launcher.nano.Launcher.ALLAPPS;
import static android.stats.launcher.nano.Launcher.BACKGROUND;
-import static android.stats.launcher.nano.Launcher.DISMISS_TASK;
import static android.stats.launcher.nano.Launcher.HOME;
-import static android.stats.launcher.nano.Launcher.LAUNCH_APP;
-import static android.stats.launcher.nano.Launcher.LAUNCH_TASK;
import static android.stats.launcher.nano.Launcher.OVERVIEW;
import android.content.Context;
-import android.content.Intent;
-import android.os.UserHandle;
-import android.stats.launcher.nano.Launcher;
-import android.stats.launcher.nano.LauncherExtension;
-import android.stats.launcher.nano.LauncherTarget;
-import android.util.Log;
-import android.view.View;
-import androidx.annotation.Nullable;
-
-import com.android.launcher3.ItemInfo;
+import com.android.launcher3.LauncherAppState;
+import com.android.launcher3.logger.LauncherAtom;
import com.android.launcher3.logging.StatsLogManager;
import com.android.launcher3.logging.StatsLogUtils;
-import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
-import com.android.launcher3.userevent.nano.LauncherLogProto.ControlType;
-import com.android.launcher3.userevent.nano.LauncherLogProto.ItemType;
-import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
-import com.android.launcher3.util.ComponentKey;
-import com.android.systemui.shared.system.SysUiStatsLog;
+import com.android.launcher3.model.AllAppsList;
+import com.android.launcher3.model.BaseModelUpdateTask;
+import com.android.launcher3.model.BgDataModel;
+import com.android.launcher3.model.data.FolderInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
+import com.android.launcher3.util.IntSparseArrayMap;
-import com.google.protobuf.nano.MessageNano;
+import java.util.ArrayList;
/**
* This method calls the StatsLog hidden method until they are made available public.
@@ -58,192 +48,59 @@
public class StatsLogCompatManager extends StatsLogManager {
private static final int SUPPORTED_TARGET_DEPTH = 2;
- private static final String TAG = "StatsLogCompatManager";
+ private static final String TAG = "StatsLog";
private static final boolean DEBUG = false;
+ private static Context sContext;
- public StatsLogCompatManager(Context context) { }
-
- @Override
- public void logAppLaunch(View v, Intent intent, @Nullable UserHandle userHandle) {
- LauncherExtension ext = new LauncherExtension();
- ext.srcTarget = new LauncherTarget[SUPPORTED_TARGET_DEPTH];
- int srcState = mStateProvider.getCurrentState();
- fillInLauncherExtension(v, ext);
- if (ext.srcTarget[0] != null) {
- ext.srcTarget[0].item = LauncherTarget.APP_ICON;
- }
- SysUiStatsLog.write(SysUiStatsLog.LAUNCHER_EVENT, LAUNCH_APP, srcState,
- BACKGROUND /* dstState */, MessageNano.toByteArray(ext), true);
+ public StatsLogCompatManager(Context context) {
+ sContext = context;
}
@Override
- public void logTaskLaunch(View v, ComponentKey componentKey) {
- LauncherExtension ext = new LauncherExtension();
- ext.srcTarget = new LauncherTarget[SUPPORTED_TARGET_DEPTH];
- int srcState = OVERVIEW;
- fillInLauncherExtension(v, ext);
- SysUiStatsLog.write(SysUiStatsLog.LAUNCHER_EVENT, LAUNCH_TASK, srcState,
- BACKGROUND /* dstState */, MessageNano.toByteArray(ext), true);
- }
-
- @Override
- public void logTaskDismiss(View v, ComponentKey componentKey) {
- LauncherExtension ext = new LauncherExtension();
- ext.srcTarget = new LauncherTarget[SUPPORTED_TARGET_DEPTH];
- int srcState = OVERVIEW;
- fillInLauncherExtension(v, ext);
- SysUiStatsLog.write(SysUiStatsLog.LAUNCHER_EVENT, DISMISS_TASK, srcState,
- BACKGROUND /* dstState */, MessageNano.toByteArray(ext), true);
- }
-
- @Override
- public void logSwipeOnContainer(boolean isSwipingToLeft, int pageId) {
- LauncherExtension ext = new LauncherExtension();
- ext.srcTarget = new LauncherTarget[1];
- int srcState = mStateProvider.getCurrentState();
- fillInLauncherExtensionWithPageId(ext, pageId);
- int launcherAction = isSwipingToLeft ? Launcher.SWIPE_LEFT : Launcher.SWIPE_RIGHT;
- SysUiStatsLog.write(SysUiStatsLog.LAUNCHER_EVENT, launcherAction, srcState, srcState,
- MessageNano.toByteArray(ext), true);
- }
-
- public static boolean fillInLauncherExtension(View v, LauncherExtension extension) {
- if (DEBUG) {
- Log.d(TAG, "fillInLauncherExtension");
- }
-
- StatsLogUtils.LogContainerProvider provider = StatsLogUtils.getLaunchProviderRecursive(v);
- if (v == null || !(v.getTag() instanceof ItemInfo) || provider == null) {
- if (DEBUG) {
- Log.d(TAG, "View or provider is null, or view doesn't have an ItemInfo tag.");
- }
-
- return false;
- }
- ItemInfo itemInfo = (ItemInfo) v.getTag();
- Target child = new Target();
- Target parent = new Target();
- provider.fillInLogContainerData(v, itemInfo, child, parent);
- extension.srcTarget[0] = new LauncherTarget();
- extension.srcTarget[1] = new LauncherTarget();
- copy(child, extension.srcTarget[0]);
- copy(parent, extension.srcTarget[1]);
- return true;
- }
-
- public static boolean fillInLauncherExtensionWithPageId(LauncherExtension ext, int pageId) {
- if (DEBUG) {
- Log.d(TAG, "fillInLauncherExtensionWithPageId, pageId = " + pageId);
- }
-
- Target target = new Target();
- target.pageIndex = pageId;
- ext.srcTarget[0] = new LauncherTarget();
- copy(target, ext.srcTarget[0]);
- return true;
- }
-
- private static void copy(Target src, LauncherTarget dst) {
- if (DEBUG) {
- Log.d(TAG, "copy target information from clearcut Target to LauncherTarget.");
- }
-
- // Fill in type
- switch (src.type) {
- case Target.Type.ITEM:
- dst.type = LauncherTarget.ITEM_TYPE;
- break;
- case Target.Type.CONTROL:
- dst.type = LauncherTarget.CONTROL_TYPE;
- break;
- case Target.Type.CONTAINER:
- dst.type = LauncherTarget.CONTAINER_TYPE;
- break;
- default:
- dst.type = LauncherTarget.NONE;
- break;
- }
-
- // Fill in item
- switch (src.itemType) {
- case ItemType.APP_ICON:
- dst.item = LauncherTarget.APP_ICON;
- break;
- case ItemType.SHORTCUT:
- dst.item = LauncherTarget.SHORTCUT;
- break;
- case ItemType.WIDGET:
- dst.item = LauncherTarget.WIDGET;
- break;
- case ItemType.FOLDER_ICON:
- dst.item = LauncherTarget.FOLDER_ICON;
- break;
- case ItemType.DEEPSHORTCUT:
- dst.item = LauncherTarget.DEEPSHORTCUT;
- break;
- case ItemType.SEARCHBOX:
- dst.item = LauncherTarget.SEARCHBOX;
- break;
- case ItemType.EDITTEXT:
- dst.item = LauncherTarget.EDITTEXT;
- break;
- case ItemType.NOTIFICATION:
- dst.item = LauncherTarget.NOTIFICATION;
- break;
- case ItemType.TASK:
- dst.item = LauncherTarget.TASK;
- break;
- default:
- dst.item = LauncherTarget.DEFAULT_ITEM;
- break;
- }
-
- // Fill in container
- switch (src.containerType) {
- case ContainerType.HOTSEAT:
- dst.container = LauncherTarget.HOTSEAT;
- break;
- case ContainerType.FOLDER:
- dst.container = LauncherTarget.FOLDER;
- break;
- case ContainerType.PREDICTION:
- dst.container = LauncherTarget.PREDICTION;
- break;
- case ContainerType.SEARCHRESULT:
- dst.container = LauncherTarget.SEARCHRESULT;
- break;
- default:
- dst.container = LauncherTarget.DEFAULT_CONTAINER;
- break;
- }
-
- // Fill in control
- switch (src.controlType) {
- case ControlType.UNINSTALL_TARGET:
- dst.control = LauncherTarget.UNINSTALL;
- break;
- case ControlType.REMOVE_TARGET:
- dst.control = LauncherTarget.REMOVE;
- break;
- default:
- dst.control = LauncherTarget.DEFAULT_CONTROL;
- break;
- }
-
- // Fill in other fields
- dst.pageId = src.pageIndex;
- dst.gridX = src.gridX;
- dst.gridY = src.gridY;
+ public void log(LauncherEvent eventId, LauncherAtom.ItemInfo item) {
+ // Call StatsLog method
}
@Override
public void verify() {
- if(!(StatsLogUtils.LAUNCHER_STATE_ALLAPPS == ALLAPPS &&
- StatsLogUtils.LAUNCHER_STATE_BACKGROUND == BACKGROUND &&
- StatsLogUtils.LAUNCHER_STATE_OVERVIEW == OVERVIEW &&
- StatsLogUtils.LAUNCHER_STATE_HOME == HOME)) {
+ if (!(StatsLogUtils.LAUNCHER_STATE_ALLAPPS == ALLAPPS
+ && StatsLogUtils.LAUNCHER_STATE_BACKGROUND == BACKGROUND
+ && StatsLogUtils.LAUNCHER_STATE_OVERVIEW == OVERVIEW
+ && StatsLogUtils.LAUNCHER_STATE_HOME == HOME)) {
throw new IllegalStateException(
"StatsLogUtil constants doesn't match enums in launcher.proto");
}
}
+
+ /**
+ * Logs the workspace layout information on the model thread.
+ */
+ public void logSnapshot() {
+ LauncherAppState.getInstance(sContext).getModel().enqueueModelUpdateTask(
+ new SnapshotWorker());
+ }
+
+ private class SnapshotWorker extends BaseModelUpdateTask {
+ @Override
+ public void execute(LauncherAppState app, BgDataModel dataModel, AllAppsList apps) {
+ IntSparseArrayMap<FolderInfo> folders = dataModel.folders.clone();
+ ArrayList<ItemInfo> workspaceItems = (ArrayList) dataModel.workspaceItems.clone();
+ ArrayList<LauncherAppWidgetInfo> appWidgets = (ArrayList) dataModel.appWidgets.clone();
+
+ for (ItemInfo info : workspaceItems) {
+ LauncherAtom.ItemInfo atomInfo = info.buildProto(null, null);
+ // call StatsLog method
+ }
+ for (FolderInfo fInfo : folders) {
+ for (ItemInfo info : fInfo.contents) {
+ LauncherAtom.ItemInfo atomInfo = info.buildProto(null, fInfo);
+ // call StatsLog method
+ }
+ }
+ for (ItemInfo info : appWidgets) {
+ LauncherAtom.ItemInfo atomInfo = info.buildProto(null, null);
+ // call StatsLog method
+ }
+ }
+ }
}
diff --git a/quickstep/src/com/android/quickstep/util/BinderTracker.java b/quickstep/src/com/android/quickstep/util/BinderTracker.java
index 32d0d53..cb04e5b 100644
--- a/quickstep/src/com/android/quickstep/util/BinderTracker.java
+++ b/quickstep/src/com/android/quickstep/util/BinderTracker.java
@@ -31,7 +31,7 @@
private static final String TAG = "BinderTracker";
public static void start() {
- if (!FeatureFlags.IS_DOGFOOD_BUILD) {
+ if (!FeatureFlags.IS_STUDIO_BUILD) {
Log.wtf(TAG, "Accessing tracker in released code.", new Exception());
return;
}
@@ -40,7 +40,7 @@
}
public static void stop() {
- if (!FeatureFlags.IS_DOGFOOD_BUILD) {
+ if (!FeatureFlags.IS_STUDIO_BUILD) {
Log.wtf(TAG, "Accessing tracker in released code.", new Exception());
return;
}
diff --git a/quickstep/src/com/android/quickstep/util/ImageActionUtils.java b/quickstep/src/com/android/quickstep/util/ImageActionUtils.java
new file mode 100644
index 0000000..f5fbf28
--- /dev/null
+++ b/quickstep/src/com/android/quickstep/util/ImageActionUtils.java
@@ -0,0 +1,169 @@
+/*
+ * 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.quickstep.util;
+
+import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
+import static android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION;
+
+import static com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR;
+
+import android.content.ClipData;
+import android.content.ClipDescription;
+import android.content.Context;
+import android.content.Intent;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.Insets;
+import android.graphics.Picture;
+import android.graphics.Rect;
+import android.net.Uri;
+import android.util.Log;
+
+import androidx.annotation.UiThread;
+import androidx.annotation.WorkerThread;
+import androidx.core.content.FileProvider;
+
+import com.android.launcher3.BuildConfig;
+import com.android.quickstep.SystemUiProxy;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.function.BiFunction;
+import java.util.function.Supplier;
+
+/**
+ * Utility class containing methods to help manage image actions such as sharing, cropping, and
+ * saving image.
+ */
+public class ImageActionUtils {
+
+ private static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".overview.fileprovider";
+
+ /**
+ * Saves screenshot to location determine by SystemUiProxy
+ */
+ public static void saveScreenshot(SystemUiProxy systemUiProxy, Bitmap screenshot,
+ Rect screenshotBounds,
+ Insets visibleInsets, int taskId) {
+ systemUiProxy.handleImageAsScreenshot(screenshot, screenshotBounds, visibleInsets, taskId);
+ }
+
+ /**
+ * Launch the activity to share image.
+ */
+ @UiThread
+ public static void startShareActivity(Context context, Supplier<Bitmap> bitmapSupplier,
+ Rect crop, Intent intent, String tag) {
+ if (bitmapSupplier.get() == null) {
+ Log.e(tag, "No snapshot available, not starting share.");
+ return;
+ }
+
+ UI_HELPER_EXECUTOR.execute(() -> persistBitmapAndStartActivity(context,
+ bitmapSupplier.get(), crop, intent, ImageActionUtils::getShareIntentForImageUri,
+ tag));
+ }
+
+ /**
+ * Starts activity based on given intent created from image uri.
+ */
+ @WorkerThread
+ public static void persistBitmapAndStartActivity(Context context, Bitmap bitmap, Rect crop,
+ Intent intent, BiFunction<Uri, Intent, Intent[]> uriToIntentMap, String tag) {
+ context.startActivities(
+ uriToIntentMap.apply(getImageUri(bitmap, crop, context, tag), intent));
+ }
+
+ /**
+ * Converts image bitmap to Uri by temporarily saving bitmap to cache, and creating Uri pointing
+ * to that location. Used to be able to share an image with another app.
+ *
+ * @param bitmap The whole bitmap to be shared.
+ * @param crop The section of the bitmap to be shared.
+ * @param context The application context, used to interact with file system.
+ * @param tag Tag used to log errors.
+ * @return Uri that points to the cropped version of desired bitmap to share.
+ */
+ @WorkerThread
+ public static Uri getImageUri(Bitmap bitmap, Rect crop, Context context, String tag) {
+ Bitmap croppedBitmap = cropBitmap(bitmap, crop);
+ int cropHash = crop == null ? 0 : crop.hashCode();
+ String baseName = "image_" + bitmap.hashCode() + "_" + cropHash + ".png";
+ File file = new File(context.getCacheDir(), baseName);
+
+ try (FileOutputStream fos = new FileOutputStream(file)) {
+ croppedBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
+ } catch (IOException e) {
+ Log.e(tag, "Error saving image", e);
+ }
+
+ return FileProvider.getUriForFile(context, AUTHORITY, file);
+ }
+
+ /**
+ * Crops the bitmap to the provided size and returns a software backed bitmap whenever possible.
+ *
+ * @param bitmap The bitmap to be cropped.
+ * @param crop The section of the bitmap in the crop.
+ * @return The cropped bitmap.
+ */
+ @WorkerThread
+ public static Bitmap cropBitmap(Bitmap bitmap, Rect crop) {
+ Rect src = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
+ if (crop == null) {
+ crop = new Rect(src);
+ }
+ if (crop.equals(src)) {
+ return bitmap;
+ } else {
+ if (bitmap.getConfig() != Bitmap.Config.HARDWARE) {
+ return Bitmap.createBitmap(bitmap, crop.left, crop.top, crop.width(),
+ crop.height());
+ }
+
+ // For hardware bitmaps, use the Picture API to directly create a software bitmap
+ Picture picture = new Picture();
+ Canvas canvas = picture.beginRecording(crop.width(), crop.height());
+ canvas.drawBitmap(bitmap, -crop.left, -crop.top, null);
+ picture.endRecording();
+ return Bitmap.createBitmap(picture, crop.width(), crop.height(),
+ Bitmap.Config.ARGB_8888);
+ }
+ }
+
+ /**
+ * Gets the intent used to share image.
+ */
+ @WorkerThread
+ private static Intent[] getShareIntentForImageUri(Uri uri, Intent intent) {
+ if (intent == null) {
+ intent = new Intent();
+ }
+ ClipData clipdata = new ClipData(new ClipDescription("content",
+ new String[]{ClipDescription.MIMETYPE_TEXT_PLAIN}),
+ new ClipData.Item(uri));
+ intent.setAction(Intent.ACTION_SEND)
+ .setComponent(null)
+ .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ .setType("image/png")
+ .setFlags(FLAG_GRANT_READ_URI_PERMISSION)
+ .putExtra(Intent.EXTRA_STREAM, uri)
+ .setClipData(clipdata);
+ return new Intent[]{Intent.createChooser(intent, null).addFlags(FLAG_ACTIVITY_NEW_TASK)};
+ }
+}
diff --git a/quickstep/src/com/android/quickstep/util/LayoutUtils.java b/quickstep/src/com/android/quickstep/util/LayoutUtils.java
index 9cf55b3..1f1a999 100644
--- a/quickstep/src/com/android/quickstep/util/LayoutUtils.java
+++ b/quickstep/src/com/android/quickstep/util/LayoutUtils.java
@@ -65,7 +65,7 @@
// UI when shown.
extraSpace = 0;
} else {
- extraSpace = getDefaultSwipeHeight(context, dp) + dp.verticalDragHandleSizePx
+ extraSpace = getDefaultSwipeHeight(context, dp) + dp.workspacePageIndicatorHeight
+ res.getDimensionPixelSize(
R.dimen.dynamic_grid_hotseat_extra_vertical_size)
+ res.getDimensionPixelSize(R.dimen.dynamic_grid_hotseat_bottom_padding);
@@ -84,6 +84,7 @@
float taskWidth, taskHeight, paddingHorz;
Resources res = context.getResources();
Rect insets = dp.getInsets();
+ final boolean overviewActionsEnabled = ENABLE_OVERVIEW_ACTIONS.get();
if (dp.isMultiWindowMode) {
if (multiWindowStrategy == MULTI_WINDOW_STRATEGY_HALF_SCREEN) {
@@ -113,7 +114,7 @@
final int paddingResId;
if (dp.isVerticalBarLayout()) {
paddingResId = R.dimen.landscape_task_card_horz_space;
- } else if (ENABLE_OVERVIEW_ACTIONS.get() && removeShelfFromOverview(context)) {
+ } else if (overviewActionsEnabled && removeShelfFromOverview(context)) {
paddingResId = R.dimen.portrait_task_card_horz_space_big_overview;
} else {
paddingResId = R.dimen.portrait_task_card_horz_space;
@@ -121,9 +122,11 @@
paddingHorz = res.getDimension(paddingResId);
}
- float topIconMargin = res.getDimension(R.dimen.task_thumbnail_top_margin);
+ float topIconMargin = res.getDimension(R.dimen.task_thumbnail_top_margin);
float bottomMargin = thumbnailBottomMargin(context);
- float paddingVert = res.getDimension(R.dimen.task_card_vert_space);
+
+ float paddingVert = overviewActionsEnabled && removeShelfFromOverview(context)
+ ? 0 : res.getDimension(R.dimen.task_card_vert_space);
// Note this should be same as dp.availableWidthPx and dp.availableHeightPx unless
// we override the insets ourselves.
@@ -141,7 +144,7 @@
// Center in the visible space
float x = insets.left + (launcherVisibleWidth - outWidth) / 2;
float y = insets.top + Math.max(topIconMargin,
- (launcherVisibleHeight - extraVerticalSpace - outHeight) / 2);
+ (launcherVisibleHeight - extraVerticalSpace - outHeight - bottomMargin) / 2);
outRect.set(Math.round(x), Math.round(y),
Math.round(x) + Math.round(outWidth), Math.round(y) + Math.round(outHeight));
}
diff --git a/quickstep/src/com/android/quickstep/util/MotionPauseDetector.java b/quickstep/src/com/android/quickstep/util/MotionPauseDetector.java
index 801a560..7d52571 100644
--- a/quickstep/src/com/android/quickstep/util/MotionPauseDetector.java
+++ b/quickstep/src/com/android/quickstep/util/MotionPauseDetector.java
@@ -15,6 +15,8 @@
*/
package com.android.quickstep.util;
+import static com.android.launcher3.config.FeatureFlags.ENABLE_LSQ_VELOCITY_PROVIDER;
+
import android.content.Context;
import android.content.res.Resources;
import android.view.MotionEvent;
@@ -37,8 +39,7 @@
private static final long FORCE_PAUSE_TIMEOUT = 300;
/**
- * After {@link #makePauseHarderToTrigger()}, must
- * move slowly for this long to trigger a pause.
+ * After {@link #mMakePauseHarderToTrigger}, must move slowly for this long to trigger a pause.
*/
private static final long HARDER_TRIGGER_TIMEOUT = 400;
@@ -49,13 +50,10 @@
private final Alarm mForcePauseTimeout;
private final boolean mMakePauseHarderToTrigger;
private final Context mContext;
+ private final VelocityProvider mVelocityProvider;
- private Long mPreviousTime = null;
- private Float mPreviousPosition = null;
private Float mPreviousVelocity = null;
- private Float mFirstPosition = null;
-
private OnMotionPauseListener mOnMotionPauseListener;
private boolean mIsPaused;
// Bias more for the first pause to make it feel extra responsive.
@@ -73,6 +71,13 @@
* @param makePauseHarderToTrigger Used for gestures that require a more explicit pause.
*/
public MotionPauseDetector(Context context, boolean makePauseHarderToTrigger) {
+ this(context, makePauseHarderToTrigger, MotionEvent.AXIS_Y);
+ }
+
+ /**
+ * @param makePauseHarderToTrigger Used for gestures that require a more explicit pause.
+ */
+ public MotionPauseDetector(Context context, boolean makePauseHarderToTrigger, int axis) {
mContext = context;
Resources res = context.getResources();
mSpeedVerySlow = res.getDimension(R.dimen.motion_pause_detector_speed_very_slow);
@@ -82,6 +87,8 @@
mForcePauseTimeout = new Alarm();
mForcePauseTimeout.setOnAlarmListener(alarm -> updatePaused(true /* isPaused */));
mMakePauseHarderToTrigger = makePauseHarderToTrigger;
+ mVelocityProvider = ENABLE_LSQ_VELOCITY_PROVIDER.get()
+ ? new LSqVelocityProvider(axis) : new LinearVelocityProvider(axis);
}
/**
@@ -101,28 +108,26 @@
/**
* Computes velocity and acceleration to determine whether the motion is paused.
- * @param position The x or y component of the motion being tracked.
- *
- * TODO: Use historical positions as well, e.g. {@link MotionEvent#getHistoricalY(int, int)}.
+ * @param ev The motion being tracked.
*/
- public void addPosition(float position, long time) {
- if (mFirstPosition == null) {
- mFirstPosition = position;
- }
+ public void addPosition(MotionEvent ev) {
+ addPosition(ev, 0);
+ }
+
+ /**
+ * Computes velocity and acceleration to determine whether the motion is paused.
+ * @param ev The motion being tracked.
+ * @param pointerIndex Index for the pointer being tracked in the motion event
+ */
+ public void addPosition(MotionEvent ev, int pointerIndex) {
mForcePauseTimeout.setAlarm(mMakePauseHarderToTrigger
? HARDER_TRIGGER_TIMEOUT
: FORCE_PAUSE_TIMEOUT);
- if (mPreviousTime != null && mPreviousPosition != null) {
- long changeInTime = Math.max(1, time - mPreviousTime);
- float changeInPosition = position - mPreviousPosition;
- float velocity = changeInPosition / changeInTime;
- if (mPreviousVelocity != null) {
- checkMotionPaused(velocity, mPreviousVelocity, time);
- }
- mPreviousVelocity = velocity;
+ Float newVelocity = mVelocityProvider.addMotionEvent(ev, pointerIndex);
+ if (newVelocity != null && mPreviousVelocity != null) {
+ checkMotionPaused(newVelocity, mPreviousVelocity, ev.getEventTime());
}
- mPreviousTime = time;
- mPreviousPosition = position;
+ mPreviousVelocity = newVelocity;
}
private void checkMotionPaused(float velocity, float prevVelocity, long time) {
@@ -178,10 +183,8 @@
}
public void clear() {
- mPreviousTime = null;
- mPreviousPosition = null;
+ mVelocityProvider.clear();
mPreviousVelocity = null;
- mFirstPosition = null;
setOnMotionPauseListener(null);
mIsPaused = mHasEverBeenPaused = false;
mSlowStartTime = 0;
@@ -195,4 +198,188 @@
public interface OnMotionPauseListener {
void onMotionPauseChanged(boolean isPaused);
}
+
+ /**
+ * Interface to abstract out velocity calculations
+ */
+ protected interface VelocityProvider {
+
+ /**
+ * Adds a new motion events, and returns the velocity at this point, or null if
+ * the velocity is not available
+ */
+ Float addMotionEvent(MotionEvent ev, int pointer);
+
+ /**
+ * Clears all stored motion event records
+ */
+ void clear();
+ }
+
+ private static class LinearVelocityProvider implements VelocityProvider {
+
+ private Long mPreviousTime = null;
+ private Float mPreviousPosition = null;
+
+ private final int mAxis;
+
+ LinearVelocityProvider(int axis) {
+ mAxis = axis;
+ }
+
+ @Override
+ public Float addMotionEvent(MotionEvent ev, int pointer) {
+ long time = ev.getEventTime();
+ float position = ev.getAxisValue(mAxis, pointer);
+ Float velocity = null;
+
+ if (mPreviousTime != null && mPreviousPosition != null) {
+ long changeInTime = Math.max(1, time - mPreviousTime);
+ float changeInPosition = position - mPreviousPosition;
+ velocity = changeInPosition / changeInTime;
+ }
+ mPreviousTime = time;
+ mPreviousPosition = position;
+ return velocity;
+ }
+
+ @Override
+ public void clear() {
+ mPreviousTime = null;
+ mPreviousPosition = null;
+ }
+ }
+
+ /**
+ * Java implementation of {@link android.view.VelocityTracker} using the Least Square (deg 2)
+ * algorithm.
+ */
+ private static class LSqVelocityProvider implements VelocityProvider {
+
+ // Maximum age of a motion event to be considered when calculating the velocity.
+ private static final long HORIZON_MS = 100;
+ // Number of samples to keep.
+ private static final int HISTORY_SIZE = 20;
+
+ // Position history are stored in a circular array
+ private final float[] mHistoricTimes = new float[HISTORY_SIZE];
+ private final float[] mHistoricPos = new float[HISTORY_SIZE];
+ private int mHistoryCount = 0;
+ private int mHistoryStart = 0;
+
+ private final int mAxis;
+
+ LSqVelocityProvider(int axis) {
+ mAxis = axis;
+ }
+
+ @Override
+ public void clear() {
+ mHistoryCount = mHistoryStart = 0;
+ }
+
+ private void addPositionAndTime(float eventTime, float eventPosition) {
+ mHistoricTimes[mHistoryStart] = eventTime;
+ mHistoricPos[mHistoryStart] = eventPosition;
+ mHistoryStart++;
+ if (mHistoryStart >= HISTORY_SIZE) {
+ mHistoryStart = 0;
+ }
+ mHistoryCount = Math.min(HISTORY_SIZE, mHistoryCount + 1);
+ }
+
+ @Override
+ public Float addMotionEvent(MotionEvent ev, int pointer) {
+ // Add all historic points
+ int historyCount = ev.getHistorySize();
+ for (int i = 0; i < historyCount; i++) {
+ addPositionAndTime(
+ ev.getHistoricalEventTime(i), ev.getHistoricalAxisValue(mAxis, pointer, i));
+ }
+
+ // Start index for the last position (about to be added)
+ int eventStartIndex = mHistoryStart;
+ addPositionAndTime(ev.getEventTime(), ev.getAxisValue(mAxis, pointer));
+ return solveUnweightedLeastSquaresDeg2(eventStartIndex);
+ }
+
+ /**
+ * Solves the instantaneous velocity.
+ * Based on solveUnweightedLeastSquaresDeg2 in VelocityTracker.cpp
+ */
+ private Float solveUnweightedLeastSquaresDeg2(final int pointPos) {
+ final float eventTime = mHistoricTimes[pointPos];
+
+ float sxi = 0, sxiyi = 0, syi = 0, sxi2 = 0, sxi3 = 0, sxi2yi = 0, sxi4 = 0;
+ int count = 0;
+ for (int i = 0; i < mHistoryCount; i++) {
+ int index = pointPos - i;
+ if (index < 0) {
+ index += HISTORY_SIZE;
+ }
+
+ float time = mHistoricTimes[index];
+ float age = eventTime - time;
+ if (age > HORIZON_MS) {
+ break;
+ }
+ count++;
+ float xi = -age;
+
+ float yi = mHistoricPos[index];
+ float xi2 = xi * xi;
+ float xi3 = xi2 * xi;
+ float xi4 = xi3 * xi;
+ float xiyi = xi * yi;
+ float xi2yi = xi2 * yi;
+
+ sxi += xi;
+ sxi2 += xi2;
+ sxiyi += xiyi;
+ sxi2yi += xi2yi;
+ syi += yi;
+ sxi3 += xi3;
+ sxi4 += xi4;
+ }
+
+ if (count < 3) {
+ // Too few samples
+ if (count == 2) {
+ int endPos = pointPos - 1;
+ if (endPos < 0) {
+ endPos += HISTORY_SIZE;
+ }
+ float denominator = eventTime - mHistoricTimes[endPos];
+ if (denominator != 0) {
+ return (eventTime - mHistoricPos[endPos]) / denominator;
+
+ }
+ }
+ return null;
+ }
+
+ float Sxx = sxi2 - sxi * sxi / count;
+ float Sxy = sxiyi - sxi * syi / count;
+ float Sxx2 = sxi3 - sxi * sxi2 / count;
+ float Sx2y = sxi2yi - sxi2 * syi / count;
+ float Sx2x2 = sxi4 - sxi2 * sxi2 / count;
+
+ float denominator = Sxx * Sx2x2 - Sxx2 * Sxx2;
+ if (denominator == 0) {
+ // division by 0 when computing velocity
+ return null;
+ }
+ // Compute a
+ // float numerator = Sx2y*Sxx - Sxy*Sxx2;
+
+ // Compute b
+ float numerator = Sxy * Sx2x2 - Sx2y * Sxx2;
+ float b = numerator / denominator;
+
+ // Compute c
+ // float c = syi/count - b * sxi/count - a * sxi2/count;
+
+ return b;
+ }
+ }
}
diff --git a/quickstep/src/com/android/quickstep/util/NavBarPosition.java b/quickstep/src/com/android/quickstep/util/NavBarPosition.java
index 8dc19dc..74e6b29 100644
--- a/quickstep/src/com/android/quickstep/util/NavBarPosition.java
+++ b/quickstep/src/com/android/quickstep/util/NavBarPosition.java
@@ -17,12 +17,8 @@
import static com.android.quickstep.SysUINavigationMode.Mode.NO_BUTTON;
-import android.content.Context;
-import android.graphics.Rect;
-import android.view.Gravity;
import android.view.Surface;
-import com.android.launcher3.graphics.RotationMode;
import com.android.launcher3.util.DefaultDisplay;
import com.android.quickstep.SysUINavigationMode;
@@ -31,79 +27,6 @@
*/
public class NavBarPosition {
- public static final RotationMode ROTATION_LANDSCAPE = new RotationMode(-90) {
- @Override
- public void mapRect(int left, int top, int right, int bottom, Rect out) {
- out.left = top;
- out.top = right;
- out.right = bottom;
- out.bottom = left;
- }
-
- @Override
- public void mapInsets(Context context, Rect insets, Rect out) {
- // If there is a display cutout, the top insets in portrait would also include the
- // cutout, which we will get as the left inset in landscape. Using the max of left and
- // top allows us to cover both cases (with or without cutout).
- if (SysUINavigationMode.getMode(context) == NO_BUTTON) {
- out.top = Math.max(insets.top, insets.left);
- out.bottom = Math.max(insets.right, insets.bottom);
- out.left = out.right = 0;
- } else {
- out.top = Math.max(insets.top, insets.left);
- out.bottom = insets.right;
- out.left = insets.bottom;
- out.right = 0;
- }
- }
- };
-
- public static final RotationMode ROTATION_SEASCAPE = new RotationMode(90) {
- @Override
- public void mapRect(int left, int top, int right, int bottom, Rect out) {
- out.left = bottom;
- out.top = left;
- out.right = top;
- out.bottom = right;
- }
-
- @Override
- public void mapInsets(Context context, Rect insets, Rect out) {
- if (SysUINavigationMode.getMode(context) == NO_BUTTON) {
- out.top = Math.max(insets.top, insets.right);
- out.bottom = Math.max(insets.left, insets.bottom);
- out.left = out.right = 0;
- } else {
- out.top = Math.max(insets.top, insets.right);
- out.bottom = insets.left;
- out.right = insets.bottom;
- out.left = 0;
- }
- }
-
- @Override
- public int toNaturalGravity(int absoluteGravity) {
- int horizontalGravity = absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK;
- int verticalGravity = absoluteGravity & Gravity.VERTICAL_GRAVITY_MASK;
-
- if (horizontalGravity == Gravity.RIGHT) {
- horizontalGravity = Gravity.LEFT;
- } else if (horizontalGravity == Gravity.LEFT) {
- horizontalGravity = Gravity.RIGHT;
- }
-
- if (verticalGravity == Gravity.TOP) {
- verticalGravity = Gravity.BOTTOM;
- } else if (verticalGravity == Gravity.BOTTOM) {
- verticalGravity = Gravity.TOP;
- }
-
- return ((absoluteGravity & ~Gravity.HORIZONTAL_GRAVITY_MASK)
- & ~Gravity.VERTICAL_GRAVITY_MASK)
- | horizontalGravity | verticalGravity;
- }
- };
-
private final SysUINavigationMode.Mode mMode;
private final int mDisplayRotation;
@@ -120,8 +43,7 @@
return mMode != NO_BUTTON && mDisplayRotation == Surface.ROTATION_270;
}
- public RotationMode getRotationMode() {
- return isLeftEdge() ? ROTATION_SEASCAPE
- : (isRightEdge() ? ROTATION_LANDSCAPE : RotationMode.NORMAL);
+ public float getRotation() {
+ return isLeftEdge() ? 90 : (isRightEdge() ? -90 : 0);
}
}
diff --git a/quickstep/src/com/android/quickstep/util/QuickstepOnboardingPrefs.java b/quickstep/src/com/android/quickstep/util/QuickstepOnboardingPrefs.java
new file mode 100644
index 0000000..ab2484d
--- /dev/null
+++ b/quickstep/src/com/android/quickstep/util/QuickstepOnboardingPrefs.java
@@ -0,0 +1,96 @@
+/*
+ * 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.quickstep.util;
+
+import static com.android.launcher3.LauncherState.ALL_APPS;
+import static com.android.launcher3.LauncherState.NORMAL;
+import static com.android.launcher3.LauncherState.OVERVIEW;
+
+import android.content.SharedPreferences;
+
+import com.android.launcher3.BaseQuickstepLauncher;
+import com.android.launcher3.LauncherState;
+import com.android.launcher3.LauncherStateManager;
+import com.android.launcher3.LauncherStateManager.StateListener;
+import com.android.launcher3.util.OnboardingPrefs;
+import com.android.quickstep.SysUINavigationMode;
+
+/**
+ * Extends {@link OnboardingPrefs} for quickstep-specific onboarding data.
+ */
+public class QuickstepOnboardingPrefs extends OnboardingPrefs<BaseQuickstepLauncher> {
+
+ public QuickstepOnboardingPrefs(BaseQuickstepLauncher launcher, SharedPreferences sharedPrefs,
+ LauncherStateManager stateManager) {
+ super(launcher, sharedPrefs, stateManager);
+
+ if (!getBoolean(HOME_BOUNCE_SEEN)) {
+ mStateManager.addStateListener(new StateListener() {
+ @Override
+ public void onStateTransitionStart(LauncherState toState) { }
+
+ @Override
+ public void onStateTransitionComplete(LauncherState finalState) {
+ boolean swipeUpEnabled = SysUINavigationMode.INSTANCE
+ .get(mLauncher).getMode().hasGestures;
+ LauncherState prevState = mStateManager.getLastState();
+
+ if (((swipeUpEnabled && finalState == OVERVIEW) || (!swipeUpEnabled
+ && finalState == ALL_APPS && prevState == NORMAL) ||
+ hasReachedMaxCount(HOME_BOUNCE_COUNT))) {
+ mSharedPrefs.edit().putBoolean(HOME_BOUNCE_SEEN, true).apply();
+ mStateManager.removeStateListener(this);
+ }
+ }
+ });
+ }
+
+ if (!getBoolean(SHELF_BOUNCE_SEEN)) {
+ mStateManager.addStateListener(new StateListener() {
+ @Override
+ public void onStateTransitionStart(LauncherState toState) { }
+
+ @Override
+ public void onStateTransitionComplete(LauncherState finalState) {
+ LauncherState prevState = mStateManager.getLastState();
+
+ if ((finalState == ALL_APPS && prevState == OVERVIEW) ||
+ hasReachedMaxCount(SHELF_BOUNCE_COUNT)) {
+ mSharedPrefs.edit().putBoolean(SHELF_BOUNCE_SEEN, true).apply();
+ mStateManager.removeStateListener(this);
+ }
+ }
+ });
+ }
+
+ if (!hasReachedMaxCount(ALL_APPS_COUNT)) {
+ mStateManager.addStateListener(new StateListener() {
+ @Override
+ public void onStateTransitionStart(LauncherState toState) { }
+
+ @Override
+ public void onStateTransitionComplete(LauncherState finalState) {
+ if (finalState == ALL_APPS) {
+ if (incrementEventCount(ALL_APPS_COUNT)) {
+ mStateManager.removeStateListener(this);
+ mLauncher.getScrimView().updateDragHandleVisibility();
+ }
+ }
+ }
+ });
+ }
+ }
+}
diff --git a/quickstep/src/com/android/quickstep/util/RecentsOrientedState.java b/quickstep/src/com/android/quickstep/util/RecentsOrientedState.java
new file mode 100644
index 0000000..f72e458
--- /dev/null
+++ b/quickstep/src/com/android/quickstep/util/RecentsOrientedState.java
@@ -0,0 +1,217 @@
+/*
+ * 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.quickstep.util;
+
+import static android.hardware.camera2.params.OutputConfiguration.ROTATION_180;
+import static android.view.Surface.ROTATION_0;
+import static android.view.Surface.ROTATION_270;
+import static android.view.Surface.ROTATION_90;
+
+import static java.lang.annotation.RetentionPolicy.SOURCE;
+
+import android.graphics.Matrix;
+import android.graphics.RectF;
+import android.view.MotionEvent;
+import android.view.Surface;
+
+import androidx.annotation.IntDef;
+
+import com.android.launcher3.config.FeatureFlags;
+import com.android.launcher3.touch.PagedOrientationHandler;
+import com.android.launcher3.touch.PortraitPagedViewHandler;
+
+import java.lang.annotation.Retention;
+
+/**
+ * Container to hold orientation/rotation related information for Launcher.
+ * This is not meant to be an abstraction layer for applying different functionality between
+ * the different orientation/rotations. For that see {@link PagedOrientationHandler}
+ *
+ * This class has initial default state assuming the device and foreground app have
+ * no ({@link Surface#ROTATION_0} rotation.
+ */
+public final class RecentsOrientedState {
+
+ @Retention(SOURCE)
+ @IntDef({ROTATION_0, ROTATION_90, ROTATION_180, ROTATION_270})
+ public @interface SurfaceRotation {}
+
+ private PagedOrientationHandler mOrientationHandler = PagedOrientationHandler.PORTRAIT;
+
+ private @SurfaceRotation int mTouchRotation = ROTATION_0;
+ private @SurfaceRotation int mDisplayRotation = ROTATION_0;
+ /**
+ * If {@code true} we default to {@link PortraitPagedViewHandler} and don't support any fake
+ * launcher orientations.
+ */
+ private boolean mDisableMultipleOrientations;
+
+ private final Matrix mTmpMatrix = new Matrix();
+ private final Matrix mTmpInverseMatrix = new Matrix();
+
+ /**
+ * Sets the appropriate {@link PagedOrientationHandler} for {@link #mOrientationHandler}
+ * @param touchRotation The rotation the nav bar region that is touched is in
+ * @param displayRotation Rotation of the display/device
+ *
+ * @return true if there was any change in the internal state as a result of this call,
+ * false otherwise
+ */
+ public boolean update(
+ @SurfaceRotation int touchRotation, @SurfaceRotation int displayRotation) {
+ if (!FeatureFlags.ENABLE_FIXED_ROTATION_TRANSFORM.get()) {
+ return false;
+ }
+ if (mDisableMultipleOrientations) {
+ return false;
+ }
+ if (mDisplayRotation == displayRotation && mTouchRotation == touchRotation) {
+ return false;
+ }
+
+ mDisplayRotation = displayRotation;
+ mTouchRotation = touchRotation;
+ if (mTouchRotation == ROTATION_90) {
+ mOrientationHandler = PagedOrientationHandler.LANDSCAPE;
+ } else if (mTouchRotation == ROTATION_270) {
+ mOrientationHandler = PagedOrientationHandler.SEASCAPE;
+ } else {
+ mOrientationHandler = PagedOrientationHandler.PORTRAIT;
+ }
+ return true;
+ }
+
+ public boolean areMultipleLayoutOrientationsDisabled() {
+ return mDisableMultipleOrientations;
+ }
+
+ /**
+ * Setting this preference will render future calls to {@link #update(int, int)} as a no-op.
+ */
+ public void disableMultipleOrientations(boolean disable) {
+ mDisableMultipleOrientations = disable;
+ if (disable) {
+ mDisplayRotation = mTouchRotation = ROTATION_0;
+ mOrientationHandler = PagedOrientationHandler.PORTRAIT;
+ }
+ }
+
+ @SurfaceRotation
+ public int getDisplayRotation() {
+ return mDisplayRotation;
+ }
+
+ @SurfaceRotation
+ public int getTouchRotation() {
+ return mTouchRotation;
+ }
+
+ public int getTouchRotationDegrees() {
+ switch (mTouchRotation) {
+ case ROTATION_90:
+ return 90;
+ case ROTATION_180:
+ return 180;
+ case ROTATION_270:
+ return 270;
+ case ROTATION_0:
+ default:
+ return 0;
+ }
+ }
+
+ public PagedOrientationHandler getOrientationHandler() {
+ return mOrientationHandler;
+ }
+
+ /**
+ * For landscape, since the navbar is already in a vertical position, we don't have to do any
+ * rotations as the change in Y coordinate is what is read. We only flip the sign of the
+ * y coordinate to make it match existing behavior of swipe to the top to go previous
+ */
+ public void flipVertical(MotionEvent ev) {
+ mTmpMatrix.setScale(1, -1);
+ ev.transform(mTmpMatrix);
+ }
+
+ /**
+ * Creates a matrix to transform the given motion event specified by degrees.
+ * If inverse is {@code true}, the inverse of that matrix will be applied
+ */
+ public void transformEvent(float degrees, MotionEvent ev, boolean inverse) {
+ mTmpMatrix.setRotate(inverse ? -degrees : degrees);
+ ev.transform(mTmpMatrix);
+
+ // TODO: Add scaling back in based on degrees
+ /*
+ if (getWidth() > 0 && getHeight() > 0) {
+ float scale = ((float) getWidth()) / getHeight();
+ transform.postScale(scale, 1 / scale);
+ }
+ */
+ }
+
+ public void mapRectFromNormalOrientation(RectF src, int screenWidth, int screenHeight) {
+ mTmpMatrix.reset();
+ postDisplayRotation(mDisplayRotation, screenWidth, screenHeight, mTmpMatrix);
+ mTmpMatrix.mapRect(src);
+ }
+
+ public void mapInverseRectFromNormalOrientation(RectF src, int screenWidth, int screenHeight) {
+ mTmpMatrix.reset();
+ postDisplayRotation(mDisplayRotation, screenWidth, screenHeight, mTmpMatrix);
+ mTmpMatrix.invert(mTmpInverseMatrix);
+ mTmpInverseMatrix.mapRect(src);
+ }
+
+ @SurfaceRotation
+ public static int getRotationForUserDegreesRotated(float degrees) {
+ int threshold = 70;
+ if (degrees >= (360 - threshold) || degrees < (threshold)) {
+ return ROTATION_0;
+ } else if (degrees < (90 + threshold)) {
+ return ROTATION_270;
+ } else if (degrees < 180 + threshold) {
+ return ROTATION_180;
+ } else {
+ return ROTATION_90;
+ }
+ }
+
+ /**
+ * Posts the transformation on the matrix representing the provided display rotation
+ */
+ public static void postDisplayRotation(@SurfaceRotation int displayRotation,
+ float screenWidth, float screenHeight, Matrix out) {
+ switch (displayRotation) {
+ case ROTATION_0:
+ return;
+ case ROTATION_90:
+ out.postRotate(270);
+ out.postTranslate(0, screenWidth);
+ break;
+ case ROTATION_180:
+ out.postRotate(180);
+ out.postTranslate(screenHeight, screenWidth);
+ break;
+ case ROTATION_270:
+ out.postRotate(90);
+ out.postTranslate(screenHeight, 0);
+ break;
+ }
+ }
+}
diff --git a/quickstep/src/com/android/quickstep/util/RemoteAnimationProvider.java b/quickstep/src/com/android/quickstep/util/RemoteAnimationProvider.java
index 6210fc2..21b97ec 100644
--- a/quickstep/src/com/android/quickstep/util/RemoteAnimationProvider.java
+++ b/quickstep/src/com/android/quickstep/util/RemoteAnimationProvider.java
@@ -21,21 +21,22 @@
import android.os.Handler;
import com.android.launcher3.LauncherAnimationRunner;
+import com.android.launcher3.WrappedLauncherAnimationRunner;
import com.android.systemui.shared.system.ActivityOptionsCompat;
import com.android.systemui.shared.system.RemoteAnimationAdapterCompat;
import com.android.systemui.shared.system.RemoteAnimationTargetCompat;
import com.android.systemui.shared.system.TransactionCompat;
-@FunctionalInterface
-public interface RemoteAnimationProvider {
+public abstract class RemoteAnimationProvider {
+ LauncherAnimationRunner mAnimationRunner;
static final int Z_BOOST_BASE = 800570000;
- AnimatorSet createWindowAnimation(RemoteAnimationTargetCompat[] appTargets,
+ public abstract AnimatorSet createWindowAnimation(RemoteAnimationTargetCompat[] appTargets,
RemoteAnimationTargetCompat[] wallpaperTargets);
- default ActivityOptions toActivityOptions(Handler handler, long duration, Context context) {
- LauncherAnimationRunner runner = new LauncherAnimationRunner(handler,
+ ActivityOptions toActivityOptions(Handler handler, long duration, Context context) {
+ mAnimationRunner = new LauncherAnimationRunner(handler,
false /* startAtFrontOfQueue */) {
@Override
@@ -44,8 +45,11 @@
result.setAnimation(createWindowAnimation(appTargets, wallpaperTargets), context);
}
};
+ final LauncherAnimationRunner wrapper = new WrappedLauncherAnimationRunner(
+ mAnimationRunner, false /* startAtFrontOfQueue */);
+
return ActivityOptionsCompat.makeRemoteAnimation(
- new RemoteAnimationAdapterCompat(runner, duration, 0));
+ new RemoteAnimationAdapterCompat(wrapper, duration, 0));
}
/**
@@ -63,9 +67,31 @@
}
}
- static int getLayer(RemoteAnimationTargetCompat target, int boostModeTarget) {
+ public static int getLayer(RemoteAnimationTargetCompat target, int boostModeTarget) {
return target.mode == boostModeTarget
? Z_BOOST_BASE + target.prefixOrderIndex
: target.prefixOrderIndex;
}
+
+ /**
+ * @return the target with the lowest opaque layer for a certain app animation, or null.
+ */
+ public static RemoteAnimationTargetCompat findLowestOpaqueLayerTarget(
+ RemoteAnimationTargetCompat[] appTargets, int mode) {
+ int lowestLayer = Integer.MAX_VALUE;
+ int lowestLayerIndex = -1;
+ for (int i = appTargets.length - 1; i >= 0; i--) {
+ RemoteAnimationTargetCompat target = appTargets[i];
+ if (target.mode == mode && !target.isTranslucent) {
+ int layer = getLayer(target, mode);
+ if (layer < lowestLayer) {
+ lowestLayer = layer;
+ lowestLayerIndex = i;
+ }
+ }
+ }
+ return lowestLayerIndex != -1
+ ? appTargets[lowestLayerIndex]
+ : null;
+ }
}
diff --git a/quickstep/src/com/android/quickstep/views/ShelfScrimView.java b/quickstep/src/com/android/quickstep/views/ShelfScrimView.java
index 1ce3549..f5498c9 100644
--- a/quickstep/src/com/android/quickstep/views/ShelfScrimView.java
+++ b/quickstep/src/com/android/quickstep/views/ShelfScrimView.java
@@ -43,6 +43,7 @@
import com.android.launcher3.anim.Interpolators;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.uioverrides.states.OverviewState;
+import com.android.launcher3.util.OnboardingPrefs;
import com.android.launcher3.util.Themes;
import com.android.launcher3.views.ScrimView;
import com.android.quickstep.SysUINavigationMode;
@@ -75,6 +76,7 @@
private final float mRadius;
private final int mMaxScrimAlpha;
private final Paint mPaint;
+ private final OnboardingPrefs mOnboardingPrefs;
// Mid point where the alpha changes
private int mMidAlpha;
@@ -88,7 +90,6 @@
private float mShiftRange;
- private final float mShelfOffset;
private float mTopOffset;
private float mShelfTop;
private float mShelfTopAtThreshold;
@@ -101,6 +102,7 @@
private boolean mRemainingScreenPathValid = false;
private Mode mSysUINavigationMode;
+ private boolean mIsTwoZoneSwipeModel;
public ShelfScrimView(Context context, AttributeSet attrs) {
super(context, attrs);
@@ -109,8 +111,8 @@
mEndAlpha = Color.alpha(mEndScrim);
mRadius = BOTTOM_CORNER_RADIUS_RATIO * Themes.getDialogCornerRadius(context);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
+ mOnboardingPrefs = mLauncher.getOnboardingPrefs();
- mShelfOffset = context.getResources().getDimension(R.dimen.shelf_surface_offset);
// Just assume the easiest UI for now, until we have the proper layout information.
mDrawingFlatColor = true;
}
@@ -142,9 +144,11 @@
// Show the shelf more quickly before reaching overview progress.
mBeforeMidProgressColorInterpolator = ACCEL_2;
mAfterMidProgressColorInterpolator = ACCEL;
+ mIsTwoZoneSwipeModel = FeatureFlags.ENABLE_OVERVIEW_ACTIONS.get();
} else {
mBeforeMidProgressColorInterpolator = ACCEL;
mAfterMidProgressColorInterpolator = Interpolators.clampToProgress(ACCEL, 0.5f, 1f);
+ mIsTwoZoneSwipeModel = false;
}
}
@@ -179,7 +183,7 @@
Math.min(hotseatSize, LayoutUtils.getDefaultSwipeHeight(context, dp));
mDragHandleProgress = 1 - (dragHandleTop / mShiftRange);
}
- mTopOffset = dp.getInsets().top - mShelfOffset;
+ mTopOffset = dp.getInsets().top - mDragHandleSize.y;
mShelfTopAtThreshold = mShiftRange * SCRIM_CATCHUP_THRESHOLD + mTopOffset;
}
updateColors();
@@ -190,12 +194,15 @@
@Override
public void updateColors() {
super.updateColors();
+ mDragHandleOffset = 0;
if (mDrawingFlatColor) {
- mDragHandleOffset = 0;
return;
}
- mDragHandleOffset = mShelfOffset - mDragHandleSize;
+ if (mProgress < mDragHandleProgress) {
+ mDragHandleOffset = mShiftRange * (mDragHandleProgress - mProgress);
+ }
+
if (mProgress >= SCRIM_CATCHUP_THRESHOLD) {
mShelfTop = mShiftRange * mProgress + mTopOffset;
} else {
@@ -231,10 +238,13 @@
(float) 0, LINEAR));
mRemainingScreenColor = setColorAlphaBound(mScrimColor, remainingScrimAlpha);
}
+ }
- if (mProgress < mDragHandleProgress) {
- mDragHandleOffset += mShiftRange * (mDragHandleProgress - mProgress);
- }
+ @Override
+ protected boolean shouldDragHandleBeVisible() {
+ boolean needsAllAppsEdu = mIsTwoZoneSwipeModel
+ && !mOnboardingPrefs.hasReachedMaxCount(OnboardingPrefs.ALL_APPS_COUNT);
+ return needsAllAppsEdu || super.shouldDragHandleBeVisible();
}
@Override
@@ -283,4 +293,9 @@
mPaint.setColor(mShelfColor);
canvas.drawRoundRect(0, mShelfTop, width, height + mRadius, mRadius, mRadius, mPaint);
}
+
+ @Override
+ public float getVisualTop() {
+ return mShelfTop;
+ }
}
diff --git a/quickstep/tests/src/com/android/quickstep/AppPredictionsUITests.java b/quickstep/tests/src/com/android/quickstep/AppPredictionsUITests.java
index 8e4762d..5904fcd 100644
--- a/quickstep/tests/src/com/android/quickstep/AppPredictionsUITests.java
+++ b/quickstep/tests/src/com/android/quickstep/AppPredictionsUITests.java
@@ -88,7 +88,6 @@
*/
@Test
public void testPredictionExistsInAllApps() {
- mDevice.pressHome();
mLauncher.pressHome().switchToAllApps();
// Dispatch an update
diff --git a/quickstep/tests/src/com/android/quickstep/DigitalWellBeingToastTest.java b/quickstep/tests/src/com/android/quickstep/DigitalWellBeingToastTest.java
index 3e84a76..ccfa3fc 100644
--- a/quickstep/tests/src/com/android/quickstep/DigitalWellBeingToastTest.java
+++ b/quickstep/tests/src/com/android/quickstep/DigitalWellBeingToastTest.java
@@ -11,6 +11,7 @@
import android.app.PendingIntent;
import android.app.usage.UsageStatsManager;
import android.content.Intent;
+import android.os.Build;
import androidx.test.filters.LargeTest;
import androidx.test.runner.AndroidJUnit4;
@@ -33,6 +34,9 @@
@Test
public void testToast() throws Exception {
+ // b/150303529
+ if (Build.MODEL.contains("Cuttlefish")) return;
+
startAppFast(CALCULATOR_PACKAGE);
final UsageStatsManager usageStatsManager =
diff --git a/quickstep/tests/src/com/android/quickstep/NavigationModeSwitchRule.java b/quickstep/tests/src/com/android/quickstep/NavigationModeSwitchRule.java
index 1229a63..0afe4a8 100644
--- a/quickstep/tests/src/com/android/quickstep/NavigationModeSwitchRule.java
+++ b/quickstep/tests/src/com/android/quickstep/NavigationModeSwitchRule.java
@@ -35,6 +35,7 @@
import com.android.launcher3.tapl.LauncherInstrumentation;
import com.android.launcher3.tapl.TestHelpers;
+import com.android.launcher3.ui.AbstractLauncherUiTest;
import com.android.launcher3.util.Wait;
import com.android.launcher3.util.rule.FailureWatcher;
import com.android.systemui.shared.system.QuickStepContract;
@@ -48,7 +49,6 @@
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
/**
* Test rule that allows executing a test with Quickstep on and then Quickstep off.
@@ -166,12 +166,9 @@
return false;
}
- setOverlayPackageEnabled(NAV_BAR_MODE_3BUTTON_OVERLAY,
- overlayPackage == NAV_BAR_MODE_3BUTTON_OVERLAY);
- setOverlayPackageEnabled(NAV_BAR_MODE_2BUTTON_OVERLAY,
- overlayPackage == NAV_BAR_MODE_2BUTTON_OVERLAY);
- setOverlayPackageEnabled(NAV_BAR_MODE_GESTURAL_OVERLAY,
- overlayPackage == NAV_BAR_MODE_GESTURAL_OVERLAY);
+ Log.d(TAG, "setActiveOverlay: " + overlayPackage + "...");
+ UiDevice.getInstance(getInstrumentation()).executeShellCommand(
+ "cmd overlay enable-exclusive " + overlayPackage);
if (currentSysUiNavigationMode() != expectedMode) {
final CountDownLatch latch = new CountDownLatch(1);
@@ -185,11 +182,18 @@
};
targetContext.getMainExecutor().execute(() ->
SYS_UI_NAVIGATION_MODE.addModeChangeListener(listener));
- latch.await(60, TimeUnit.SECONDS);
+ // b/139137636
+// latch.await(60, TimeUnit.SECONDS);
targetContext.getMainExecutor().execute(() ->
SYS_UI_NAVIGATION_MODE.removeModeChangeListener(listener));
- assertTrue(launcher, "Navigation mode didn't change to " + expectedMode,
- currentSysUiNavigationMode() == expectedMode, description);
+
+ Wait.atMost(() -> "Navigation mode didn't change to " + expectedMode,
+ () -> currentSysUiNavigationMode() == expectedMode, 60000 /* b/148422894 */,
+ launcher);
+ // b/139137636
+// assertTrue(launcher, "Navigation mode didn't change to " + expectedMode,
+// currentSysUiNavigationMode() == expectedMode, description);
+
}
Wait.atMost("Couldn't switch to " + overlayPackage,
@@ -199,18 +203,10 @@
+ launcher.getNavigationModeMismatchError(),
() -> launcher.getNavigationModeMismatchError() == null,
60000 /* b/148422894 */, launcher);
-
+ AbstractLauncherUiTest.checkDetectedLeaks();
return true;
}
- private static void setOverlayPackageEnabled(String overlayPackage, boolean enable)
- throws Exception {
- Log.d(TAG, "setOverlayPackageEnabled: " + overlayPackage + " " + enable);
- final String action = enable ? "enable" : "disable";
- UiDevice.getInstance(getInstrumentation()).executeShellCommand(
- "cmd overlay " + action + " " + overlayPackage);
- }
-
private static boolean packageExists(String packageName) {
try {
PackageManager pm = getInstrumentation().getContext().getPackageManager();
diff --git a/quickstep/tests/src/com/android/quickstep/TaplTestsQuickstep.java b/quickstep/tests/src/com/android/quickstep/TaplTestsQuickstep.java
index d2f5d8f..75fcfe2 100644
--- a/quickstep/tests/src/com/android/quickstep/TaplTestsQuickstep.java
+++ b/quickstep/tests/src/com/android/quickstep/TaplTestsQuickstep.java
@@ -17,15 +17,12 @@
package com.android.quickstep;
import static com.android.launcher3.ui.TaplTestsLauncher3.getAppPackageName;
-import static com.android.launcher3.util.rule.TestStabilityRule.LOCAL;
-import static com.android.launcher3.util.rule.TestStabilityRule.UNBUNDLED_POSTSUBMIT;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import android.content.Intent;
-import android.os.RemoteException;
import androidx.test.filters.LargeTest;
import androidx.test.runner.AndroidJUnit4;
@@ -42,34 +39,20 @@
import com.android.launcher3.tapl.OverviewTask;
import com.android.launcher3.tapl.TestHelpers;
import com.android.launcher3.ui.TaplTestsLauncher3;
-import com.android.launcher3.util.rule.TestStabilityRule;
import com.android.quickstep.NavigationModeSwitchRule.NavigationModeSwitch;
import com.android.quickstep.views.RecentsView;
-import org.junit.After;
import org.junit.Before;
-import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
@LargeTest
@RunWith(AndroidJUnit4.class)
public class TaplTestsQuickstep extends AbstractQuickStepTest {
- private int mLauncherPid;
-
@Before
public void setUp() throws Exception {
- mLauncherPid = 0;
super.setUp();
TaplTestsLauncher3.initialize(this);
- mLauncherPid = mLauncher.getPid();
- }
-
- @After
- public void teardown() {
- if (mLauncherPid != 0) {
- assertEquals("Launcher crashed, pid mismatch:", mLauncherPid, mLauncher.getPid());
- }
}
private void startTestApps() throws Exception {
@@ -84,17 +67,6 @@
}
@Test
- @PortraitLandscape
- @Ignore // Enable after b/131115533
- public void testPressRecentAppsLauncherAndGetOverview() throws RemoteException {
- mDevice.pressRecentApps();
- waitForState("Launcher internal state didn't switch to Overview",
- () -> LauncherState.OVERVIEW);
-
- assertNotNull("getOverview() returned null", mLauncher.getOverview());
- }
-
- @Test
@NavigationModeSwitch
@PortraitLandscape
public void testWorkspaceSwitchToAllApps() {
@@ -106,6 +78,10 @@
@Test
public void testAllAppsFromOverview() throws Exception {
+ if (!mLauncher.hasAllAppsInOverview()) {
+ return;
+ }
+
// Test opening all apps from Overview.
assertNotNull("switchToAllApps() returned null",
mLauncher.getWorkspace().switchToOverview().switchToAllApps());
@@ -166,8 +142,8 @@
launcher -> assertEquals("Dismissing a task didn't remove 1 task from Overview",
numTasks - 1, getTaskCount(launcher)));
- if (!TestHelpers.isInLauncherProcess() ||
- getFromLauncher(launcher -> !launcher.getDeviceProfile().isLandscape)) {
+ if (mLauncher.hasAllAppsInOverview() && (!TestHelpers.isInLauncherProcess()
+ || getFromLauncher(launcher -> !launcher.getDeviceProfile().isLandscape))) {
// Test switching to all apps and back.
final AllAppsFromOverview allApps = overview.switchToAllApps();
assertNotNull("overview.switchToAllApps() returned null (1)", allApps);
@@ -210,6 +186,10 @@
@Test
public void testAppIconLaunchFromAllAppsFromOverview() throws Exception {
+ if (!mLauncher.hasAllAppsInOverview()) {
+ return;
+ }
+
final AllApps allApps =
mLauncher.getWorkspace().switchToOverview().switchToAllApps();
assertTrue("Launcher internal state is not All Apps",
@@ -271,10 +251,6 @@
@Test
@NavigationModeSwitch
@PortraitLandscape
- // b/143285809 Remove @Stability on 02/21/20 if the test doesn't flake.
- @TestStabilityRule.Stability(flavors = LOCAL | UNBUNDLED_POSTSUBMIT)
- // b/143285809
- @Ignore
public void testQuickSwitchFromApp() throws Exception {
startTestActivity(2);
startTestActivity(3);
diff --git a/quickstep/tests/src/com/android/quickstep/ViewInflationDuringSwipeUp.java b/quickstep/tests/src/com/android/quickstep/ViewInflationDuringSwipeUp.java
index f8f22a1..8ecd88a 100644
--- a/quickstep/tests/src/com/android/quickstep/ViewInflationDuringSwipeUp.java
+++ b/quickstep/tests/src/com/android/quickstep/ViewInflationDuringSwipeUp.java
@@ -48,9 +48,9 @@
import androidx.test.uiautomator.UiDevice;
import androidx.test.uiautomator.Until;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherAppWidgetProviderInfo;
import com.android.launcher3.LauncherSettings;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
import com.android.launcher3.tapl.Background;
import com.android.launcher3.testcomponent.ListViewService;
import com.android.launcher3.testcomponent.ListViewService.SimpleViewsFactory;
diff --git a/iconloaderlib/res/values/dimens.xml b/res/drawable-v24/drag_handle_indicator_shadow.xml
similarity index 61%
copy from iconloaderlib/res/values/dimens.xml
copy to res/drawable-v24/drag_handle_indicator_shadow.xml
index e8c0c44..774bc38 100644
--- a/iconloaderlib/res/values/dimens.xml
+++ b/res/drawable-v24/drag_handle_indicator_shadow.xml
@@ -1,11 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2018 The Android Open Source Project
+<!-- 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
+ http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
@@ -13,7 +13,7 @@
See the License for the specific language governing permissions and
limitations under the License.
-->
-
-<resources>
- <dimen name="profile_badge_size">24dp</dimen>
-</resources>
+<com.android.launcher3.graphics.ShadowDrawable
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:src="@drawable/drag_handle_indicator_no_shadow"
+ android:elevation="@dimen/vertical_drag_handle_elevation" />
diff --git a/iconloaderlib/res/values/dimens.xml b/res/drawable-v24/ic_block_shadow.xml
similarity index 62%
copy from iconloaderlib/res/values/dimens.xml
copy to res/drawable-v24/ic_block_shadow.xml
index e8c0c44..045fe8d 100644
--- a/iconloaderlib/res/values/dimens.xml
+++ b/res/drawable-v24/ic_block_shadow.xml
@@ -1,11 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2018 The Android Open Source Project
+<!-- 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
+ http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
@@ -13,7 +13,7 @@
See the License for the specific language governing permissions and
limitations under the License.
-->
-
-<resources>
- <dimen name="profile_badge_size">24dp</dimen>
-</resources>
+<com.android.launcher3.graphics.ShadowDrawable
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:src="@drawable/ic_block_no_shadow"
+ android:elevation="@dimen/drop_target_shadow_elevation" />
diff --git a/quickstep/recents_ui_overrides/res/drawable/arrow_toast_rounded_background.xml b/res/drawable/arrow_toast_rounded_background.xml
similarity index 100%
rename from quickstep/recents_ui_overrides/res/drawable/arrow_toast_rounded_background.xml
rename to res/drawable/arrow_toast_rounded_background.xml
diff --git a/res/drawable/drag_handle_indicator.xml b/res/drawable/drag_handle_indicator.xml
deleted file mode 100644
index b01b84a..0000000
--- a/res/drawable/drag_handle_indicator.xml
+++ /dev/null
@@ -1,40 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 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.
--->
-
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
- android:width="@dimen/vertical_drag_handle_size"
- android:height="@dimen/vertical_drag_handle_size"
- android:viewportWidth="36.0"
- android:viewportHeight="36.0" >
-
- <group
- android:translateX="11.5"
- android:translateY="11.5">
- <path
- android:pathData="M2 8.5L6.5 4L11 8.5"
- android:strokeColor="?attr/workspaceAmbientShadowColor"
- android:strokeWidth="3.6"
- android:strokeLineCap="round"
- android:strokeLineJoin="round" />
-
- <path
- android:pathData="M2 8.5L6.5 4L11 8.5"
- android:strokeColor="?attr/workspaceTextColor"
- android:strokeWidth="1.8"
- android:strokeLineCap="round"
- android:strokeLineJoin="round" />
- </group>
-</vector>
diff --git a/res/drawable/drag_handle_indicator_no_shadow.xml b/res/drawable/drag_handle_indicator_no_shadow.xml
new file mode 100644
index 0000000..341e60c
--- /dev/null
+++ b/res/drawable/drag_handle_indicator_no_shadow.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
+
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="@dimen/vertical_drag_handle_width"
+ android:height="@dimen/vertical_drag_handle_height"
+ android:viewportWidth="18.0"
+ android:viewportHeight="6.0"
+ android:tint="?attr/workspaceTextColor" >
+
+ <path
+ android:pathData="M17,6c-0.15,0-0.3-0.03-0.45-0.11L9,2.12L1.45,5.89c-0.5,0.25-1.09,
+ 0.05-1.34-0.45S0.06,4.35,0.55,4.11l8-4c0.28-0.14,0.61-0.14,0.89,0l8,4c0.49,0.25,0.69,
+ 0.85,0.45,1.34C17.72,5.8,17.37,6,17,6z"
+ android:fillColor="@android:color/white" />
+</vector>
diff --git a/res/drawable/ic_block.xml b/res/drawable/ic_block_no_shadow.xml
similarity index 100%
rename from res/drawable/ic_block.xml
rename to res/drawable/ic_block_no_shadow.xml
diff --git a/quickstep/recents_ui_overrides/res/layout/arrow_toast.xml b/res/layout/arrow_toast.xml
similarity index 97%
rename from quickstep/recents_ui_overrides/res/layout/arrow_toast.xml
rename to res/layout/arrow_toast.xml
index b0f2b4b..087e45a 100644
--- a/quickstep/recents_ui_overrides/res/layout/arrow_toast.xml
+++ b/res/layout/arrow_toast.xml
@@ -34,6 +34,7 @@
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
+ android:gravity="center"
android:layout_gravity="center_vertical"
android:textColor="@android:color/white"
android:textSize="16sp"/>
@@ -49,7 +50,7 @@
android:src="@drawable/ic_remove_no_shadow"
android:tint="@android:color/white"
android:background="?android:attr/selectableItemBackgroundBorderless"
- android:contentDescription="@string/accessibility_close_task"/>
+ android:contentDescription="@string/accessibility_close"/>
</LinearLayout>
<View
diff --git a/res/layout/launcher.xml b/res/layout/launcher.xml
index cca899b..de13277 100644
--- a/res/layout/launcher.xml
+++ b/res/layout/launcher.xml
@@ -48,12 +48,16 @@
layout="@layout/overview_panel"
android:visibility="gone" />
+ <include
+ android:id="@+id/overview_actions_view"
+ layout="@layout/overview_actions_container" />
+
<!-- Keep these behind the workspace so that they are not visible when
we go into AllApps -->
<com.android.launcher3.pageindicators.WorkspacePageIndicator
android:id="@+id/page_indicator"
android:layout_width="match_parent"
- android:layout_height="@dimen/vertical_drag_handle_size"
+ android:layout_height="@dimen/workspace_page_indicator_height"
android:layout_gravity="bottom|center_horizontal"
android:theme="@style/HomeScreenElementTheme" />
diff --git a/iconloaderlib/res/values/dimens.xml b/res/layout/overview_actions_container.xml
similarity index 75%
copy from iconloaderlib/res/values/dimens.xml
copy to res/layout/overview_actions_container.xml
index e8c0c44..5946bf6 100644
--- a/iconloaderlib/res/values/dimens.xml
+++ b/res/layout/overview_actions_container.xml
@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2018 The Android Open Source Project
+<!--
+ 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.
@@ -13,7 +14,7 @@
See the License for the specific language governing permissions and
limitations under the License.
-->
-
-<resources>
- <dimen name="profile_badge_size">24dp</dimen>
-</resources>
+<Space
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="0dp"
+ android:layout_height="0dp" />
diff --git a/res/layout/overview_panel.xml b/res/layout/overview_panel.xml
index bdd5d23..2637f03 100644
--- a/res/layout/overview_panel.xml
+++ b/res/layout/overview_panel.xml
@@ -15,6 +15,6 @@
limitations under the License.
-->
<Space
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="0dp"
- android:layout_height="0dp" />
\ No newline at end of file
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="0dp"
+ android:layout_height="0dp" />
\ No newline at end of file
diff --git a/res/layout/search_container_all_apps.xml b/res/layout/search_container_all_apps.xml
index fd9cb60..e1646ba 100644
--- a/res/layout/search_container_all_apps.xml
+++ b/res/layout/search_container_all_apps.xml
@@ -34,5 +34,4 @@
android:singleLine="true"
android:textColor="?android:attr/textColorSecondary"
android:textColorHint="@drawable/all_apps_search_hint"
- android:textSize="16sp"
- android:translationY="24dp" />
\ No newline at end of file
+ android:textSize="16sp" />
\ No newline at end of file
diff --git a/res/layout/work_apps_paused.xml b/res/layout/work_apps_paused.xml
index 5607e78..08e1c98 100644
--- a/res/layout/work_apps_paused.xml
+++ b/res/layout/work_apps_paused.xml
@@ -15,22 +15,13 @@
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
- android:padding="8dp"
+ android:padding="48dp"
android:orientation="vertical"
- android:background="?attr/allAppsScrimColor"
android:gravity="center">
- <ImageView
- android:id="@+id/icon"
- android:contentDescription="@string/work_apps_paused_title"
- android:layout_width="48dp"
- android:layout_height="48dp"
- android:tint="?attr/folderTextColor"
- android:src="@drawable/ic_corp_off" />
-
<TextView
- style="@style/TextHeadline"
- android:textColor="?attr/folderTextColor"
+ style="@style/PrimaryHeadline"
+ android:textColor="?attr/workProfileOverlayTextColor"
android:id="@+id/work_apps_paused_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
@@ -38,12 +29,12 @@
android:layout_marginBottom="8dp"
android:text="@string/work_apps_paused_title"
android:textAlignment="center"
- android:textSize="24sp" />
+ android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:textColor="?attr/folderTextColor"
+ android:textColor="?attr/workProfileOverlayTextColor"
android:text="@string/work_apps_paused_body"
android:textAlignment="center"
android:textSize="16sp" />
diff --git a/res/layout/work_mode_switch.xml b/res/layout/work_mode_switch.xml
new file mode 100644
index 0000000..9cb7ce8
--- /dev/null
+++ b/res/layout/work_mode_switch.xml
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
+<com.android.launcher3.allapps.WorkModeSwitch
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ style="@style/PrimaryMediumText"
+ android:id="@+id/work_mode_toggle"
+ android:drawableStart="@drawable/ic_corp"
+ android:drawablePadding="16dp"
+ android:drawableTint="?attr/workProfileOverlayTextColor"
+ android:textColor="?attr/workProfileOverlayTextColor"
+ android:layout_alignParentBottom="true"
+ android:ellipsize="end"
+ android:gravity="start"
+ android:lines="1"
+ android:showText="false"
+ android:textSize="16sp"
+ android:background="?attr/allAppsScrimColor"
+ android:text="@string/work_profile_toggle_label"
+ android:paddingBottom="@dimen/all_apps_work_profile_tab_footer_padding"
+ android:paddingLeft="@dimen/all_apps_work_profile_tab_footer_padding"
+ android:paddingRight="@dimen/all_apps_work_profile_tab_footer_padding"
+ android:paddingTop="@dimen/all_apps_work_profile_tab_footer_padding"
+/>
diff --git a/res/layout/work_profile_edu.xml b/res/layout/work_profile_edu.xml
index f7a529d..5506b94 100644
--- a/res/layout/work_profile_edu.xml
+++ b/res/layout/work_profile_edu.xml
@@ -21,26 +21,27 @@
<View
android:layout_width="match_parent"
- android:backgroundTint="@color/bottom_panel_background"
android:layout_height="32dp"
- android:background="@drawable/bottom_sheet_top_border" />
+ android:background="@drawable/bottom_sheet_top_border"
+ android:backgroundTint="?android:attr/colorAccent" />
<LinearLayout
android:id="@+id/view_wrapper"
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:background="@color/bottom_panel_background"
+ android:background="?android:attr/colorAccent"
android:orientation="vertical"
android:paddingLeft="@dimen/bottom_sheet_edu_padding"
android:paddingRight="@dimen/bottom_sheet_edu_padding">
<TextView
- style="@style/TextHeadline"
android:id="@+id/content_text"
+ style="@style/TextHeadline"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="48dp"
android:layout_marginBottom="48dp"
+ android:gravity="center"
android:text="@string/work_profile_edu_personal_apps"
android:textAlignment="center"
android:textColor="@android:color/white"
@@ -57,5 +58,4 @@
android:textAlignment="center"
android:textColor="@android:color/white" />
</LinearLayout>
-
</com.android.launcher3.views.WorkEduView>
\ No newline at end of file
diff --git a/res/layout/work_tab_footer.xml b/res/layout/work_tab_footer.xml
deleted file mode 100644
index db95416..0000000
--- a/res/layout/work_tab_footer.xml
+++ /dev/null
@@ -1,47 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 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.
--->
-<com.android.launcher3.views.WorkFooterContainer
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/work_toggle_container"
- android:focusable="true"
- android:paddingBottom="@dimen/all_apps_work_profile_tab_footer_padding_vertical"
- android:orientation="horizontal"
- android:paddingLeft="@dimen/all_apps_work_profile_tab_footer_padding_horizontal"
- android:background="?attr/allAppsScrimColor"
- android:paddingRight="@dimen/all_apps_work_profile_tab_footer_padding_horizontal"
- android:paddingTop="@dimen/all_apps_work_profile_tab_footer_padding_vertical">
-
- <TextView
- android:id="@+id/work_mode_label"
- android:layout_width="0dp"
- android:layout_weight="1"
- android:drawableStart="@drawable/ic_corp"
- android:drawablePadding="3dp"
- android:layout_height="wrap_content"
- android:ellipsize="end"
- android:gravity="center_vertical"
- android:lines="1"
- android:minHeight="24dp"
- android:paddingEnd="12dp"
- android:textSize="16sp"/>
- <com.android.launcher3.allapps.WorkModeSwitch
- android:id="@+id/work_mode_toggle"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"/>
-
-</com.android.launcher3.views.WorkFooterContainer>
\ No newline at end of file
diff --git a/res/values/attrs.xml b/res/values/attrs.xml
index aef878b..5a15ec6 100644
--- a/res/values/attrs.xml
+++ b/res/values/attrs.xml
@@ -41,6 +41,7 @@
<attr name="folderIconBorderColor" format="color" />
<attr name="folderTextColor" format="color" />
<attr name="folderHintColor" format="color" />
+ <attr name="workProfileOverlayTextColor" format="color" />
<!-- BubbleTextView specific attributes. -->
<declare-styleable name="BubbleTextView">
diff --git a/res/values/colors.xml b/res/values/colors.xml
index 36f8468..194ef2c 100644
--- a/res/values/colors.xml
+++ b/res/values/colors.xml
@@ -45,5 +45,4 @@
<color name="back_gesture_tutorial_primary_color">#1A73E8</color> <!-- Blue -->
- <color name="bottom_panel_background">#f01A73E8</color>
</resources>
diff --git a/res/values/config.xml b/res/values/config.xml
index ef34dcd..0657b86 100644
--- a/res/values/config.xml
+++ b/res/values/config.xml
@@ -109,6 +109,7 @@
<item type="id" name="action_dismiss_notification" />
<item type="id" name="action_remote_action_shortcut" />
<item type="id" name="action_dismiss_prediction" />
+ <item type="id" name="action_pin_prediction"/>
<!-- QSB IDs. DO not change -->
<item type="id" name="search_container_workspace" />
@@ -117,6 +118,66 @@
<!-- Recents -->
<item type="id" name="overview_panel"/>
+ <!-- Whether to enable background preloading of task thumbnails. -->
+ <bool name="config_enableTaskSnapshotPreloading">true</bool>
+
<!-- Configuration resources -->
- <array name="dynamic_resources"> </array>
+ <item name="all_apps_spring_damping_ratio" type="dimen" format="float">0.75</item>
+ <item name="all_apps_spring_stiffness" type="dimen" format="float">600</item>
+
+ <item name="dismiss_task_trans_y_damping_ratio" type="dimen" format="float">0.5</item>
+ <item name="dismiss_task_trans_y_stiffness" type="dimen" format="float">1500</item>
+
+ <item name="dismiss_task_trans_x_damping_ratio" type="dimen" format="float">0.5</item>
+ <item name="dismiss_task_trans_x_stiffness" type="dimen" format="float">1500</item>
+
+ <item name="horizontal_spring_damping_ratio" type="dimen" format="float">0.8</item>
+ <item name="horizontal_spring_stiffness" type="dimen" format="float">400</item>
+
+ <item name="swipe_up_rect_scale_damping_ratio" type="dimen" format="float">0.75</item>
+ <item name="swipe_up_rect_scale_stiffness" type="dimen" format="float">200</item>
+
+ <item name="swipe_up_rect_xy_fling_friction" type="dimen" format="float">1.5</item>
+ <item name="swipe_up_rect_xy_damping_ratio" type="dimen" format="float">0.8</item>
+ <item name="swipe_up_rect_xy_stiffness" type="dimen" format="float">200</item>
+
+ <item name="staggered_damping_ratio" type="dimen" format="float">0.7</item>
+ <item name="staggered_stiffness" type="dimen" format="float">150</item>
+ <dimen name="unlock_staggered_velocity_dp_per_s">3dp</dimen>
+
+ <!-- Swipe up to home related -->
+ <dimen name="swipe_up_fling_min_visible_change">18dp</dimen>
+ <dimen name="swipe_up_y_overshoot">10dp</dimen>
+ <dimen name="swipe_up_max_workspace_trans_y">-60dp</dimen>
+
+ <array name="dynamic_resources">
+ <item>@dimen/all_apps_spring_damping_ratio</item>
+ <item>@dimen/all_apps_spring_stiffness</item>
+
+ <item>@dimen/dismiss_task_trans_y_damping_ratio</item>
+ <item>@dimen/dismiss_task_trans_y_stiffness</item>
+
+ <item>@dimen/dismiss_task_trans_x_damping_ratio</item>
+ <item>@dimen/dismiss_task_trans_x_stiffness</item>
+
+ <item>@dimen/horizontal_spring_damping_ratio</item>
+ <item>@dimen/horizontal_spring_stiffness</item>
+
+ <item>@dimen/swipe_up_rect_scale_damping_ratio</item>
+ <item>@dimen/swipe_up_rect_scale_stiffness</item>
+
+ <item>@dimen/swipe_up_rect_xy_fling_friction</item>
+ <item>@dimen/swipe_up_rect_xy_damping_ratio</item>
+ <item>@dimen/swipe_up_rect_xy_stiffness</item>
+
+ <item>@dimen/staggered_damping_ratio</item>
+ <item>@dimen/staggered_stiffness</item>
+ <item>@dimen/unlock_staggered_velocity_dp_per_s</item>
+
+ <item>@dimen/swipe_up_fling_min_visible_change</item>
+ <item>@dimen/swipe_up_y_overshoot</item>
+ </array>
+
+ <string-array name="live_wallpapers_remove_sysui_scrims">
+ </string-array>
</resources>
diff --git a/res/values/dimens.xml b/res/values/dimens.xml
index edae7f4..0b589a2 100644
--- a/res/values/dimens.xml
+++ b/res/values/dimens.xml
@@ -20,7 +20,6 @@
<!-- Dynamic Grid -->
<dimen name="dynamic_grid_edge_margin">8dp</dimen>
- <dimen name="dynamic_grid_page_indicator_line_height">1dp</dimen>
<dimen name="dynamic_grid_icon_drawable_padding">8dp</dimen>
<!-- Minimum space between workspace and hotseat in spring loaded mode -->
<dimen name="dynamic_grid_min_spring_loaded_space">8dp</dimen>
@@ -36,10 +35,18 @@
<dimen name="dynamic_grid_hotseat_extra_vertical_size">34dp</dimen>
<dimen name="dynamic_grid_hotseat_side_padding">0dp</dimen>
+ <!-- Workspace page indicator -->
+ <dimen name="workspace_page_indicator_height">24dp</dimen>
+ <dimen name="workspace_page_indicator_line_height">1dp</dimen>
+ <dimen name="workspace_page_indicator_overlap_workspace">0dp</dimen>
+
<!-- Hotseat/all-apps scrim -->
<dimen name="all_apps_scrim_blur">4dp</dimen>
- <dimen name="vertical_drag_handle_size">24dp</dimen>
- <dimen name="vertical_drag_handle_overlap_workspace">0dp</dimen>
+ <dimen name="vertical_drag_handle_width">18dp</dimen>
+ <dimen name="vertical_drag_handle_height">6dp</dimen>
+ <dimen name="vertical_drag_handle_elevation">1dp</dimen>
+ <dimen name="vertical_drag_handle_touch_size">48dp</dimen>
+ <dimen name="vertical_drag_handle_padding_in_vertical_bar_layout">16dp</dimen>
<!-- Drop target bar -->
<dimen name="dynamic_grid_drop_target_size">48dp</dimen>
@@ -85,8 +92,11 @@
<dimen name="all_apps_tabs_side_padding">12dp</dimen>
<dimen name="all_apps_divider_height">1dp</dimen>
- <dimen name="all_apps_work_profile_tab_footer_padding_vertical">20dp</dimen>
- <dimen name="all_apps_work_profile_tab_footer_padding_horizontal">24dp</dimen>
+ <dimen name="all_apps_tip_bottom_margin">8dp</dimen>
+ <!-- The size of corner radius of the arrow in the arrow toast. -->
+ <dimen name="arrow_toast_corner_radius">2dp</dimen>
+
+ <dimen name="all_apps_work_profile_tab_footer_padding">20dp</dimen>
<!-- Search bar in All Apps -->
<dimen name="all_apps_header_max_elevation">3dp</dimen>
diff --git a/res/values/drawables.xml b/res/values/drawables.xml
index 1367174..7d63142 100644
--- a/res/values/drawables.xml
+++ b/res/values/drawables.xml
@@ -17,4 +17,6 @@
<drawable name="ic_setup_shadow">@drawable/ic_setting</drawable>
<drawable name="ic_remove_shadow">@drawable/ic_remove_no_shadow</drawable>
<drawable name="ic_uninstall_shadow">@drawable/ic_uninstall_no_shadow</drawable>
+ <drawable name="ic_block_shadow">@drawable/ic_block_no_shadow</drawable>
+ <drawable name="all_apps_arrow_shadow">@drawable/drag_handle_indicator_no_shadow</drawable>
</resources>
\ No newline at end of file
diff --git a/res/values/strings.xml b/res/values/strings.xml
index bde3c31..a9ce24c 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -142,7 +142,7 @@
<string name="uninstall_system_app_text">This is a system app and can\'t be uninstalled.</string>
<!-- Default folder title -->
- <string name="folder_hint_text">Tap to edit</string>
+ <string name="folder_hint_text">Edit Name</string>
<!-- Accessibility -->
<!-- The format string for when an app is temporarily disabled. -->
@@ -208,7 +208,7 @@
<string name="notification_dots_service_title">Show notification dots</string>
<!-- Label for the setting that allows the automatic placement of launcher shortcuts for applications and games installed on the device [CHAR LIMIT=40] -->
- <string name="auto_add_shortcuts_label">Add icon to Home screen</string>
+ <string name="auto_add_shortcuts_label">Add app icons to Home screen</string>
<!-- Text description of the setting that allows the automatic placement of launcher shortcuts for applications and games installed on the device [CHAR LIMIT=NONE] -->
<string name="auto_add_shortcuts_description">For new apps</string>
@@ -316,6 +316,9 @@
<!-- Accessibility action to dismiss a notification in the shortcuts menu for an icon. [CHAR_LIMIT=30] -->
<string name="action_dismiss_notification">Dismiss</string>
+ <!-- Content description for arrow tip close button. [CHAR LIMIT=NONE] -->
+ <string name="accessibility_close">Close</string>
+
<!-- Accessibility confirmation for notification being dismissed. -->
<string name="notification_dismissed">Notification dismissed</string>
@@ -328,22 +331,25 @@
<!-- This string is in the work profile tab when a user has All Apps open on their phone. This is a label for a toggle to turn the work profile on and off. "Work profile" means a separate profile on a user's phone that's specifically for their work apps and managed by their company. "Work" is used as an adjective.-->
<string name="work_profile_toggle_label">Work profile</string>
<!--- User onboarding title for personal apps -->
- <string name="work_profile_edu_personal_apps">Personal apps are private & can\'t be seen by IT</string>
+ <string name="work_profile_edu_personal_apps">Personal data is separate & hidden from work apps</string>
<!--- User onboarding title for work profile apps -->
- <string name="work_profile_edu_work_apps">Work apps are badged and monitored by IT</string>
+ <string name="work_profile_edu_work_apps">Work apps & data are visible to your IT admin</string>
<!-- Action label to proceed to the next work profile edu section-->
<string name="work_profile_edu_next">Next</string>
<!-- Action label to finish work profile edu-->
<string name="work_profile_edu_accept">Got it</string>
- <!-- This string is in the work profile tab when a user has All Apps open on their phone. It describes the label of a toggle, "Work profile," as being managed by the user's employer.
- "Organization" is used to represent a variety of businesses, non-profits, and educational institutions).-->
- <string name="work_mode_on_label">Work apps: On</string>
- <!-- This string appears under a the label of a toggle in the work profile tab on a user's phone. It describes the status of the toggle, "Work profile," when it's turned off. "Work profile" means a separate profile on a user's phone that's speficially for their work apps and is managed by their company.-->
- <string name="work_mode_off_label">Work apps: Paused</string>
+ <!--- heading shown when user opens work apps tab while work apps are paused -->
+ <string name="work_apps_paused_title">Work profile is paused</string>
+ <!--- body shown when user opens work apps tab while work apps are paused -->
+ <string name="work_apps_paused_body">Work apps can\’t send you notifications, use your battery, or access your location</string>
+ <!-- content description for paused work apps list -->
+ <string name="work_apps_paused_content_description">Work profile is paused. Work apps can\’t send you notifications, use your battery, or access your location</string>
- <string name="work_apps_paused_title">Work apps are paused</string>
- <string name="work_apps_paused_body">You won\'t get any work notifications, and your IT admin can\'t see your location</string>
+
+
+ <!-- A tip shown pointing at work toggle -->
+ <string name="work_switch_tip">Pause work apps and notifications</string>
<!-- Failed action error message: e.g. Failed: Pause -->
<string name="remote_action_failed">Failed: <xliff:g id="what" example="Pause">%1$s</xliff:g></string>
diff --git a/res/values/styles.xml b/res/values/styles.xml
index 1174a2f..fcc651b 100644
--- a/res/values/styles.xml
+++ b/res/values/styles.xml
@@ -50,6 +50,7 @@
<item name="folderTextColor">#FF212121</item>
<item name="folderHintColor">#FF616161</item>
<item name="loadingIconColor">#CCFFFFFF</item>
+ <item name="workProfileOverlayTextColor">#FF212121</item>
<item name="android:windowTranslucentStatus">false</item>
<item name="android:windowTranslucentNavigation">false</item>
@@ -77,6 +78,7 @@
<item name="folderFillColor">#CDFFFFFF</item>
<item name="folderIconBorderColor">#FF80868B</item>
<item name="folderTextColor">?attr/workspaceTextColor</item>
+
</style>
<style name="LauncherTheme.Dark" parent="@style/LauncherTheme">
@@ -100,6 +102,7 @@
<item name="folderHintColor">#FFCCCCCC</item>
<item name="isMainColorDark">true</item>
<item name="loadingIconColor">#99FFFFFF</item>
+ <item name="workProfileOverlayTextColor">@android:color/white</item>
</style>
<style name="LauncherTheme.Dark.DarkMainColor" parent="@style/LauncherTheme.Dark">
@@ -222,6 +225,10 @@
<style name="DropTargetButton" parent="DropTargetButtonBase" />
<style name="TextHeadline" parent="@android:style/TextAppearance.DeviceDefault.DialogWindowTitle" />
+ <style name="PrimaryMediumText" parent="@android:style/TextAppearance.DeviceDefault.Medium"/>
+ <style name="PrimaryHeadline" parent="@android:style/TextAppearance.DeviceDefault.DialogWindowTitle">
+ <item name="android:textStyle">bold</item>
+ </style>
<style name="TextTitle" parent="@android:style/TextAppearance.DeviceDefault" />
diff --git a/robolectric_tests/Android.mk b/robolectric_tests/Android.mk
index 7c7e73c..bbc62e9 100644
--- a/robolectric_tests/Android.mk
+++ b/robolectric_tests/Android.mk
@@ -21,7 +21,7 @@
LOCAL_MODULE := LauncherRoboTests
LOCAL_MODULE_CLASS := JAVA_LIBRARIES
-LOCAL_SDK_VERSION := current
+LOCAL_SDK_VERSION := system_current
LOCAL_SRC_FILES := $(call all-java-files-under, src)
LOCAL_STATIC_JAVA_LIBRARIES := \
androidx.test.runner \
@@ -47,7 +47,7 @@
include $(CLEAR_VARS)
LOCAL_MODULE := RunLauncherRoboTests
-LOCAL_SDK_VERSION := current
+LOCAL_SDK_VERSION := system_current
LOCAL_JAVA_LIBRARIES := LauncherRoboTests
LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
diff --git a/robolectric_tests/config/robolectric.properties b/robolectric_tests/config/robolectric.properties
index 3d78689..0579400 100644
--- a/robolectric_tests/config/robolectric.properties
+++ b/robolectric_tests/config/robolectric.properties
@@ -1 +1,17 @@
sdk=29
+shadows= \
+ com.android.launcher3.shadows.LShadowAppPredictionManager \
+ com.android.launcher3.shadows.LShadowAppWidgetManager \
+ com.android.launcher3.shadows.LShadowBackupManager \
+ com.android.launcher3.shadows.LShadowBitmap \
+ com.android.launcher3.shadows.LShadowLauncherApps \
+ com.android.launcher3.shadows.LShadowTypeface \
+ com.android.launcher3.shadows.LShadowUserManager \
+ com.android.launcher3.shadows.LShadowWallpaperManager \
+ com.android.launcher3.shadows.ShadowDeviceFlag \
+ com.android.launcher3.shadows.ShadowLooperExecutor \
+ com.android.launcher3.shadows.ShadowMainThreadInitializedObject \
+ com.android.launcher3.shadows.ShadowOverrides \
+ com.android.launcher3.shadows.ShadowSyncRtSurfaceTransactionApplierCompat \
+
+application=com.android.launcher3.util.LauncherTestApplication
\ No newline at end of file
diff --git a/robolectric_tests/resources/cache_data_updated_task_data.txt b/robolectric_tests/resources/cache_data_updated_task_data.txt
index 302d58f..603dbe3 100644
--- a/robolectric_tests/resources/cache_data_updated_task_data.txt
+++ b/robolectric_tests/resources/cache_data_updated_task_data.txt
@@ -1,6 +1,6 @@
# Model data used by CacheDataUpdatedTaskTest
-classMap s com.android.launcher3.WorkspaceItemInfo
+classMap s com.android.launcher3.model.data.WorkspaceItemInfo
# Items for the BgDataModel
diff --git a/robolectric_tests/resources/package_install_state_change_task_data.txt b/robolectric_tests/resources/package_install_state_change_task_data.txt
index 4d63664..e82ea9d 100644
--- a/robolectric_tests/resources/package_install_state_change_task_data.txt
+++ b/robolectric_tests/resources/package_install_state_change_task_data.txt
@@ -1,7 +1,7 @@
# Model data used by PackageInstallStateChangeTaskTest
-classMap s com.android.launcher3.WorkspaceItemInfo
-classMap w com.android.launcher3.LauncherAppWidgetInfo
+classMap s com.android.launcher3.model.data.WorkspaceItemInfo
+classMap w com.android.launcher3.model.data.LauncherAppWidgetInfo
# Items for the BgDataModel
diff --git a/robolectric_tests/src/com/android/launcher3/folder/FolderNameProviderTest.java b/robolectric_tests/src/com/android/launcher3/folder/FolderNameProviderTest.java
index f769055..d927ffc 100644
--- a/robolectric_tests/src/com/android/launcher3/folder/FolderNameProviderTest.java
+++ b/robolectric_tests/src/com/android/launcher3/folder/FolderNameProviderTest.java
@@ -15,25 +15,25 @@
*/
package com.android.launcher3.folder;
-import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertEquals;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
+import android.os.UserHandle;
-import com.android.launcher3.AppInfo;
-import com.android.launcher3.WorkspaceItemInfo;
-import com.android.launcher3.shadows.LShadowUserManager;
-import com.android.launcher3.util.LauncherRoboTestRunner;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import java.util.ArrayList;
-@RunWith(LauncherRoboTestRunner.class)
+@RunWith(RobolectricTestRunner.class)
public final class FolderNameProviderTest {
private Context mContext;
private WorkspaceItemInfo mItem1;
@@ -45,13 +45,13 @@
mItem1 = new WorkspaceItemInfo(new AppInfo(
new ComponentName("a.b.c", "a.b.c/a.b.c.d"),
"title1",
- LShadowUserManager.newUserHandle(10),
+ UserHandle.of(10),
new Intent().setComponent(new ComponentName("a.b.c", "a.b.c/a.b.c.d"))
));
mItem2 = new WorkspaceItemInfo(new AppInfo(
new ComponentName("a.b.c", "a.b.c/a.b.c.d"),
"title2",
- LShadowUserManager.newUserHandle(10),
+ UserHandle.of(10),
new Intent().setComponent(new ComponentName("a.b.c", "a.b.c/a.b.c.d"))
));
}
@@ -61,15 +61,16 @@
ArrayList<WorkspaceItemInfo> list = new ArrayList<>();
list.add(mItem1);
list.add(mItem2);
- String[] suggestedNameOut = new String[FolderNameProvider.SUGGEST_MAX];
- new FolderNameProvider().getSuggestedFolderName(mContext, list, suggestedNameOut);
- assertTrue(suggestedNameOut[0].equals("Work"));
+ FolderNameInfo[] nameInfos =
+ new FolderNameInfo[FolderNameProvider.SUGGEST_MAX];
+ new FolderNameProvider().getSuggestedFolderName(mContext, list, nameInfos);
+ assertEquals("Work", nameInfos[0].getLabel());
- suggestedNameOut[0] = "candidate1";
- suggestedNameOut[1] = "candidate2";
- suggestedNameOut[2] = "candidate3";
- new FolderNameProvider().getSuggestedFolderName(mContext, list, suggestedNameOut);
- assertTrue(suggestedNameOut[3].equals("Work"));
+ nameInfos[0] = new FolderNameInfo("candidate1", 0.9);
+ nameInfos[1] = new FolderNameInfo("candidate2", 0.8);
+ nameInfos[2] = new FolderNameInfo("candidate3", 0.7);
+ new FolderNameProvider().getSuggestedFolderName(mContext, list, nameInfos);
+ assertEquals("Work", nameInfos[3].getLabel());
}
}
diff --git a/robolectric_tests/src/com/android/launcher3/logging/FileLogTest.java b/robolectric_tests/src/com/android/launcher3/logging/FileLogTest.java
index 48b5a45..c892618 100644
--- a/robolectric_tests/src/com/android/launcher3/logging/FileLogTest.java
+++ b/robolectric_tests/src/com/android/launcher3/logging/FileLogTest.java
@@ -3,12 +3,11 @@
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-import com.android.launcher3.util.LauncherRoboTestRunner;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.Shadows;
import org.robolectric.util.Scheduler;
@@ -21,7 +20,7 @@
/**
* Tests for {@link FileLog}
*/
-@RunWith(LauncherRoboTestRunner.class)
+@RunWith(RobolectricTestRunner.class)
public class FileLogTest {
private File mTempDir;
@@ -49,8 +48,9 @@
@After
public void tearDown() {
// Clear existing logs
- new File(mTempDir, "log-0").delete();
- new File(mTempDir, "log-1").delete();
+ for (int i = 0; i < FileLog.LOG_DAYS; i++) {
+ new File(mTempDir, "log-" + i).delete();
+ }
mTempDir.delete();
mTestActive = false;
@@ -89,8 +89,9 @@
Calendar threeDaysAgo = Calendar.getInstance();
threeDaysAgo.add(Calendar.HOUR, -72);
- new File(mTempDir, "log-0").setLastModified(threeDaysAgo.getTimeInMillis());
- new File(mTempDir, "log-1").setLastModified(threeDaysAgo.getTimeInMillis());
+ for (int i = 0; i < FileLog.LOG_DAYS; i++) {
+ new File(mTempDir, "log-" + i).setLastModified(threeDaysAgo.getTimeInMillis());
+ }
FileLog.print("Testing", "abracadabra", new Exception("cat! cat!"));
writer = new StringWriter();
diff --git a/robolectric_tests/src/com/android/launcher3/model/AddWorkspaceItemsTaskTest.java b/robolectric_tests/src/com/android/launcher3/model/AddWorkspaceItemsTaskTest.java
index b7f2243..8aa6f37 100644
--- a/robolectric_tests/src/com/android/launcher3/model/AddWorkspaceItemsTaskTest.java
+++ b/robolectric_tests/src/com/android/launcher3/model/AddWorkspaceItemsTaskTest.java
@@ -14,23 +14,23 @@
import android.util.Pair;
import com.android.launcher3.InvariantDeviceProfile;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.LauncherSettings.Favorites;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.model.BgDataModel.Callbacks;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.util.ContentWriter;
import com.android.launcher3.util.GridOccupancy;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.IntSparseArrayMap;
import com.android.launcher3.util.LauncherModelHelper;
-import com.android.launcher3.util.LauncherRoboTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
+import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.LooperMode;
import org.robolectric.annotation.LooperMode.Mode;
@@ -41,7 +41,7 @@
/**
* Tests for {@link AddWorkspaceItemsTask}
*/
-@RunWith(LauncherRoboTestRunner.class)
+@RunWith(RobolectricTestRunner.class)
@LooperMode(Mode.PAUSED)
public class AddWorkspaceItemsTaskTest {
diff --git a/robolectric_tests/src/com/android/launcher3/model/BackupRestoreTest.java b/robolectric_tests/src/com/android/launcher3/model/BackupRestoreTest.java
index 50f9494..90313ab 100644
--- a/robolectric_tests/src/com/android/launcher3/model/BackupRestoreTest.java
+++ b/robolectric_tests/src/com/android/launcher3/model/BackupRestoreTest.java
@@ -43,11 +43,11 @@
import com.android.launcher3.shadows.LShadowBackupManager;
import com.android.launcher3.shadows.LShadowUserManager;
import com.android.launcher3.util.LauncherModelHelper;
-import com.android.launcher3.util.LauncherRoboTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.LooperMode;
import org.robolectric.shadow.api.Shadow;
@@ -55,7 +55,7 @@
/**
* Tests to verify backup and restore flow.
*/
-@RunWith(LauncherRoboTestRunner.class)
+@RunWith(RobolectricTestRunner.class)
@LooperMode(LooperMode.Mode.PAUSED)
public class BackupRestoreTest {
@@ -134,7 +134,7 @@
{ APP_ICON, SHORTCUT, SHORTCUT, NO__ICON},
}}, 2, OLD_WORK_PROFILE_ID);
// simulates the creation of backup upon restore
- new GridBackupTable(RuntimeEnvironment.application, mDb, mDb, mIdp.numHotseatIcons,
+ new GridBackupTable(RuntimeEnvironment.application, mDb, mIdp.numHotseatIcons,
mIdp.numColumns, mIdp.numRows).doBackup(
MY_OLD_PROFILE_ID, GridBackupTable.OPTION_REQUIRES_SANITIZATION);
// reset favorites table
diff --git a/robolectric_tests/src/com/android/launcher3/model/CacheDataUpdatedTaskTest.java b/robolectric_tests/src/com/android/launcher3/model/CacheDataUpdatedTaskTest.java
index f128e24..5610b0e 100644
--- a/robolectric_tests/src/com/android/launcher3/model/CacheDataUpdatedTaskTest.java
+++ b/robolectric_tests/src/com/android/launcher3/model/CacheDataUpdatedTaskTest.java
@@ -17,19 +17,19 @@
import androidx.annotation.NonNull;
-import com.android.launcher3.AppInfo;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppState;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.icons.BitmapInfo;
import com.android.launcher3.icons.IconCache;
import com.android.launcher3.icons.cache.CachingLogic;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.util.LauncherModelHelper;
-import com.android.launcher3.util.LauncherRoboTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.LooperMode;
import org.robolectric.annotation.LooperMode.Mode;
@@ -40,7 +40,7 @@
/**
* Tests for {@link CacheDataUpdatedTask}
*/
-@RunWith(LauncherRoboTestRunner.class)
+@RunWith(RobolectricTestRunner.class)
@LooperMode(Mode.PAUSED)
public class CacheDataUpdatedTaskTest {
diff --git a/robolectric_tests/src/com/android/launcher3/model/DbDowngradeHelperTest.java b/robolectric_tests/src/com/android/launcher3/model/DbDowngradeHelperTest.java
index 1442c55..b7340cf 100644
--- a/robolectric_tests/src/com/android/launcher3/model/DbDowngradeHelperTest.java
+++ b/robolectric_tests/src/com/android/launcher3/model/DbDowngradeHelperTest.java
@@ -36,11 +36,11 @@
import com.android.launcher3.LauncherProvider.DatabaseHelper;
import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.R;
-import com.android.launcher3.util.LauncherRoboTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import java.io.File;
@@ -48,7 +48,7 @@
/**
* Tests for {@link DbDowngradeHelper}
*/
-@RunWith(LauncherRoboTestRunner.class)
+@RunWith(RobolectricTestRunner.class)
public class DbDowngradeHelperTest {
private static final String SCHEMA_FILE = "test_schema.json";
diff --git a/robolectric_tests/src/com/android/launcher3/model/DefaultLayoutProviderTest.java b/robolectric_tests/src/com/android/launcher3/model/DefaultLayoutProviderTest.java
index f8ac010..7ca416d 100644
--- a/robolectric_tests/src/com/android/launcher3/model/DefaultLayoutProviderTest.java
+++ b/robolectric_tests/src/com/android/launcher3/model/DefaultLayoutProviderTest.java
@@ -28,30 +28,25 @@
import android.content.pm.PackageInstaller.SessionInfo;
import android.content.pm.PackageInstaller.SessionParams;
-import com.android.launcher3.FolderInfo;
-import com.android.launcher3.ItemInfo;
-import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.icons.BitmapInfo;
-import com.android.launcher3.model.BgDataModel.Callbacks;
-import com.android.launcher3.util.Executors;
+import com.android.launcher3.model.data.FolderInfo;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.util.LauncherLayoutBuilder;
import com.android.launcher3.util.LauncherModelHelper;
-import com.android.launcher3.util.LauncherRoboTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.LooperMode;
import org.robolectric.annotation.LooperMode.Mode;
-import java.util.ArrayList;
-
/**
* Tests for layout parser for remote layout
*/
-@RunWith(LauncherRoboTestRunner.class)
+@RunWith(RobolectricTestRunner.class)
@LooperMode(Mode.PAUSED)
public class DefaultLayoutProviderTest {
@@ -120,18 +115,6 @@
}
private void writeLayoutAndLoad(LauncherLayoutBuilder builder) throws Exception {
- mModelHelper.setupDefaultLayoutProvider(builder);
-
- LoaderResults results = new LoaderResults(
- LauncherAppState.getInstance(mTargetContext),
- mModelHelper.getBgDataModel(),
- mModelHelper.getAllAppsList(),
- new Callbacks[0]);
- LoaderTask task = new LoaderTask(
- LauncherAppState.getInstance(mTargetContext),
- mModelHelper.getAllAppsList(),
- mModelHelper.getBgDataModel(),
- results);
- Executors.MODEL_EXECUTOR.submit(() -> task.loadWorkspace(new ArrayList<>())).get();
+ mModelHelper.setupDefaultLayoutProvider(builder).loadModelSync();
}
}
diff --git a/robolectric_tests/src/com/android/launcher3/model/GridBackupTableTest.java b/robolectric_tests/src/com/android/launcher3/model/GridBackupTableTest.java
index 36fd96b..56ce215 100644
--- a/robolectric_tests/src/com/android/launcher3/model/GridBackupTableTest.java
+++ b/robolectric_tests/src/com/android/launcher3/model/GridBackupTableTest.java
@@ -23,17 +23,17 @@
import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.LauncherSettings.Settings;
import com.android.launcher3.util.LauncherModelHelper;
-import com.android.launcher3.util.LauncherRoboTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
/**
* Unit tests for {@link GridBackupTable}
*/
-@RunWith(LauncherRoboTestRunner.class)
+@RunWith(RobolectricTestRunner.class)
public class GridBackupTableTest {
private static final int BACKUP_ITEM_COUNT = 12;
@@ -63,7 +63,7 @@
@Test
public void backupTableCreated() {
- GridBackupTable backupTable = new GridBackupTable(mContext, mDb, mDb, 4, 4, 4);
+ GridBackupTable backupTable = new GridBackupTable(mContext, mDb, 4, 4, 4);
assertFalse(backupTable.backupOrRestoreAsNeeded());
Settings.call(mContext.getContentResolver(), Settings.METHOD_REFRESH_BACKUP_TABLE);
@@ -75,14 +75,14 @@
@Test
public void backupTableRestored() {
- assertFalse(new GridBackupTable(mContext, mDb, mDb, 4, 4, 4).backupOrRestoreAsNeeded());
+ assertFalse(new GridBackupTable(mContext, mDb, 4, 4, 4).backupOrRestoreAsNeeded());
Settings.call(mContext.getContentResolver(), Settings.METHOD_REFRESH_BACKUP_TABLE);
// Delete entries
mDb.delete(TABLE_NAME, null, null);
assertEquals(0, queryNumEntries(mDb, TABLE_NAME));
- GridBackupTable backupTable = new GridBackupTable(mContext, mDb, mDb, 3, 3, 3);
+ GridBackupTable backupTable = new GridBackupTable(mContext, mDb, 3, 3, 3);
assertTrue(backupTable.backupOrRestoreAsNeeded());
// Items have been restored
@@ -96,7 +96,7 @@
@Test
public void backupTableRemovedOnAdd() {
- assertFalse(new GridBackupTable(mContext, mDb, mDb, 4, 4, 4).backupOrRestoreAsNeeded());
+ assertFalse(new GridBackupTable(mContext, mDb, 4, 4, 4).backupOrRestoreAsNeeded());
Settings.call(mContext.getContentResolver(), Settings.METHOD_REFRESH_BACKUP_TABLE);
assertTrue(tableExists(mDb, BACKUP_TABLE_NAME));
@@ -107,7 +107,7 @@
@Test
public void backupTableRemovedOnDelete() {
- assertFalse(new GridBackupTable(mContext, mDb, mDb, 4, 4, 4).backupOrRestoreAsNeeded());
+ assertFalse(new GridBackupTable(mContext, mDb, 4, 4, 4).backupOrRestoreAsNeeded());
Settings.call(mContext.getContentResolver(), Settings.METHOD_REFRESH_BACKUP_TABLE);
assertTrue(tableExists(mDb, BACKUP_TABLE_NAME));
@@ -118,7 +118,7 @@
@Test
public void backupTableRetainedOnUpdate() {
- assertFalse(new GridBackupTable(mContext, mDb, mDb, 4, 4, 4).backupOrRestoreAsNeeded());
+ assertFalse(new GridBackupTable(mContext, mDb, 4, 4, 4).backupOrRestoreAsNeeded());
Settings.call(mContext.getContentResolver(), Settings.METHOD_REFRESH_BACKUP_TABLE);
assertTrue(tableExists(mDb, BACKUP_TABLE_NAME));
diff --git a/robolectric_tests/src/com/android/launcher3/model/GridSizeMigrationTaskTest.java b/robolectric_tests/src/com/android/launcher3/model/GridSizeMigrationTaskTest.java
index 1ed4bca..8e00dcb 100644
--- a/robolectric_tests/src/com/android/launcher3/model/GridSizeMigrationTaskTest.java
+++ b/robolectric_tests/src/com/android/launcher3/model/GridSizeMigrationTaskTest.java
@@ -20,11 +20,11 @@
import com.android.launcher3.model.GridSizeMigrationTask.MultiStepMigrationTask;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.LauncherModelHelper;
-import com.android.launcher3.util.LauncherRoboTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import java.util.HashSet;
@@ -33,7 +33,7 @@
/**
* Unit tests for {@link GridSizeMigrationTask}
*/
-@RunWith(LauncherRoboTestRunner.class)
+@RunWith(RobolectricTestRunner.class)
public class GridSizeMigrationTaskTest {
private LauncherModelHelper mModelHelper;
@@ -65,7 +65,7 @@
};
mIdp.numHotseatIcons = 3;
- new GridSizeMigrationTask(mContext, mDb, mValidPackages, 5, 3)
+ new GridSizeMigrationTask(mContext, mDb, mValidPackages, false, 5, 3)
.migrateHotseat();
// First item is dropped as it has the least weight.
verifyHotseat(hotseatItems[1], hotseatItems[3], hotseatItems[4]);
@@ -82,7 +82,7 @@
};
mIdp.numHotseatIcons = 3;
- new GridSizeMigrationTask(mContext, mDb, mValidPackages, 5, 3)
+ new GridSizeMigrationTask(mContext, mDb, mValidPackages, false, 5, 3)
.migrateHotseat();
// First item is dropped as it has the least weight.
verifyHotseat(hotseatItems[1], hotseatItems[3], hotseatItems[4]);
@@ -127,7 +127,7 @@
{ 5, 2, -1, 6},
}});
- new GridSizeMigrationTask(mContext, mDb, mValidPackages,
+ new GridSizeMigrationTask(mContext, mDb, mValidPackages, false,
new Point(4, 4), new Point(3, 3)).migrateWorkspace();
// Column 2 and row 2 got removed.
@@ -147,7 +147,7 @@
{ 5, 2, -1, 6},
}});
- new GridSizeMigrationTask(mContext, mDb, mValidPackages,
+ new GridSizeMigrationTask(mContext, mDb, mValidPackages, false,
new Point(4, 4), new Point(3, 3)).migrateWorkspace();
// Items in the second column get moved to new screen
@@ -172,7 +172,7 @@
{ 3, 1, -1, 4},
}});
- new GridSizeMigrationTask(mContext, mDb, mValidPackages,
+ new GridSizeMigrationTask(mContext, mDb, mValidPackages, false,
new Point(4, 4), new Point(3, 3)).migrateWorkspace();
// Items in the second column of the first screen should get placed on the 3rd
@@ -204,7 +204,7 @@
{ 5, 2, -1, 6},
}});
- new GridSizeMigrationTask(mContext, mDb, mValidPackages,
+ new GridSizeMigrationTask(mContext, mDb, mValidPackages, false,
new Point(4, 4), new Point(3, 3)).migrateWorkspace();
// Items in the second column of the first screen should get placed on a new screen.
@@ -235,7 +235,7 @@
{ 5, 2, 7, -1},
}}, 0);
- new GridSizeMigrationTask(mContext, mDb, mValidPackages,
+ new GridSizeMigrationTask(mContext, mDb, mValidPackages, false,
new Point(4, 4), new Point(3, 4)).migrateWorkspace();
// Items in the second column of the first screen should get placed on a new screen.
@@ -262,7 +262,7 @@
{ 5, 6, 7, -1},
}}, 0);
- new GridSizeMigrationTask(mContext, mDb, mValidPackages,
+ new GridSizeMigrationTask(mContext, mDb, mValidPackages, false,
new Point(4, 4), new Point(3, 3)).migrateWorkspace();
// Items in the second column of the first screen should get placed on a new screen.
@@ -282,7 +282,7 @@
* represent the workspace grid.
*/
private void verifyWorkspace(int[][][] ids) {
- IntArray allScreens = getWorkspaceScreenIds(mDb);
+ IntArray allScreens = getWorkspaceScreenIds(mDb, LauncherSettings.Favorites.TABLE_NAME);
assertEquals(ids.length, allScreens.size());
int total = 0;
@@ -351,7 +351,7 @@
private final LinkedList<Point> mPoints;
public MultiStepMigrationTaskVerifier(int... points) {
- super(null, null, null);
+ super(null, null, null, false);
mPoints = new LinkedList<>();
for (int i = 0; i < points.length; i += 2) {
diff --git a/robolectric_tests/src/com/android/launcher3/model/GridSizeMigrationTaskV2Test.java b/robolectric_tests/src/com/android/launcher3/model/GridSizeMigrationTaskV2Test.java
new file mode 100644
index 0000000..59c9480
--- /dev/null
+++ b/robolectric_tests/src/com/android/launcher3/model/GridSizeMigrationTaskV2Test.java
@@ -0,0 +1,155 @@
+/*
+ * 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.launcher3.model;
+
+import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_DESKTOP;
+import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_HOTSEAT;
+import static com.android.launcher3.LauncherSettings.Favorites.TMP_CONTENT_URI;
+import static com.android.launcher3.provider.LauncherDbUtils.dropTable;
+import static com.android.launcher3.util.LauncherModelHelper.APP_ICON;
+import static com.android.launcher3.util.LauncherModelHelper.DESKTOP;
+import static com.android.launcher3.util.LauncherModelHelper.HOTSEAT;
+import static com.android.launcher3.util.LauncherModelHelper.SHORTCUT;
+import static com.android.launcher3.util.LauncherModelHelper.TEST_PACKAGE;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import android.content.Context;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteDatabase;
+import android.graphics.Point;
+import android.os.Process;
+
+import com.android.launcher3.InvariantDeviceProfile;
+import com.android.launcher3.LauncherSettings;
+import com.android.launcher3.pm.UserCache;
+import com.android.launcher3.util.LauncherModelHelper;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
+import org.robolectric.RuntimeEnvironment;
+
+import java.util.HashSet;
+
+/** Unit tests for {@link GridSizeMigrationTaskV2} */
+@RunWith(RobolectricTestRunner.class)
+public class GridSizeMigrationTaskV2Test {
+
+ private LauncherModelHelper mModelHelper;
+ private Context mContext;
+ private SQLiteDatabase mDb;
+
+ private HashSet<String> mValidPackages;
+ private InvariantDeviceProfile mIdp;
+
+ @Before
+ public void setUp() {
+ mModelHelper = new LauncherModelHelper();
+ mContext = RuntimeEnvironment.application;
+ mDb = mModelHelper.provider.getDb();
+
+ mValidPackages = new HashSet<>();
+ mValidPackages.add(TEST_PACKAGE);
+ mIdp = InvariantDeviceProfile.INSTANCE.get(mContext);
+
+ long userSerial = UserCache.INSTANCE.get(mContext).getSerialNumberForUser(
+ Process.myUserHandle());
+ dropTable(mDb, LauncherSettings.Favorites.TMP_TABLE);
+ LauncherSettings.Favorites.addTableToDb(mDb, userSerial, false,
+ LauncherSettings.Favorites.TMP_TABLE);
+ }
+
+ @Test
+ public void testMigration() {
+ final String testPackage1 = "com.android.launcher3.validpackage1";
+ final String testPackage2 = "com.android.launcher3.validpackage2";
+ final String testPackage3 = "com.android.launcher3.validpackage3";
+ final String testPackage4 = "com.android.launcher3.validpackage4";
+ final String testPackage5 = "com.android.launcher3.validpackage5";
+ final String testPackage7 = "com.android.launcher3.validpackage7";
+
+ mValidPackages.add(testPackage1);
+ mValidPackages.add(testPackage2);
+ mValidPackages.add(testPackage3);
+ mValidPackages.add(testPackage4);
+ mValidPackages.add(testPackage5);
+ mValidPackages.add(testPackage7);
+
+ int[] srcHotseatItems = {
+ mModelHelper.addItem(APP_ICON, 0, HOTSEAT, 0, 0, testPackage1, 1, TMP_CONTENT_URI),
+ mModelHelper.addItem(SHORTCUT, 1, HOTSEAT, 0, 0, testPackage2, 2, TMP_CONTENT_URI),
+ -1,
+ mModelHelper.addItem(SHORTCUT, 3, HOTSEAT, 0, 0, testPackage3, 3, TMP_CONTENT_URI),
+ mModelHelper.addItem(APP_ICON, 4, HOTSEAT, 0, 0, testPackage4, 4, TMP_CONTENT_URI),
+ };
+ mModelHelper.addItem(APP_ICON, 0, DESKTOP, 2, 2, testPackage5, 5, TMP_CONTENT_URI);
+
+ int[] destHotseatItems = {
+ -1,
+ mModelHelper.addItem(SHORTCUT, 1, HOTSEAT, 0, 0, testPackage2),
+ -1,
+ };
+ mModelHelper.addItem(APP_ICON, 0, DESKTOP, 2, 2, testPackage7);
+
+ mIdp.numHotseatIcons = 3;
+ mIdp.numColumns = 3;
+ mIdp.numRows = 3;
+ GridSizeMigrationTaskV2.DbReader srcReader = new GridSizeMigrationTaskV2.DbReader(mDb,
+ LauncherSettings.Favorites.TMP_TABLE, mContext, mValidPackages, 5);
+ GridSizeMigrationTaskV2.DbReader destReader = new GridSizeMigrationTaskV2.DbReader(mDb,
+ LauncherSettings.Favorites.TABLE_NAME, mContext, mValidPackages, 3);
+ GridSizeMigrationTaskV2 task = new GridSizeMigrationTaskV2(mContext, mDb, srcReader,
+ destReader, 3, new Point(mIdp.numColumns, mIdp.numRows));
+ task.migrate();
+
+ Cursor c = mContext.getContentResolver().query(LauncherSettings.Favorites.CONTENT_URI,
+ new String[]{LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.INTENT},
+ "container=" + CONTAINER_HOTSEAT, null, null, null);
+ assertEquals(c.getCount(), 3);
+ int screenIndex = c.getColumnIndex(LauncherSettings.Favorites.SCREEN);
+ int intentIndex = c.getColumnIndex(LauncherSettings.Favorites.INTENT);
+ c.moveToNext();
+ assertEquals(c.getInt(screenIndex), 1);
+ assertTrue(c.getString(intentIndex).contains(testPackage2));
+ c.moveToNext();
+ assertEquals(c.getInt(screenIndex), 0);
+ assertTrue(c.getString(intentIndex).contains(testPackage1));
+ c.moveToNext();
+ assertEquals(c.getInt(screenIndex), 2);
+ assertTrue(c.getString(intentIndex).contains(testPackage3));
+ c.close();
+
+ c = mContext.getContentResolver().query(LauncherSettings.Favorites.CONTENT_URI,
+ new String[]{LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
+ LauncherSettings.Favorites.INTENT},
+ "container=" + CONTAINER_DESKTOP, null, null, null);
+ assertEquals(c.getCount(), 2);
+ intentIndex = c.getColumnIndex(LauncherSettings.Favorites.INTENT);
+ int cellXIndex = c.getColumnIndex(LauncherSettings.Favorites.CELLX);
+ int cellYIndex = c.getColumnIndex(LauncherSettings.Favorites.CELLY);
+
+ c.moveToNext();
+ assertTrue(c.getString(intentIndex).contains(testPackage7));
+ c.moveToNext();
+ assertTrue(c.getString(intentIndex).contains(testPackage5));
+ assertEquals(c.getInt(cellXIndex), 0);
+ assertEquals(c.getInt(cellYIndex), 2);
+ }
+}
diff --git a/robolectric_tests/src/com/android/launcher3/model/LoaderCursorTest.java b/robolectric_tests/src/com/android/launcher3/model/LoaderCursorTest.java
index 7fa3ee9..2584f65 100644
--- a/robolectric_tests/src/com/android/launcher3/model/LoaderCursorTest.java
+++ b/robolectric_tests/src/com/android/launcher3/model/LoaderCursorTest.java
@@ -50,16 +50,17 @@
import android.os.Process;
import com.android.launcher3.InvariantDeviceProfile;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppState;
-import com.android.launcher3.WorkspaceItemInfo;
+import com.android.launcher3.LauncherSettings;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.util.Executors;
-import com.android.launcher3.util.LauncherRoboTestRunner;
import com.android.launcher3.util.PackageManagerHelper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.LooperMode;
import org.robolectric.annotation.LooperMode.Mode;
@@ -67,7 +68,7 @@
/**
* Tests for {@link LoaderCursor}
*/
-@RunWith(LauncherRoboTestRunner.class)
+@RunWith(RobolectricTestRunner.class)
@LooperMode(Mode.PAUSED)
public class LoaderCursorTest {
@@ -91,7 +92,7 @@
SCREEN, CELLX, CELLY, RESTORED, INTENT
});
- mLoaderCursor = new LoaderCursor(mCursor, mApp);
+ mLoaderCursor = new LoaderCursor(mCursor, LauncherSettings.Favorites.CONTENT_URI, mApp);
mLoaderCursor.allUsers.put(0, Process.myUserHandle());
}
@@ -126,7 +127,7 @@
new Intent().setComponent(cn), false /* allowMissingTarget */, true))
.get();
assertNotNull(info);
- assertTrue(PackageManagerHelper.isLauncherAppTarget(info.intent));
+ assertTrue(PackageManagerHelper.isLauncherAppTarget(info.getIntent()));
}
@Test
@@ -140,7 +141,7 @@
new Intent().setComponent(cn), true /* allowMissingTarget */, true))
.get();
assertNotNull(info);
- assertTrue(PackageManagerHelper.isLauncherAppTarget(info.intent));
+ assertTrue(PackageManagerHelper.isLauncherAppTarget(info.getIntent()));
}
@Test
diff --git a/robolectric_tests/src/com/android/launcher3/model/ModelMultiCallbacksTest.java b/robolectric_tests/src/com/android/launcher3/model/ModelMultiCallbacksTest.java
index c7979b2..4b0ae7e 100644
--- a/robolectric_tests/src/com/android/launcher3/model/ModelMultiCallbacksTest.java
+++ b/robolectric_tests/src/com/android/launcher3/model/ModelMultiCallbacksTest.java
@@ -26,20 +26,20 @@
import android.os.Process;
-import com.android.launcher3.AppInfo;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.PagedView;
import com.android.launcher3.model.BgDataModel.Callbacks;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.util.Executors;
import com.android.launcher3.util.LauncherLayoutBuilder;
import com.android.launcher3.util.LauncherModelHelper;
-import com.android.launcher3.util.LauncherRoboTestRunner;
import com.android.launcher3.util.LooperExecutor;
import com.android.launcher3.util.ViewOnDrawExecutor;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.LooperMode;
import org.robolectric.annotation.LooperMode.Mode;
@@ -55,7 +55,7 @@
/**
* Tests to verify multiple callbacks in Loader
*/
-@RunWith(LauncherRoboTestRunner.class)
+@RunWith(RobolectricTestRunner.class)
@LooperMode(Mode.PAUSED)
public class ModelMultiCallbacksTest {
diff --git a/robolectric_tests/src/com/android/launcher3/model/PackageInstallStateChangedTaskTest.java b/robolectric_tests/src/com/android/launcher3/model/PackageInstallStateChangedTaskTest.java
index bd71f01..e43df21 100644
--- a/robolectric_tests/src/com/android/launcher3/model/PackageInstallStateChangedTaskTest.java
+++ b/robolectric_tests/src/com/android/launcher3/model/PackageInstallStateChangedTaskTest.java
@@ -2,16 +2,16 @@
import static org.junit.Assert.assertEquals;
-import com.android.launcher3.ItemInfo;
-import com.android.launcher3.LauncherAppWidgetInfo;
-import com.android.launcher3.WorkspaceItemInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.pm.PackageInstallInfo;
import com.android.launcher3.util.LauncherModelHelper;
-import com.android.launcher3.util.LauncherRoboTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.LooperMode;
import org.robolectric.annotation.LooperMode.Mode;
@@ -21,7 +21,7 @@
/**
* Tests for {@link PackageInstallStateChangedTask}
*/
-@RunWith(LauncherRoboTestRunner.class)
+@RunWith(RobolectricTestRunner.class)
@LooperMode(Mode.PAUSED)
public class PackageInstallStateChangedTaskTest {
diff --git a/robolectric_tests/src/com/android/launcher3/popup/PopupPopulatorTest.java b/robolectric_tests/src/com/android/launcher3/popup/PopupPopulatorTest.java
index 7612ae1..83bf7da 100644
--- a/robolectric_tests/src/com/android/launcher3/popup/PopupPopulatorTest.java
+++ b/robolectric_tests/src/com/android/launcher3/popup/PopupPopulatorTest.java
@@ -27,10 +27,9 @@
import android.content.pm.ShortcutInfo;
-import com.android.launcher3.util.LauncherRoboTestRunner;
-
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import java.util.ArrayList;
@@ -40,7 +39,7 @@
/**
* Tests the sorting and filtering of shortcuts in {@link PopupPopulator}.
*/
-@RunWith(LauncherRoboTestRunner.class)
+@RunWith(RobolectricTestRunner.class)
public class PopupPopulatorTest {
@Test
diff --git a/robolectric_tests/src/com/android/launcher3/provider/RestoreDbTaskTest.java b/robolectric_tests/src/com/android/launcher3/provider/RestoreDbTaskTest.java
index 7ef670c..58174c7 100644
--- a/robolectric_tests/src/com/android/launcher3/provider/RestoreDbTaskTest.java
+++ b/robolectric_tests/src/com/android/launcher3/provider/RestoreDbTaskTest.java
@@ -23,16 +23,16 @@
import com.android.launcher3.LauncherProvider.DatabaseHelper;
import com.android.launcher3.LauncherSettings.Favorites;
-import com.android.launcher3.util.LauncherRoboTestRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
/**
* Tests for {@link RestoreDbTask}
*/
-@RunWith(LauncherRoboTestRunner.class)
+@RunWith(RobolectricTestRunner.class)
public class RestoreDbTaskTest {
@Test
diff --git a/robolectric_tests/src/com/android/launcher3/shadows/LShadowAppPredictionManager.java b/robolectric_tests/src/com/android/launcher3/shadows/LShadowAppPredictionManager.java
new file mode 100644
index 0000000..ae051f7
--- /dev/null
+++ b/robolectric_tests/src/com/android/launcher3/shadows/LShadowAppPredictionManager.java
@@ -0,0 +1,38 @@
+/*
+ * 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.launcher3.shadows;
+
+import static org.mockito.Mockito.mock;
+
+import android.app.prediction.AppPredictionContext;
+import android.app.prediction.AppPredictionManager;
+import android.app.prediction.AppPredictor;
+
+import org.robolectric.annotation.Implementation;
+import org.robolectric.annotation.Implements;
+
+/**
+ * Shadow for {@link AppPredictionManager} which create mock predictors
+ */
+@Implements(value = AppPredictionManager.class)
+public class LShadowAppPredictionManager {
+
+ @Implementation
+ public AppPredictor createAppPredictionSession(AppPredictionContext predictionContext) {
+ return mock(AppPredictor.class);
+ }
+}
diff --git a/robolectric_tests/src/com/android/launcher3/shadows/LShadowLauncherApps.java b/robolectric_tests/src/com/android/launcher3/shadows/LShadowLauncherApps.java
index f16ed33..76cb747 100644
--- a/robolectric_tests/src/com/android/launcher3/shadows/LShadowLauncherApps.java
+++ b/robolectric_tests/src/com/android/launcher3/shadows/LShadowLauncherApps.java
@@ -127,6 +127,10 @@
@Override
protected List<LauncherActivityInfo> getShortcutConfigActivityList(String packageName,
UserHandle user) {
- return Collections.emptyList();
+ Intent intent = new Intent(Intent.ACTION_CREATE_SHORTCUT).setPackage(packageName);
+ return RuntimeEnvironment.application.getPackageManager().queryIntentActivities(intent, 0)
+ .stream()
+ .map(ri -> getLauncherActivityInfo(ri.activityInfo))
+ .collect(Collectors.toList());
}
}
diff --git a/robolectric_tests/src/com/android/launcher3/shadows/LShadowTypeface.java b/robolectric_tests/src/com/android/launcher3/shadows/LShadowTypeface.java
new file mode 100644
index 0000000..0e7c1de
--- /dev/null
+++ b/robolectric_tests/src/com/android/launcher3/shadows/LShadowTypeface.java
@@ -0,0 +1,38 @@
+/*
+ * 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.launcher3.shadows;
+
+import android.graphics.Typeface;
+
+import org.robolectric.annotation.Implementation;
+import org.robolectric.annotation.Implements;
+import org.robolectric.shadows.ShadowTypeface;
+
+/**
+ * Extension of {@link ShadowTypeface} with missing shadow methods
+ */
+@Implements(Typeface.class)
+public class LShadowTypeface extends ShadowTypeface {
+
+ @Implementation
+ public static Typeface create(Typeface family, int weight, boolean italic) {
+ int style = italic ? Typeface.ITALIC : Typeface.NORMAL;
+ if (weight >= 400) {
+ style |= Typeface.BOLD;
+ }
+ return create(family, style);
+ }
+}
diff --git a/robolectric_tests/src/com/android/launcher3/shadows/LShadowUserManager.java b/robolectric_tests/src/com/android/launcher3/shadows/LShadowUserManager.java
index 576ddbd..edf8edb 100644
--- a/robolectric_tests/src/com/android/launcher3/shadows/LShadowUserManager.java
+++ b/robolectric_tests/src/com/android/launcher3/shadows/LShadowUserManager.java
@@ -16,7 +16,6 @@
package com.android.launcher3.shadows;
-import android.os.Parcel;
import android.os.UserHandle;
import android.os.UserManager;
import android.util.SparseBooleanArray;
@@ -51,12 +50,4 @@
public void setUserLocked(UserHandle userHandle, boolean enabled) {
mLockedUsers.put(userHandle.hashCode(), enabled);
}
-
- // Create user handle from parcel since UserHandle.of() was only added in later APIs.
- public static UserHandle newUserHandle(int uid) {
- Parcel userParcel = Parcel.obtain();
- userParcel.writeInt(uid);
- userParcel.setDataPosition(0);
- return new UserHandle(userParcel);
- }
}
diff --git a/robolectric_tests/src/com/android/launcher3/shadows/LShadowWallpaperManager.java b/robolectric_tests/src/com/android/launcher3/shadows/LShadowWallpaperManager.java
new file mode 100644
index 0000000..d60251c
--- /dev/null
+++ b/robolectric_tests/src/com/android/launcher3/shadows/LShadowWallpaperManager.java
@@ -0,0 +1,56 @@
+/*
+ * 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.launcher3.shadows;
+
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+
+import android.app.WallpaperManager;
+import android.content.Context;
+
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.Shadows;
+import org.robolectric.annotation.Implementation;
+import org.robolectric.annotation.Implements;
+import org.robolectric.shadows.ShadowApplication;
+import org.robolectric.shadows.ShadowUserManager;
+import org.robolectric.shadows.ShadowWallpaperManager;
+
+/**
+ * Extension of {@link ShadowUserManager} with missing shadow methods
+ */
+@Implements(WallpaperManager.class)
+public class LShadowWallpaperManager extends ShadowWallpaperManager {
+
+ @Implementation
+ protected static WallpaperManager getInstance(Context context) {
+ return context.getSystemService(WallpaperManager.class);
+ }
+
+ /**
+ * Remove this once the fix for
+ * https://github.com/robolectric/robolectric/issues/5285
+ * is available
+ */
+ public static void initializeMock() {
+ WallpaperManager wm = mock(WallpaperManager.class);
+ ShadowApplication shadowApplication = Shadows.shadowOf(RuntimeEnvironment.application);
+ shadowApplication.setSystemService(Context.WALLPAPER_SERVICE, wm);
+ doReturn(0).when(wm).getDesiredMinimumWidth();
+ doReturn(0).when(wm).getDesiredMinimumHeight();
+ }
+}
diff --git a/robolectric_tests/src/com/android/launcher3/shadows/ShadowOverrides.java b/robolectric_tests/src/com/android/launcher3/shadows/ShadowOverrides.java
new file mode 100644
index 0000000..131f691
--- /dev/null
+++ b/robolectric_tests/src/com/android/launcher3/shadows/ShadowOverrides.java
@@ -0,0 +1,61 @@
+/*
+ * 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.launcher3.shadows;
+
+import android.content.Context;
+
+import com.android.launcher3.util.MainThreadInitializedObject.ObjectProvider;
+import com.android.launcher3.util.ResourceBasedOverride;
+import com.android.launcher3.util.ResourceBasedOverride.Overrides;
+
+import org.robolectric.annotation.Implementation;
+import org.robolectric.annotation.Implements;
+import org.robolectric.shadow.api.Shadow;
+import org.robolectric.util.ReflectionHelpers.ClassParameter;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Shadow for {@link Overrides} to provide custom overrides for test
+ */
+@Implements(value = Overrides.class, isInAndroidSdk = false)
+public class ShadowOverrides {
+
+ private static Map<Class, ObjectProvider> sProviderMap = new HashMap<>();
+
+ @Implementation
+ public static <T extends ResourceBasedOverride> T getObject(
+ Class<T> clazz, Context context, int resId) {
+ ObjectProvider<T> provider = sProviderMap.get(clazz);
+ if (provider != null) {
+ return provider.get(context);
+ }
+ return Shadow.directlyOn(Overrides.class, "getObject",
+ ClassParameter.from(Class.class, clazz),
+ ClassParameter.from(Context.class, context),
+ ClassParameter.from(int.class, resId));
+ }
+
+ public static <T> void setProvider(Class<T> clazz, ObjectProvider<T> provider) {
+ sProviderMap.put(clazz, provider);
+ }
+
+ public static void clearProvider() {
+ sProviderMap.clear();
+ }
+}
diff --git a/robolectric_tests/src/com/android/launcher3/shadows/ShadowSyncRtSurfaceTransactionApplierCompat.java b/robolectric_tests/src/com/android/launcher3/shadows/ShadowSyncRtSurfaceTransactionApplierCompat.java
new file mode 100644
index 0000000..238926c
--- /dev/null
+++ b/robolectric_tests/src/com/android/launcher3/shadows/ShadowSyncRtSurfaceTransactionApplierCompat.java
@@ -0,0 +1,42 @@
+/*
+ * 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.launcher3.shadows;
+
+import static org.robolectric.shadow.api.Shadow.invokeConstructor;
+import static org.robolectric.util.ReflectionHelpers.ClassParameter.from;
+
+import android.view.View;
+
+import org.robolectric.annotation.Implementation;
+import org.robolectric.annotation.Implements;
+import org.robolectric.annotation.RealObject;
+
+/**
+ * Shadow for SyncRtSurfaceTransactionApplierCompat to override default functionality
+ */
+@Implements(className = "com.android.systemui.shared.system.SyncRtSurfaceTransactionApplierCompat",
+ isInAndroidSdk = false)
+public class ShadowSyncRtSurfaceTransactionApplierCompat {
+
+ @RealObject
+ private Object mRealObject;
+
+ @Implementation
+ protected void __constructor__(View view) {
+ invokeConstructor(mRealObject.getClass(), mRealObject, from(View.class, null));
+ }
+}
diff --git a/robolectric_tests/src/com/android/launcher3/ui/LauncherUIScrollTest.java b/robolectric_tests/src/com/android/launcher3/ui/LauncherUIScrollTest.java
new file mode 100644
index 0000000..d330d10
--- /dev/null
+++ b/robolectric_tests/src/com/android/launcher3/ui/LauncherUIScrollTest.java
@@ -0,0 +1,185 @@
+/*
+ * 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.launcher3.ui;
+
+import static com.android.launcher3.util.LauncherModelHelper.TEST_PACKAGE;
+import static com.android.launcher3.util.LauncherUIHelper.buildAndBindLauncher;
+import static com.android.launcher3.util.LauncherUIHelper.doLayout;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.mockito.Mockito.mock;
+
+import android.content.Context;
+import android.os.SystemClock;
+import android.provider.Settings;
+import android.view.InputDevice;
+import android.view.MotionEvent;
+import android.view.MotionEvent.PointerProperties;
+
+import com.android.launcher3.DeviceProfile;
+import com.android.launcher3.InvariantDeviceProfile;
+import com.android.launcher3.Launcher;
+import com.android.launcher3.LauncherState;
+import com.android.launcher3.folder.Folder;
+import com.android.launcher3.folder.FolderIcon;
+import com.android.launcher3.folder.FolderPagedView;
+import com.android.launcher3.logging.UserEventDispatcher;
+import com.android.launcher3.shadows.ShadowOverrides;
+import com.android.launcher3.util.LauncherLayoutBuilder;
+import com.android.launcher3.util.LauncherLayoutBuilder.FolderBuilder;
+import com.android.launcher3.util.LauncherModelHelper;
+import com.android.launcher3.widget.WidgetsFullSheet;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.LooperMode;
+import org.robolectric.annotation.LooperMode.Mode;
+import org.robolectric.shadows.ShadowLooper;
+
+/**
+ * Tests scroll behavior at various Launcher UI components
+ */
+@RunWith(RobolectricTestRunner.class)
+@LooperMode(Mode.PAUSED)
+public class LauncherUIScrollTest {
+
+ private Context mTargetContext;
+ private InvariantDeviceProfile mIdp;
+ private LauncherModelHelper mModelHelper;
+
+ private LauncherLayoutBuilder mLayoutBuilder;
+
+ @Before
+ public void setup() throws Exception {
+ mModelHelper = new LauncherModelHelper();
+ mTargetContext = RuntimeEnvironment.application;
+ mIdp = InvariantDeviceProfile.INSTANCE.get(mTargetContext);
+ ShadowOverrides.setProvider(UserEventDispatcher.class,
+ c -> mock(UserEventDispatcher.class));
+
+ Settings.Global.putFloat(mTargetContext.getContentResolver(),
+ Settings.Global.WINDOW_ANIMATION_SCALE, 0);
+
+ mModelHelper.installApp(TEST_PACKAGE);
+ // LayoutBuilder with 3 workspace pages
+ mLayoutBuilder = new LauncherLayoutBuilder()
+ .atWorkspace(0, mIdp.numRows - 1, 0).putApp(TEST_PACKAGE, TEST_PACKAGE)
+ .atWorkspace(0, mIdp.numRows - 1, 1).putApp(TEST_PACKAGE, TEST_PACKAGE)
+ .atWorkspace(0, mIdp.numRows - 1, 2).putApp(TEST_PACKAGE, TEST_PACKAGE);
+ }
+
+ @Test
+ public void testWorkspacePagesBound() throws Exception {
+ // Verify that the workspace if bound synchronously
+ Launcher launcher = loadLauncher();
+ assertEquals(3, launcher.getWorkspace().getPageCount());
+ assertEquals(0, launcher.getWorkspace().getCurrentPage());
+
+ launcher.dispatchGenericMotionEvent(createScrollEvent(-1));
+ assertNotEquals("Workspace was not scrolled",
+ 0, launcher.getWorkspace().getNextPage());
+ }
+
+ @Test
+ public void testAllAppsScroll() throws Exception {
+ // Install 100 apps
+ for (int i = 0; i < 100; i++) {
+ mModelHelper.installApp(TEST_PACKAGE + i);
+ }
+
+ // Bind and open all-apps
+ Launcher launcher = loadLauncher();
+ launcher.getStateManager().goToState(LauncherState.ALL_APPS, false);
+ doLayout(launcher);
+
+ int currentScroll = launcher.getAppsView().getActiveRecyclerView().getCurrentScrollY();
+ launcher.dispatchGenericMotionEvent(createScrollEvent(-1));
+ int newScroll = launcher.getAppsView().getActiveRecyclerView().getCurrentScrollY();
+
+ assertNotEquals("All Apps was not scrolled", currentScroll, newScroll);
+ assertEquals("Workspace was scrolled", 0, launcher.getWorkspace().getNextPage());
+ }
+
+ @Test
+ public void testWidgetsListScroll() throws Exception {
+ // Install 100 widgets
+ for (int i = 0; i < 100; i++) {
+ mModelHelper.installCustomShortcut(TEST_PACKAGE + i, "shortcutProvider");
+ }
+
+ // Bind and open widgets
+ Launcher launcher = loadLauncher();
+ WidgetsFullSheet widgets = WidgetsFullSheet.show(launcher, false);
+ doLayout(launcher);
+
+ int currentScroll = widgets.getRecyclerView().getCurrentScrollY();
+ launcher.dispatchGenericMotionEvent(createScrollEvent(-1));
+ int newScroll = widgets.getRecyclerView().getCurrentScrollY();
+ assertNotEquals("Widgets was not scrolled", currentScroll, newScroll);
+ assertEquals("Workspace was scrolled", 0, launcher.getWorkspace().getNextPage());
+ }
+
+ @Test
+ public void testFolderPageScroll() throws Exception {
+ // Add a folder with multiple icons
+ FolderBuilder fb = mLayoutBuilder.atWorkspace(mIdp.numColumns / 2, mIdp.numRows / 2, 0)
+ .putFolder(0);
+ for (int i = 0; i < 100; i++) {
+ fb.addApp(TEST_PACKAGE, TEST_PACKAGE);
+ }
+
+ // Bind and open folder
+ Launcher launcher = loadLauncher();
+ doLayout(launcher);
+ launcher.getWorkspace().getFirstMatch((i, v) -> v instanceof FolderIcon).performClick();
+ ShadowLooper.idleMainLooper();
+ doLayout(launcher);
+ FolderPagedView folderPages = Folder.getOpen(launcher).getContent();
+
+ assertEquals(0, folderPages.getNextPage());
+ launcher.dispatchGenericMotionEvent(createScrollEvent(-1));
+ assertNotEquals("Folder page was not scrolled", 0, folderPages.getNextPage());
+ assertEquals("Workspace was scrolled", 0, launcher.getWorkspace().getNextPage());
+ }
+
+ private Launcher loadLauncher() throws Exception {
+ mModelHelper.setupDefaultLayoutProvider(mLayoutBuilder).loadModelSync();
+ return buildAndBindLauncher();
+ }
+
+ private static MotionEvent createScrollEvent(int scroll) {
+ DeviceProfile dp = InvariantDeviceProfile.INSTANCE
+ .get(RuntimeEnvironment.application).portraitProfile;
+
+ final PointerProperties[] pointerProperties = new PointerProperties[1];
+ pointerProperties[0] = new PointerProperties();
+ pointerProperties[0].id = 0;
+ final MotionEvent.PointerCoords[] coords = new MotionEvent.PointerCoords[1];
+ coords[0] = new MotionEvent.PointerCoords();
+ coords[0].setAxisValue(MotionEvent.AXIS_VSCROLL, scroll);
+ coords[0].x = dp.widthPx / 2;
+ coords[0].y = dp.heightPx / 2;
+
+ final long time = SystemClock.uptimeMillis();
+ return MotionEvent.obtain(time, time, MotionEvent.ACTION_SCROLL, 1,
+ pointerProperties, coords, 0, 0, 1.0f, 1.0f, 0, 0,
+ InputDevice.SOURCE_CLASS_POINTER, 0);
+ }
+
+}
diff --git a/robolectric_tests/src/com/android/launcher3/util/GridOccupancyTest.java b/robolectric_tests/src/com/android/launcher3/util/GridOccupancyTest.java
index e453e31..2f3fc37 100644
--- a/robolectric_tests/src/com/android/launcher3/util/GridOccupancyTest.java
+++ b/robolectric_tests/src/com/android/launcher3/util/GridOccupancyTest.java
@@ -1,16 +1,17 @@
package com.android.launcher3.util;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
+
/**
* Unit tests for {@link GridOccupancy}
*/
-@RunWith(LauncherRoboTestRunner.class)
+@RunWith(RobolectricTestRunner.class)
public class GridOccupancyTest {
@Test
diff --git a/robolectric_tests/src/com/android/launcher3/util/IntArrayTest.java b/robolectric_tests/src/com/android/launcher3/util/IntArrayTest.java
index 5974ea5..c08e198 100644
--- a/robolectric_tests/src/com/android/launcher3/util/IntArrayTest.java
+++ b/robolectric_tests/src/com/android/launcher3/util/IntArrayTest.java
@@ -19,11 +19,12 @@
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
/**
* Robolectric unit tests for {@link IntArray}
*/
-@RunWith(LauncherRoboTestRunner.class)
+@RunWith(RobolectricTestRunner.class)
public class IntArrayTest {
@Test
diff --git a/robolectric_tests/src/com/android/launcher3/util/IntSetTest.java b/robolectric_tests/src/com/android/launcher3/util/IntSetTest.java
index aedf71e..7a8c00b 100644
--- a/robolectric_tests/src/com/android/launcher3/util/IntSetTest.java
+++ b/robolectric_tests/src/com/android/launcher3/util/IntSetTest.java
@@ -17,17 +17,18 @@
import static com.google.common.truth.Truth.assertThat;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
+
/**
* Robolectric unit tests for {@link IntSet}
*/
-@RunWith(LauncherRoboTestRunner.class)
+@RunWith(RobolectricTestRunner.class)
public class IntSetTest {
@Test
diff --git a/robolectric_tests/src/com/android/launcher3/util/LauncherModelHelper.java b/robolectric_tests/src/com/android/launcher3/util/LauncherModelHelper.java
index e133cf2..0388087 100644
--- a/robolectric_tests/src/com/android/launcher3/util/LauncherModelHelper.java
+++ b/robolectric_tests/src/com/android/launcher3/util/LauncherModelHelper.java
@@ -15,6 +15,8 @@
*/
package com.android.launcher3.util;
+import static android.content.Intent.ACTION_CREATE_SHORTCUT;
+
import static com.android.launcher3.LauncherSettings.Favorites.CONTENT_URI;
import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
@@ -34,9 +36,7 @@
import android.os.Process;
import android.provider.Settings;
-import com.android.launcher3.AppInfo;
import com.android.launcher3.InvariantDeviceProfile;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherModel;
import com.android.launcher3.LauncherModel.ModelUpdateTask;
@@ -44,6 +44,9 @@
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.model.AllAppsList;
import com.android.launcher3.model.BgDataModel;
+import com.android.launcher3.model.BgDataModel.Callbacks;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.pm.UserCache;
import org.mockito.ArgumentCaptor;
@@ -61,6 +64,7 @@
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
+import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.function.Function;
@@ -230,7 +234,21 @@
}
public int addItem(int type, int screen, int container, int x, int y) {
- return addItem(type, screen, container, x, y, mDefaultProfileId);
+ return addItem(type, screen, container, x, y, mDefaultProfileId, TEST_PACKAGE);
+ }
+
+ public int addItem(int type, int screen, int container, int x, int y, long profileId) {
+ return addItem(type, screen, container, x, y, profileId, TEST_PACKAGE);
+ }
+
+ public int addItem(int type, int screen, int container, int x, int y, String packageName) {
+ return addItem(type, screen, container, x, y, mDefaultProfileId, packageName);
+ }
+
+ public int addItem(int type, int screen, int container, int x, int y, String packageName,
+ int id, Uri contentUri) {
+ addItem(type, screen, container, x, y, mDefaultProfileId, packageName, id, contentUri);
+ return id;
}
/**
@@ -238,11 +256,19 @@
* @param type {@link #APP_ICON} or {@link #SHORTCUT} or >= 2 for
* folder (where the type represents the number of items in the folder).
*/
- public int addItem(int type, int screen, int container, int x, int y, long profileId) {
+ public int addItem(int type, int screen, int container, int x, int y, long profileId,
+ String packageName) {
Context context = RuntimeEnvironment.application;
int id = LauncherSettings.Settings.call(context.getContentResolver(),
LauncherSettings.Settings.METHOD_NEW_ITEM_ID)
.getInt(LauncherSettings.Settings.EXTRA_VALUE);
+ addItem(type, screen, container, x, y, profileId, packageName, id, CONTENT_URI);
+ return id;
+ }
+
+ public void addItem(int type, int screen, int container, int x, int y, long profileId,
+ String packageName, int id, Uri contentUri) {
+ Context context = RuntimeEnvironment.application;
ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites._ID, id);
@@ -257,7 +283,7 @@
if (type == APP_ICON || type == SHORTCUT) {
values.put(LauncherSettings.Favorites.ITEM_TYPE, type);
values.put(LauncherSettings.Favorites.INTENT,
- new Intent(Intent.ACTION_MAIN).setPackage(TEST_PACKAGE).toUri(0));
+ new Intent(Intent.ACTION_MAIN).setPackage(packageName).toUri(0));
} else {
values.put(LauncherSettings.Favorites.ITEM_TYPE,
LauncherSettings.Favorites.ITEM_TYPE_FOLDER);
@@ -267,8 +293,7 @@
}
}
- context.getContentResolver().insert(CONTENT_URI, values);
- return id;
+ context.getContentResolver().insert(contentUri, values);
}
public int[][][] createGrid(int[][][] typeArray) {
@@ -324,7 +349,8 @@
/**
* Sets up a dummy provider to load the provided layout by default, next time the layout loads
*/
- public void setupDefaultLayoutProvider(LauncherLayoutBuilder builder) throws Exception {
+ public LauncherModelHelper setupDefaultLayoutProvider(LauncherLayoutBuilder builder)
+ throws Exception {
Context context = RuntimeEnvironment.application;
InvariantDeviceProfile idp = InvariantDeviceProfile.INSTANCE.get(context);
idp.numRows = idp.numColumns = idp.numHotseatIcons = DEFAULT_GRID_SIZE;
@@ -342,23 +368,53 @@
Uri layoutUri = LauncherProvider.getLayoutUri(TEST_PROVIDER_AUTHORITY, context);
shadowOf(context.getContentResolver()).registerInputStream(layoutUri,
new ByteArrayInputStream(bos.toByteArray()));
+ return this;
}
/**
* Simulates an apk install with a default main activity with same class and package name
*/
public void installApp(String component) throws NameNotFoundException {
- ShadowPackageManager spm = shadowOf(RuntimeEnvironment.application.getPackageManager());
- ComponentName cn = new ComponentName(component, component);
- spm.addActivityIfNotPresent(cn);
-
IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
filter.addCategory(Intent.CATEGORY_LAUNCHER);
+ installApp(component, component, filter);
+ }
+
+ /**
+ * Simulates a custom shortcut install
+ */
+ public void installCustomShortcut(String pkg, String clazz) throws NameNotFoundException {
+ installApp(pkg, clazz, new IntentFilter(ACTION_CREATE_SHORTCUT));
+ }
+
+ private void installApp(String pkg, String clazz, IntentFilter filter)
+ throws NameNotFoundException {
+ ShadowPackageManager spm = shadowOf(RuntimeEnvironment.application.getPackageManager());
+ ComponentName cn = new ComponentName(pkg, clazz);
+ spm.addActivityIfNotPresent(cn);
+
filter.addCategory(Intent.CATEGORY_DEFAULT);
spm.addIntentFilterForActivity(cn, filter);
}
/**
+ * Loads the model in memory synchronously
+ */
+ public void loadModelSync() throws ExecutionException, InterruptedException {
+ // Since robolectric tests run on main thread, we run the loader-UI calls on a temp thread,
+ // so that we can wait appropriately for the loader to complete.
+ ReflectionHelpers.setField(getModel(), "mMainExecutor", Executors.UI_HELPER_EXECUTOR);
+
+ Callbacks mockCb = mock(Callbacks.class);
+ getModel().addCallbacksAndLoad(mockCb);
+
+ Executors.MODEL_EXECUTOR.submit(() -> { }).get();
+ Executors.UI_HELPER_EXECUTOR.submit(() -> { }).get();
+ ReflectionHelpers.setField(getModel(), "mMainExecutor", Executors.MAIN_EXECUTOR);
+ getModel().removeCallbacks(mockCb);
+ }
+
+ /**
* An extension of LauncherProvider backed up by in-memory database.
*/
public static class TestLauncherProvider extends LauncherProvider {
diff --git a/robolectric_tests/src/com/android/launcher3/util/LauncherRoboTestRunner.java b/robolectric_tests/src/com/android/launcher3/util/LauncherRoboTestRunner.java
deleted file mode 100644
index 6277c66..0000000
--- a/robolectric_tests/src/com/android/launcher3/util/LauncherRoboTestRunner.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * 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.launcher3.util;
-
-import static org.mockito.Mockito.mock;
-
-import com.android.launcher3.shadows.LShadowAppWidgetManager;
-import com.android.launcher3.shadows.LShadowBackupManager;
-import com.android.launcher3.shadows.LShadowBitmap;
-import com.android.launcher3.shadows.LShadowLauncherApps;
-import com.android.launcher3.shadows.LShadowUserManager;
-import com.android.launcher3.shadows.ShadowDeviceFlag;
-import com.android.launcher3.shadows.ShadowLooperExecutor;
-import com.android.launcher3.shadows.ShadowMainThreadInitializedObject;
-import com.android.launcher3.uioverrides.plugins.PluginManagerWrapper;
-
-import org.junit.runners.model.InitializationError;
-import org.robolectric.DefaultTestLifecycle;
-import org.robolectric.RobolectricTestRunner;
-import org.robolectric.TestLifecycle;
-import org.robolectric.annotation.Config;
-import org.robolectric.shadows.ShadowLog;
-
-import java.lang.reflect.Method;
-
-import javax.annotation.Nonnull;
-
-/**
- * Test runner with Launcher specific configurations
- */
-public class LauncherRoboTestRunner extends RobolectricTestRunner {
-
- private static final Class<?>[] SHADOWS = new Class<?>[] {
- LShadowAppWidgetManager.class,
- LShadowUserManager.class,
- LShadowLauncherApps.class,
- LShadowBitmap.class,
- LShadowBackupManager.class,
- ShadowLooperExecutor.class,
- ShadowMainThreadInitializedObject.class,
- ShadowDeviceFlag.class,
- };
-
- public LauncherRoboTestRunner(Class<?> testClass) throws InitializationError {
- super(testClass);
- }
-
- @Override
- protected Config buildGlobalConfig() {
- return new Config.Builder().setShadows(SHADOWS).build();
- }
-
- @Nonnull
- @Override
- protected Class<? extends TestLifecycle> getTestLifecycleClass() {
- return LauncherTestLifecycle.class;
- }
-
- public static class LauncherTestLifecycle extends DefaultTestLifecycle {
-
- @Override
- public void beforeTest(Method method) {
- super.beforeTest(method);
- ShadowLog.stream = System.out;
-
- // Disable plugins
- PluginManagerWrapper.INSTANCE.initializeForTesting(mock(PluginManagerWrapper.class));
- }
-
- @Override
- public void afterTest(Method method) {
- super.afterTest(method);
-
- ShadowLog.stream = null;
- ShadowMainThreadInitializedObject.resetInitializedObjects();
- }
- }
-}
diff --git a/robolectric_tests/src/com/android/launcher3/util/LauncherTestApplication.java b/robolectric_tests/src/com/android/launcher3/util/LauncherTestApplication.java
new file mode 100644
index 0000000..6dd4df8
--- /dev/null
+++ b/robolectric_tests/src/com/android/launcher3/util/LauncherTestApplication.java
@@ -0,0 +1,54 @@
+/*
+ * 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.launcher3.util;
+
+import static org.mockito.Mockito.mock;
+
+import android.app.Application;
+
+import com.android.launcher3.shadows.LShadowWallpaperManager;
+import com.android.launcher3.shadows.ShadowMainThreadInitializedObject;
+import com.android.launcher3.shadows.ShadowOverrides;
+import com.android.launcher3.uioverrides.plugins.PluginManagerWrapper;
+
+import org.robolectric.TestLifecycleApplication;
+import org.robolectric.shadows.ShadowLog;
+
+import java.lang.reflect.Method;
+
+public class LauncherTestApplication extends Application implements TestLifecycleApplication {
+
+ @Override
+ public void beforeTest(Method method) {
+ ShadowLog.stream = System.out;
+
+ // Disable plugins
+ PluginManagerWrapper.INSTANCE.initializeForTesting(mock(PluginManagerWrapper.class));
+
+ // Initialize mock wallpaper manager
+ LShadowWallpaperManager.initializeMock();
+ }
+
+ @Override
+ public void prepareTest(Object test) { }
+
+ @Override
+ public void afterTest(Method method) {
+ ShadowLog.stream = null;
+ ShadowMainThreadInitializedObject.resetInitializedObjects();
+ ShadowOverrides.clearProvider();
+ }
+}
diff --git a/robolectric_tests/src/com/android/launcher3/util/LauncherUIHelper.java b/robolectric_tests/src/com/android/launcher3/util/LauncherUIHelper.java
new file mode 100644
index 0000000..f019a20
--- /dev/null
+++ b/robolectric_tests/src/com/android/launcher3/util/LauncherUIHelper.java
@@ -0,0 +1,102 @@
+/*
+ * 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.launcher3.util;
+
+import static android.view.View.MeasureSpec.EXACTLY;
+import static android.view.View.MeasureSpec.makeMeasureSpec;
+
+import android.app.Activity;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.ResolveInfo;
+import android.graphics.Point;
+import android.view.View;
+import android.view.WindowManager;
+
+import com.android.launcher3.Launcher;
+
+import org.robolectric.Robolectric;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.android.controller.ActivityController;
+import org.robolectric.shadows.ShadowLooper;
+import org.robolectric.util.ReflectionHelpers;
+
+import java.util.List;
+
+/**
+ * Utility class to help manage Launcher UI and related objects for test.
+ */
+public class LauncherUIHelper {
+
+ /**
+ * Returns the class name for the Launcher activity as defined in the manifest
+ */
+ public static String getLauncherClassName() {
+ Context context = RuntimeEnvironment.application;
+ Intent homeIntent = new Intent(Intent.ACTION_MAIN)
+ .addCategory(Intent.CATEGORY_HOME)
+ .setPackage(context.getPackageName())
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+
+ List<ResolveInfo> launchers = context.getPackageManager()
+ .queryIntentActivities(homeIntent, 0);
+ if (launchers.size() != 1) {
+ return null;
+ }
+ return launchers.get(0).activityInfo.name;
+ }
+
+ /**
+ * Returns an activity controller for Launcher activity defined in the manifest
+ */
+ public static <T extends Launcher> ActivityController<T> buildLauncher() {
+ try {
+ Class<T> tClass = (Class<T>) Class.forName(getLauncherClassName());
+ return Robolectric.buildActivity(tClass);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Creates and binds a Launcher activity defined in the manifest.
+ * Note that the model must be bound before calling this
+ */
+ public static <T extends Launcher> T buildAndBindLauncher() {
+ ActivityController<T> controller = buildLauncher();
+
+ T launcher = controller.setup().get();
+ doLayout(launcher);
+ ViewOnDrawExecutor executor = ReflectionHelpers.getField(launcher, "mPendingExecutor");
+ if (executor != null) {
+ executor.runAllTasks();
+ }
+ return launcher;
+ }
+
+ /**
+ * Performs a measure and layout pass for the given activity
+ */
+ public static void doLayout(Activity activity) {
+ Point size = new Point();
+ RuntimeEnvironment.application.getSystemService(WindowManager.class)
+ .getDefaultDisplay().getSize(size);
+ View view = activity.getWindow().getDecorView();
+ view.measure(makeMeasureSpec(size.x, EXACTLY), makeMeasureSpec(size.y, EXACTLY));
+ view.layout(0, 0, size.x, size.y);
+ ShadowLooper.idleMainLooper();
+ }
+}
diff --git a/robolectric_tests/src/com/android/launcher3/widget/WidgetsListAdapterTest.java b/robolectric_tests/src/com/android/launcher3/widget/WidgetsListAdapterTest.java
index daae818..84c65b1 100644
--- a/robolectric_tests/src/com/android/launcher3/widget/WidgetsListAdapterTest.java
+++ b/robolectric_tests/src/com/android/launcher3/widget/WidgetsListAdapterTest.java
@@ -34,15 +34,15 @@
import com.android.launcher3.WidgetPreviewLoader;
import com.android.launcher3.icons.BitmapInfo;
import com.android.launcher3.icons.IconCache;
-import com.android.launcher3.model.PackageItemInfo;
import com.android.launcher3.model.WidgetItem;
-import com.android.launcher3.util.LauncherRoboTestRunner;
+import com.android.launcher3.model.data.PackageItemInfo;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.shadows.ShadowPackageManager;
import org.robolectric.util.ReflectionHelpers;
@@ -50,7 +50,7 @@
import java.util.ArrayList;
import java.util.Collections;
-@RunWith(LauncherRoboTestRunner.class)
+@RunWith(RobolectricTestRunner.class)
public class WidgetsListAdapterTest {
@Mock private LayoutInflater mMockLayoutInflater;
diff --git a/src/com/android/launcher3/AbstractFloatingView.java b/src/com/android/launcher3/AbstractFloatingView.java
index af2cdc3..bed8278 100644
--- a/src/com/android/launcher3/AbstractFloatingView.java
+++ b/src/com/android/launcher3/AbstractFloatingView.java
@@ -22,7 +22,6 @@
import static com.android.launcher3.compat.AccessibilityManagerCompat.isAccessibilityEnabled;
import static com.android.launcher3.compat.AccessibilityManagerCompat.sendCustomAccessibilityEvent;
-import android.animation.Animator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
@@ -30,11 +29,12 @@
import android.view.MotionEvent;
import android.view.View;
import android.view.accessibility.AccessibilityNodeInfo;
+import android.view.animation.Interpolator;
import android.widget.LinearLayout;
import androidx.annotation.IntDef;
-import androidx.annotation.Nullable;
+import com.android.launcher3.anim.PendingAnimation;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action;
import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
import com.android.launcher3.util.TouchController;
@@ -134,9 +134,8 @@
* Creates a user-controlled animation to hint that the view will be closed if completed.
* @param distanceToMove The max distance that elements should move from their starting point.
*/
- public @Nullable Animator createHintCloseAnim(float distanceToMove) {
- return null;
- }
+ public void addHintCloseAnim(
+ float distanceToMove, Interpolator interpolator, PendingAnimation target) { }
public abstract void logActionCommand(int command);
@@ -181,7 +180,10 @@
return null;
}
- protected static <T extends AbstractFloatingView> T getOpenView(
+ /**
+ * Returns a view matching FloatingViewType
+ */
+ public static <T extends AbstractFloatingView> T getOpenView(
ActivityContext activity, @FloatingViewType int type) {
BaseDragLayer dragLayer = activity.getDragLayer();
if (dragLayer == null) return null;
diff --git a/src/com/android/launcher3/AppWidgetResizeFrame.java b/src/com/android/launcher3/AppWidgetResizeFrame.java
index 73d8a88..6f7b684 100644
--- a/src/com/android/launcher3/AppWidgetResizeFrame.java
+++ b/src/com/android/launcher3/AppWidgetResizeFrame.java
@@ -350,7 +350,7 @@
mWidgetView.requestLayout();
}
- static void updateWidgetSizeRanges(AppWidgetHostView widgetView, Launcher launcher,
+ public static void updateWidgetSizeRanges(AppWidgetHostView widgetView, Launcher launcher,
int spanX, int spanY) {
getWidgetSizeRanges(launcher, spanX, spanY, sTmpRect);
widgetView.updateAppWidgetSize(null, sTmpRect.left, sTmpRect.top,
diff --git a/src/com/android/launcher3/AppWidgetsRestoredReceiver.java b/src/com/android/launcher3/AppWidgetsRestoredReceiver.java
index 71b7206..a55c90d 100644
--- a/src/com/android/launcher3/AppWidgetsRestoredReceiver.java
+++ b/src/com/android/launcher3/AppWidgetsRestoredReceiver.java
@@ -17,6 +17,7 @@
import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.model.LoaderTask;
import com.android.launcher3.model.WidgetsModel;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
import com.android.launcher3.pm.UserCache;
import com.android.launcher3.provider.RestoreDbTask;
import com.android.launcher3.util.ContentWriter;
diff --git a/src/com/android/launcher3/AutoInstallsLayout.java b/src/com/android/launcher3/AutoInstallsLayout.java
index ac43967..5971a02 100644
--- a/src/com/android/launcher3/AutoInstallsLayout.java
+++ b/src/com/android/launcher3/AutoInstallsLayout.java
@@ -44,6 +44,8 @@
import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.icons.GraphicsUtils;
import com.android.launcher3.icons.LauncherIcons;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.qsb.QsbContainerView;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.PackageManagerHelper;
diff --git a/src/com/android/launcher3/BaseActivity.java b/src/com/android/launcher3/BaseActivity.java
index f3c5191..814b728 100644
--- a/src/com/android/launcher3/BaseActivity.java
+++ b/src/com/android/launcher3/BaseActivity.java
@@ -40,8 +40,8 @@
import com.android.launcher3.logging.StatsLogUtils;
import com.android.launcher3.logging.StatsLogUtils.LogStateProvider;
import com.android.launcher3.logging.UserEventDispatcher;
-import com.android.launcher3.logging.UserEventDispatcher.UserEventDelegate;
import com.android.launcher3.testing.TestLogging;
+import com.android.launcher3.testing.TestProtocol;
import com.android.launcher3.userevent.nano.LauncherLogProto;
import com.android.launcher3.util.SystemUiController;
import com.android.launcher3.util.ViewCache;
@@ -51,8 +51,10 @@
import java.lang.annotation.Retention;
import java.util.ArrayList;
-public abstract class BaseActivity extends Activity
- implements UserEventDelegate, LogStateProvider, ActivityContext {
+/**
+ * Launcher BaseActivity
+ */
+public abstract class BaseActivity extends Activity implements LogStateProvider, ActivityContext {
private static final String TAG = "BaseActivity";
@@ -154,7 +156,7 @@
public final UserEventDispatcher getUserEventDispatcher() {
if (mUserEventDispatcher == null) {
- mUserEventDispatcher = UserEventDispatcher.newInstance(this, this);
+ mUserEventDispatcher = UserEventDispatcher.newInstance(this);
}
return mUserEventDispatcher;
}
@@ -330,9 +332,7 @@
return;
}
try {
- if (Utilities.IS_RUNNING_IN_TEST_HARNESS) {
- TestLogging.recordEvent("start: shortcut: " + packageName);
- }
+ TestLogging.recordEvent(TestProtocol.SEQUENCE_MAIN, "start: shortcut", packageName);
getSystemService(LauncherApps.class).startShortcut(packageName, id, sourceBounds,
startActivityOptions, user);
} catch (SecurityException | IllegalStateException e) {
diff --git a/src/com/android/launcher3/BaseDraggingActivity.java b/src/com/android/launcher3/BaseDraggingActivity.java
index dda38b3..2dc7836 100644
--- a/src/com/android/launcher3/BaseDraggingActivity.java
+++ b/src/com/android/launcher3/BaseDraggingActivity.java
@@ -16,6 +16,9 @@
package com.android.launcher3;
+import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.APP_LAUNCH_TAP;
+import static com.android.launcher3.util.DefaultDisplay.CHANGE_ROTATION;
+
import android.app.ActivityOptions;
import android.content.ActivityNotFoundException;
import android.content.Intent;
@@ -36,10 +39,15 @@
import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.model.AppLaunchTracker;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.testing.TestLogging;
+import com.android.launcher3.testing.TestProtocol;
import com.android.launcher3.touch.ItemClickHandler;
-import com.android.launcher3.uioverrides.DisplayRotationListener;
import com.android.launcher3.uioverrides.WallpaperColorInfo;
+import com.android.launcher3.util.DefaultDisplay;
+import com.android.launcher3.util.DefaultDisplay.DisplayInfoChangeListener;
+import com.android.launcher3.util.DefaultDisplay.Info;
import com.android.launcher3.util.PackageManagerHelper;
import com.android.launcher3.util.Themes;
import com.android.launcher3.util.TraceHelper;
@@ -48,7 +56,7 @@
* Extension of BaseActivity allowing support for drag-n-drop
*/
public abstract class BaseDraggingActivity extends BaseActivity
- implements WallpaperColorInfo.OnChangeListener {
+ implements WallpaperColorInfo.OnChangeListener, DisplayInfoChangeListener {
private static final String TAG = "BaseDraggingActivity";
@@ -63,8 +71,6 @@
private int mThemeRes = R.style.AppTheme;
- private DisplayRotationListener mRotationListener;
-
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@@ -72,7 +78,7 @@
mIsSafeModeEnabled = TraceHelper.whitelistIpcs("isSafeMode",
() -> getPackageManager().isSafeMode());
- mRotationListener = new DisplayRotationListener(this, this::onDeviceRotationChanged);
+ DefaultDisplay.INSTANCE.get(this).addChangeListener(this);
// Update theme
WallpaperColorInfo.INSTANCE.get(this).addOnChangeListener(this);
@@ -167,9 +173,7 @@
startShortcutIntentSafely(intent, optsBundle, item, sourceContainer);
} else if (user == null || user.equals(Process.myUserHandle())) {
// Could be launching some bookkeeping activity
- if (Utilities.IS_RUNNING_IN_TEST_HARNESS) {
- TestLogging.recordEvent("start: activity: " + intent);
- }
+ TestLogging.recordEvent(TestProtocol.SEQUENCE_MAIN, "start: activity", intent);
startActivity(intent, optsBundle);
AppLaunchTracker.INSTANCE.get(this).onStartApp(intent.getComponent(),
Process.myUserHandle(), sourceContainer);
@@ -180,7 +184,7 @@
sourceContainer);
}
getUserEventDispatcher().logAppLaunch(v, intent, user);
- getStatsLogManager().logAppLaunch(v, intent, user);
+ getStatsLogManager().log(APP_LAUNCH_TAP, item.buildProto(null, null));
return true;
} catch (NullPointerException|ActivityNotFoundException|SecurityException e) {
Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
@@ -238,7 +242,7 @@
protected void onDestroy() {
super.onDestroy();
WallpaperColorInfo.INSTANCE.get(this).removeOnChangeListener(this);
- mRotationListener.disable();
+ DefaultDisplay.INSTANCE.get(this).removeChangeListener(this);
}
public void runOnceOnStart(Runnable action) {
@@ -251,15 +255,13 @@
protected void onDeviceProfileInitiated() {
if (mDeviceProfile.isVerticalBarLayout()) {
- mRotationListener.enable();
mDeviceProfile.updateIsSeascape(this);
- } else {
- mRotationListener.disable();
}
}
- private void onDeviceRotationChanged() {
- if (mDeviceProfile.updateIsSeascape(this)) {
+ @Override
+ public void onDisplayInfoChanged(Info info, int flags) {
+ if ((flags & CHANGE_ROTATION) != 0 && mDeviceProfile.updateIsSeascape(this)) {
reapplyUi();
}
}
diff --git a/src/com/android/launcher3/BaseRecyclerView.java b/src/com/android/launcher3/BaseRecyclerView.java
index 864fa6e..9e8441a 100644
--- a/src/com/android/launcher3/BaseRecyclerView.java
+++ b/src/com/android/launcher3/BaseRecyclerView.java
@@ -18,15 +18,17 @@
import android.content.Context;
import android.util.AttributeSet;
+import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
-import com.android.launcher3.compat.AccessibilityManagerCompat;
-import com.android.launcher3.views.RecyclerViewFastScroller;
-
import androidx.recyclerview.widget.RecyclerView;
+import com.android.launcher3.compat.AccessibilityManagerCompat;
+import com.android.launcher3.testing.TestProtocol;
+import com.android.launcher3.views.RecyclerViewFastScroller;
+
/**
* A base {@link RecyclerView}, which does the following:
@@ -138,7 +140,7 @@
if (getCurrentScrollY() == 0) {
return true;
}
- return false;
+ return getAdapter() == null || getAdapter().getItemCount() == 0;
}
/**
@@ -177,6 +179,10 @@
public void onScrollStateChanged(int state) {
super.onScrollStateChanged(state);
+ if (TestProtocol.sDebugTracing) {
+ Log.d(TestProtocol.NO_SCROLL_END_WIDGETS, "onScrollStateChanged: " + state);
+ }
+
if (state == SCROLL_STATE_IDLE) {
AccessibilityManagerCompat.sendScrollFinishedEventToTest(getContext());
}
diff --git a/src/com/android/launcher3/BubbleTextView.java b/src/com/android/launcher3/BubbleTextView.java
index e6f8a85..93247ab 100644
--- a/src/com/android/launcher3/BubbleTextView.java
+++ b/src/com/android/launcher3/BubbleTextView.java
@@ -39,13 +39,13 @@
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
-import android.view.ViewConfiguration;
import android.view.ViewDebug;
import android.widget.TextView;
import com.android.launcher3.Launcher.OnResumeCallback;
import com.android.launcher3.accessibility.LauncherAccessibilityDelegate;
import com.android.launcher3.dot.DotInfo;
+import com.android.launcher3.dragndrop.DraggableView;
import com.android.launcher3.folder.FolderIcon;
import com.android.launcher3.graphics.IconPalette;
import com.android.launcher3.graphics.IconShape;
@@ -53,7 +53,12 @@
import com.android.launcher3.icons.DotRenderer;
import com.android.launcher3.icons.IconCache.IconLoadRequest;
import com.android.launcher3.icons.IconCache.ItemInfoUpdateReceiver;
-import com.android.launcher3.model.PackageItemInfo;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.ItemInfoWithIcon;
+import com.android.launcher3.model.data.PackageItemInfo;
+import com.android.launcher3.model.data.PromiseAppInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.views.ActivityContext;
import com.android.launcher3.views.IconLabelDotView;
@@ -65,7 +70,7 @@
* too aggressive.
*/
public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver, OnResumeCallback,
- IconLabelDotView {
+ IconLabelDotView, DraggableView {
private static final int DISPLAY_WORKSPACE = 0;
private static final int DISPLAY_ALL_APPS = 1;
@@ -103,13 +108,11 @@
private final ActivityContext mActivity;
private Drawable mIcon;
- private final boolean mCenterVertically;
+ private boolean mCenterVertically;
private final int mDisplay;
private final CheckLongPressHelper mLongPressHelper;
- private final StylusEventHelper mStylusEventHelper;
- private final float mSlop;
private final boolean mLayoutHorizontal;
private final int mIconSize;
@@ -136,9 +139,6 @@
@ViewDebug.ExportedProperty(category = "launcher")
private boolean mDisableRelayout = false;
- @ViewDebug.ExportedProperty(category = "launcher")
- private final boolean mIgnorePaddingTouch;
-
private IconLoadRequest mIconLoadRequest;
public BubbleTextView(Context context) {
@@ -152,36 +152,29 @@
public BubbleTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mActivity = ActivityContext.lookupContext(context);
- mSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.BubbleTextView, defStyle, 0);
mLayoutHorizontal = a.getBoolean(R.styleable.BubbleTextView_layoutHorizontal, false);
+ DeviceProfile grid = mActivity.getDeviceProfile();
mDisplay = a.getInteger(R.styleable.BubbleTextView_iconDisplay, DISPLAY_WORKSPACE);
final int defaultIconSize;
if (mDisplay == DISPLAY_WORKSPACE) {
- DeviceProfile grid = mActivity.getWallpaperDeviceProfile();
setTextSize(TypedValue.COMPLEX_UNIT_PX, grid.iconTextSizePx);
setCompoundDrawablePadding(grid.iconDrawablePaddingPx);
defaultIconSize = grid.iconSizePx;
- mIgnorePaddingTouch = true;
} else if (mDisplay == DISPLAY_ALL_APPS) {
- DeviceProfile grid = mActivity.getDeviceProfile();
setTextSize(TypedValue.COMPLEX_UNIT_PX, grid.allAppsIconTextSizePx);
setCompoundDrawablePadding(grid.allAppsIconDrawablePaddingPx);
defaultIconSize = grid.allAppsIconSizePx;
- mIgnorePaddingTouch = true;
} else if (mDisplay == DISPLAY_FOLDER) {
- DeviceProfile grid = mActivity.getDeviceProfile();
setTextSize(TypedValue.COMPLEX_UNIT_PX, grid.folderChildTextSizePx);
setCompoundDrawablePadding(grid.folderChildDrawablePaddingPx);
defaultIconSize = grid.folderChildIconSizePx;
- mIgnorePaddingTouch = true;
} else {
// widget_selection or shortcut_popup
- defaultIconSize = mActivity.getDeviceProfile().iconSizePx;
- mIgnorePaddingTouch = false;
+ defaultIconSize = grid.iconSizePx;
}
mCenterVertically = a.getBoolean(R.styleable.BubbleTextView_centerVertically, false);
@@ -191,7 +184,6 @@
a.recycle();
mLongPressHelper = new CheckLongPressHelper(this);
- mStylusEventHelper = new StylusEventHelper(new SimpleOnStylusPressListener(this), this);
mDotParams = new DotRenderer.DrawParams();
@@ -332,42 +324,21 @@
@Override
public boolean onTouchEvent(MotionEvent event) {
// ignore events if they happen in padding area
- if (event.getAction() == MotionEvent.ACTION_DOWN && mIgnorePaddingTouch
+ if (event.getAction() == MotionEvent.ACTION_DOWN
&& (event.getY() < getPaddingTop()
|| event.getX() < getPaddingLeft()
|| event.getY() > getHeight() - getPaddingBottom()
|| event.getX() > getWidth() - getPaddingRight())) {
return false;
}
-
- // Call the superclass onTouchEvent first, because sometimes it changes the state to
- // isPressed() on an ACTION_UP
- boolean result = super.onTouchEvent(event);
-
- // Check for a stylus button press, if it occurs cancel any long press checks.
- if (mStylusEventHelper.onMotionEvent(event)) {
- mLongPressHelper.cancelLongPress();
- result = true;
+ if (isLongClickable()) {
+ super.onTouchEvent(event);
+ mLongPressHelper.onTouchEvent(event);
+ // Keep receiving the rest of the events
+ return true;
+ } else {
+ return super.onTouchEvent(event);
}
-
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:
- // If we're in a stylus button press, don't check for long press.
- if (!mStylusEventHelper.inStylusButtonPressed()) {
- mLongPressHelper.postCheckForLongPress();
- }
- break;
- case MotionEvent.ACTION_CANCEL:
- case MotionEvent.ACTION_UP:
- mLongPressHelper.cancelLongPress();
- break;
- case MotionEvent.ACTION_MOVE:
- if (!Utilities.pointInView(this, event.getX(), event.getY(), mSlop)) {
- mLongPressHelper.cancelLongPress();
- }
- break;
- }
- return result;
}
void setStayPressed(boolean stayPressed) {
@@ -530,7 +501,6 @@
@Override
public void cancelLongPress() {
super.cancelLongPress();
-
mLongPressHelper.cancelLongPress();
}
@@ -701,4 +671,24 @@
public int getIconSize() {
return mIconSize;
}
+
+ @Override
+ public int getViewType() {
+ return DRAGGABLE_ICON;
+ }
+
+ @Override
+ public void getVisualDragBounds(Rect bounds) {
+ DeviceProfile grid = mActivity.getDeviceProfile();
+ BubbleTextView.getIconBounds(this, bounds, grid.iconSizePx);
+ }
+
+ @Override
+ public void prepareDrawDragView() {
+ if (getIcon() instanceof FastBitmapDrawable) {
+ FastBitmapDrawable icon = (FastBitmapDrawable) getIcon();
+ icon.setScale(1f);
+ }
+ setForceHideDot(true);
+ }
}
diff --git a/src/com/android/launcher3/ButtonDropTarget.java b/src/com/android/launcher3/ButtonDropTarget.java
index 2b0da43..09827d6 100644
--- a/src/com/android/launcher3/ButtonDropTarget.java
+++ b/src/com/android/launcher3/ButtonDropTarget.java
@@ -46,6 +46,7 @@
import com.android.launcher3.dragndrop.DragLayer;
import com.android.launcher3.dragndrop.DragOptions;
import com.android.launcher3.dragndrop.DragView;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
import com.android.launcher3.util.Themes;
import com.android.launcher3.util.Thunk;
@@ -155,7 +156,7 @@
@Override
public final void onDragEnter(DragObject d) {
- if (!d.accessibleDrag && !mTextVisible) {
+ if (!mAccessibleDrag && !mTextVisible) {
// Show tooltip
hideTooltip();
diff --git a/src/com/android/launcher3/CellLayout.java b/src/com/android/launcher3/CellLayout.java
index ac61c49..99416c4 100644
--- a/src/com/android/launcher3/CellLayout.java
+++ b/src/com/android/launcher3/CellLayout.java
@@ -53,21 +53,19 @@
import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.accessibility.DragAndDropAccessibilityDelegate;
-import com.android.launcher3.accessibility.FolderAccessibilityHelper;
-import com.android.launcher3.accessibility.WorkspaceAccessibilityHelper;
import com.android.launcher3.anim.Interpolators;
import com.android.launcher3.anim.PropertyListBuilder;
import com.android.launcher3.config.FeatureFlags;
+import com.android.launcher3.dragndrop.DraggableView;
import com.android.launcher3.folder.PreviewBackground;
import com.android.launcher3.graphics.DragPreviewProvider;
-import com.android.launcher3.graphics.RotationMode;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.util.CellAndSpan;
import com.android.launcher3.util.GridOccupancy;
import com.android.launcher3.util.ParcelableSparseArray;
import com.android.launcher3.util.Themes;
import com.android.launcher3.util.Thunk;
import com.android.launcher3.views.ActivityContext;
-import com.android.launcher3.views.Transposable;
import com.android.launcher3.widget.LauncherAppWidgetHostView;
import java.lang.annotation.Retention;
@@ -78,10 +76,7 @@
import java.util.Comparator;
import java.util.Stack;
-public class CellLayout extends ViewGroup implements Transposable {
- public static final int WORKSPACE_ACCESSIBILITY_DRAG = 2;
- public static final int FOLDER_ACCESSIBILITY_DRAG = 1;
-
+public class CellLayout extends ViewGroup {
private static final String TAG = "CellLayout";
private static final boolean LOGD = false;
@@ -105,6 +100,11 @@
@Thunk final int[] mTmpPoint = new int[2];
@Thunk final int[] mTempLocation = new int[2];
+ // Used to visualize / debug the Grid of the CellLayout
+ private static final boolean VISUALIZE_GRID = false;
+ private Rect mVisualizeGridRect = new Rect();
+ private Paint mVisualizeGridPaint = new Paint();
+
private GridOccupancy mOccupied;
private GridOccupancy mTmpOccupied;
@@ -182,9 +182,7 @@
private static final Paint sPaint = new Paint();
// Related to accessible drag and drop
- private DragAndDropAccessibilityDelegate mTouchHelper;
private boolean mUseTouchHelper = false;
- private RotationMode mRotationMode = RotationMode.NORMAL;
public CellLayout(Context context) {
this(context, null);
@@ -206,7 +204,7 @@
setClipToPadding(false);
mActivity = ActivityContext.lookupContext(context);
- DeviceProfile grid = mActivity.getWallpaperDeviceProfile();
+ DeviceProfile grid = mActivity.getDeviceProfile();
mCellWidth = mCellHeight = -1;
mFixedCellWidth = mFixedCellHeight = -1;
@@ -292,26 +290,20 @@
addView(mShortcutsAndWidgets);
}
- public void enableAccessibleDrag(boolean enable, int dragType) {
- mUseTouchHelper = enable;
- if (!enable) {
- ViewCompat.setAccessibilityDelegate(this, null);
- setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
- getShortcutsAndWidgets().setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
- setOnClickListener(null);
- } else {
- if (dragType == WORKSPACE_ACCESSIBILITY_DRAG &&
- !(mTouchHelper instanceof WorkspaceAccessibilityHelper)) {
- mTouchHelper = new WorkspaceAccessibilityHelper(this);
- } else if (dragType == FOLDER_ACCESSIBILITY_DRAG &&
- !(mTouchHelper instanceof FolderAccessibilityHelper)) {
- mTouchHelper = new FolderAccessibilityHelper(this);
- }
- ViewCompat.setAccessibilityDelegate(this, mTouchHelper);
- setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
- getShortcutsAndWidgets().setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
- setOnClickListener(mTouchHelper);
- }
+
+ /**
+ * Sets or clears a delegate used for accessible drag and drop
+ */
+ public void setDragAndDropAccessibilityDelegate(DragAndDropAccessibilityDelegate delegate) {
+ setOnClickListener(delegate);
+ setOnHoverListener(delegate);
+ ViewCompat.setAccessibilityDelegate(this, delegate);
+
+ mUseTouchHelper = delegate != null;
+ int accessibilityFlag = mUseTouchHelper
+ ? IMPORTANT_FOR_ACCESSIBILITY_YES : IMPORTANT_FOR_ACCESSIBILITY_NO;
+ setImportantForAccessibility(accessibilityFlag);
+ getShortcutsAndWidgets().setImportantForAccessibility(accessibilityFlag);
// Invalidate the accessibility hierarchy
if (getParent() != null) {
@@ -320,33 +312,6 @@
}
}
- public void setRotationMode(RotationMode mode) {
- if (mRotationMode != mode) {
- mRotationMode = mode;
- requestLayout();
- }
- }
-
- @Override
- public RotationMode getRotationMode() {
- return mRotationMode;
- }
-
- @Override
- public void setPadding(int left, int top, int right, int bottom) {
- mRotationMode.mapRect(left, top, right, bottom, mTempRect);
- super.setPadding(mTempRect.left, mTempRect.top, mTempRect.right, mTempRect.bottom);
- }
-
- @Override
- public boolean dispatchHoverEvent(MotionEvent event) {
- // Always attempt to dispatch hover events to accessibility first.
- if (mUseTouchHelper && mTouchHelper.dispatchHoverEvent(event)) {
- return true;
- }
- return super.dispatchHoverEvent(event);
- }
-
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (mUseTouchHelper ||
@@ -483,6 +448,37 @@
mFolderLeaveBehind.drawLeaveBehind(canvas);
canvas.restore();
}
+
+ if (VISUALIZE_GRID) {
+ visualizeGrid(canvas);
+ }
+ }
+
+ protected void visualizeGrid(Canvas canvas) {
+ mVisualizeGridRect.set(0, 0, mCellWidth, mCellHeight);
+ mVisualizeGridPaint.setStrokeWidth(4);
+
+ for (int i = 0; i < mCountX; i++) {
+ for (int j = 0; j < mCountY; j++) {
+ canvas.save();
+
+ int transX = i * mCellWidth;
+ int transY = j * mCellHeight;
+
+ canvas.translate(getPaddingLeft() + transX, getPaddingTop() + transY);
+
+ mVisualizeGridPaint.setStyle(Paint.Style.FILL);
+ mVisualizeGridPaint.setColor(Color.argb(80, 255, 100, 100));
+
+ canvas.drawRect(mVisualizeGridRect, mVisualizeGridPaint);
+
+ mVisualizeGridPaint.setStyle(Paint.Style.STROKE);
+ mVisualizeGridPaint.setColor(Color.argb(255, 255, 100, 100));
+
+ canvas.drawRect(mVisualizeGridRect, mVisualizeGridPaint);
+ canvas.restore();
+ }
+ }
}
@Override
@@ -538,7 +534,7 @@
try {
dispatchRestoreInstanceState(states);
} catch (IllegalArgumentException ex) {
- if (FeatureFlags.IS_DOGFOOD_BUILD) {
+ if (FeatureFlags.IS_STUDIO_BUILD) {
throw ex;
}
// Mismatched viewId / viewType preventing restore. Skip restore on production builds.
@@ -773,13 +769,6 @@
int childWidthSize = widthSize - (getPaddingLeft() + getPaddingRight());
int childHeightSize = heightSize - (getPaddingTop() + getPaddingBottom());
- mShortcutsAndWidgets.setRotation(mRotationMode.surfaceRotation);
- if (mRotationMode.isTransposed) {
- int tmp = childWidthSize;
- childWidthSize = childHeightSize;
- childHeightSize = tmp;
- }
-
if (mFixedCellWidth < 0 || mFixedCellHeight < 0) {
int cw = DeviceProfile.calculateCellWidth(childWidthSize, mCountX);
int ch = DeviceProfile.calculateCellHeight(childHeightSize, mCountY);
@@ -830,15 +819,7 @@
right + mTempRect.right + getPaddingRight(),
bottom + mTempRect.bottom + getPaddingBottom());
- if (mRotationMode.isTransposed) {
- int halfW = mShortcutsAndWidgets.getMeasuredWidth() / 2;
- int halfH = mShortcutsAndWidgets.getMeasuredHeight() / 2;
- int cX = (left + right) / 2;
- int cY = (top + bottom) / 2;
- mShortcutsAndWidgets.layout(cX - halfW, cY - halfH, cX + halfW, cY + halfH);
- } else {
- mShortcutsAndWidgets.layout(left, top, right, bottom);
- }
+ mShortcutsAndWidgets.layout(left, top, right, bottom);
}
/**
@@ -847,8 +828,7 @@
* width in {@link DeviceProfile#calculateCellWidth(int, int)}.
*/
public int getUnusedHorizontalSpace() {
- return (mRotationMode.isTransposed ? getMeasuredHeight() : getMeasuredWidth())
- - getPaddingLeft() - getPaddingRight() - (mCountX * mCellWidth);
+ return getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - (mCountX * mCellWidth);
}
public Drawable getScrimBackground() {
@@ -949,8 +929,8 @@
return false;
}
- void visualizeDropLocation(View v, DragPreviewProvider outlineProvider, int cellX, int cellY,
- int spanX, int spanY, boolean resize, DropTarget.DragObject dragObject) {
+ void visualizeDropLocation(DraggableView v, DragPreviewProvider outlineProvider, int cellX, int
+ cellY, int spanX, int spanY, boolean resize, DropTarget.DragObject dragObject) {
final int oldDragCellX = mDragCell[0];
final int oldDragCellY = mDragCell[1];
@@ -960,9 +940,6 @@
Bitmap dragOutline = outlineProvider.generatedDragOutline;
if (cellX != oldDragCellX || cellY != oldDragCellY) {
- Point dragOffset = dragObject.dragView.getDragVisualizeOffset();
- Rect dragRegion = dragObject.dragView.getDragRegion();
-
mDragCell[0] = cellX;
mDragCell[1] = cellY;
@@ -971,50 +948,32 @@
mDragOutlineCurrent = (oldIndex + 1) % mDragOutlines.length;
Rect r = mDragOutlines[mDragOutlineCurrent];
+ cellToRect(cellX, cellY, spanX, spanY, r);
+ int left = r.left;
+ int top = r.top;
+
+ int width = dragOutline.getWidth();
+ int height = dragOutline.getHeight();
+
if (resize) {
- cellToRect(cellX, cellY, spanX, spanY, r);
- if (v instanceof LauncherAppWidgetHostView) {
- DeviceProfile profile = mActivity.getWallpaperDeviceProfile();
- Utilities.shrinkRect(r, profile.appWidgetScale.x, profile.appWidgetScale.y);
- }
- } else {
- // Find the top left corner of the rect the object will occupy
- final int[] topLeft = mTmpPoint;
- cellToPoint(cellX, cellY, topLeft);
-
- int left = topLeft[0];
- int top = topLeft[1];
-
- if (v != null && dragOffset == null) {
- // When drawing the drag outline, it did not account for margin offsets
- // added by the view's parent.
- MarginLayoutParams lp = (MarginLayoutParams) v.getLayoutParams();
- left += lp.leftMargin;
- top += lp.topMargin;
-
- // Offsets due to the size difference between the View and the dragOutline.
- // There is a size difference to account for the outer blur, which may lie
- // outside the bounds of the view.
- top += ((mCellHeight * spanY) - dragOutline.getHeight()) / 2;
- // We center about the x axis
- left += ((mCellWidth * spanX) - dragOutline.getWidth()) / 2;
- } else {
- if (dragOffset != null && dragRegion != null) {
- // Center the drag region *horizontally* in the cell and apply a drag
- // outline offset
- left += dragOffset.x + ((mCellWidth * spanX) - dragRegion.width()) / 2;
- int cHeight = getShortcutsAndWidgets().getCellContentHeight();
- int cellPaddingY = (int) Math.max(0, ((mCellHeight - cHeight) / 2f));
- top += dragOffset.y + cellPaddingY;
- } else {
- // Center the drag outline in the cell
- left += ((mCellWidth * spanX) - dragOutline.getWidth()) / 2;
- top += ((mCellHeight * spanY) - dragOutline.getHeight()) / 2;
- }
- }
- r.set(left, top, left + dragOutline.getWidth(), top + dragOutline.getHeight());
+ width = r.width();
+ height = r.height();
}
+ // Center horizontaly
+ left += ((mCellWidth * spanX) - dragOutline.getWidth()) / 2;
+
+ if (v != null && v.getViewType() == DraggableView.DRAGGABLE_WIDGET) {
+ // Center vertically
+ top += ((mCellHeight * spanY) - dragOutline.getHeight()) / 2;
+ } else if (v != null && v.getViewType() == DraggableView.DRAGGABLE_ICON) {
+ int cHeight = getShortcutsAndWidgets().getCellContentHeight();
+ int cellPaddingY = (int) Math.max(0, ((mCellHeight - cHeight) / 2f));
+ top += cellPaddingY;
+ }
+
+ r.set(left, top, left + width, top + height);
+
Utilities.scaleRectAboutCenter(r, mChildScale);
mDragOutlineAnims[mDragOutlineCurrent].setTag(dragOutline);
mDragOutlineAnims[mDragOutlineCurrent].animateIn();
@@ -1900,7 +1859,7 @@
// This method starts or changes the reorder preview animations
private void beginOrAdjustReorderPreviewAnimations(ItemConfiguration solution,
- View dragView, int delay, int mode) {
+ View dragView, int mode) {
int childCount = mShortcutsAndWidgets.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = mShortcutsAndWidgets.getChildAt(i);
@@ -1967,6 +1926,8 @@
this.child = child;
this.mode = mode;
+
+ // TODO issue!
setInitialAnimationValues(false);
finalScale = (mChildScale - (CHILD_DIVIDEND / child.getWidth())) * initScale;
finalDeltaX = initDeltaX;
@@ -2162,6 +2123,8 @@
*/
private void getDirectionVectorForDrop(int dragViewCenterX, int dragViewCenterY, int spanX,
int spanY, View dragView, int[] resultDirection) {
+
+ //TODO(adamcohen) b/151776141 use the items visual center for the direction vector
int[] targetDestination = new int[2];
findNearestArea(dragViewCenterX, dragViewCenterY, spanX, spanY, targetDestination);
@@ -2272,7 +2235,7 @@
setItemPlacementDirty(false);
} else {
beginOrAdjustReorderPreviewAnimations(swapSolution, dragView,
- REORDER_ANIMATION_DURATION, ReorderPreviewAnimation.MODE_PREVIEW);
+ ReorderPreviewAnimation.MODE_PREVIEW);
}
mShortcutsAndWidgets.requestLayout();
}
@@ -2326,7 +2289,7 @@
if (mode == MODE_SHOW_REORDER_HINT) {
if (finalSolution != null) {
- beginOrAdjustReorderPreviewAnimations(finalSolution, dragView, 0,
+ beginOrAdjustReorderPreviewAnimations(finalSolution, dragView,
ReorderPreviewAnimation.MODE_HINT);
result[0] = finalSolution.cellX;
result[1] = finalSolution.cellY;
@@ -2366,7 +2329,7 @@
setItemPlacementDirty(false);
} else {
beginOrAdjustReorderPreviewAnimations(finalSolution, dragView,
- REORDER_ANIMATION_DURATION, ReorderPreviewAnimation.MODE_PREVIEW);
+ ReorderPreviewAnimation.MODE_PREVIEW);
}
}
} else {
@@ -2783,6 +2746,36 @@
return false;
}
+ /**
+ * Finds solution to accept hotseat migration to cell layout. commits solution if commitConfig
+ */
+ public boolean makeSpaceForHotseatMigration(boolean commitConfig) {
+ int[] cellPoint = new int[2];
+ int[] directionVector = new int[]{0, -1};
+ cellToPoint(0, mCountY, cellPoint);
+ ItemConfiguration configuration = new ItemConfiguration();
+ if (findReorderSolution(cellPoint[0], cellPoint[1], mCountX, 1, mCountX, 1,
+ directionVector, null, false, configuration).isSolution) {
+ if (commitConfig) {
+ copySolutionToTempState(configuration, null);
+ commitTempPlacement();
+ // undo marking cells occupied since there is actually nothing being placed yet.
+ mOccupied.markCells(0, mCountY - 1, mCountX, 1, false);
+ }
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * returns a copy of cell layout's grid occupancy
+ */
+ public GridOccupancy cloneGridOccupancy() {
+ GridOccupancy occupancy = new GridOccupancy(mCountX, mCountY);
+ mOccupied.copyTo(occupancy);
+ return occupancy;
+ }
+
public boolean isRegionVacant(int x, int y, int spanX, int spanY) {
return mOccupied.isRegionVacant(x, y, spanX, spanY);
}
diff --git a/src/com/android/launcher3/CheckLongPressHelper.java b/src/com/android/launcher3/CheckLongPressHelper.java
index 639c173..ef353f9 100644
--- a/src/com/android/launcher3/CheckLongPressHelper.java
+++ b/src/com/android/launcher3/CheckLongPressHelper.java
@@ -16,46 +16,68 @@
package com.android.launcher3;
+import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
-import com.android.launcher3.util.Thunk;
-
+/**
+ * Utility class to handle tripper long press on a view with custom timeout and stylus event
+ */
public class CheckLongPressHelper {
public static final float DEFAULT_LONG_PRESS_TIMEOUT_FACTOR = 0.75f;
- @Thunk View mView;
- @Thunk View.OnLongClickListener mListener;
- @Thunk boolean mHasPerformedLongPress;
- private float mLongPressTimeoutFactor = DEFAULT_LONG_PRESS_TIMEOUT_FACTOR;
- private CheckForLongPress mPendingCheckForLongPress;
+ private final View mView;
+ private final View.OnLongClickListener mListener;
+ private final float mSlop;
- class CheckForLongPress implements Runnable {
- public void run() {
- if ((mView.getParent() != null) && mView.hasWindowFocus()
- && !mHasPerformedLongPress) {
- boolean handled;
- if (mListener != null) {
- handled = mListener.onLongClick(mView);
- } else {
- handled = mView.performLongClick();
- }
- if (handled) {
- mView.setPressed(false);
- mHasPerformedLongPress = true;
- }
- }
- }
- }
+ private float mLongPressTimeoutFactor = DEFAULT_LONG_PRESS_TIMEOUT_FACTOR;
+
+ private boolean mHasPerformedLongPress;
+
+ private Runnable mPendingCheckForLongPress;
public CheckLongPressHelper(View v) {
- mView = v;
+ this(v, null);
}
public CheckLongPressHelper(View v, View.OnLongClickListener listener) {
mView = v;
mListener = listener;
+ mSlop = ViewConfiguration.get(mView.getContext()).getScaledTouchSlop();
+ }
+
+ /**
+ * Handles the touch event on a view
+ *
+ * @see View#onTouchEvent(MotionEvent)
+ */
+ public void onTouchEvent(MotionEvent ev) {
+ switch (ev.getAction()) {
+ case MotionEvent.ACTION_DOWN: {
+ // Just in case the previous long press hasn't been cleared, we make sure to
+ // start fresh on touch down.
+ cancelLongPress();
+
+ postCheckForLongPress();
+ if (isStylusButtonPressed(ev)) {
+ triggerLongPress();
+ }
+ break;
+ }
+ case MotionEvent.ACTION_CANCEL:
+ case MotionEvent.ACTION_UP:
+ cancelLongPress();
+ break;
+ case MotionEvent.ACTION_MOVE:
+ if (!Utilities.pointInView(mView, ev.getX(), ev.getY(), mSlop)) {
+ cancelLongPress();
+ } else if (mPendingCheckForLongPress != null && isStylusButtonPressed(ev)) {
+ // Only trigger long press if it has not been cancelled before
+ triggerLongPress();
+ }
+ break;
+ }
}
/**
@@ -65,25 +87,64 @@
mLongPressTimeoutFactor = longPressTimeoutFactor;
}
- public void postCheckForLongPress() {
+ private void postCheckForLongPress() {
mHasPerformedLongPress = false;
if (mPendingCheckForLongPress == null) {
- mPendingCheckForLongPress = new CheckForLongPress();
+ mPendingCheckForLongPress = this::triggerLongPress;
}
mView.postDelayed(mPendingCheckForLongPress,
(long) (ViewConfiguration.getLongPressTimeout() * mLongPressTimeoutFactor));
}
+ /**
+ * Cancels any pending long press
+ */
public void cancelLongPress() {
mHasPerformedLongPress = false;
+ clearCallbacks();
+ }
+
+ /**
+ * Returns true if long press has been performed in the current touch gesture
+ */
+ public boolean hasPerformedLongPress() {
+ return mHasPerformedLongPress;
+ }
+
+ private void triggerLongPress() {
+ if ((mView.getParent() != null) && mView.hasWindowFocus() && !mHasPerformedLongPress) {
+ boolean handled;
+ if (mListener != null) {
+ handled = mListener.onLongClick(mView);
+ } else {
+ handled = mView.performLongClick();
+ }
+ if (handled) {
+ mView.setPressed(false);
+ mHasPerformedLongPress = true;
+ }
+ clearCallbacks();
+ }
+ }
+
+ private void clearCallbacks() {
if (mPendingCheckForLongPress != null) {
mView.removeCallbacks(mPendingCheckForLongPress);
mPendingCheckForLongPress = null;
}
}
- public boolean hasPerformedLongPress() {
- return mHasPerformedLongPress;
+
+ /**
+ * Identifies if the provided {@link MotionEvent} is a stylus with the primary stylus button
+ * pressed.
+ *
+ * @param event The event to check.
+ * @return Whether a stylus button press occurred.
+ */
+ private static boolean isStylusButtonPressed(MotionEvent event) {
+ return event.getToolType(0) == MotionEvent.TOOL_TYPE_STYLUS
+ && event.isButtonPressed(MotionEvent.BUTTON_SECONDARY);
}
}
diff --git a/src/com/android/launcher3/DeleteDropTarget.java b/src/com/android/launcher3/DeleteDropTarget.java
index 423f2bb..b4c5f96 100644
--- a/src/com/android/launcher3/DeleteDropTarget.java
+++ b/src/com/android/launcher3/DeleteDropTarget.java
@@ -28,6 +28,10 @@
import com.android.launcher3.dragndrop.DragOptions;
import com.android.launcher3.logging.LoggerUtils;
import com.android.launcher3.model.ModelWriter;
+import com.android.launcher3.model.data.FolderInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.userevent.nano.LauncherLogProto.ControlType;
import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
import com.android.launcher3.views.Snackbar;
@@ -67,7 +71,7 @@
public boolean supportsAccessibilityDrop(ItemInfo info, View view) {
if (info instanceof WorkspaceItemInfo) {
// Support the action unless the item is in a context menu.
- return info.screenId >= 0;
+ return canRemove(info);
}
return (info instanceof LauncherAppWidgetInfo)
diff --git a/src/com/android/launcher3/DeviceProfile.java b/src/com/android/launcher3/DeviceProfile.java
index 0d71da4..0cc9a2c 100644
--- a/src/com/android/launcher3/DeviceProfile.java
+++ b/src/com/android/launcher3/DeviceProfile.java
@@ -76,9 +76,9 @@
public float workspaceSpringLoadShrinkFactor;
public final int workspaceSpringLoadedBottomSpace;
- // Drag handle
- public final int verticalDragHandleSizePx;
- private final int verticalDragHandleOverlapWorkspace;
+ // Workspace page indicator
+ public final int workspacePageIndicatorHeight;
+ private final int mWorkspacePageIndicatorOverlapWorkspace;
// Workspace icons
public int iconSizePx;
@@ -190,10 +190,10 @@
cellLayoutBottomPaddingPx = 0;
}
- verticalDragHandleSizePx = res.getDimensionPixelSize(
- R.dimen.vertical_drag_handle_size);
- verticalDragHandleOverlapWorkspace =
- res.getDimensionPixelSize(R.dimen.vertical_drag_handle_overlap_workspace);
+ workspacePageIndicatorHeight = res.getDimensionPixelSize(
+ R.dimen.workspace_page_indicator_height);
+ mWorkspacePageIndicatorOverlapWorkspace =
+ res.getDimensionPixelSize(R.dimen.workspace_page_indicator_overlap_workspace);
iconDrawablePaddingOriginalPx =
res.getDimensionPixelSize(R.dimen.dynamic_grid_icon_drawable_padding);
@@ -211,7 +211,7 @@
hotseatBarSidePaddingEndPx =
res.getDimensionPixelSize(R.dimen.dynamic_grid_hotseat_side_padding);
// Add a bit of space between nav bar and hotseat in vertical bar layout.
- hotseatBarSidePaddingStartPx = isVerticalBarLayout() ? verticalDragHandleSizePx : 0;
+ hotseatBarSidePaddingStartPx = isVerticalBarLayout() ? workspacePageIndicatorHeight : 0;
hotseatBarSizePx = ResourceUtils.pxFromDp(inv.iconSize, dm) + (isVerticalBarLayout()
? (hotseatBarSidePaddingStartPx + hotseatBarSidePaddingEndPx)
: (res.getDimensionPixelSize(R.dimen.dynamic_grid_hotseat_extra_vertical_size)
@@ -227,7 +227,7 @@
// in portrait mode closer together by adding more height to the hotseat.
// Note: This calculation was created after noticing a pattern in the design spec.
int extraSpace = getCellSize().y - iconSizePx - iconDrawablePaddingPx * 2
- - verticalDragHandleSizePx;
+ - workspacePageIndicatorHeight;
hotseatBarSizePx += extraSpace;
hotseatBarBottomPaddingPx += extraSpace;
@@ -376,7 +376,7 @@
if (!isVerticalLayout) {
int expectedWorkspaceHeight = availableHeightPx - hotseatBarSizePx
- - verticalDragHandleSizePx - edgeMarginPx;
+ - workspacePageIndicatorHeight - edgeMarginPx;
float minRequiredHeight = dropTargetBarSizePx + workspaceSpringLoadedBottomSpace;
workspaceSpringLoadShrinkFactor = Math.min(
res.getInteger(R.integer.config_workspaceSpringLoadShrinkPercentage) / 100.0f,
@@ -480,14 +480,14 @@
padding.bottom = edgeMarginPx;
if (isSeascape()) {
padding.left = hotseatBarSizePx;
- padding.right = verticalDragHandleSizePx;
+ padding.right = hotseatBarSidePaddingStartPx;
} else {
- padding.left = verticalDragHandleSizePx;
+ padding.left = hotseatBarSidePaddingStartPx;
padding.right = hotseatBarSizePx;
}
} else {
- int paddingBottom = hotseatBarSizePx + verticalDragHandleSizePx
- - verticalDragHandleOverlapWorkspace;
+ int paddingBottom = hotseatBarSizePx + workspacePageIndicatorHeight
+ - mWorkspacePageIndicatorOverlapWorkspace;
if (isTablet) {
// Pad the left and right of the workspace to ensure consistent spacing
// between all icons
@@ -554,7 +554,7 @@
mInsets.top + dropTargetBarSizePx + edgeMarginPx,
mInsets.left + availableWidthPx - edgeMarginPx,
mInsets.top + availableHeightPx - hotseatBarSizePx
- - verticalDragHandleSizePx - edgeMarginPx);
+ - workspacePageIndicatorHeight - edgeMarginPx);
}
}
diff --git a/src/com/android/launcher3/DropTarget.java b/src/com/android/launcher3/DropTarget.java
index a32fd12..0a0f9ad 100644
--- a/src/com/android/launcher3/DropTarget.java
+++ b/src/com/android/launcher3/DropTarget.java
@@ -23,7 +23,9 @@
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.dragndrop.DragOptions;
import com.android.launcher3.dragndrop.DragView;
+import com.android.launcher3.dragndrop.DraggableView;
import com.android.launcher3.folder.FolderNameProvider;
+import com.android.launcher3.model.data.ItemInfo;
/**
* Interface defining an object that can receive a drag.
@@ -59,9 +61,6 @@
/** Where the drag originated */
public DragSource dragSource = null;
- /** The object is part of an accessible drag operation */
- public boolean accessibleDrag;
-
/** Indicates that the drag operation was cancelled */
public boolean cancelled = false;
@@ -72,6 +71,10 @@
public FolderNameProvider folderNameProvider;
+ /** The source view (ie. icon, widget etc.) that is being dragged and which the
+ * DragView represents. May be an actual View class or a virtual stand-in */
+ public DraggableView originalView = null;
+
public DragObject(Context context) {
if (FeatureFlags.FOLDER_NAME_SUGGEST.get()) {
folderNameProvider = FolderNameProvider.newInstance(context);
diff --git a/src/com/android/launcher3/FastBitmapDrawable.java b/src/com/android/launcher3/FastBitmapDrawable.java
index a78159f..f96aafa 100644
--- a/src/com/android/launcher3/FastBitmapDrawable.java
+++ b/src/com/android/launcher3/FastBitmapDrawable.java
@@ -35,6 +35,7 @@
import com.android.launcher3.graphics.PlaceHolderIconDrawable;
import com.android.launcher3.icons.BitmapInfo;
+import com.android.launcher3.model.data.ItemInfoWithIcon;
public class FastBitmapDrawable extends Drawable {
diff --git a/src/com/android/launcher3/FocusHelper.java b/src/com/android/launcher3/FocusHelper.java
index 466b7b2..e5aecf7 100644
--- a/src/com/android/launcher3/FocusHelper.java
+++ b/src/com/android/launcher3/FocusHelper.java
@@ -25,6 +25,7 @@
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.folder.Folder;
import com.android.launcher3.folder.FolderPagedView;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.util.FocusLogic;
import com.android.launcher3.util.Thunk;
@@ -96,7 +97,7 @@
}
if (!(v.getParent() instanceof ShortcutAndWidgetContainer)) {
- if (FeatureFlags.IS_DOGFOOD_BUILD) {
+ if (FeatureFlags.IS_STUDIO_BUILD) {
throw new IllegalStateException("Parent of the focused item is not supported.");
} else {
return false;
diff --git a/src/com/android/launcher3/Hotseat.java b/src/com/android/launcher3/Hotseat.java
index b89e727..be941f2 100644
--- a/src/com/android/launcher3/Hotseat.java
+++ b/src/com/android/launcher3/Hotseat.java
@@ -16,23 +16,25 @@
package com.android.launcher3;
+import static com.android.launcher3.logging.LoggerUtils.newContainerTarget;
+
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
-import android.view.View;
import android.view.ViewDebug;
import android.view.ViewGroup;
import android.widget.FrameLayout;
-import com.android.launcher3.graphics.RotationMode;
import com.android.launcher3.logging.StatsLogUtils.LogContainerProvider;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.userevent.nano.LauncherLogProto;
import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
-import com.android.launcher3.views.Transposable;
-public class Hotseat extends CellLayout implements LogContainerProvider, Insettable, Transposable {
+import java.util.ArrayList;
+
+public class Hotseat extends CellLayout implements LogContainerProvider, Insettable {
@ViewDebug.ExportedProperty(category = "launcher")
private boolean mHasVerticalHotseat;
@@ -75,16 +77,18 @@
}
@Override
- public void fillInLogContainerData(View v, ItemInfo info, Target target, Target targetParent) {
- target.gridX = info.cellX;
- target.gridY = info.cellY;
- targetParent.containerType = LauncherLogProto.ContainerType.HOTSEAT;
+ public void fillInLogContainerData(ItemInfo childInfo, Target child,
+ ArrayList<Target> parents) {
+ child.rank = childInfo.rank;
+ child.gridX = childInfo.cellX;
+ child.gridY = childInfo.cellY;
+ parents.add(newContainerTarget(LauncherLogProto.ContainerType.HOTSEAT));
}
@Override
public void setInsets(Rect insets) {
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) getLayoutParams();
- DeviceProfile grid = mActivity.getWallpaperDeviceProfile();
+ DeviceProfile grid = mActivity.getDeviceProfile();
insets = grid.getInsets();
if (grid.isVerticalBarLayout()) {
@@ -112,9 +116,4 @@
public boolean onTouchEvent(MotionEvent event) {
return event.getY() > getCellHeight();
}
-
- @Override
- public RotationMode getRotationMode() {
- return Launcher.getLauncher(getContext()).getRotationMode();
- }
}
diff --git a/src/com/android/launcher3/InstallShortcutReceiver.java b/src/com/android/launcher3/InstallShortcutReceiver.java
index a5142d8..62c9b4d 100644
--- a/src/com/android/launcher3/InstallShortcutReceiver.java
+++ b/src/com/android/launcher3/InstallShortcutReceiver.java
@@ -46,6 +46,10 @@
import com.android.launcher3.icons.BitmapInfo;
import com.android.launcher3.icons.GraphicsUtils;
import com.android.launcher3.icons.LauncherIcons;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.pm.UserCache;
import com.android.launcher3.shortcuts.ShortcutKey;
import com.android.launcher3.shortcuts.ShortcutRequest;
diff --git a/src/com/android/launcher3/InvariantDeviceProfile.java b/src/com/android/launcher3/InvariantDeviceProfile.java
index 857db8e..7414a88 100644
--- a/src/com/android/launcher3/InvariantDeviceProfile.java
+++ b/src/com/android/launcher3/InvariantDeviceProfile.java
@@ -47,6 +47,7 @@
import androidx.annotation.VisibleForTesting;
import com.android.launcher3.graphics.IconShape;
+import com.android.launcher3.graphics.LauncherPreviewRenderer;
import com.android.launcher3.util.ConfigMonitor;
import com.android.launcher3.util.DefaultDisplay;
import com.android.launcher3.util.DefaultDisplay.Info;
@@ -156,9 +157,12 @@
@TargetApi(23)
private InvariantDeviceProfile(Context context) {
- String gridName = Utilities.getPrefs(context).getBoolean(GRID_OPTIONS_PREFERENCE_KEY, false)
- ? Utilities.getPrefs(context).getString(KEY_IDP_GRID_NAME, null)
- : null;
+ if (context instanceof LauncherPreviewRenderer.PreviewContext) {
+ throw new IllegalArgumentException(
+ "PreviewContext is passed into this IDP constructor");
+ }
+
+ String gridName = getCurrentGridName(context);
initGrid(context, gridName);
mConfigMonitor = new ConfigMonitor(context,
APPLY_CONFIG_AT_RUNTIME.get() ? this::onConfigChanged : this::killProcess);
@@ -182,6 +186,12 @@
initGrid(context, null, new Info(display));
}
+ public static String getCurrentGridName(Context context) {
+ return Utilities.getPrefs(context).getBoolean(GRID_OPTIONS_PREFERENCE_KEY, false)
+ ? Utilities.getPrefs(context).getString(KEY_IDP_GRID_NAME, null)
+ : null;
+ }
+
/**
* Retrieve system defined or RRO overriden icon shape.
*/
diff --git a/src/com/android/launcher3/ItemInfo.java b/src/com/android/launcher3/ItemInfo.java
deleted file mode 100644
index c99465c..0000000
--- a/src/com/android/launcher3/ItemInfo.java
+++ /dev/null
@@ -1,224 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open 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.launcher3;
-
-import android.content.ComponentName;
-import android.content.ContentValues;
-import android.content.Intent;
-import android.os.Process;
-import android.os.UserHandle;
-
-import androidx.annotation.Nullable;
-
-import com.android.launcher3.util.ContentWriter;
-
-/**
- * Represents an item in the launcher.
- */
-public class ItemInfo {
-
- public static final int NO_ID = -1;
-
- /**
- * The id in the settings database for this item
- */
- public int id = NO_ID;
-
- /**
- * One of {@link LauncherSettings.Favorites#ITEM_TYPE_APPLICATION},
- * {@link LauncherSettings.Favorites#ITEM_TYPE_SHORTCUT},
- * {@link LauncherSettings.Favorites#ITEM_TYPE_DEEP_SHORTCUT}
- * {@link LauncherSettings.Favorites#ITEM_TYPE_FOLDER},
- * {@link LauncherSettings.Favorites#ITEM_TYPE_APPWIDGET} or
- * {@link LauncherSettings.Favorites#ITEM_TYPE_CUSTOM_APPWIDGET}.
- */
- public int itemType;
-
- /**
- * The id of the container that holds this item. For the desktop, this will be
- * {@link LauncherSettings.Favorites#CONTAINER_DESKTOP}. For the all applications folder it
- * will be {@link #NO_ID} (since it is not stored in the settings DB). For user folders
- * it will be the id of the folder.
- */
- public int container = NO_ID;
-
- /**
- * Indicates the screen in which the shortcut appears if the container types is
- * {@link LauncherSettings.Favorites#CONTAINER_DESKTOP}. (i.e., ignore if the container type is
- * {@link LauncherSettings.Favorites#CONTAINER_HOTSEAT})
- */
- public int screenId = -1;
-
- /**
- * Indicates the X position of the associated cell.
- */
- public int cellX = -1;
-
- /**
- * Indicates the Y position of the associated cell.
- */
- public int cellY = -1;
-
- /**
- * Indicates the X cell span.
- */
- public int spanX = 1;
-
- /**
- * Indicates the Y cell span.
- */
- public int spanY = 1;
-
- /**
- * Indicates the minimum X cell span.
- */
- public int minSpanX = 1;
-
- /**
- * Indicates the minimum Y cell span.
- */
- public int minSpanY = 1;
-
- /**
- * Indicates the position in an ordered list.
- */
- public int rank = 0;
-
- /**
- * Title of the item
- */
- public CharSequence title;
-
- /**
- * Content description of the item.
- */
- public CharSequence contentDescription;
-
- public UserHandle user;
-
- public ItemInfo() {
- user = Process.myUserHandle();
- }
-
- ItemInfo(ItemInfo info) {
- copyFrom(info);
- }
-
- public void copyFrom(ItemInfo info) {
- id = info.id;
- cellX = info.cellX;
- cellY = info.cellY;
- spanX = info.spanX;
- spanY = info.spanY;
- rank = info.rank;
- screenId = info.screenId;
- itemType = info.itemType;
- container = info.container;
- user = info.user;
- contentDescription = info.contentDescription;
- }
-
- public Intent getIntent() {
- return null;
- }
-
- @Nullable
- public ComponentName getTargetComponent() {
- Intent intent = getIntent();
- if (intent != null) {
- return intent.getComponent();
- } else {
- return null;
- }
- }
-
- public void writeToValues(ContentWriter writer) {
- writer.put(LauncherSettings.Favorites.ITEM_TYPE, itemType)
- .put(LauncherSettings.Favorites.CONTAINER, container)
- .put(LauncherSettings.Favorites.SCREEN, screenId)
- .put(LauncherSettings.Favorites.CELLX, cellX)
- .put(LauncherSettings.Favorites.CELLY, cellY)
- .put(LauncherSettings.Favorites.SPANX, spanX)
- .put(LauncherSettings.Favorites.SPANY, spanY)
- .put(LauncherSettings.Favorites.RANK, rank);
- }
-
- public void readFromValues(ContentValues values) {
- itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
- container = values.getAsInteger(LauncherSettings.Favorites.CONTAINER);
- screenId = values.getAsInteger(LauncherSettings.Favorites.SCREEN);
- cellX = values.getAsInteger(LauncherSettings.Favorites.CELLX);
- cellY = values.getAsInteger(LauncherSettings.Favorites.CELLY);
- spanX = values.getAsInteger(LauncherSettings.Favorites.SPANX);
- spanY = values.getAsInteger(LauncherSettings.Favorites.SPANY);
- rank = values.getAsInteger(LauncherSettings.Favorites.RANK);
- }
-
- /**
- * Write the fields of this item to the DB
- */
- public void onAddToDatabase(ContentWriter writer) {
- if (screenId == Workspace.EXTRA_EMPTY_SCREEN_ID) {
- // We should never persist an item on the extra empty screen.
- throw new RuntimeException("Screen id should not be EXTRA_EMPTY_SCREEN_ID");
- }
-
- writeToValues(writer);
- writer.put(LauncherSettings.Favorites.PROFILE_ID, user);
- }
-
- @Override
- public final String toString() {
- return getClass().getSimpleName() + "(" + dumpProperties() + ")";
- }
-
- protected String dumpProperties() {
- return "id=" + id
- + " type=" + LauncherSettings.Favorites.itemTypeToString(itemType)
- + " container=" + LauncherSettings.Favorites.containerToString((int)container)
- + " screen=" + screenId
- + " cell(" + cellX + "," + cellY + ")"
- + " span(" + spanX + "," + spanY + ")"
- + " minSpan(" + minSpanX + "," + minSpanY + ")"
- + " rank=" + rank
- + " user=" + user
- + " title=" + title;
- }
-
- /**
- * Whether this item is disabled.
- */
- public boolean isDisabled() {
- return false;
- }
-
- public int getViewId() {
- // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
- // This cast is safe as long as the id < 0x00FFFFFF
- // Since we jail all the dynamically generated views, there should be no clashes
- // with any other views.
- return id;
- }
-
- /**
- * Returns if an Item is a predicted item
- */
- public boolean isPredictedItem() {
- return container == LauncherSettings.Favorites.CONTAINER_HOTSEAT_PREDICTION
- || container == LauncherSettings.Favorites.CONTAINER_PREDICTION;
- }
-}
diff --git a/src/com/android/launcher3/Launcher.java b/src/com/android/launcher3/Launcher.java
index 89c3b93..f69940b 100644
--- a/src/com/android/launcher3/Launcher.java
+++ b/src/com/android/launcher3/Launcher.java
@@ -30,7 +30,6 @@
import static com.android.launcher3.Utilities.postAsyncCallback;
import static com.android.launcher3.dragndrop.DragLayer.ALPHA_INDEX_LAUNCHER_LOAD;
import static com.android.launcher3.logging.LoggerUtils.newContainerTarget;
-import static com.android.launcher3.logging.LoggerUtils.newTarget;
import static com.android.launcher3.popup.SystemShortcut.APP_INFO;
import static com.android.launcher3.popup.SystemShortcut.INSTALL;
import static com.android.launcher3.popup.SystemShortcut.WIDGETS;
@@ -57,7 +56,6 @@
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Point;
-import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.CancellationSignal;
@@ -103,19 +101,24 @@
import com.android.launcher3.folder.Folder;
import com.android.launcher3.folder.FolderGridOrganizer;
import com.android.launcher3.folder.FolderIcon;
-import com.android.launcher3.graphics.RotationMode;
import com.android.launcher3.icons.IconCache;
import com.android.launcher3.keyboard.CustomActionsPopup;
import com.android.launcher3.keyboard.ViewGroupFocusHelper;
import com.android.launcher3.logging.FileLog;
import com.android.launcher3.logging.StatsLogUtils;
import com.android.launcher3.logging.UserEventDispatcher;
-import com.android.launcher3.logging.UserEventDispatcher.UserEventDelegate;
import com.android.launcher3.model.AppLaunchTracker;
import com.android.launcher3.model.BgDataModel.Callbacks;
import com.android.launcher3.model.ModelWriter;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.FolderInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
+import com.android.launcher3.model.data.PromiseAppInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.notification.NotificationListener;
import com.android.launcher3.pm.PinRequestHelper;
+import com.android.launcher3.pm.UserCache;
import com.android.launcher3.popup.PopupContainerWithArrow;
import com.android.launcher3.popup.PopupDataProvider;
import com.android.launcher3.popup.SystemShortcut;
@@ -126,7 +129,6 @@
import com.android.launcher3.touch.AllAppsSwipeController;
import com.android.launcher3.touch.ItemClickHandler;
import com.android.launcher3.uioverrides.plugins.PluginManagerWrapper;
-import com.android.launcher3.userevent.nano.LauncherLogProto;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action;
import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
@@ -137,9 +139,11 @@
import com.android.launcher3.util.ItemInfoMatcher;
import com.android.launcher3.util.MultiValueAlpha;
import com.android.launcher3.util.MultiValueAlpha.AlphaProperty;
+import com.android.launcher3.util.OnboardingPrefs;
import com.android.launcher3.util.PackageManagerHelper;
import com.android.launcher3.util.PackageUserKey;
import com.android.launcher3.util.PendingRequestArgs;
+import com.android.launcher3.util.SafeCloseable;
import com.android.launcher3.util.ShortcutUtil;
import com.android.launcher3.util.SystemUiController;
import com.android.launcher3.util.Themes;
@@ -183,8 +187,7 @@
* Default launcher application.
*/
public class Launcher extends BaseDraggingActivity implements LauncherExterns,
- Callbacks, UserEventDelegate,
- InvariantDeviceProfile.OnIDPChangeListener, PluginListener<OverlayPlugin> {
+ Callbacks, InvariantDeviceProfile.OnIDPChangeListener, PluginListener<OverlayPlugin> {
public static final String TAG = "Launcher";
public static final ActivityTracker<Launcher> ACTIVITY_TRACKER = new ActivityTracker<>();
@@ -298,6 +301,7 @@
// We only want to get the SharedPreferences once since it does an FS stat each time we get
// it from the context.
private SharedPreferences mSharedPrefs;
+ private OnboardingPrefs mOnboardingPrefs;
// Activity result which needs to be processed after workspace has loaded.
private ActivityResultInfo mPendingActivityResult;
@@ -319,14 +323,16 @@
private float mCurrentAssistantVisibility = 0f;
- private DeviceProfile mStableDeviceProfile;
- private RotationMode mRotationMode = RotationMode.NORMAL;
-
protected LauncherOverlayManager mOverlayManager;
// If true, overlay callbacks are deferred
private boolean mDeferOverlayCallbacks;
private final Runnable mDeferredOverlayCallbacks = this::checkIfOverlayStillDeferred;
+ private long mLastTouchUpTime = -1;
+ private boolean mTouchInProgress;
+
+ private SafeCloseable mUserChangedCallbackCloseable;
+
@Override
protected void onCreate(Bundle savedInstanceState) {
Object traceToken = TraceHelper.INSTANCE.beginSection(ON_CREATE_EVT,
@@ -363,6 +369,8 @@
mAllAppsController = new AllAppsTransitionController(this);
mStateManager = new LauncherStateManager(this);
+ mOnboardingPrefs = createOnboardingPrefs(mSharedPrefs, mStateManager);
+
mAppWidgetManager = new WidgetManagerHelper(this);
mAppWidgetHost = new LauncherAppWidgetHost(this,
appWidgetId -> getWorkspace().removeWidget(appWidgetId));
@@ -445,12 +453,24 @@
});
TraceHelper.INSTANCE.endSection(traceToken);
+
+ mUserChangedCallbackCloseable = UserCache.INSTANCE.get(this).addUserChangeListener(
+ () -> getStateManager().goToState(NORMAL));
}
protected LauncherOverlayManager getDefaultOverlay() {
return new LauncherOverlayManager() { };
}
+ protected OnboardingPrefs createOnboardingPrefs(SharedPreferences sharedPrefs,
+ LauncherStateManager stateManager) {
+ return new OnboardingPrefs<>(this, sharedPrefs, stateManager);
+ }
+
+ public OnboardingPrefs getOnboardingPrefs() {
+ return mOnboardingPrefs;
+ }
+
@Override
public void onPluginConnected(OverlayPlugin overlayManager, Context context) {
switchOverlay(() -> overlayManager.createOverlayManager(this, this));
@@ -482,7 +502,6 @@
@Override
public void onEnterAnimationComplete() {
super.onEnterAnimationComplete();
- mAllAppsController.highlightWorkTabIfNecessary();
mRotationHelper.setCurrentTransitionRequest(REQUEST_NONE);
}
@@ -498,24 +517,12 @@
super.onConfigurationChanged(newConfig);
}
- public void reload() {
- onIdpChanged(mDeviceProfile.inv);
- }
-
- private boolean supportsFakeLandscapeUI() {
- return FeatureFlags.FAKE_LANDSCAPE_UI.get() && !mRotationHelper.homeScreenCanRotate();
- }
-
@Override
public void reapplyUi() {
reapplyUi(true /* cancelCurrentAnimation */);
}
public void reapplyUi(boolean cancelCurrentAnimation) {
- if (supportsFakeLandscapeUI()) {
- mRotationMode = mStableDeviceProfile == null
- ? RotationMode.NORMAL : getFakeRotationMode(mDeviceProfile);
- }
getRootView().dispatchInsets();
getStateManager().reapplyState(cancelCurrentAnimation);
}
@@ -528,7 +535,6 @@
private void onIdpChanged(InvariantDeviceProfile idp) {
mUserEventDispatcher = null;
- DeviceProfile oldWallpaperProfile = getWallpaperDeviceProfile();
initDeviceProfile(idp);
dispatchDeviceProfileChanged();
reapplyUi();
@@ -537,9 +543,7 @@
// Calling onSaveInstanceState ensures that static cache used by listWidgets is
// initialized properly.
onSaveInstanceState(new Bundle());
- if (oldWallpaperProfile != getWallpaperDeviceProfile()) {
- mModel.rebindCallbacks();
- }
+ mModel.rebindCallbacks();
}
public void onAssistantVisibilityChanged(float visibility) {
@@ -566,41 +570,8 @@
mDeviceProfile = mDeviceProfile.getMultiWindowProfile(this, mwSize);
}
- if (supportsFakeLandscapeUI() && mDeviceProfile.isVerticalBarLayout()) {
- mStableDeviceProfile = mDeviceProfile.inv.portraitProfile;
- mRotationMode = getFakeRotationMode(mDeviceProfile);
- } else {
- mStableDeviceProfile = null;
- mRotationMode = RotationMode.NORMAL;
- }
-
- mRotationHelper.updateRotationAnimation();
onDeviceProfileInitiated();
- mModelWriter = mModel.getWriter(getWallpaperDeviceProfile().isVerticalBarLayout(), true);
- }
-
- public void updateInsets(Rect insets) {
- mDeviceProfile.updateInsets(insets);
- if (mStableDeviceProfile != null) {
- Rect r = mStableDeviceProfile.getInsets();
- mRotationMode.mapInsets(this, insets, r);
- mStableDeviceProfile.updateInsets(r);
- }
- }
-
- @Override
- public RotationMode getRotationMode() {
- return mRotationMode;
- }
-
- /**
- * Device profile to be used by UI elements which are shown directly on top of the wallpaper
- * and whose presentation is tied to the wallpaper (and physical device) and not the activity
- * configuration.
- */
- @Override
- public DeviceProfile getWallpaperDeviceProfile() {
- return mStableDeviceProfile == null ? mDeviceProfile : mStableDeviceProfile;
+ mModelWriter = mModel.getWriter(getDeviceProfile().isVerticalBarLayout(), true);
}
public RotationHelper getRotationHelper() {
@@ -747,8 +718,8 @@
data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) : -1;
if (resultCode == RESULT_CANCELED) {
completeTwoStageWidgetDrop(RESULT_CANCELED, appWidgetId, requestArgs);
- mWorkspace.removeExtraEmptyScreenDelayed(true, exitSpringLoaded,
- ON_ACTIVITY_RESULT_ANIMATION_DELAY, false);
+ mWorkspace.removeExtraEmptyScreenDelayed(
+ ON_ACTIVITY_RESULT_ANIMATION_DELAY, false, exitSpringLoaded);
} else if (resultCode == RESULT_OK) {
addAppWidgetImpl(
appWidgetId, requestArgs, null,
@@ -778,15 +749,9 @@
"returned from the widget configuration activity.");
result = RESULT_CANCELED;
completeTwoStageWidgetDrop(result, appWidgetId, requestArgs);
- final Runnable onComplete = new Runnable() {
- @Override
- public void run() {
- getStateManager().goToState(NORMAL);
- }
- };
-
- mWorkspace.removeExtraEmptyScreenDelayed(true, onComplete,
- ON_ACTIVITY_RESULT_ANIMATION_DELAY, false);
+ mWorkspace.removeExtraEmptyScreenDelayed(
+ ON_ACTIVITY_RESULT_ANIMATION_DELAY, false,
+ () -> getStateManager().goToState(NORMAL));
} else {
if (requestArgs.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
// When the screen id represents an actual screen (as opposed to a rank)
@@ -805,8 +770,8 @@
dropLayout.setDropPending(false);
}
};
- mWorkspace.removeExtraEmptyScreenDelayed(true, onComplete,
- ON_ACTIVITY_RESULT_ANIMATION_DELAY, false);
+ mWorkspace.removeExtraEmptyScreenDelayed(
+ ON_ACTIVITY_RESULT_ANIMATION_DELAY, false, onComplete);
}
return;
}
@@ -825,14 +790,15 @@
// Handle custom shortcuts created using ACTION_CREATE_SHORTCUT.
if (resultCode == RESULT_OK && requestArgs.container != ItemInfo.NO_ID) {
completeAdd(requestCode, data, -1, requestArgs);
- mWorkspace.removeExtraEmptyScreenDelayed(true, exitSpringLoaded,
- ON_ACTIVITY_RESULT_ANIMATION_DELAY, false);
+ mWorkspace.removeExtraEmptyScreenDelayed(
+ ON_ACTIVITY_RESULT_ANIMATION_DELAY, false, exitSpringLoaded);
} else if (resultCode == RESULT_CANCELED) {
- mWorkspace.removeExtraEmptyScreenDelayed(true, exitSpringLoaded,
- ON_ACTIVITY_RESULT_ANIMATION_DELAY, false);
+ mWorkspace.removeExtraEmptyScreenDelayed(
+ ON_ACTIVITY_RESULT_ANIMATION_DELAY, false, exitSpringLoaded);
}
}
+
mDragLayer.clearAnimatedView();
}
@@ -923,6 +889,9 @@
@Override
protected void onStop() {
+ final boolean wasActive = isUserActive();
+ final LauncherState origState = getStateManager().getState();
+ final int origDragLayerChildCount = mDragLayer.getChildCount();
super.onStop();
if (mDeferOverlayCallbacks) {
@@ -940,6 +909,22 @@
// Workaround for b/78520668, explicitly trim memory once UI is hidden
onTrimMemory(TRIM_MEMORY_UI_HIDDEN);
+
+ if (wasActive) {
+ // The expected condition is that this activity is stopped because the device goes to
+ // sleep and the UI may have noticeable changes.
+ mDragLayer.post(() -> {
+ if ((!getStateManager().isInStableState(origState)
+ // The drag layer may be animating (e.g. dismissing QSB).
+ || mDragLayer.getAlpha() < 1
+ // Maybe an ArrowPopup is closed.
+ || mDragLayer.getChildCount() != origDragLayerChildCount)) {
+ onUiChangedWhileSleeping();
+ }
+ });
+ }
+
+ TestLogging.recordEvent(TestProtocol.SEQUENCE_MAIN, "Activity.onStop");
}
@Override
@@ -953,6 +938,7 @@
mAppWidgetHost.setListenIfResumed(true);
TraceHelper.INSTANCE.endSection(traceToken);
+ TestLogging.recordEvent(TestProtocol.SEQUENCE_MAIN, "Activity.onStart");
}
private void handleDeferredResume() {
@@ -1082,7 +1068,7 @@
super.onPause();
mDragController.cancelDrag();
- mDragController.resetLastGestureUpTime();
+ mLastTouchUpTime = -1;
mDropTargetBar.animateToVisibility(false);
if (!mDeferOverlayCallbacks) {
@@ -1171,10 +1157,9 @@
mScrimView = findViewById(R.id.scrim_view);
// Setup the drag controller (drop targets have to be added in reverse order in priority)
- mDragController.setMoveTarget(mWorkspace);
mDropTargetBar.setup(mDragController);
- mAllAppsController.setupViews(mAppsView);
+ mAllAppsController.setupViews(mAppsView, mScrimView);
}
/**
@@ -1334,11 +1319,16 @@
// Reset AllApps to its initial state only if we are not in the middle of
// processing a multi-step drop
if (mPendingRequestArgs == null) {
+ if (!isInState(NORMAL)) {
+ onUiChangedWhileSleeping();
+ }
mStateManager.goToState(NORMAL);
}
}
};
+ protected void onUiChangedWhileSleeping() { }
+
private void updateNotificationDots(Predicate<PackageUserKey> updatedDots) {
mWorkspace.updateNotificationDots(updatedDots);
mAppsView.getAppsStore().updateNotificationDots(updatedDots);
@@ -1391,6 +1381,10 @@
return mDropTargetBar;
}
+ public ScrimView getScrimView() {
+ return mScrimView;
+ }
+
public LauncherAppWidgetHost getAppWidgetHost() {
return mAppWidgetHost;
}
@@ -1438,7 +1432,7 @@
if (isActionMain) {
if (!internalStateHandled) {
// In all these cases, only animate if we're already on home
- AbstractFloatingView.closeAllOpenViews(this, isStarted());
+ closeOpenViews(isStarted());
if (!isInState(NORMAL)) {
// Only change state, if not already the same. This prevents cancelling any
@@ -1462,21 +1456,29 @@
target.pageIndex = mWorkspace.getCurrentPage();
ued.logActionCommand(Action.Command.HOME_INTENT, target,
newContainerTarget(ContainerType.WORKSPACE));
-
- final View v = getWindow().peekDecorView();
- if (v != null && v.getWindowToken() != null) {
- UiThreadHelper.hideKeyboardAsync(this, v.getWindowToken());
- }
+ hideKeyboard();
if (mLauncherCallbacks != null) {
mLauncherCallbacks.onHomeIntent(internalStateHandled);
}
mOverlayManager.hideOverlay(isStarted() && !isForceInvisible());
+ } else if (Intent.ACTION_ALL_APPS.equals(intent.getAction())) {
+ getStateManager().goToState(ALL_APPS, alreadyOnHome);
}
TraceHelper.INSTANCE.endSection(traceToken);
}
+ /**
+ * Hides the keyboard if visible
+ */
+ public void hideKeyboard() {
+ final View v = getWindow().peekDecorView();
+ if (v != null && v.getWindowToken() != null) {
+ UiThreadHelper.hideKeyboardAsync(this, v.getWindowToken());
+ }
+ }
+
@Override
public void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
@@ -1544,6 +1546,7 @@
mOverlayManager.onActivityDestroyed(this);
mAppTransitionManager.unregisterRemoteAnimations();
+ mUserChangedCallbackCloseable.close();
}
public LauncherAccessibilityDelegate getAccessibilityDelegate() {
@@ -1637,7 +1640,7 @@
};
completeAddAppWidget(appWidgetId, info, boundWidget,
addFlowHandler.getProviderInfo(this));
- mWorkspace.removeExtraEmptyScreenDelayed(true, onComplete, delay, false);
+ mWorkspace.removeExtraEmptyScreenDelayed(delay, false, onComplete);
}
}
@@ -1722,7 +1725,6 @@
public FolderIcon addFolder(CellLayout layout, int container, final int screenId, int cellX,
int cellY) {
final FolderInfo folderInfo = new FolderInfo();
- folderInfo.title = "";
// Update the model
getModelWriter().addItemToDatabase(folderInfo, container, screenId, cellX, cellY);
@@ -1789,20 +1791,34 @@
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
- if (Utilities.IS_RUNNING_IN_TEST_HARNESS) {
- TestLogging.recordEvent("Key event: " + event);
- }
+ TestLogging.recordEvent(TestProtocol.SEQUENCE_MAIN, "Key event", event);
return (event.getKeyCode() == KeyEvent.KEYCODE_HOME) || super.dispatchKeyEvent(event);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
- if (Utilities.IS_RUNNING_IN_TEST_HARNESS && ev.getAction() != MotionEvent.ACTION_MOVE) {
- TestLogging.recordEvent("Touch event: " + ev);
+ switch (ev.getAction()) {
+ case MotionEvent.ACTION_DOWN:
+ mTouchInProgress = true;
+ break;
+ case MotionEvent.ACTION_UP:
+ mLastTouchUpTime = System.currentTimeMillis();
+ // Follow through
+ case MotionEvent.ACTION_CANCEL:
+ mTouchInProgress = false;
+ break;
}
+ TestLogging.recordMotionEvent(TestProtocol.SEQUENCE_MAIN, "Touch event", ev);
return super.dispatchTouchEvent(ev);
}
+ /**
+ * Returns true if a touch interaction is in progress
+ */
+ public boolean isTouchInProgress() {
+ return mTouchInProgress;
+ }
+
@Override
public void onBackPressed() {
if (finishAutoCancelActionMode()) {
@@ -1866,24 +1882,6 @@
}
@Override
- public void modifyUserEvent(LauncherLogProto.LauncherEvent event) {
- if (event.srcTarget != null && event.srcTarget.length > 0 &&
- event.srcTarget[1].containerType == ContainerType.PREDICTION) {
- Target[] targets = new Target[3];
- targets[0] = event.srcTarget[0];
- targets[1] = event.srcTarget[1];
- targets[2] = newTarget(Target.Type.CONTAINER);
- event.srcTarget = targets;
- LauncherState state = mStateManager.getState();
- if (state == LauncherState.ALL_APPS) {
- event.srcTarget[2].containerType = ContainerType.ALLAPPS;
- } else if (state == OVERVIEW) {
- event.srcTarget[2].containerType = ContainerType.TASKSWITCHER;
- }
- }
- }
-
- @Override
public boolean startActivitySafely(View v, Intent intent, ItemInfo item,
@Nullable String sourceContainer) {
if (!hasBeenResumed()) {
@@ -2022,7 +2020,7 @@
mAppWidgetHost.clearViews();
if (mHotseat != null) {
- mHotseat.resetLayout(getWallpaperDeviceProfile().isVerticalBarLayout());
+ mHotseat.resetLayout(getDeviceProfile().isVerticalBarLayout());
}
TraceHelper.INSTANCE.endSection(traceToken);
}
@@ -2086,7 +2084,7 @@
}
// Remove the extra empty screen
- mWorkspace.removeExtraEmptyScreen(false, false);
+ mWorkspace.removeExtraEmptyScreen(false);
}
/**
@@ -2148,7 +2146,7 @@
Object tag = v.getTag();
String desc = "Collision while binding workspace item: " + item
+ ". Collides with " + tag;
- if (FeatureFlags.IS_DOGFOOD_BUILD) {
+ if (FeatureFlags.IS_STUDIO_BUILD) {
throw (new RuntimeException(desc));
} else {
Log.d(TAG, desc);
@@ -2183,7 +2181,7 @@
mWorkspace.postDelayed(new Runnable() {
public void run() {
if (mWorkspace != null) {
- AbstractFloatingView.closeAllOpenViews(Launcher.this, false);
+ closeOpenViews(false);
mWorkspace.snapToPage(newScreenIndex);
mWorkspace.postDelayed(startBounceAnimRunnable,
@@ -2303,6 +2301,13 @@
item.restoreStatus = LauncherAppWidgetInfo.RESTORE_COMPLETED;
getModelWriter().updateItemInDatabase(item);
}
+ else if (item.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_UI_NOT_READY)
+ && appWidgetInfo.configure != null) {
+ if (mAppWidgetManager.isAppWidgetRestored(item.appWidgetId)) {
+ item.restoreStatus = LauncherAppWidgetInfo.RESTORE_COMPLETED;
+ getModelWriter().updateItemInDatabase(item);
+ }
+ }
}
if (item.restoreStatus == LauncherAppWidgetInfo.RESTORE_COMPLETED) {
@@ -2316,6 +2321,11 @@
item.minSpanX = appWidgetInfo.minSpanX;
item.minSpanY = appWidgetInfo.minSpanY;
view = mAppWidgetHost.createView(this, item.appWidgetId, appWidgetInfo);
+ } else if (!item.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_ID_NOT_VALID)
+ && appWidgetInfo != null) {
+ mAppWidgetHost.addPendingView(item.appWidgetId,
+ new PendingAppWidgetHostView(this, item, mIconCache, false));
+ view = mAppWidgetHost.createView(this, item.appWidgetId, appWidgetInfo);
} else {
view = new PendingAppWidgetHostView(this, item, mIconCache, false);
}
@@ -2432,8 +2442,12 @@
}
private boolean canRunNewAppsAnimation() {
- long diff = System.currentTimeMillis() - mDragController.getLastGestureUpTime();
- return diff > (NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS * 1000);
+ if (mDragController.isDragging()) {
+ return false;
+ } else {
+ return (System.currentTimeMillis() - mLastTouchUpTime)
+ > (NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS * 1000);
+ }
}
private ValueAnimator createNewAppBounceAnimation(View v, int i) {
@@ -2564,9 +2578,10 @@
writer.println(prefix + "\tmRotationHelper: " + mRotationHelper);
writer.println(prefix + "\tmAppWidgetHost.isListening: " + mAppWidgetHost.isListening());
- // Extra logging for b/116853349
+ // Extra logging for general debugging
mDragLayer.dump(prefix, writer);
mStateManager.dump(prefix, writer);
+ mPopupDataProvider.dump(prefix, writer);
try {
FileLog.flushAll(writer);
@@ -2659,7 +2674,7 @@
if (!mDragController.isDragging() && !mWorkspace.isSwitchingState() &&
isInState(NORMAL)) {
// Close any open floating views.
- AbstractFloatingView.closeAllOpenViews(this);
+ closeOpenViews();
// Setting the touch point to (-1, -1) will show the options popup in the center of
// the screen.
@@ -2681,10 +2696,6 @@
return new TouchController[] {getDragController(), new AllAppsSwipeController(this)};
}
- protected RotationMode getFakeRotationMode(DeviceProfile deviceProfile) {
- return RotationMode.NORMAL;
- }
-
protected ScaleAndTranslation getOverviewScaleAndTranslationForNormalState() {
return new ScaleAndTranslation(1.1f, 0f, 0f);
}
@@ -2699,12 +2710,20 @@
getStateManager().goToState(LauncherState.NORMAL);
}
+ private void closeOpenViews() {
+ closeOpenViews(true);
+ }
+
+ protected void closeOpenViews(boolean animate) {
+ AbstractFloatingView.closeAllOpenViews(this, animate);
+ }
+
public Stream<SystemShortcut.Factory> getSupportedShortcuts() {
return Stream.of(APP_INFO, WIDGETS, INSTALL);
}
public static Launcher getLauncher(Context context) {
- return (Launcher) fromContext(context);
+ return fromContext(context);
}
/**
diff --git a/src/com/android/launcher3/LauncherAnimUtils.java b/src/com/android/launcher3/LauncherAnimUtils.java
index 32e9c14..d9cf7f1 100644
--- a/src/com/android/launcher3/LauncherAnimUtils.java
+++ b/src/com/android/launcher3/LauncherAnimUtils.java
@@ -18,7 +18,7 @@
import android.graphics.drawable.Drawable;
import android.util.FloatProperty;
-import android.util.Property;
+import android.util.IntProperty;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
@@ -32,15 +32,15 @@
// The progress of an animation to all apps must be at least this far along to snap to all apps.
public static final float MIN_PROGRESS_TO_ALL_APPS = 0.5f;
- public static final Property<Drawable, Integer> DRAWABLE_ALPHA =
- new Property<Drawable, Integer>(Integer.TYPE, "drawableAlpha") {
+ public static final IntProperty<Drawable> DRAWABLE_ALPHA =
+ new IntProperty<Drawable>("drawableAlpha") {
@Override
public Integer get(Drawable drawable) {
return drawable.getAlpha();
}
@Override
- public void set(Drawable drawable, Integer alpha) {
+ public void setValue(Drawable drawable, int alpha) {
drawable.setAlpha(alpha);
}
};
@@ -64,28 +64,28 @@
return (int) Utilities.boundToRange(Math.abs(velocity) / 2, 2f, 6f);
}
- public static final Property<LayoutParams, Integer> LAYOUT_WIDTH =
- new Property<LayoutParams, Integer>(Integer.TYPE, "width") {
+ public static final IntProperty<LayoutParams> LAYOUT_WIDTH =
+ new IntProperty<LayoutParams>("width") {
@Override
public Integer get(LayoutParams lp) {
return lp.width;
}
@Override
- public void set(LayoutParams lp, Integer width) {
+ public void setValue(LayoutParams lp, int width) {
lp.width = width;
}
};
- public static final Property<LayoutParams, Integer> LAYOUT_HEIGHT =
- new Property<LayoutParams, Integer>(Integer.TYPE, "height") {
+ public static final IntProperty<LayoutParams> LAYOUT_HEIGHT =
+ new IntProperty<LayoutParams>("height") {
@Override
public Integer get(LayoutParams lp) {
return lp.height;
}
@Override
- public void set(LayoutParams lp, Integer height) {
+ public void setValue(LayoutParams lp, int height) {
lp.height = height;
}
};
@@ -117,4 +117,18 @@
return view.getTranslationY();
}
};
+
+ public static final FloatProperty<View> VIEW_ALPHA =
+ View.ALPHA instanceof FloatProperty ? (FloatProperty) View.ALPHA
+ : new FloatProperty<View>("alpha") {
+ @Override
+ public void setValue(View view, float v) {
+ view.setAlpha(v);
+ }
+
+ @Override
+ public Float get(View view) {
+ return view.getAlpha();
+ }
+ };
}
diff --git a/src/com/android/launcher3/LauncherAppState.java b/src/com/android/launcher3/LauncherAppState.java
index 4cd038d..2f38037 100644
--- a/src/com/android/launcher3/LauncherAppState.java
+++ b/src/com/android/launcher3/LauncherAppState.java
@@ -27,6 +27,8 @@
import android.os.Handler;
import android.util.Log;
+import androidx.annotation.Nullable;
+
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.icons.IconCache;
import com.android.launcher3.icons.IconProvider;
@@ -55,12 +57,12 @@
private final IconCache mIconCache;
private final WidgetPreviewLoader mWidgetCache;
private final InvariantDeviceProfile mInvariantDeviceProfile;
- private final SecureSettingsObserver mNotificationDotsObserver;
- private final InstallSessionTracker mInstallSessionTracker;
- private final SimpleBroadcastReceiver mModelChangeReceiver;
- private final SafeCloseable mCalendarChangeTracker;
- private final SafeCloseable mUserChangeListener;
+ private SecureSettingsObserver mNotificationDotsObserver;
+ private InstallSessionTracker mInstallSessionTracker;
+ private SimpleBroadcastReceiver mModelChangeReceiver;
+ private SafeCloseable mCalendarChangeTracker;
+ private SafeCloseable mUserChangeListener;
public static LauncherAppState getInstance(final Context context) {
return INSTANCE.get(context);
@@ -74,15 +76,8 @@
return mContext;
}
- private LauncherAppState(Context context) {
- Log.v(Launcher.TAG, "LauncherAppState initiated");
- Preconditions.assertUIThread();
- mContext = context;
-
- mInvariantDeviceProfile = InvariantDeviceProfile.INSTANCE.get(mContext);
- mIconCache = new IconCache(mContext, mInvariantDeviceProfile);
- mWidgetCache = new WidgetPreviewLoader(mContext, mIconCache);
- mModel = new LauncherModel(this, mIconCache, AppFilter.newInstance(mContext));
+ public LauncherAppState(Context context) {
+ this(context, LauncherFiles.APP_ICONS_DB);
mModelChangeReceiver = new SimpleBroadcastReceiver(mModel::onBroadcastIntent);
@@ -91,7 +86,7 @@
Intent.ACTION_MANAGED_PROFILE_AVAILABLE,
Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE,
Intent.ACTION_MANAGED_PROFILE_UNLOCKED);
- if (FeatureFlags.IS_DOGFOOD_BUILD) {
+ if (FeatureFlags.IS_STUDIO_BUILD) {
mModelChangeReceiver.register(mContext, ACTION_FORCE_ROLOAD);
}
@@ -123,6 +118,17 @@
}
}
+ public LauncherAppState(Context context, @Nullable String iconCacheFileName) {
+ Log.v(Launcher.TAG, "LauncherAppState initiated");
+ Preconditions.assertUIThread();
+ mContext = context;
+
+ mInvariantDeviceProfile = InvariantDeviceProfile.INSTANCE.get(context);
+ mIconCache = new IconCache(mContext, mInvariantDeviceProfile, iconCacheFileName);
+ mWidgetCache = new WidgetPreviewLoader(mContext, mIconCache);
+ mModel = new LauncherModel(this, mIconCache, AppFilter.newInstance(mContext));
+ }
+
protected void onNotificationSettingsChanged(boolean areNotificationDotsEnabled) {
if (areNotificationDotsEnabled) {
NotificationListener.requestRebind(new ComponentName(
@@ -148,11 +154,19 @@
* Call from Application.onTerminate(), which is not guaranteed to ever be called.
*/
public void onTerminate() {
- mContext.unregisterReceiver(mModelChangeReceiver);
+ if (mModelChangeReceiver != null) {
+ mContext.unregisterReceiver(mModelChangeReceiver);
+ }
mContext.getSystemService(LauncherApps.class).unregisterCallback(mModel);
- mInstallSessionTracker.unregister();
- mCalendarChangeTracker.close();
- mUserChangeListener.close();
+ if (mInstallSessionTracker != null) {
+ mInstallSessionTracker.unregister();
+ }
+ if (mCalendarChangeTracker != null) {
+ mCalendarChangeTracker.close();
+ }
+ if (mUserChangeListener != null) {
+ mUserChangeListener.close();
+ }
CustomWidgetManager.INSTANCE.get(mContext).setWidgetRefreshCallback(null);
if (mNotificationDotsObserver != null) {
diff --git a/src/com/android/launcher3/LauncherAppWidgetHost.java b/src/com/android/launcher3/LauncherAppWidgetHost.java
index 4e29a95..9921f76 100644
--- a/src/com/android/launcher3/LauncherAppWidgetHost.java
+++ b/src/com/android/launcher3/LauncherAppWidgetHost.java
@@ -32,6 +32,7 @@
import com.android.launcher3.model.WidgetsModel;
import com.android.launcher3.widget.DeferredAppWidgetHostView;
import com.android.launcher3.widget.LauncherAppWidgetHostView;
+import com.android.launcher3.widget.PendingAppWidgetHostView;
import com.android.launcher3.widget.custom.CustomWidgetManager;
import java.util.ArrayList;
@@ -53,12 +54,14 @@
private final ArrayList<ProviderChangedListener> mProviderChangeListeners = new ArrayList<>();
private final SparseArray<LauncherAppWidgetHostView> mViews = new SparseArray<>();
+ private final SparseArray<PendingAppWidgetHostView> mPendingViews = new SparseArray<>();
private final Context mContext;
private int mFlags = FLAG_RESUMED;
private IntConsumer mAppWidgetRemovedCallback = null;
+
public LauncherAppWidgetHost(Context context) {
this(context, null);
}
@@ -73,7 +76,13 @@
@Override
protected LauncherAppWidgetHostView onCreateView(Context context, int appWidgetId,
AppWidgetProviderInfo appWidget) {
- LauncherAppWidgetHostView view = new LauncherAppWidgetHostView(context);
+ final LauncherAppWidgetHostView view;
+ if (mPendingViews.get(appWidgetId) != null) {
+ view = mPendingViews.get(appWidgetId);
+ mPendingViews.remove(appWidgetId);
+ } else {
+ view = new LauncherAppWidgetHostView(context);
+ }
mViews.put(appWidgetId, view);
return view;
}
@@ -189,6 +198,10 @@
}
}
+ void addPendingView(int appWidgetId, PendingAppWidgetHostView view) {
+ mPendingViews.put(appWidgetId, view);
+ }
+
public AppWidgetHostView createView(Context context, int appWidgetId,
LauncherAppWidgetProviderInfo appWidget) {
if (appWidget.isCustomWidget()) {
@@ -238,8 +251,8 @@
/**
* Called on an appWidget is removed for a widgetId
- * @param appWidgetId
- * TODO: make this override when SDK is updated
+ *
+ * @param appWidgetId TODO: make this override when SDK is updated
*/
public void onAppWidgetRemoved(int appWidgetId) {
if (mAppWidgetRemovedCallback == null) {
diff --git a/src/com/android/launcher3/LauncherAppWidgetProviderInfo.java b/src/com/android/launcher3/LauncherAppWidgetProviderInfo.java
index 56cce78..618b5de 100644
--- a/src/com/android/launcher3/LauncherAppWidgetProviderInfo.java
+++ b/src/com/android/launcher3/LauncherAppWidgetProviderInfo.java
@@ -13,6 +13,7 @@
import com.android.launcher3.icons.ComponentWithLabelAndIcon;
import com.android.launcher3.icons.IconCache;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
/**
* This class is a thin wrapper around the framework AppWidgetProviderInfo class. This class affords
diff --git a/src/com/android/launcher3/LauncherModel.java b/src/com/android/launcher3/LauncherModel.java
index efe85c7..3b1c7bb 100644
--- a/src/com/android/launcher3/LauncherModel.java
+++ b/src/com/android/launcher3/LauncherModel.java
@@ -17,7 +17,7 @@
package com.android.launcher3;
import static com.android.launcher3.LauncherAppState.ACTION_FORCE_ROLOAD;
-import static com.android.launcher3.config.FeatureFlags.IS_DOGFOOD_BUILD;
+import static com.android.launcher3.config.FeatureFlags.IS_STUDIO_BUILD;
import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
import static com.android.launcher3.util.PackageManagerHelper.hasShortcutsPermission;
@@ -51,11 +51,13 @@
import com.android.launcher3.model.PackageUpdatedTask;
import com.android.launcher3.model.ShortcutsChangedTask;
import com.android.launcher3.model.UserLockStateChangedTask;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.pm.InstallSessionTracker;
import com.android.launcher3.pm.PackageInstallInfo;
import com.android.launcher3.pm.UserCache;
import com.android.launcher3.shortcuts.ShortcutRequest;
-import com.android.launcher3.testing.TestProtocol;
import com.android.launcher3.util.IntSparseArrayMap;
import com.android.launcher3.util.ItemInfoMatcher;
import com.android.launcher3.util.LooperExecutor;
@@ -67,7 +69,6 @@
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
-import java.util.Optional;
import java.util.concurrent.CancellationException;
import java.util.concurrent.Executor;
import java.util.function.Supplier;
@@ -96,10 +97,6 @@
private boolean mModelLoaded;
public boolean isModelLoaded() {
synchronized (mLock) {
- if (TestProtocol.sDebugTracing) {
- Log.d(TestProtocol.LAUNCHER_DIDNT_INITIALIZE,
- "isModelLoaded: " + mModelLoaded + ", " + mLoaderTask);
- }
return mModelLoaded && mLoaderTask == null;
}
}
@@ -132,16 +129,6 @@
}
/**
- * Returns AppInfo with corresponding package name.
- * TODO: move to enqueueModelTask
- */
- public Optional<AppInfo> getAppInfoByPackageName(String pkg) {
- return mBgAllAppsList.data.stream()
- .filter(info -> info.componentName.getPackageName().equals(pkg))
- .findAny();
- }
-
- /**
* Adds the provided items to the workspace.
*/
public void addAndBindAddedWorkspaceItems(List<Pair<ItemInfo, Object>> itemList) {
@@ -169,7 +156,7 @@
public void onPackagesRemoved(UserHandle user, String... packages) {
int op = PackageUpdatedTask.OP_REMOVE;
- FileLog.d(TAG, "package removed received " + String.join("," + packages));
+ FileLog.d(TAG, "package removed received " + TextUtils.join(",", packages));
enqueueModelUpdateTask(new PackageUpdatedTask(op, user, packages));
}
@@ -251,10 +238,11 @@
// we need to run the state change task again.
if (Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE.equals(action) ||
Intent.ACTION_MANAGED_PROFILE_UNLOCKED.equals(action)) {
- enqueueModelUpdateTask(new UserLockStateChangedTask(user));
+ enqueueModelUpdateTask(new UserLockStateChangedTask(
+ user, Intent.ACTION_MANAGED_PROFILE_UNLOCKED.equals(action)));
}
}
- } else if (IS_DOGFOOD_BUILD && ACTION_FORCE_ROLOAD.equals(action)) {
+ } else if (IS_STUDIO_BUILD && ACTION_FORCE_ROLOAD.equals(action)) {
for (Callbacks cb : getCallbacks()) {
if (cb instanceof Launcher) {
((Launcher) cb).recreate();
@@ -372,9 +360,6 @@
public boolean stopLoader() {
synchronized (mLock) {
LoaderTask oldTask = mLoaderTask;
- if (TestProtocol.sDebugTracing) {
- Log.d(TestProtocol.LAUNCHER_DIDNT_INITIALIZE, "LauncherModel.stopLoader");
- }
mLoaderTask = null;
if (oldTask != null) {
oldTask.stopLocked();
@@ -388,10 +373,6 @@
synchronized (mLock) {
stopLoader();
mLoaderTask = new LoaderTask(mApp, mBgAllAppsList, mBgDataModel, results);
- if (TestProtocol.sDebugTracing) {
- Log.d(TestProtocol.LAUNCHER_DIDNT_INITIALIZE,
- "LauncherModel.startLoaderForResults " + mLoaderTask);
- }
// Always post the loader task, instead of running directly (even on same thread) so
// that we exit any nested synchronized blocks
@@ -493,10 +474,6 @@
public void close() {
synchronized (mLock) {
// If we are still the last one to be scheduled, remove ourselves.
- if (TestProtocol.sDebugTracing) {
- Log.d(TestProtocol.LAUNCHER_DIDNT_INITIALIZE,
- "LauncherModel.close " + mLoaderTask + ", " + mTask);
- }
if (mLoaderTask == mTask) {
mLoaderTask = null;
}
diff --git a/src/com/android/launcher3/LauncherProvider.java b/src/com/android/launcher3/LauncherProvider.java
index 5544240..8d20bd6 100644
--- a/src/com/android/launcher3/LauncherProvider.java
+++ b/src/com/android/launcher3/LauncherProvider.java
@@ -17,6 +17,7 @@
package com.android.launcher3;
import static com.android.launcher3.config.FeatureFlags.MULTI_DB_GRID_MIRATION_ALGO;
+import static com.android.launcher3.provider.LauncherDbUtils.copyTable;
import static com.android.launcher3.provider.LauncherDbUtils.dropTable;
import static com.android.launcher3.provider.LauncherDbUtils.tableExists;
import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
@@ -84,6 +85,7 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
+import java.util.function.Supplier;
public class LauncherProvider extends ContentProvider {
private static final String TAG = "LauncherProvider";
@@ -119,7 +121,7 @@
@Override
public boolean onCreate() {
- if (FeatureFlags.IS_DOGFOOD_BUILD) {
+ if (FeatureFlags.IS_STUDIO_BUILD) {
Log.d(TAG, "Launcher process started");
}
@@ -144,7 +146,7 @@
*/
protected synchronized void createDbIfNotExists() {
if (mOpenHelper == null) {
- mOpenHelper = new DatabaseHelper(getContext());
+ mOpenHelper = DatabaseHelper.createDatabaseHelper(getContext());
if (RestoreDbTask.isPending(getContext())) {
if (!RestoreDbTask.performRestore(getContext(), mOpenHelper,
@@ -158,14 +160,17 @@
}
}
- private synchronized boolean updateCurrentOpenHelper() {
- final InvariantDeviceProfile idp = InvariantDeviceProfile.INSTANCE.get(getContext());
- if (TextUtils.equals(idp.dbFile, mOpenHelper.getDatabaseName())) {
+ private synchronized boolean prepForMigration(String dbFile, String targetTableName,
+ Supplier<DatabaseHelper> src, Supplier<DatabaseHelper> dst) {
+ if (TextUtils.equals(dbFile, mOpenHelper.getDatabaseName())) {
return false;
}
- mOpenHelper.close();
- mOpenHelper = new DatabaseHelper(getContext());
+ final DatabaseHelper helper = src.get();
+ mOpenHelper = dst.get();
+ copyTable(helper.getReadableDatabase(), Favorites.TABLE_NAME,
+ mOpenHelper.getWritableDatabase(), targetTableName, getContext());
+ helper.close();
return true;
}
@@ -421,7 +426,23 @@
if (MULTI_DB_GRID_MIRATION_ALGO.get()) {
Bundle result = new Bundle();
result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
- updateCurrentOpenHelper());
+ prepForMigration(
+ InvariantDeviceProfile.INSTANCE.get(getContext()).dbFile,
+ Favorites.TMP_TABLE,
+ () -> mOpenHelper,
+ () -> DatabaseHelper.createDatabaseHelper(getContext())));
+ return result;
+ }
+ }
+ case LauncherSettings.Settings.METHOD_PREP_FOR_PREVIEW: {
+ if (MULTI_DB_GRID_MIRATION_ALGO.get()) {
+ Bundle result = new Bundle();
+ result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
+ prepForMigration(
+ arg /* dbFile */,
+ Favorites.PREVIEW_TABLE_NAME,
+ () -> DatabaseHelper.createDatabaseHelper(getContext(), arg),
+ () -> mOpenHelper));
return result;
}
}
@@ -592,23 +613,31 @@
private int mMaxScreenId = -1;
private boolean mBackupTableExists;
- DatabaseHelper(Context context) {
- this(context, MULTI_DB_GRID_MIRATION_ALGO.get() ? InvariantDeviceProfile.INSTANCE.get(
- context).dbFile : LauncherFiles.LAUNCHER_DB);
+ static DatabaseHelper createDatabaseHelper(Context context) {
+ return createDatabaseHelper(context, null);
+ }
+
+ static DatabaseHelper createDatabaseHelper(Context context, String dbName) {
+ if (dbName == null) {
+ dbName = MULTI_DB_GRID_MIRATION_ALGO.get() ? InvariantDeviceProfile.INSTANCE.get(
+ context).dbFile : LauncherFiles.LAUNCHER_DB;
+ }
+ DatabaseHelper databaseHelper = new DatabaseHelper(context, dbName);
// Table creation sometimes fails silently, which leads to a crash loop.
// This way, we will try to create a table every time after crash, so the device
// would eventually be able to recover.
- if (!tableExists(getReadableDatabase(), Favorites.TABLE_NAME)) {
+ if (!tableExists(databaseHelper.getReadableDatabase(), Favorites.TABLE_NAME)) {
Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
// This operation is a no-op if the table already exists.
- addFavoritesTable(getWritableDatabase(), true);
+ databaseHelper.addFavoritesTable(databaseHelper.getWritableDatabase(), true);
}
if (!MULTI_DB_GRID_MIRATION_ALGO.get()) {
- mBackupTableExists = tableExists(getReadableDatabase(),
- Favorites.BACKUP_TABLE_NAME);
+ databaseHelper.mBackupTableExists = tableExists(
+ databaseHelper.getReadableDatabase(), Favorites.BACKUP_TABLE_NAME);
}
- initIds();
+ databaseHelper.initIds();
+ return databaseHelper;
}
/**
diff --git a/src/com/android/launcher3/LauncherRootView.java b/src/com/android/launcher3/LauncherRootView.java
index 2b2224a..b4fbbc3 100644
--- a/src/com/android/launcher3/LauncherRootView.java
+++ b/src/com/android/launcher3/LauncherRootView.java
@@ -83,7 +83,7 @@
UI_STATE_ROOT_VIEW, drawInsetBar ? FLAG_DARK_NAV : 0);
// Update device profile before notifying th children.
- mLauncher.updateInsets(insets);
+ mLauncher.getDeviceProfile().updateInsets(insets);
boolean resetState = !insets.equals(mInsets);
setInsets(insets);
@@ -127,7 +127,7 @@
}
public void dispatchInsets() {
- mLauncher.updateInsets(mInsets);
+ mLauncher.getDeviceProfile().updateInsets(mInsets);
super.setInsets(mInsets);
}
diff --git a/src/com/android/launcher3/LauncherSettings.java b/src/com/android/launcher3/LauncherSettings.java
index 49831f6..d3af5fc 100644
--- a/src/com/android/launcher3/LauncherSettings.java
+++ b/src/com/android/launcher3/LauncherSettings.java
@@ -22,6 +22,8 @@
import android.os.Bundle;
import android.provider.BaseColumns;
+import com.android.launcher3.model.data.ItemInfo;
+
/**
* Settings related utilities.
*/
@@ -93,15 +95,37 @@
public static final String TABLE_NAME = "favorites";
/**
- * Backup table created when when the favorites table is modified during grid migration
+ * Backup table created when the favorites table is modified during grid migration
*/
public static final String BACKUP_TABLE_NAME = "favorites_bakup";
/**
- * The content:// style URL for this table
+ * Temporary table used specifically for grid migrations during wallpaper preview
*/
- public static final Uri CONTENT_URI = Uri.parse("content://" +
- LauncherProvider.AUTHORITY + "/" + TABLE_NAME);
+ public static final String PREVIEW_TABLE_NAME = "favorites_preview";
+
+ /**
+ * Temporary table used specifically for multi-db grid migrations
+ */
+ public static final String TMP_TABLE = "favorites_tmp";
+
+ /**
+ * The content:// style URL for "favorites" table
+ */
+ public static final Uri CONTENT_URI = Uri.parse("content://"
+ + LauncherProvider.AUTHORITY + "/" + TABLE_NAME);
+
+ /**
+ * The content:// style URL for "favorites_preview" table
+ */
+ public static final Uri PREVIEW_CONTENT_URI = Uri.parse("content://"
+ + LauncherProvider.AUTHORITY + "/" + PREVIEW_TABLE_NAME);
+
+ /**
+ * The content:// style URL for "favorites_tmp" table
+ */
+ public static final Uri TMP_CONTENT_URI = Uri.parse("content://"
+ + LauncherProvider.AUTHORITY + "/" + TMP_TABLE);
/**
* The content:// style URL for a given row, identified by its id.
@@ -111,8 +135,8 @@
* @return The unique content URL for the specified row.
*/
public static Uri getContentUri(int id) {
- return Uri.parse("content://" + LauncherProvider.AUTHORITY +
- "/" + TABLE_NAME + "/" + id);
+ return Uri.parse("content://" + LauncherProvider.AUTHORITY
+ + "/" + TABLE_NAME + "/" + id);
}
/**
@@ -129,7 +153,7 @@
public static final int CONTAINER_PREDICTION = -102;
public static final int CONTAINER_HOTSEAT_PREDICTION = -103;
- static final String containerToString(int container) {
+ public static final String containerToString(int container) {
switch (container) {
case CONTAINER_DESKTOP: return "desktop";
case CONTAINER_HOTSEAT: return "hotseat";
@@ -138,7 +162,7 @@
}
}
- static final String itemTypeToString(int type) {
+ public static final String itemTypeToString(int type) {
switch(type) {
case ITEM_TYPE_APPLICATION: return "APP";
case ITEM_TYPE_SHORTCUT: return "SHORTCUT";
@@ -304,10 +328,16 @@
public static final String METHOD_UPDATE_CURRENT_OPEN_HELPER = "update_current_open_helper";
+ public static final String METHOD_PREP_FOR_PREVIEW = "prep_for_preview";
+
public static final String EXTRA_VALUE = "value";
public static Bundle call(ContentResolver cr, String method) {
- return cr.call(CONTENT_URI, method, null, null);
+ return call(cr, method, null);
+ }
+
+ public static Bundle call(ContentResolver cr, String method, String arg) {
+ return cr.call(CONTENT_URI, method, arg, null);
}
}
}
diff --git a/src/com/android/launcher3/LauncherState.java b/src/com/android/launcher3/LauncherState.java
index 16be391..504666a 100644
--- a/src/com/android/launcher3/LauncherState.java
+++ b/src/com/android/launcher3/LauncherState.java
@@ -20,11 +20,6 @@
import static android.view.View.VISIBLE;
import static android.view.accessibility.AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_FADE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_SCALE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_TRANSLATE_X;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_WORKSPACE_FADE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_WORKSPACE_SCALE;
import static com.android.launcher3.anim.Interpolators.ACCEL;
import static com.android.launcher3.anim.Interpolators.ACCEL_2;
import static com.android.launcher3.anim.Interpolators.DEACCEL;
@@ -32,6 +27,11 @@
import static com.android.launcher3.anim.Interpolators.clampToProgress;
import static com.android.launcher3.config.FeatureFlags.ENABLE_OVERVIEW_ACTIONS;
import static com.android.launcher3.states.RotationHelper.REQUEST_NONE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_FADE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_SCALE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_TRANSLATE_X;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_WORKSPACE_FADE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_WORKSPACE_SCALE;
import static com.android.launcher3.testing.TestProtocol.ALL_APPS_STATE_ORDINAL;
import static com.android.launcher3.testing.TestProtocol.BACKGROUND_APP_STATE_ORDINAL;
import static com.android.launcher3.testing.TestProtocol.HINT_STATE_ORDINAL;
@@ -41,13 +41,14 @@
import static com.android.launcher3.testing.TestProtocol.QUICK_SWITCH_STATE_ORDINAL;
import static com.android.launcher3.testing.TestProtocol.SPRING_LOADED_STATE_ORDINAL;
+import android.content.Context;
import android.view.View;
import android.view.animation.Interpolator;
import com.android.launcher3.allapps.AllAppsContainerView;
-import com.android.launcher3.anim.AnimatorSetBuilder;
import com.android.launcher3.states.HintState;
import com.android.launcher3.states.SpringLoadedState;
+import com.android.launcher3.states.StateAnimationConfig;
import com.android.launcher3.uioverrides.states.AllAppsState;
import com.android.launcher3.uioverrides.states.OverviewState;
import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
@@ -72,7 +73,11 @@
public static final int ALL_APPS_HEADER_EXTRA = 1 << 3; // e.g. app predictions
public static final int ALL_APPS_CONTENT = 1 << 4;
public static final int VERTICAL_SWIPE_INDICATOR = 1 << 5;
- public static final int RECENTS_CLEAR_ALL_BUTTON = 1 << 6;
+ public static final int OVERVIEW_BUTTONS = 1 << 6;
+
+ /** Mask of all the items that are contained in the apps view. */
+ public static final int APPS_VIEW_ITEM_MASK =
+ HOTSEAT_SEARCH_BOX | ALL_APPS_HEADER | ALL_APPS_HEADER_EXTRA | ALL_APPS_CONTENT;
protected static final int FLAG_MULTI_PAGE = 1 << 0;
protected static final int FLAG_DISABLE_ACCESSIBILITY = 1 << 1;
@@ -265,6 +270,16 @@
return 0;
}
+ /**
+ * The amount of blur and wallpaper zoom to apply to the background of either the app
+ * or Launcher surface in this state. Should be a number between 0 and 1, inclusive.
+ *
+ * 0 means completely zoomed in, without blurs. 1 is zoomed out, with blurs.
+ */
+ public float getDepth(Context context) {
+ return 0f;
+ }
+
public String getDescription(Launcher launcher) {
return launcher.getWorkspace().getCurrentPageDescription();
}
@@ -312,13 +327,13 @@
* - Setting some start values (e.g. scale) for views that are hidden but about to be shown.
*/
public void prepareForAtomicAnimation(Launcher launcher, LauncherState fromState,
- AnimatorSetBuilder builder) {
+ StateAnimationConfig config) {
if (this == NORMAL && fromState == OVERVIEW) {
- builder.setInterpolator(ANIM_WORKSPACE_SCALE, DEACCEL);
- builder.setInterpolator(ANIM_WORKSPACE_FADE, ACCEL);
- builder.setInterpolator(ANIM_OVERVIEW_SCALE, clampToProgress(ACCEL, 0, 0.9f));
- builder.setInterpolator(ANIM_OVERVIEW_TRANSLATE_X, ACCEL);
- builder.setInterpolator(ANIM_OVERVIEW_FADE, DEACCEL_1_7);
+ config.setInterpolator(ANIM_WORKSPACE_SCALE, DEACCEL);
+ config.setInterpolator(ANIM_WORKSPACE_FADE, ACCEL);
+ config.setInterpolator(ANIM_OVERVIEW_SCALE, clampToProgress(ACCEL, 0, 0.9f));
+ config.setInterpolator(ANIM_OVERVIEW_TRANSLATE_X, ACCEL);
+ config.setInterpolator(ANIM_OVERVIEW_FADE, DEACCEL_1_7);
Workspace workspace = launcher.getWorkspace();
// Start from a higher workspace scale, but only if we're invisible so we don't jump.
@@ -350,7 +365,7 @@
}
} else if (this == NORMAL && fromState == OVERVIEW_PEEK) {
// Keep fully visible until the very end (when overview is offscreen) to make invisible.
- builder.setInterpolator(ANIM_OVERVIEW_FADE, t -> t < 1 ? 0 : 1);
+ config.setInterpolator(ANIM_OVERVIEW_FADE, t -> t < 1 ? 0 : 1);
}
}
diff --git a/src/com/android/launcher3/LauncherStateManager.java b/src/com/android/launcher3/LauncherStateManager.java
index 195e69b..e071777 100644
--- a/src/com/android/launcher3/LauncherStateManager.java
+++ b/src/com/android/launcher3/LauncherStateManager.java
@@ -17,26 +17,23 @@
package com.android.launcher3;
import static com.android.launcher3.LauncherState.NORMAL;
-import static com.android.launcher3.anim.PropertySetter.NO_ANIM_PROPERTY_SETTER;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_ALL_COMPONENTS;
import android.animation.Animator;
+import android.animation.Animator.AnimatorListener;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.os.Handler;
import android.os.Looper;
-import androidx.annotation.IntDef;
-
import com.android.launcher3.anim.AnimationSuccessListener;
import com.android.launcher3.anim.AnimatorPlaybackController;
-import com.android.launcher3.anim.AnimatorSetBuilder;
-import com.android.launcher3.anim.PropertySetter;
-import com.android.launcher3.anim.PropertySetter.AnimatedPropertySetter;
+import com.android.launcher3.anim.PendingAnimation;
import com.android.launcher3.compat.AccessibilityManagerCompat;
+import com.android.launcher3.states.StateAnimationConfig;
+import com.android.launcher3.states.StateAnimationConfig.AnimationFlags;
import java.io.PrintWriter;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
/**
@@ -84,26 +81,7 @@
public static final String TAG = "StateManager";
- // We separate the state animations into "atomic" and "non-atomic" components. The atomic
- // components may be run atomically - that is, all at once, instead of user-controlled. However,
- // atomic components are not restricted to this purpose; they can be user-controlled alongside
- // non atomic components as well. Note that each gesture model has exactly one atomic component,
- // ATOMIC_OVERVIEW_SCALE_COMPONENT *or* ATOMIC_OVERVIEW_PEEK_COMPONENT.
- @IntDef(flag = true, value = {
- NON_ATOMIC_COMPONENT,
- ATOMIC_OVERVIEW_SCALE_COMPONENT,
- ATOMIC_OVERVIEW_PEEK_COMPONENT,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface AnimationComponents {}
- public static final int NON_ATOMIC_COMPONENT = 1 << 0;
- public static final int ATOMIC_OVERVIEW_SCALE_COMPONENT = 1 << 1;
- public static final int ATOMIC_OVERVIEW_PEEK_COMPONENT = 1 << 2;
-
- public static final int ANIM_ALL = NON_ATOMIC_COMPONENT | ATOMIC_OVERVIEW_SCALE_COMPONENT
- | ATOMIC_OVERVIEW_PEEK_COMPONENT;
-
- private final AnimationConfig mConfig = new AnimationConfig();
+ private final AnimationState mConfig = new AnimationState();
private final Handler mUiHandler;
private final Launcher mLauncher;
private final ArrayList<StateListener> mListeners = new ArrayList<>();
@@ -138,7 +116,7 @@
writer.println(prefix + "\tmCurrentStableState:" + mCurrentStableState);
writer.println(prefix + "\tmState:" + mState);
writer.println(prefix + "\tmRestState:" + mRestState);
- writer.println(prefix + "\tisInTransition:" + (mConfig.mCurrentAnimation != null));
+ writer.println(prefix + "\tisInTransition:" + (mConfig.currentAnimation != null));
}
public StateHandler[] getStateHandlers() {
@@ -164,6 +142,15 @@
}
/**
+ * @return {@code true} if the state matches the current state and there is no active
+ * transition to different state.
+ */
+ public boolean isInStableState(LauncherState state) {
+ return mState == state && mCurrentStableState == state
+ && (mConfig.targetState == null || mConfig.targetState == state);
+ }
+
+ /**
* @see #goToState(LauncherState, boolean, Runnable)
*/
public void goToState(LauncherState state) {
@@ -207,12 +194,12 @@
}
public void reapplyState(boolean cancelCurrentAnimation) {
- boolean wasInAnimation = mConfig.mCurrentAnimation != null;
+ boolean wasInAnimation = mConfig.currentAnimation != null;
if (cancelCurrentAnimation) {
cancelAllStateElementAnimation();
cancelAnimation();
}
- if (mConfig.mCurrentAnimation == null) {
+ if (mConfig.currentAnimation == null) {
for (StateHandler handler : getStateHandlers()) {
handler.setState(mState);
}
@@ -226,21 +213,17 @@
final Runnable onCompleteRunnable) {
animated &= Utilities.areAnimationsEnabled(mLauncher);
if (mLauncher.isInState(state)) {
- if (mConfig.mCurrentAnimation == null) {
+ if (mConfig.currentAnimation == null) {
// Run any queued runnable
if (onCompleteRunnable != null) {
onCompleteRunnable.run();
}
return;
- } else if (!mConfig.userControlled && animated && mConfig.mTargetState == state) {
+ } else if (!mConfig.userControlled && animated && mConfig.targetState == state) {
// We are running the same animation as requested
if (onCompleteRunnable != null) {
- mConfig.mCurrentAnimation.addListener(new AnimationSuccessListener() {
- @Override
- public void onAnimationSuccess(Animator animator) {
- onCompleteRunnable.run();
- }
- });
+ mConfig.currentAnimation.addListener(
+ AnimationSuccessListener.forRunnable(onCompleteRunnable));
}
return;
}
@@ -269,9 +252,9 @@
if (delay > 0) {
// Create the animation after the delay as some properties can change between preparing
// the animation and running the animation.
- int startChangeId = mConfig.mChangeId;
+ int startChangeId = mConfig.changeId;
mUiHandler.postDelayed(() -> {
- if (mConfig.mChangeId == startChangeId) {
+ if (mConfig.changeId == startChangeId) {
goToStateAnimated(state, fromState, onCompleteRunnable);
}
}, delay);
@@ -287,11 +270,11 @@
mConfig.duration = state == NORMAL
? fromState.getTransitionDuration(mLauncher)
: state.getTransitionDuration(mLauncher);
-
- AnimatorSetBuilder builder = new AnimatorSetBuilder();
- prepareForAtomicAnimation(fromState, state, builder);
- AnimatorSet animation = createAnimationToNewWorkspaceInternal(
- state, builder, onCompleteRunnable);
+ prepareForAtomicAnimation(fromState, state, mConfig);
+ AnimatorSet animation = createAnimationToNewWorkspaceInternal(state).getAnim();
+ if (onCompleteRunnable != null) {
+ animation.addListener(AnimationSuccessListener.forRunnable(onCompleteRunnable));
+ }
mUiHandler.post(new StartAnimRunnable(animation));
}
@@ -301,44 +284,22 @@
* - Setting some start values (e.g. scale) for views that are hidden but about to be shown.
*/
public void prepareForAtomicAnimation(LauncherState fromState, LauncherState toState,
- AnimatorSetBuilder builder) {
- toState.prepareForAtomicAnimation(mLauncher, fromState, builder);
- }
-
- public AnimatorSet createAtomicAnimation(LauncherState fromState, LauncherState toState,
- AnimatorSetBuilder builder, @AnimationComponents int atomicComponent, long duration) {
- prepareForAtomicAnimation(fromState, toState, builder);
- AnimationConfig config = new AnimationConfig();
- config.animComponents = atomicComponent;
- config.duration = duration;
- for (StateHandler handler : mLauncher.getStateManager().getStateHandlers()) {
- handler.setStateWithAnimation(toState, builder, config);
- }
- return builder.build();
+ StateAnimationConfig config) {
+ toState.prepareForAtomicAnimation(mLauncher, fromState, config);
}
/**
- * Creates a {@link AnimatorPlaybackController} that can be used for a controlled
- * state transition. The UI is force-set to fromState before creating the controller.
- * @param fromState the initial state for the transition.
- * @param state the final state for the transition.
- * @param duration intended duration for normal playback. Use higher duration for better
- * accuracy.
+ * Creates an animation representing atomic transitions between the provided states
*/
- public AnimatorPlaybackController createAnimationToNewWorkspace(
- LauncherState fromState, LauncherState state, long duration) {
- // Since we are creating a state animation to a different state, temporarily prevent state
- // change as part of config reset.
- LauncherState originalRestState = mRestState;
- mRestState = state;
- mConfig.reset();
- mRestState = originalRestState;
+ public AnimatorSet createAtomicAnimation(
+ LauncherState fromState, LauncherState toState, StateAnimationConfig config) {
+ PendingAnimation builder = new PendingAnimation(config.duration);
+ prepareForAtomicAnimation(fromState, toState, config);
- for (StateHandler handler : getStateHandlers()) {
- handler.setState(fromState);
+ for (StateHandler handler : mLauncher.getStateManager().getStateHandlers()) {
+ handler.setStateWithAnimation(toState, config, builder);
}
-
- return createAnimationToNewWorkspace(state, duration);
+ return builder.getAnim();
}
/**
@@ -350,37 +311,33 @@
*/
public AnimatorPlaybackController createAnimationToNewWorkspace(
LauncherState state, long duration) {
- return createAnimationToNewWorkspace(state, duration, LauncherStateManager.ANIM_ALL);
+ return createAnimationToNewWorkspace(state, duration, ANIM_ALL_COMPONENTS);
}
public AnimatorPlaybackController createAnimationToNewWorkspace(
- LauncherState state, long duration, @AnimationComponents int animComponents) {
- return createAnimationToNewWorkspace(state, new AnimatorSetBuilder(), duration, null,
- animComponents);
+ LauncherState state, long duration, @AnimationFlags int animComponents) {
+ StateAnimationConfig config = new StateAnimationConfig();
+ config.duration = duration;
+ config.animFlags = animComponents;
+ return createAnimationToNewWorkspace(state, config);
}
public AnimatorPlaybackController createAnimationToNewWorkspace(LauncherState state,
- AnimatorSetBuilder builder, long duration, Runnable onCancelRunnable,
- @AnimationComponents int animComponents) {
+ StateAnimationConfig config) {
+ config.userControlled = true;
mConfig.reset();
- mConfig.userControlled = true;
- mConfig.animComponents = animComponents;
- mConfig.duration = duration;
- mConfig.playbackController = AnimatorPlaybackController.wrap(
- createAnimationToNewWorkspaceInternal(state, builder, null), duration,
- onCancelRunnable);
+ config.copyTo(mConfig);
+ mConfig.playbackController = createAnimationToNewWorkspaceInternal(state)
+ .createPlaybackController();
return mConfig.playbackController;
}
- protected AnimatorSet createAnimationToNewWorkspaceInternal(final LauncherState state,
- AnimatorSetBuilder builder, final Runnable onCompleteRunnable) {
-
+ private PendingAnimation createAnimationToNewWorkspaceInternal(final LauncherState state) {
+ PendingAnimation builder = new PendingAnimation(mConfig.duration);
for (StateHandler handler : getStateHandlers()) {
- handler.setStateWithAnimation(state, builder, mConfig);
+ handler.setStateWithAnimation(state, mConfig, builder);
}
-
- final AnimatorSet animation = builder.build();
- animation.addListener(new AnimationSuccessListener() {
+ builder.getAnim().addListener(new AnimationSuccessListener() {
@Override
public void onAnimationStart(Animator animation) {
@@ -390,15 +347,11 @@
@Override
public void onAnimationSuccess(Animator animator) {
- // Run any queued runnables
- if (onCompleteRunnable != null) {
- onCompleteRunnable.run();
- }
onStateTransitionEnd(state);
}
});
- mConfig.setAnimation(animation, state);
- return mConfig.mCurrentAnimation;
+ mConfig.setAnimation(builder.getAnim(), state);
+ return builder;
}
private void onStateTransitionStart(LauncherState state) {
@@ -445,7 +398,7 @@
}
public void moveToRestState() {
- if (mConfig.mCurrentAnimation != null && mConfig.userControlled) {
+ if (mConfig.currentAnimation != null && mConfig.userControlled) {
// The user is doing something. Lets not mess it up
return;
}
@@ -493,12 +446,12 @@
&& mConfig.playbackController.getTarget() == childAnim) {
clearCurrentAnimation();
break;
- } else if (mConfig.mCurrentAnimation == childAnim) {
+ } else if (mConfig.currentAnimation == childAnim) {
clearCurrentAnimation();
break;
}
}
- boolean reapplyNeeded = mConfig.mCurrentAnimation != null;
+ boolean reapplyNeeded = mConfig.currentAnimation != null;
cancelAnimation();
if (reapplyNeeded) {
reapplyState();
@@ -550,9 +503,9 @@
}
private void clearCurrentAnimation() {
- if (mConfig.mCurrentAnimation != null) {
- mConfig.mCurrentAnimation.removeListener(mConfig);
- mConfig.mCurrentAnimation = null;
+ if (mConfig.currentAnimation != null) {
+ mConfig.currentAnimation.removeListener(mConfig);
+ mConfig.currentAnimation = null;
}
mConfig.playbackController = null;
}
@@ -567,54 +520,42 @@
@Override
public void run() {
- if (mConfig.mCurrentAnimation != mAnim) {
+ if (mConfig.currentAnimation != mAnim) {
return;
}
mAnim.start();
}
}
- public static class AnimationConfig extends AnimatorListenerAdapter {
- public long duration;
- public boolean userControlled;
- public AnimatorPlaybackController playbackController;
- public @AnimationComponents int animComponents = ANIM_ALL;
- private PropertySetter mPropertySetter;
+ private static class AnimationState extends StateAnimationConfig implements AnimatorListener {
- private AnimatorSet mCurrentAnimation;
- private LauncherState mTargetState;
+ private static final StateAnimationConfig DEFAULT = new StateAnimationConfig();
+
+ public AnimatorPlaybackController playbackController;
+ public AnimatorSet currentAnimation;
+ public LauncherState targetState;
+
// Id to keep track of config changes, to tie an animation with the corresponding request
- private int mChangeId = 0;
+ public int changeId = 0;
/**
* Cancels the current animation and resets config variables.
*/
public void reset() {
- duration = 0;
- userControlled = false;
- animComponents = ANIM_ALL;
- mPropertySetter = null;
- mTargetState = null;
+ DEFAULT.copyTo(this);
+ targetState = null;
if (playbackController != null) {
playbackController.getAnimationPlayer().cancel();
playbackController.dispatchOnCancel();
- } else if (mCurrentAnimation != null) {
- mCurrentAnimation.setDuration(0);
- mCurrentAnimation.cancel();
+ } else if (currentAnimation != null) {
+ currentAnimation.setDuration(0);
+ currentAnimation.cancel();
}
- mCurrentAnimation = null;
+ currentAnimation = null;
playbackController = null;
- mChangeId ++;
- }
-
- public PropertySetter getPropertySetter(AnimatorSetBuilder builder) {
- if (mPropertySetter == null) {
- mPropertySetter = duration == 0 ? NO_ANIM_PROPERTY_SETTER
- : new AnimatedPropertySetter(duration, builder);
- }
- return mPropertySetter;
+ changeId++;
}
@Override
@@ -622,28 +563,25 @@
if (playbackController != null && playbackController.getTarget() == animation) {
playbackController = null;
}
- if (mCurrentAnimation == animation) {
- mCurrentAnimation = null;
+ if (currentAnimation == animation) {
+ currentAnimation = null;
}
}
public void setAnimation(AnimatorSet animation, LauncherState targetState) {
- mCurrentAnimation = animation;
- mTargetState = targetState;
- mCurrentAnimation.addListener(this);
+ currentAnimation = animation;
+ this.targetState = targetState;
+ currentAnimation.addListener(this);
}
- public boolean playAtomicOverviewScaleComponent() {
- return (animComponents & ATOMIC_OVERVIEW_SCALE_COMPONENT) != 0;
- }
+ @Override
+ public void onAnimationStart(Animator animator) { }
- public boolean playAtomicOverviewPeekComponent() {
- return (animComponents & ATOMIC_OVERVIEW_PEEK_COMPONENT) != 0;
- }
+ @Override
+ public void onAnimationCancel(Animator animator) { }
- public boolean playNonAtomicComponent() {
- return (animComponents & NON_ATOMIC_COMPONENT) != 0;
- }
+ @Override
+ public void onAnimationRepeat(Animator animator) { }
}
public interface StateHandler {
@@ -656,8 +594,8 @@
/**
* Sets the UI to {@param state} by animating any changes.
*/
- void setStateWithAnimation(LauncherState toState,
- AnimatorSetBuilder builder, AnimationConfig config);
+ void setStateWithAnimation(
+ LauncherState toState, StateAnimationConfig config, PendingAnimation animation);
}
public interface StateListener {
diff --git a/src/com/android/launcher3/PagedView.java b/src/com/android/launcher3/PagedView.java
index ae4eae9..5343424 100644
--- a/src/com/android/launcher3/PagedView.java
+++ b/src/com/android/launcher3/PagedView.java
@@ -20,6 +20,9 @@
import static com.android.launcher3.compat.AccessibilityManagerCompat.isObservedEventType;
import static com.android.launcher3.config.FeatureFlags.QUICKSTEP_SPRINGS;
import static com.android.launcher3.touch.OverScroll.OVERSCROLL_DAMP_FACTOR;
+import static com.android.launcher3.touch.PagedOrientationHandler.CANVAS_TRANSLATE;
+import static com.android.launcher3.touch.PagedOrientationHandler.VIEW_SCROLL_BY;
+import static com.android.launcher3.touch.PagedOrientationHandler.VIEW_SCROLL_TO;
import android.animation.LayoutTransition;
import android.animation.TimeInterpolator;
@@ -46,13 +49,18 @@
import android.view.animation.Interpolator;
import android.widget.ScrollView;
+import androidx.annotation.Nullable;
+
import com.android.launcher3.anim.Interpolators;
import com.android.launcher3.compat.AccessibilityManagerCompat;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.pageindicators.PageIndicator;
import com.android.launcher3.touch.OverScroll;
+import com.android.launcher3.touch.PagedOrientationHandler;
+import com.android.launcher3.touch.PagedOrientationHandler.ChildBounds;
import com.android.launcher3.util.OverScroller;
import com.android.launcher3.util.Thunk;
+import com.android.launcher3.views.ActivityContext;
import java.util.ArrayList;
@@ -97,8 +105,8 @@
@ViewDebug.ExportedProperty(category = "launcher")
protected int mNextPage = INVALID_PAGE;
- protected int mMinScrollX;
- protected int mMaxScrollX;
+ protected int mMaxScroll;
+ protected int mMinScroll;
protected OverScroller mScroller;
private Interpolator mDefaultInterpolator;
private VelocityTracker mVelocityTracker;
@@ -106,9 +114,11 @@
private float mDownMotionX;
private float mDownMotionY;
- private float mLastMotionX;
- private float mLastMotionXRemainder;
- private float mTotalMotionX;
+ private float mDownMotionPrimary;
+ private float mLastMotion;
+ private float mLastMotionRemainder;
+ private float mTotalMotion;
+ protected PagedOrientationHandler mOrientationHandler = PagedOrientationHandler.PORTRAIT;
protected int[] mPageScrolls;
private boolean mIsBeingDragged;
@@ -122,12 +132,13 @@
protected int mActivePointerId = INVALID_POINTER;
protected boolean mIsPageInTransition = false;
+ private Runnable mOnPageTransitionEndCallback;
- protected float mSpringOverScrollX;
+ protected float mSpringOverScroll;
protected boolean mWasInOverscroll = false;
- protected int mUnboundedScrollX;
+ protected int mUnboundedScroll;
// Page Indicator
@Thunk int mPageIndicatorViewId;
@@ -166,11 +177,12 @@
* Initializes various states for this workspace.
*/
protected void init() {
- mScroller = new OverScroller(getContext());
+ Context context = getContext();
+ mScroller = new OverScroller(context);
setDefaultInterpolator(Interpolators.SCROLL);
mCurrentPage = 0;
- final ViewConfiguration configuration = ViewConfiguration.get(getContext());
+ final ViewConfiguration configuration = ViewConfiguration.get(context);
mTouchSlop = configuration.getScaledPagingTouchSlop();
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
@@ -236,12 +248,12 @@
*/
protected void updateCurrentPageScroll() {
// If the current page is invalid, just reset the scroll position to zero
- int newX = 0;
+ int newPosition = 0;
if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
- newX = getScrollForPage(mCurrentPage);
+ newPosition = getScrollForPage(mCurrentPage);
}
- scrollTo(newX, 0);
- mScroller.startScroll(mScroller.getCurrPos(), newX - mScroller.getCurrPos());
+ mOrientationHandler.set(this, VIEW_SCROLL_TO, newPosition);
+ mOrientationHandler.scrollerStartScroll(mScroller, newPosition);
forceFinishScroller(true);
}
@@ -285,7 +297,7 @@
int dir = !mIsRtl ? 1 : - 1;
int currScroll = getScrollForPage(page);
int prevScroll;
- while (currScroll < mMinScrollX) {
+ while (currScroll < mMinScroll) {
page += dir;
prevScroll = currScroll;
currScroll = getScrollForPage(page);
@@ -294,7 +306,7 @@
break;
}
}
- while (currScroll > mMaxScrollX) {
+ while (currScroll > mMaxScroll) {
page -= dir;
prevScroll = currScroll;
currScroll = getScrollForPage(page);
@@ -374,47 +386,62 @@
protected void onPageEndTransition() {
mWasInOverscroll = false;
AccessibilityManagerCompat.sendScrollFinishedEventToTest(getContext());
+ AccessibilityManagerCompat.sendCustomAccessibilityEvent(getPageAt(mCurrentPage),
+ AccessibilityEvent.TYPE_VIEW_FOCUSED, null);
+ if (mOnPageTransitionEndCallback != null) {
+ mOnPageTransitionEndCallback.run();
+ mOnPageTransitionEndCallback = null;
+ }
}
- protected int getUnboundedScrollX() {
- return mUnboundedScrollX;
+ /**
+ * Sets a callback to run once when the scrolling finishes. If there is currently
+ * no page in transition, then the callback is called immediately.
+ */
+ public void setOnPageTransitionEndCallback(@Nullable Runnable callback) {
+ if (mIsPageInTransition || callback == null) {
+ mOnPageTransitionEndCallback = callback;
+ } else {
+ callback.run();
+ }
+ }
+
+ protected int getUnboundedScroll() {
+ return mUnboundedScroll;
}
@Override
public void scrollBy(int x, int y) {
- scrollTo(getUnboundedScrollX() + x, getScrollY() + y);
+ mOrientationHandler.delegateScrollBy(this, getUnboundedScroll(), x, y);
}
@Override
public void scrollTo(int x, int y) {
- mUnboundedScrollX = x;
+ int primaryScroll = mOrientationHandler.getPrimaryValue(x, y);
+ int secondaryScroll = mOrientationHandler.getSecondaryValue(x, y);
+ mUnboundedScroll = primaryScroll;
- boolean isXBeforeFirstPage = mIsRtl ? (x > mMaxScrollX) : (x < mMinScrollX);
- boolean isXAfterLastPage = mIsRtl ? (x < mMinScrollX) : (x > mMaxScrollX);
-
- if (!isXBeforeFirstPage && !isXAfterLastPage) {
- mSpringOverScrollX = 0;
+ boolean isBeforeFirstPage = mIsRtl ?
+ (primaryScroll > mMaxScroll) : (primaryScroll < mMinScroll);
+ boolean isAfterLastPage = mIsRtl ?
+ (primaryScroll < mMinScroll) : (primaryScroll > mMaxScroll);
+ if (!isBeforeFirstPage && !isAfterLastPage) {
+ mSpringOverScroll = 0;
}
- if (isXBeforeFirstPage) {
- super.scrollTo(mIsRtl ? mMaxScrollX : mMinScrollX, y);
+ if (isBeforeFirstPage) {
+ mOrientationHandler.delegateScrollTo(this,
+ secondaryScroll, mIsRtl ? mMaxScroll : mMinScroll);
if (mAllowOverScroll) {
mWasInOverscroll = true;
- if (mIsRtl) {
- overScroll(x - mMaxScrollX);
- } else {
- overScroll(x - mMinScrollX);
- }
+ overScroll(primaryScroll - (mIsRtl ? mMaxScroll : mMinScroll));
}
- } else if (isXAfterLastPage) {
- super.scrollTo(mIsRtl ? mMinScrollX : mMaxScrollX, y);
+ } else if (isAfterLastPage) {
+ mOrientationHandler.delegateScrollTo(this,
+ secondaryScroll, mIsRtl ? mMinScroll : mMaxScroll);
if (mAllowOverScroll) {
mWasInOverscroll = true;
- if (mIsRtl) {
- overScroll(x - mMinScrollX);
- } else {
- overScroll(x - mMaxScrollX);
- }
+ overScroll(primaryScroll - (mIsRtl ? mMinScroll : mMaxScroll));
}
} else {
if (mWasInOverscroll) {
@@ -423,7 +450,13 @@
}
super.scrollTo(x, y);
}
+ }
+ /**
+ * Helper for {@link PagedOrientationHandler} to be able to call parent's scrollTo method
+ */
+ public void superScrollTo(int x, int y) {
+ super.scrollTo(x, y);
}
private void sendScrollAccessibilityEvent() {
@@ -434,9 +467,7 @@
ev.setScrollable(true);
ev.setScrollX(getScrollX());
ev.setScrollY(getScrollY());
- ev.setMaxScrollX(mMaxScrollX);
- ev.setMaxScrollY(0);
-
+ mOrientationHandler.setMaxScroll(ev, mMaxScroll);
sendAccessibilityEventUnchecked(ev);
}
}
@@ -457,9 +488,10 @@
protected boolean computeScrollHelper(boolean shouldInvalidate) {
if (mScroller.computeScrollOffset()) {
// Don't bother scrolling if the page does not need to be moved
- if (getUnboundedScrollX() != mScroller.getCurrPos()
- || getScrollX() != mScroller.getCurrPos()) {
- scrollTo(mScroller.getCurrPos(), 0);
+ int currentScroll = mOrientationHandler.getPrimaryScroll(this);
+ if (mUnboundedScroll != mScroller.getCurrPos()
+ || currentScroll != mScroller.getCurrPos()) {
+ mOrientationHandler.set(this, VIEW_SCROLL_TO, mScroller.getCurrPos());
}
if (shouldInvalidate) {
invalidate();
@@ -578,7 +610,8 @@
if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
- if (getPageScrolls(mPageScrolls, true, SIMPLE_SCROLL_LOGIC)) {
+ boolean isScrollChanged = getPageScrolls(mPageScrolls, true, SIMPLE_SCROLL_LOGIC);
+ if (isScrollChanged) {
pageScrollChanged = true;
}
@@ -619,7 +652,6 @@
/**
* Initializes {@code outPageScrolls} with scroll positions for view at that index. The length
* of {@code outPageScrolls} should be same as the the childCount
- *
*/
protected boolean getPageScrolls(int[] outPageScrolls, boolean layoutChildren,
ComputePageScrollsLogic scrollLogic) {
@@ -629,36 +661,30 @@
final int endIndex = mIsRtl ? -1 : childCount;
final int delta = mIsRtl ? -1 : 1;
- final int verticalCenter = (getPaddingTop() + getMeasuredHeight() + mInsets.top
- - mInsets.bottom - getPaddingBottom()) / 2;
+ final int pageCenter = mOrientationHandler.getCenterForPage(this, mInsets);
- final int scrollOffsetLeft = mInsets.left + getPaddingLeft();
- final int scrollOffsetRight = getWidth() - getPaddingRight() - mInsets.right;
+ final int scrollOffsetStart = mOrientationHandler.getScrollOffsetStart(this, mInsets);
+ final int scrollOffsetEnd = mOrientationHandler.getScrollOffsetEnd(this, mInsets);
boolean pageScrollChanged = false;
- for (int i = startIndex, childLeft = scrollOffsetLeft; i != endIndex; i += delta) {
+ for (int i = startIndex, childStart = scrollOffsetStart; i != endIndex; i += delta) {
final View child = getPageAt(i);
if (scrollLogic.shouldIncludeView(child)) {
- final int childWidth = child.getMeasuredWidth();
- final int childRight = childLeft + childWidth;
-
- if (layoutChildren) {
- final int childHeight = child.getMeasuredHeight();
- final int childTop = verticalCenter - childHeight / 2;
- child.layout(childLeft, childTop, childRight, childTop + childHeight);
- }
+ ChildBounds bounds = mOrientationHandler.getChildBounds(child, childStart,
+ pageCenter, layoutChildren);
+ final int primaryDimension = bounds.primaryDimension;
+ final int childPrimaryEnd = bounds.childPrimaryEnd;
// In case the pages are of different width, align the page to left or right edge
// based on the orientation.
final int pageScroll = mIsRtl
- ? (childLeft - scrollOffsetLeft)
- : Math.max(0, childRight - scrollOffsetRight);
+ ? (childStart - scrollOffsetStart)
+ : Math.max(0, childPrimaryEnd - scrollOffsetEnd);
if (outPageScrolls[i] != pageScroll) {
pageScrollChanged = true;
outPageScrolls[i] = pageScroll;
}
-
- childLeft += childWidth + mPageSpacing + getChildGap();
+ childStart += primaryDimension + mPageSpacing + getChildGap();
}
}
return pageScrollChanged;
@@ -669,15 +695,15 @@
}
protected void updateMinAndMaxScrollX() {
- mMinScrollX = computeMinScrollX();
- mMaxScrollX = computeMaxScrollX();
+ mMinScroll = computeMinScroll();
+ mMaxScroll = computeMaxScroll();
}
- protected int computeMinScrollX() {
+ protected int computeMinScroll() {
return 0;
}
- protected int computeMaxScrollX() {
+ protected int computeMaxScroll() {
int childCount = getChildCount();
if (childCount > 0) {
final int index = mIsRtl ? 0 : childCount - 1;
@@ -720,7 +746,8 @@
protected int getChildOffset(int index) {
if (index < 0 || index > getChildCount() - 1) return 0;
- return getPageAt(index).getLeft();
+ View pageAtIndex = getPageAt(index);
+ return mOrientationHandler.getChildStart(pageAtIndex);
}
@Override
@@ -871,13 +898,13 @@
case MotionEvent.ACTION_MOVE: {
/*
* mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
- * whether the user has moved far enough from his original down touch.
+ * whether the user has moved far enough from their original down touch.
*/
if (mActivePointerId != INVALID_POINTER) {
determineScrollingStart(ev);
}
// if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
- // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
+ // event. in that case, treat the first occurrence of a move event as a ACTION_DOWN
// i.e. fall through to the next case (don't break)
// (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
// while it's small- this was causing a crash before we checked for INVALID_POINTER)
@@ -890,9 +917,9 @@
// Remember location of down touch
mDownMotionX = x;
mDownMotionY = y;
- mLastMotionX = x;
- mLastMotionXRemainder = 0;
- mTotalMotionX = 0;
+ mDownMotionPrimary = mLastMotion = mOrientationHandler.getPrimaryDirection(ev, 0);
+ mLastMotionRemainder = 0;
+ mTotalMotion = 0;
mActivePointerId = ev.getPointerId(0);
updateIsBeingDraggedOnTouchDown();
@@ -954,17 +981,17 @@
final int pointerIndex = ev.findPointerIndex(mActivePointerId);
if (pointerIndex == -1) return;
- final float x = ev.getX(pointerIndex);
- final int xDiff = (int) Math.abs(x - mLastMotionX);
+ final float primaryDirection = mOrientationHandler.getPrimaryDirection(ev, pointerIndex);
+ final int diff = (int) Math.abs(primaryDirection - mLastMotion);
final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
- boolean xMoved = xDiff > touchSlop;
+ boolean moved = diff > touchSlop;
- if (xMoved) {
+ if (moved) {
// Scroll if the user moved far enough along the X axis
mIsBeingDragged = true;
- mTotalMotionX += Math.abs(mLastMotionX - x);
- mLastMotionX = x;
- mLastMotionXRemainder = 0;
+ mTotalMotion += Math.abs(mLastMotion - primaryDirection);
+ mLastMotion = primaryDirection;
+ mLastMotionRemainder = 0;
onScrollInteractionBegin();
pageBeginTransition();
// Stop listening for things like pinches.
@@ -1031,10 +1058,9 @@
@Override
protected void dispatchDraw(Canvas canvas) {
- if (mScroller.isSpringing() && mSpringOverScrollX != 0) {
+ if (mScroller.isSpringing() && mSpringOverScroll != 0) {
int saveCount = canvas.save();
-
- canvas.translate(-mSpringOverScrollX, 0);
+ mOrientationHandler.set(canvas, CANVAS_TRANSLATE, -mSpringOverScroll);
super.dispatchDraw(canvas);
canvas.restoreToCount(saveCount);
@@ -1043,27 +1069,41 @@
}
}
+ /**
+ * Returns the amount of overscroll caused by the spring in {@link OverScroller}.
+ */
+ private int getSpringOverScroll(int amount) {
+ if (mScroller.isSpringing()) {
+ return amount < 0
+ ? mScroller.getCurrPos()
+ : Math.max(0, mScroller.getCurrPos() - mMaxScroll);
+ } else {
+ return 0;
+ }
+ }
+
protected void dampedOverScroll(int amount) {
- mSpringOverScrollX = amount;
if (amount == 0) {
return;
}
- int overScrollAmount = OverScroll.dampedScroll(amount, getMeasuredWidth());
- mSpringOverScrollX = overScrollAmount;
+ int size = mOrientationHandler.getMeasuredSize(this);
+ int overScrollAmount = OverScroll.dampedScroll(amount, size);
if (mScroller.isSpringing()) {
+ mSpringOverScroll = getSpringOverScroll(amount);
invalidate();
return;
}
- int x = Utilities.boundToRange(getScrollX(), mMinScrollX, mMaxScrollX);
- super.scrollTo(x + overScrollAmount, getScrollY());
+ int primaryScroll = mOrientationHandler.getPrimaryScroll(this);
+ int boundedScroll = Utilities.boundToRange(primaryScroll, mMinScroll, mMaxScroll);
+ mOrientationHandler.delegateScrollTo(this, boundedScroll + overScrollAmount);
invalidate();
}
protected void overScroll(int amount) {
- mSpringOverScrollX = amount;
if (mScroller.isSpringing()) {
+ mSpringOverScroll = getSpringOverScroll(amount);
invalidate();
return;
}
@@ -1071,11 +1111,8 @@
if (amount == 0) return;
if (mFreeScroll && !mScroller.isFinished()) {
- if (amount < 0) {
- super.scrollTo(mMinScrollX + amount, getScrollY());
- } else {
- super.scrollTo(mMaxScrollX + amount, getScrollY());
- }
+ int scrollAmount = amount < 0 ? mMinScroll + amount : mMaxScroll + amount;
+ mOrientationHandler.delegateScrollTo(this, scrollAmount);
} else {
dampedOverScroll(amount);
}
@@ -1125,37 +1162,37 @@
}
// Remember where the motion event started
- mDownMotionX = mLastMotionX = ev.getX();
+ mDownMotionX = ev.getX();
mDownMotionY = ev.getY();
- mLastMotionXRemainder = 0;
- mTotalMotionX = 0;
+ mDownMotionPrimary = mLastMotion = mOrientationHandler.getPrimaryDirection(ev, 0);
+ mLastMotionRemainder = 0;
+ mTotalMotion = 0;
mActivePointerId = ev.getPointerId(0);
-
if (mIsBeingDragged) {
onScrollInteractionBegin();
pageBeginTransition();
}
break;
- case MotionEvent.ACTION_MOVE:
- if (mIsBeingDragged) {
+ case MotionEvent.ACTION_MOVE:
+ if (mIsBeingDragged) {
// Scroll to follow the motion event
final int pointerIndex = ev.findPointerIndex(mActivePointerId);
if (pointerIndex == -1) return true;
- final float x = ev.getX(pointerIndex);
- final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
-
- mTotalMotionX += Math.abs(deltaX);
+ float direction = mOrientationHandler.getPrimaryDirection(ev, pointerIndex);
+ float delta = mLastMotion + mLastMotionRemainder - direction;
+ mTotalMotion += Math.abs(delta);
// Only scroll and update mLastMotionX if we have moved some discrete amount. We
// keep the remainder because we are actually testing if we've moved from the last
// scrolled position (which is discrete).
- if (Math.abs(deltaX) >= 1.0f) {
- scrollBy((int) deltaX, 0);
- mLastMotionX = x;
- mLastMotionXRemainder = deltaX - (int) deltaX;
+ if (Math.abs(delta) >= 1.0f) {
+ mLastMotion = direction;
+ mLastMotionRemainder = delta - (int) delta;
+
+ mOrientationHandler.set(this, VIEW_SCROLL_BY, (int) delta);
} else {
awakenScrollBars();
}
@@ -1168,27 +1205,31 @@
if (mIsBeingDragged) {
final int activePointerId = mActivePointerId;
final int pointerIndex = ev.findPointerIndex(activePointerId);
- final float x = ev.getX(pointerIndex);
+ final float primaryDirection = mOrientationHandler.getPrimaryDirection(ev,
+ pointerIndex);
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
- int velocityX = (int) velocityTracker.getXVelocity(mActivePointerId);
- final int deltaX = (int) (x - mDownMotionX);
- final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
- boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
- SIGNIFICANT_MOVE_THRESHOLD;
- mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
- boolean isFling = mTotalMotionX > mTouchSlop && shouldFlingForVelocity(velocityX);
- boolean isDeltaXLeft = mIsRtl ? deltaX > 0 : deltaX < 0;
- boolean isVelocityXLeft = mIsRtl ? velocityX > 0 : velocityX < 0;
+ int velocity = (int) mOrientationHandler.getPrimaryVelocity(velocityTracker,
+ mActivePointerId);
+ int delta = (int) (primaryDirection - mDownMotionPrimary);
+ int pageOrientedSize = mOrientationHandler.getMeasuredSize(getPageAt(mCurrentPage));
+
+ boolean isSignificantMove = Math.abs(delta) > pageOrientedSize *
+ SIGNIFICANT_MOVE_THRESHOLD;
+
+ mTotalMotion += Math.abs(mLastMotion + mLastMotionRemainder - primaryDirection);
+ boolean isFling = mTotalMotion > mTouchSlop && shouldFlingForVelocity(velocity);
+ boolean isDeltaLeft = mIsRtl ? delta > 0 : delta < 0;
+ boolean isVelocityLeft = mIsRtl ? velocity > 0 : velocity < 0;
if (!mFreeScroll) {
// In the case that the page is moved far to one direction and then is flung
// in the opposite direction, we use a threshold to determine whether we should
// just return to the starting page, or if we should skip one further.
boolean returnToOriginalPage = false;
- if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
- Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
+ if (Math.abs(delta) > pageOrientedSize * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
+ Math.signum(velocity) != Math.signum(delta) && isFling) {
returnToOriginalPage = true;
}
@@ -1197,15 +1238,15 @@
// test for a large move if a fling has been registered. That is, a large
// move to the left and fling to the right will register as a fling to the right.
- if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
- (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
+ if (((isSignificantMove && !isDeltaLeft && !isFling) ||
+ (isFling && !isVelocityLeft)) && mCurrentPage > 0) {
finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
- snapToPageWithVelocity(finalPage, velocityX);
- } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
- (isFling && isVelocityXLeft)) &&
+ snapToPageWithVelocity(finalPage, velocity);
+ } else if (((isSignificantMove && isDeltaLeft && !isFling) ||
+ (isFling && isVelocityLeft)) &&
mCurrentPage < getChildCount() - 1) {
finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
- snapToPageWithVelocity(finalPage, velocityX);
+ snapToPageWithVelocity(finalPage, velocity);
} else {
snapToDestination();
}
@@ -1214,38 +1255,40 @@
abortScrollerAnimation(true);
}
- int initialScrollX = getScrollX();
+ int initialScroll = mOrientationHandler.getPrimaryScroll(this);
+ int maxScroll = mMaxScroll;
+ int minScroll = mMinScroll;
- if (((initialScrollX >= mMaxScrollX) && (isVelocityXLeft || !isFling)) ||
- ((initialScrollX <= mMinScrollX) && (!isVelocityXLeft || !isFling))) {
- mScroller.springBack(getScrollX(), mMinScrollX, mMaxScrollX);
+ if (((initialScroll >= maxScroll) && (isVelocityLeft || !isFling)) ||
+ ((initialScroll <= minScroll) && (!isVelocityLeft || !isFling))) {
+ mScroller.springBack(initialScroll, minScroll, maxScroll);
mNextPage = getPageNearestToCenterOfScreen();
} else {
mScroller.setInterpolator(mDefaultInterpolator);
- mScroller.fling(initialScrollX, -velocityX,
- mMinScrollX, mMaxScrollX,
- Math.round(getWidth() * 0.5f * OVERSCROLL_DAMP_FACTOR));
+ mScroller.fling(initialScroll, -velocity,
+ minScroll, maxScroll,
+ Math.round(getWidth() * 0.5f * OVERSCROLL_DAMP_FACTOR));
- int finalX = mScroller.getFinalPos();
- mNextPage = getPageNearestToCenterOfScreen(finalX);
+ int finalPos = mScroller.getFinalPos();
+ mNextPage = getPageNearestToCenterOfScreen(finalPos);
int firstPageScroll = getScrollForPage(!mIsRtl ? 0 : getPageCount() - 1);
int lastPageScroll = getScrollForPage(!mIsRtl ? getPageCount() - 1 : 0);
- if (finalX > mMinScrollX && finalX < mMaxScrollX) {
+ if (finalPos > minScroll && finalPos < maxScroll) {
// If scrolling ends in the half of the added space that is closer to
// the end, settle to the end. Otherwise snap to the nearest page.
// If flinging past one of the ends, don't change the velocity as it
// will get stopped at the end anyway.
- int pageSnappedX = finalX < (firstPageScroll + mMinScrollX) / 2
- ? mMinScrollX
- : finalX > (lastPageScroll + mMaxScrollX) / 2
- ? mMaxScrollX
- : getScrollForPage(mNextPage);
+ int pageSnapped = finalPos < (firstPageScroll + minScroll) / 2
+ ? minScroll
+ : finalPos > (lastPageScroll + maxScroll) / 2
+ ? maxScroll
+ : getScrollForPage(mNextPage);
- mScroller.setFinalPos(pageSnappedX);
+ mScroller.setFinalPos(pageSnapped);
// Ensure the scroll/snap doesn't happen too fast;
int extraScrollDuration = OVERSCROLL_PAGE_SNAP_ANIMATION_DURATION
- - mScroller.getDuration();
+ - mScroller.getDuration();
if (extraScrollDuration > 0) {
mScroller.extendDuration(extraScrollDuration);
}
@@ -1277,8 +1320,8 @@
return true;
}
- protected boolean shouldFlingForVelocity(int velocityX) {
- return Math.abs(velocityX) > mFlingThresholdVelocity;
+ protected boolean shouldFlingForVelocity(int velocity) {
+ return Math.abs(velocity) > mFlingThresholdVelocity;
}
private void resetTouchState() {
@@ -1301,10 +1344,6 @@
if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
switch (event.getAction()) {
case MotionEvent.ACTION_SCROLL: {
- Launcher launcher = Launcher.getLauncher(getContext());
- if (launcher != null) {
- AbstractFloatingView.closeAllOpenViews(launcher);
- }
// Handle mouse (or ext. device) by shifting the page depending on the scroll
final float vscroll;
final float hscroll;
@@ -1315,8 +1354,8 @@
vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
}
- if (Math.abs(vscroll) > Math.abs(hscroll) && !isVerticalScrollable()) {
- return true;
+ if (!canScroll(Math.abs(vscroll), Math.abs(hscroll))) {
+ return false;
}
if (hscroll != 0 || vscroll != 0) {
boolean isForwardScroll = mIsRtl ? (hscroll < 0 || vscroll < 0)
@@ -1334,8 +1373,13 @@
return super.onGenericMotionEvent(event);
}
- protected boolean isVerticalScrollable() {
- return true;
+ /**
+ * Returns true if the paged view can scroll for the provided vertical and horizontal
+ * scroll values
+ */
+ protected boolean canScroll(float absVScroll, float absHScroll) {
+ ActivityContext ac = ActivityContext.lookupContext(getContext());
+ return (ac == null || AbstractFloatingView.getTopOpenView(ac) == null);
}
private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
@@ -1362,8 +1406,9 @@
// active pointer and adjust accordingly.
// TODO: Make this decision more intelligent.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
- mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
- mLastMotionXRemainder = 0;
+ mLastMotion = mDownMotionPrimary = mOrientationHandler.getPrimaryDirection(ev,
+ newPointerIndex);
+ mLastMotionRemainder = 0;
mActivePointerId = ev.getPointerId(newPointerIndex);
if (mVelocityTracker != null) {
mVelocityTracker.clear();
@@ -1381,19 +1426,20 @@
}
public int getPageNearestToCenterOfScreen() {
- return getPageNearestToCenterOfScreen(getScrollX());
+ return getPageNearestToCenterOfScreen(mOrientationHandler.getPrimaryScroll(this));
}
- private int getPageNearestToCenterOfScreen(int scaledScrollX) {
- int screenCenter = scaledScrollX + (getMeasuredWidth() / 2);
+ private int getPageNearestToCenterOfScreen(int scaledScroll) {
+ int pageOrientationSize = mOrientationHandler.getMeasuredSize(this);
+ int screenCenter = scaledScroll + (pageOrientationSize / 2);
int minDistanceFromScreenCenter = Integer.MAX_VALUE;
int minDistanceFromScreenCenterIndex = -1;
final int childCount = getChildCount();
for (int i = 0; i < childCount; ++i) {
View layout = getPageAt(i);
- int childWidth = layout.getMeasuredWidth();
- int halfChildWidth = (childWidth / 2);
- int childCenter = getChildOffset(i) + halfChildWidth;
+ int childSize = mOrientationHandler.getMeasuredSize(layout);
+ int halfChildSize = (childSize / 2);
+ int childCenter = getChildOffset(i) + halfChildSize;
int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
minDistanceFromScreenCenter = distanceFromScreenCenter;
@@ -1408,7 +1454,8 @@
}
protected boolean isInOverScroll() {
- return (getScrollX() > mMaxScrollX || getScrollX() < mMinScrollX);
+ int scroll = mOrientationHandler.getPrimaryScroll(this);
+ return scroll > mMaxScroll || scroll < mMinScroll;
}
protected int getPageSnapDuration() {
@@ -1430,10 +1477,10 @@
protected boolean snapToPageWithVelocity(int whichPage, int velocity) {
whichPage = validateNewPage(whichPage);
- int halfScreenSize = getMeasuredWidth() / 2;
+ int halfScreenSize = mOrientationHandler.getMeasuredSize(this) / 2;
- final int newX = getScrollForPage(whichPage);
- int delta = newX - getUnboundedScrollX();
+ final int newLoc = getScrollForPage(whichPage);
+ int delta = newLoc - getUnboundedScroll();
int duration = 0;
if (Math.abs(velocity) < mMinFlingVelocity) {
@@ -1458,9 +1505,9 @@
// interpolator at zero, ie. 5. We use 4 to make it a little slower.
duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
- if (QUICKSTEP_SPRINGS.get()) {
+ if (QUICKSTEP_SPRINGS.get() && mCurrentPage != whichPage) {
return snapToPage(whichPage, delta, duration, false, null,
- velocity * Math.signum(newX - getUnboundedScrollX()), true);
+ velocity * Math.signum(delta), true);
} else {
return snapToPage(whichPage, delta, duration);
}
@@ -1486,8 +1533,8 @@
TimeInterpolator interpolator) {
whichPage = validateNewPage(whichPage);
- int newX = getScrollForPage(whichPage);
- final int delta = newX - getUnboundedScrollX();
+ int newLoc = getScrollForPage(whichPage);
+ final int delta = newLoc - getUnboundedScroll();
return snapToPage(whichPage, delta, duration, immediate, interpolator, 0, false);
}
@@ -1502,7 +1549,7 @@
return false;
}
- if (FeatureFlags.IS_DOGFOOD_BUILD) {
+ if (FeatureFlags.IS_STUDIO_BUILD) {
duration *= Settings.Global.getFloat(getContext().getContentResolver(),
Settings.Global.WINDOW_ANIMATION_SCALE, 1);
}
@@ -1533,9 +1580,9 @@
}
if (spring && QUICKSTEP_SPRINGS.get()) {
- mScroller.startScrollSpring(getUnboundedScrollX(), delta, duration, velocity);
+ mScroller.startScrollSpring(getUnboundedScroll(), delta, duration, velocity);
} else {
- mScroller.startScroll(getUnboundedScrollX(), delta, duration);
+ mScroller.startScroll(getUnboundedScroll(), delta, duration);
}
updatePageIndicator();
diff --git a/src/com/android/launcher3/PendingAddItemInfo.java b/src/com/android/launcher3/PendingAddItemInfo.java
index 76de3e7..29c9d93 100644
--- a/src/com/android/launcher3/PendingAddItemInfo.java
+++ b/src/com/android/launcher3/PendingAddItemInfo.java
@@ -18,6 +18,8 @@
import android.content.ComponentName;
+import com.android.launcher3.model.data.ItemInfo;
+
/**
* Meta data that is used for deferred binding.
* e.g., this object is used to pass information on draggable targets when they are dropped onto
diff --git a/src/com/android/launcher3/ResourceUtils.java b/src/com/android/launcher3/ResourceUtils.java
index 7f327a5..403d779 100644
--- a/src/com/android/launcher3/ResourceUtils.java
+++ b/src/com/android/launcher3/ResourceUtils.java
@@ -21,12 +21,12 @@
import android.util.TypedValue;
public class ResourceUtils {
+ public static final int DEFAULT_NAVBAR_VALUE = 48;
public static final String NAVBAR_LANDSCAPE_LEFT_RIGHT_SIZE = "navigation_bar_width";
public static final String NAVBAR_BOTTOM_GESTURE_SIZE = "navigation_bar_gesture_height";
-
public static int getNavbarSize(String resName, Resources res) {
- return getDimenByName(resName, res, 48);
+ return getDimenByName(resName, res, DEFAULT_NAVBAR_VALUE);
}
public static int getDimenByName(String resName, Resources res, int defaultValue) {
diff --git a/src/com/android/launcher3/SecondaryDropTarget.java b/src/com/android/launcher3/SecondaryDropTarget.java
index 1dbe195..9dbb5fc 100644
--- a/src/com/android/launcher3/SecondaryDropTarget.java
+++ b/src/com/android/launcher3/SecondaryDropTarget.java
@@ -3,12 +3,12 @@
import static android.appwidget.AppWidgetManager.INVALID_APPWIDGET_ID;
import static android.appwidget.AppWidgetProviderInfo.WIDGET_FEATURE_RECONFIGURABLE;
-import static com.android.launcher3.ItemInfoWithIcon.FLAG_SYSTEM_MASK;
-import static com.android.launcher3.ItemInfoWithIcon.FLAG_SYSTEM_NO;
import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_DESKTOP;
import static com.android.launcher3.accessibility.LauncherAccessibilityDelegate.DISMISS_PREDICTION;
import static com.android.launcher3.accessibility.LauncherAccessibilityDelegate.RECONFIGURE;
import static com.android.launcher3.accessibility.LauncherAccessibilityDelegate.UNINSTALL;
+import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_SYSTEM_MASK;
+import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_SYSTEM_NO;
import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetProviderInfo;
@@ -35,12 +35,16 @@
import com.android.launcher3.logging.FileLog;
import com.android.launcher3.logging.LoggerUtils;
import com.android.launcher3.model.AppLaunchTracker;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.ItemInfoWithIcon;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
import com.android.launcher3.userevent.nano.LauncherLogProto.ControlType;
import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
import com.android.launcher3.util.PackageManagerHelper;
import com.android.launcher3.util.Themes;
import java.net.URISyntaxException;
+import java.util.ArrayList;
/**
* Drop target which provides a secondary option for an item.
@@ -56,6 +60,7 @@
private final ArrayMap<UserHandle, Boolean> mUninstallDisabledCache = new ArrayMap<>(1);
private final Alarm mCacheExpireAlarm;
+ private boolean mHadPendingAlarm;
protected int mCurrentAccessibilityAction = -1;
public SecondaryDropTarget(Context context, AttributeSet attrs) {
@@ -66,7 +71,26 @@
super(context, attrs, defStyle);
mCacheExpireAlarm = new Alarm();
- mCacheExpireAlarm.setOnAlarmListener(this);
+ }
+
+ @Override
+ protected void onAttachedToWindow() {
+ super.onAttachedToWindow();
+ if (mHadPendingAlarm) {
+ mCacheExpireAlarm.setAlarm(CACHE_EXPIRE_TIMEOUT);
+ mCacheExpireAlarm.setOnAlarmListener(this);
+ mHadPendingAlarm = false;
+ }
+ }
+
+ @Override
+ protected void onDetachedFromWindow() {
+ super.onDetachedFromWindow();
+ if (mCacheExpireAlarm.alarmPending()) {
+ mCacheExpireAlarm.cancelAlarm();
+ mCacheExpireAlarm.setOnAlarmListener(null);
+ mHadPendingAlarm = true;
+ }
}
@Override
@@ -87,7 +111,7 @@
updateText(R.string.uninstall_drop_target_label);
} else if (action == DISMISS_PREDICTION) {
mHoverColor = Themes.getColorAccent(getContext());
- setDrawable(R.drawable.ic_block);
+ setDrawable(R.drawable.ic_block_shadow);
updateText(R.string.dismiss_prediction_label);
} else if (action == RECONFIGURE) {
mHoverColor = Themes.getColorAccent(getContext());
@@ -149,6 +173,7 @@
}
// Cancel any pending alarm and set cache expiry after some time
mCacheExpireAlarm.setAlarm(CACHE_EXPIRE_TIMEOUT);
+ mCacheExpireAlarm.setOnAlarmListener(this);
if (uninstallDisabled) {
return false;
}
@@ -301,9 +326,9 @@
}
@Override
- public void fillInLogContainerData(View v, ItemInfo info, Target target,
- Target targetParent) {
- mOriginal.fillInLogContainerData(v, info, target, targetParent);
+ public void fillInLogContainerData(ItemInfo childInfo, Target child,
+ ArrayList<Target> parents) {
+ mOriginal.fillInLogContainerData(childInfo, child, parents);
}
@Override
diff --git a/src/com/android/launcher3/ShortcutAndWidgetContainer.java b/src/com/android/launcher3/ShortcutAndWidgetContainer.java
index 1bd8263..6326b7a 100644
--- a/src/com/android/launcher3/ShortcutAndWidgetContainer.java
+++ b/src/com/android/launcher3/ShortcutAndWidgetContainer.java
@@ -93,7 +93,7 @@
public void setupLp(View child) {
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
if (child instanceof LauncherAppWidgetHostView) {
- DeviceProfile profile = mActivity.getWallpaperDeviceProfile();
+ DeviceProfile profile = mActivity.getDeviceProfile();
lp.setup(mCellWidth, mCellHeight, invertLayoutHorizontally(), mCountX,
profile.appWidgetScale.x, profile.appWidgetScale.y);
} else {
@@ -108,12 +108,12 @@
public int getCellContentHeight() {
return Math.min(getMeasuredHeight(),
- mActivity.getWallpaperDeviceProfile().getCellHeight(mContainerType));
+ mActivity.getDeviceProfile().getCellHeight(mContainerType));
}
public void measureChild(View child) {
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
- final DeviceProfile profile = mActivity.getWallpaperDeviceProfile();
+ final DeviceProfile profile = mActivity.getDeviceProfile();
if (child instanceof LauncherAppWidgetHostView) {
lp.setup(mCellWidth, mCellHeight, invertLayoutHorizontally(), mCountX,
@@ -145,38 +145,46 @@
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
-
- if (child instanceof LauncherAppWidgetHostView) {
- LauncherAppWidgetHostView lahv = (LauncherAppWidgetHostView) child;
-
- // Scale and center the widget to fit within its cells.
- DeviceProfile profile = mActivity.getDeviceProfile();
- float scaleX = profile.appWidgetScale.x;
- float scaleY = profile.appWidgetScale.y;
-
- lahv.setScaleToFit(Math.min(scaleX, scaleY));
- lahv.setTranslationForCentering(-(lp.width - (lp.width * scaleX)) / 2.0f,
- -(lp.height - (lp.height * scaleY)) / 2.0f);
- }
-
- int childLeft = lp.x;
- int childTop = lp.y;
- child.layout(childLeft, childTop, childLeft + lp.width, childTop + lp.height);
-
- if (lp.dropped) {
- lp.dropped = false;
-
- final int[] cellXY = mTmpCellXY;
- getLocationOnScreen(cellXY);
- mWallpaperManager.sendWallpaperCommand(getWindowToken(),
- WallpaperManager.COMMAND_DROP,
- cellXY[0] + childLeft + lp.width / 2,
- cellXY[1] + childTop + lp.height / 2, 0, null);
- }
+ layoutChild(child);
}
}
}
+ /**
+ * Core logic to layout a child for this ViewGroup.
+ */
+ public void layoutChild(View child) {
+ CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
+ if (child instanceof LauncherAppWidgetHostView) {
+ LauncherAppWidgetHostView lahv = (LauncherAppWidgetHostView) child;
+
+ // Scale and center the widget to fit within its cells.
+ DeviceProfile profile = mActivity.getDeviceProfile();
+ float scaleX = profile.appWidgetScale.x;
+ float scaleY = profile.appWidgetScale.y;
+
+ lahv.setScaleToFit(Math.min(scaleX, scaleY));
+ lahv.setTranslationForCentering(-(lp.width - (lp.width * scaleX)) / 2.0f,
+ -(lp.height - (lp.height * scaleY)) / 2.0f);
+ }
+
+ int childLeft = lp.x;
+ int childTop = lp.y;
+ child.layout(childLeft, childTop, childLeft + lp.width, childTop + lp.height);
+
+ if (lp.dropped) {
+ lp.dropped = false;
+
+ final int[] cellXY = mTmpCellXY;
+ getLocationOnScreen(cellXY);
+ mWallpaperManager.sendWallpaperCommand(getWindowToken(),
+ WallpaperManager.COMMAND_DROP,
+ cellXY[0] + childLeft + lp.width / 2,
+ cellXY[1] + childTop + lp.height / 2, 0, null);
+ }
+ }
+
+
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (ev.getAction() == ACTION_DOWN && getAlpha() == 0) {
diff --git a/src/com/android/launcher3/SimpleOnStylusPressListener.java b/src/com/android/launcher3/SimpleOnStylusPressListener.java
deleted file mode 100644
index 6b97dce..0000000
--- a/src/com/android/launcher3/SimpleOnStylusPressListener.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package com.android.launcher3;
-
-import android.view.MotionEvent;
-import android.view.View;
-
-import com.android.launcher3.StylusEventHelper.StylusButtonListener;
-
-/**
- * Simple listener that performs a long click on the view after a stylus button press.
- */
-public class SimpleOnStylusPressListener implements StylusButtonListener {
- private View mView;
-
- public SimpleOnStylusPressListener(View view) {
- mView = view;
- }
-
- public boolean onPressed(MotionEvent event) {
- return mView.isLongClickable() && mView.performLongClick();
- }
-
- public boolean onReleased(MotionEvent event) {
- return false;
- }
-}
\ No newline at end of file
diff --git a/src/com/android/launcher3/StylusEventHelper.java b/src/com/android/launcher3/StylusEventHelper.java
deleted file mode 100644
index d5fc0fa..0000000
--- a/src/com/android/launcher3/StylusEventHelper.java
+++ /dev/null
@@ -1,109 +0,0 @@
-package com.android.launcher3;
-
-import android.view.MotionEvent;
-import android.view.View;
-import android.view.ViewConfiguration;
-
-/**
- * Helper for identifying when a stylus touches a view while the primary stylus button is pressed.
- * This can occur in {@value MotionEvent#ACTION_DOWN} or {@value MotionEvent#ACTION_MOVE}.
- */
-public class StylusEventHelper {
-
- /**
- * Implement this interface to receive callbacks for a stylus button press and release.
- */
- public interface StylusButtonListener {
- /**
- * Called when the stylus button is pressed.
- *
- * @param event The MotionEvent that the button press occurred for.
- * @return Whether the event was handled.
- */
- public boolean onPressed(MotionEvent event);
-
- /**
- * Called when the stylus button is released after a button press. This is also called if
- * the event is canceled or the stylus is lifted off the screen.
- *
- * @param event The MotionEvent the button release occurred for.
- * @return Whether the event was handled.
- */
- public boolean onReleased(MotionEvent event);
- }
-
- private boolean mIsButtonPressed;
- private View mView;
- private StylusButtonListener mListener;
- private final float mSlop;
-
- /**
- * Constructs a helper for listening to stylus button presses and releases. Ensure that {
- * {@link #onMotionEvent(MotionEvent)} and {@link #onGenericMotionEvent(MotionEvent)} are called on
- * the helper to correctly identify stylus events.
- *
- * @param listener The listener to call for stylus events.
- * @param view Optional view associated with the touch events.
- */
- public StylusEventHelper(StylusButtonListener listener, View view) {
- mListener = listener;
- mView = view;
- if (mView != null) {
- mSlop = ViewConfiguration.get(mView.getContext()).getScaledTouchSlop();
- } else {
- mSlop = ViewConfiguration.getTouchSlop();
- }
- }
-
- public boolean onMotionEvent(MotionEvent event) {
- final boolean stylusButtonPressed = isStylusButtonPressed(event);
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:
- mIsButtonPressed = stylusButtonPressed;
- if (mIsButtonPressed) {
- return mListener.onPressed(event);
- }
- break;
- case MotionEvent.ACTION_MOVE:
- if (!Utilities.pointInView(mView, event.getX(), event.getY(), mSlop)) {
- return false;
- }
- if (!mIsButtonPressed && stylusButtonPressed) {
- mIsButtonPressed = true;
- return mListener.onPressed(event);
- } else if (mIsButtonPressed && !stylusButtonPressed) {
- mIsButtonPressed = false;
- return mListener.onReleased(event);
- }
- break;
- case MotionEvent.ACTION_UP:
- case MotionEvent.ACTION_CANCEL:
- if (mIsButtonPressed) {
- mIsButtonPressed = false;
- return mListener.onReleased(event);
- }
- break;
- }
- return false;
- }
-
- /**
- * Whether a stylus button press is occurring.
- */
- public boolean inStylusButtonPressed() {
- return mIsButtonPressed;
- }
-
- /**
- * Identifies if the provided {@link MotionEvent} is a stylus with the primary stylus button
- * pressed.
- *
- * @param event The event to check.
- * @return Whether a stylus button press occurred.
- */
- private static boolean isStylusButtonPressed(MotionEvent event) {
- return event.getToolType(0) == MotionEvent.TOOL_TYPE_STYLUS
- && ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY)
- == MotionEvent.BUTTON_SECONDARY);
- }
-}
\ No newline at end of file
diff --git a/src/com/android/launcher3/Utilities.java b/src/com/android/launcher3/Utilities.java
index e0e4cc0..3c3ab6c 100644
--- a/src/com/android/launcher3/Utilities.java
+++ b/src/com/android/launcher3/Utilities.java
@@ -16,7 +16,7 @@
package com.android.launcher3;
-import static com.android.launcher3.ItemInfoWithIcon.FLAG_ICON_BADGED;
+import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_ICON_BADGED;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
@@ -60,18 +60,19 @@
import android.view.ViewConfiguration;
import android.view.animation.Interpolator;
+import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.dragndrop.FolderAdaptiveIcon;
-import com.android.launcher3.graphics.RotationMode;
import com.android.launcher3.graphics.TintedDrawableSpan;
import com.android.launcher3.icons.IconProvider;
import com.android.launcher3.icons.LauncherIcons;
import com.android.launcher3.icons.ShortcutCachingLogic;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.ItemInfoWithIcon;
import com.android.launcher3.pm.ShortcutConfigActivityInfo;
import com.android.launcher3.shortcuts.ShortcutKey;
import com.android.launcher3.shortcuts.ShortcutRequest;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.PackageManagerHelper;
-import com.android.launcher3.views.Transposable;
import com.android.launcher3.widget.PendingAddShortcutInfo;
import java.lang.reflect.Method;
@@ -164,7 +165,7 @@
public static float getDescendantCoordRelativeToAncestor(
View descendant, View ancestor, float[] coord, boolean includeRootScroll) {
return getDescendantCoordRelativeToAncestor(descendant, ancestor, coord, includeRootScroll,
- false, null);
+ false);
}
/**
@@ -177,15 +178,12 @@
* @param includeRootScroll Whether or not to account for the scroll of the descendant:
* sometimes this is relevant as in a child's coordinates within the descendant.
* @param ignoreTransform If true, view transform is ignored
- * @param outRotation If not null, and {@param ignoreTransform} is true, this is set to the
- * overall rotation of the view in degrees.
* @return The factor by which this descendant is scaled relative to this DragLayer. Caution
* this scale factor is assumed to be equal in X and Y, and so if at any point this
* assumption fails, we will need to return a pair of scale factors.
*/
public static float getDescendantCoordRelativeToAncestor(View descendant, View ancestor,
- float[] coord, boolean includeRootScroll, boolean ignoreTransform,
- float[] outRotation) {
+ float[] coord, boolean includeRootScroll, boolean ignoreTransform) {
float scale = 1.0f;
View v = descendant;
while(v != ancestor && v != null) {
@@ -195,19 +193,7 @@
offsetPoints(coord, -v.getScrollX(), -v.getScrollY());
}
- if (ignoreTransform) {
- if (v instanceof Transposable) {
- RotationMode m = ((Transposable) v).getRotationMode();
- if (m.isTransposed) {
- sMatrix.setRotate(m.surfaceRotation, v.getPivotX(), v.getPivotY());
- sMatrix.mapPoints(coord);
-
- if (outRotation != null) {
- outRotation[0] += m.surfaceRotation;
- }
- }
- }
- } else {
+ if (!ignoreTransform) {
v.getMatrix().mapPoints(coord);
}
offsetPoints(coord, v.getLeft(), v.getTop());
@@ -475,6 +461,15 @@
LauncherFiles.DEVICE_PREFERENCES_KEY, Context.MODE_PRIVATE);
}
+ /**
+ * @return {@link SharedPreferences} that backs {@link FeatureFlags}
+ */
+ public static SharedPreferences getFeatureFlagsPrefs(Context context) {
+ // Use application context for shared preferences, so that we use a single cached instance
+ return context.getApplicationContext().getSharedPreferences(
+ FeatureFlags.FLAGS_PREF_NAME, Context.MODE_PRIVATE);
+ }
+
public static boolean areAnimationsEnabled(Context context) {
return ATLEAST_OREO
? ValueAnimator.areAnimatorsEnabled()
diff --git a/src/com/android/launcher3/Workspace.java b/src/com/android/launcher3/Workspace.java
index b7f8547..70a5cc5 100644
--- a/src/com/android/launcher3/Workspace.java
+++ b/src/com/android/launcher3/Workspace.java
@@ -24,11 +24,11 @@
import static com.android.launcher3.LauncherState.SPRING_LOADED;
import static com.android.launcher3.config.FeatureFlags.ADAPTIVE_ICON_WINDOW_ANIM;
import static com.android.launcher3.dragndrop.DragLayer.ALPHA_INDEX_OVERLAY;
+import static com.android.launcher3.logging.LoggerUtils.newContainerTarget;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.LayoutTransition;
-import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.SuppressLint;
@@ -42,7 +42,6 @@
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Handler;
-import android.os.IBinder;
import android.os.Message;
import android.os.Parcelable;
import android.os.UserHandle;
@@ -59,29 +58,33 @@
import android.widget.Toast;
import com.android.launcher3.LauncherAppWidgetHost.ProviderChangedListener;
-import com.android.launcher3.LauncherStateManager.AnimationConfig;
import com.android.launcher3.accessibility.AccessibleDragListenerAdapter;
import com.android.launcher3.accessibility.WorkspaceAccessibilityHelper;
-import com.android.launcher3.anim.AnimatorSetBuilder;
import com.android.launcher3.anim.Interpolators;
+import com.android.launcher3.anim.PendingAnimation;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.dot.FolderDotInfo;
import com.android.launcher3.dragndrop.DragController;
import com.android.launcher3.dragndrop.DragLayer;
import com.android.launcher3.dragndrop.DragOptions;
import com.android.launcher3.dragndrop.DragView;
+import com.android.launcher3.dragndrop.DraggableView;
import com.android.launcher3.dragndrop.SpringLoadedDragController;
import com.android.launcher3.folder.Folder;
import com.android.launcher3.folder.FolderIcon;
import com.android.launcher3.folder.PreviewBackground;
import com.android.launcher3.graphics.DragPreviewProvider;
import com.android.launcher3.graphics.PreloadIconDrawable;
-import com.android.launcher3.graphics.RotationMode;
import com.android.launcher3.icons.BitmapRenderer;
import com.android.launcher3.logging.UserEventDispatcher;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.FolderInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.pageindicators.WorkspacePageIndicator;
import com.android.launcher3.popup.PopupContainerWithArrow;
-import com.android.launcher3.shortcuts.ShortcutDragPreviewProvider;
+import com.android.launcher3.states.StateAnimationConfig;
import com.android.launcher3.touch.WorkspaceTouchListener;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action;
import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
@@ -124,12 +127,9 @@
private static final boolean ENFORCE_DRAG_EVENT_ORDER = false;
- private static final int SNAP_OFF_EMPTY_SCREEN_DURATION = 400;
- private static final int FADE_EMPTY_SCREEN_DURATION = 150;
-
private static final int ADJACENT_SCREEN_DROP_DURATION = 300;
- private static final int DEFAULT_PAGE = 0;
+ public static final int DEFAULT_PAGE = 0;
private LayoutTransition mLayoutTransition;
@Thunk final WallpaperManager mWallpaperManager;
@@ -139,7 +139,6 @@
@Thunk final IntSparseArrayMap<CellLayout> mWorkspaceScreens = new IntSparseArrayMap<>();
@Thunk final IntArray mScreenOrder = new IntArray();
- @Thunk Runnable mRemoveEmptyScreenRunnable;
@Thunk boolean mDeferRemoveExtraEmptyScreen = false;
/**
@@ -191,10 +190,7 @@
final WallpaperOffsetInterpolator mWallpaperOffset;
private boolean mUnlockWallpaperFromDefaultPageOnLayout;
- // Variables relating to the creation of user folders by hovering shortcuts over shortcuts
- private static final int FOLDER_CREATION_TIMEOUT = 0;
public static final int REORDER_TIMEOUT = 650;
- private final Alarm mFolderCreationAlarm = new Alarm();
private final Alarm mReorderAlarm = new Alarm();
private PreviewBackground mFolderCreateBg;
private FolderIcon mDragOverFolderIcon = null;
@@ -284,20 +280,14 @@
@Override
public void setInsets(Rect insets) {
DeviceProfile grid = mLauncher.getDeviceProfile();
- DeviceProfile stableGrid = mLauncher.getWallpaperDeviceProfile();
- mMaxDistanceForFolderCreation = stableGrid.isTablet
- ? 0.75f * stableGrid.iconSizePx
- : 0.55f * stableGrid.iconSizePx;
+ mMaxDistanceForFolderCreation = grid.isTablet
+ ? 0.75f * grid.iconSizePx : 0.55f * grid.iconSizePx;
mWorkspaceFadeInAdjacentScreens = grid.shouldFadeAdjacentWorkspaceScreens();
- Rect padding = stableGrid.workspacePadding;
-
- RotationMode rotationMode = mLauncher.getRotationMode();
-
- rotationMode.mapRect(padding, mTempRect);
- setPadding(mTempRect.left, mTempRect.top, mTempRect.right, mTempRect.bottom);
- rotationMode.mapRect(stableGrid.getInsets(), mInsets);
+ Rect padding = grid.workspacePadding;
+ setPadding(padding.left, padding.top, padding.right, padding.bottom);
+ mInsets.set(insets);
if (mWorkspaceFadeInAdjacentScreens) {
// In landscape mode the page spacing is set to the default.
@@ -310,12 +300,11 @@
}
- int paddingLeftRight = stableGrid.cellLayoutPaddingLeftRightPx;
- int paddingBottom = stableGrid.cellLayoutBottomPaddingPx;
+ int paddingLeftRight = grid.cellLayoutPaddingLeftRightPx;
+ int paddingBottom = grid.cellLayoutBottomPaddingPx;
for (int i = mWorkspaceScreens.size() - 1; i >= 0; i--) {
- CellLayout page = mWorkspaceScreens.valueAt(i);
- page.setRotationMode(rotationMode);
- page.setPadding(paddingLeftRight, 0, paddingLeftRight, paddingBottom);
+ mWorkspaceScreens.valueAt(i)
+ .setPadding(paddingLeftRight, 0, paddingLeftRight, paddingBottom);
}
}
@@ -335,7 +324,7 @@
float scale = 1;
if (isWidget) {
- DeviceProfile profile = mLauncher.getWallpaperDeviceProfile();
+ DeviceProfile profile = mLauncher.getDeviceProfile();
scale = Utilities.shrinkRect(r, profile.appWidgetScale.x, profile.appWidgetScale.y);
}
size[0] = r.width();
@@ -430,7 +419,7 @@
}
if (!mDeferRemoveExtraEmptyScreen) {
- removeExtraEmptyScreen(true, mDragSourceInternal != null);
+ removeExtraEmptyScreen(mDragSourceInternal != null);
}
updateChildrenLayersEnabled();
@@ -455,8 +444,16 @@
private void setupLayoutTransition() {
// We want to show layout transitions when pages are deleted, to close the gap.
mLayoutTransition = new LayoutTransition();
+
mLayoutTransition.enableTransitionType(LayoutTransition.DISAPPEARING);
mLayoutTransition.enableTransitionType(LayoutTransition.CHANGE_DISAPPEARING);
+ // Change the interpolators such that the fade animation plays before the move animation.
+ // This prevents empty adjacent pages to overlay during animation
+ mLayoutTransition.setInterpolator(LayoutTransition.DISAPPEARING,
+ Interpolators.clampToProgress(Interpolators.ACCEL_DEACCEL, 0, 0.5f));
+ mLayoutTransition.setInterpolator(LayoutTransition.CHANGE_DISAPPEARING,
+ Interpolators.clampToProgress(Interpolators.ACCEL_DEACCEL, 0.5f, 1));
+
mLayoutTransition.disableTransitionType(LayoutTransition.APPEARING);
mLayoutTransition.disableTransitionType(LayoutTransition.CHANGE_APPEARING);
setLayoutTransition(mLayoutTransition);
@@ -555,10 +552,9 @@
// created CellLayout.
CellLayout newScreen = (CellLayout) LayoutInflater.from(getContext()).inflate(
R.layout.workspace_screen, this, false /* attachToRoot */);
- DeviceProfile grid = mLauncher.getWallpaperDeviceProfile();
+ DeviceProfile grid = mLauncher.getDeviceProfile();
int paddingLeftRight = grid.cellLayoutPaddingLeftRightPx;
int paddingBottom = grid.cellLayoutBottomPaddingPx;
- newScreen.setRotationMode(mLauncher.getRotationMode());
newScreen.setPadding(paddingLeftRight, 0, paddingLeftRight, paddingBottom);
mWorkspaceScreens.put(screenId, newScreen);
@@ -566,11 +562,6 @@
addView(newScreen, insertIndex);
mStateTransitionAnimation.applyChildState(
mLauncher.getStateManager().getState(), newScreen, insertIndex);
-
- if (mLauncher.getAccessibilityDelegate().isInAccessibleDrag()) {
- newScreen.enableAccessibleDrag(true, CellLayout.WORKSPACE_ACCESSIBILITY_DRAG);
- }
-
return newScreen;
}
@@ -578,9 +569,6 @@
boolean lastChildOnScreen = false;
boolean childOnFinalScreen = false;
- // Cancel any pending removal of empty screen
- mRemoveEmptyScreenRunnable = null;
-
if (mDragSourceInternal != null) {
if (mDragSourceInternal.getChildCount() == 1) {
lastChildOnScreen = true;
@@ -631,43 +619,34 @@
}
}
- public void removeExtraEmptyScreen(final boolean animate, boolean stripEmptyScreens) {
- removeExtraEmptyScreenDelayed(animate, null, 0, stripEmptyScreens);
+ public void removeExtraEmptyScreen(boolean stripEmptyScreens) {
+ removeExtraEmptyScreenDelayed(0, stripEmptyScreens, null);
}
- public void removeExtraEmptyScreenDelayed(final boolean animate, final Runnable onComplete,
- final int delay, final boolean stripEmptyScreens) {
+ public void removeExtraEmptyScreenDelayed(
+ int delay, boolean stripEmptyScreens, Runnable onComplete) {
if (mLauncher.isWorkspaceLoading()) {
// Don't strip empty screens if the workspace is still loading
return;
}
if (delay > 0) {
- postDelayed(new Runnable() {
- @Override
- public void run() {
- removeExtraEmptyScreenDelayed(animate, onComplete, 0, stripEmptyScreens);
- }
- }, delay);
+ postDelayed(
+ () -> removeExtraEmptyScreenDelayed(0, stripEmptyScreens, onComplete), delay);
return;
}
convertFinalScreenToEmptyScreenIfNecessary();
if (hasExtraEmptyScreen()) {
- int emptyIndex = mScreenOrder.indexOf(EXTRA_EMPTY_SCREEN_ID);
- if (getNextPage() == emptyIndex) {
- snapToPage(getNextPage() - 1, SNAP_OFF_EMPTY_SCREEN_DURATION);
- fadeAndRemoveEmptyScreen(SNAP_OFF_EMPTY_SCREEN_DURATION, FADE_EMPTY_SCREEN_DURATION,
- onComplete, stripEmptyScreens);
- } else {
- snapToPage(getNextPage(), 0);
- fadeAndRemoveEmptyScreen(0, FADE_EMPTY_SCREEN_DURATION,
- onComplete, stripEmptyScreens);
- }
- return;
- } else if (stripEmptyScreens) {
- // If we're not going to strip the empty screens after removing
- // the extra empty screen, do it right away.
+ removeView(mWorkspaceScreens.get(EXTRA_EMPTY_SCREEN_ID));
+ mWorkspaceScreens.remove(EXTRA_EMPTY_SCREEN_ID);
+ mScreenOrder.removeValue(EXTRA_EMPTY_SCREEN_ID);
+
+ // Update the page indicator to reflect the removed page.
+ showPageIndicatorAtCurrentScroll();
+ }
+
+ if (stripEmptyScreens) {
stripEmptyScreens();
}
@@ -676,44 +655,6 @@
}
}
- private void fadeAndRemoveEmptyScreen(int delay, int duration, final Runnable onComplete,
- final boolean stripEmptyScreens) {
- // XXX: Do we need to update LM workspace screens below?
- final CellLayout cl = mWorkspaceScreens.get(EXTRA_EMPTY_SCREEN_ID);
-
- mRemoveEmptyScreenRunnable = new Runnable() {
- @Override
- public void run() {
- if (hasExtraEmptyScreen()) {
- mWorkspaceScreens.remove(EXTRA_EMPTY_SCREEN_ID);
- mScreenOrder.removeValue(EXTRA_EMPTY_SCREEN_ID);
- removeView(cl);
- if (stripEmptyScreens) {
- stripEmptyScreens();
- }
- // Update the page indicator to reflect the removed page.
- showPageIndicatorAtCurrentScroll();
- }
- }
- };
-
- ObjectAnimator oa = ObjectAnimator.ofFloat(cl, ALPHA, 0f);
- oa.setDuration(duration);
- oa.setStartDelay(delay);
- oa.addListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationEnd(Animator animation) {
- if (mRemoveEmptyScreenRunnable != null) {
- mRemoveEmptyScreenRunnable.run();
- }
- if (onComplete != null) {
- onComplete.run();
- }
- }
- });
- oa.start();
- }
-
public boolean hasExtraEmptyScreen() {
return mWorkspaceScreens.containsKey(EXTRA_EMPTY_SCREEN_ID) && getChildCount() > 1;
}
@@ -800,8 +741,6 @@
}
}
- boolean isInAccessibleDrag = mLauncher.getAccessibilityDelegate().isInAccessibleDrag();
-
// We enforce at least one page to add new items to. In the case that we remove the last
// such screen, we convert the last screen to the empty screen
int minScreens = 1;
@@ -817,15 +756,9 @@
if (indexOfChild(cl) < currentPage) {
pageShift++;
}
-
- if (isInAccessibleDrag) {
- cl.enableAccessibleDrag(false, CellLayout.WORKSPACE_ACCESSIBILITY_DRAG);
- }
-
removeView(cl);
} else {
// if this is the last screen, convert it to the empty screen
- mRemoveEmptyScreenRunnable = null;
mWorkspaceScreens.put(EXTRA_EMPTY_SCREEN_ID, cl);
mScreenOrder.add(EXTRA_EMPTY_SCREEN_ID);
}
@@ -966,8 +899,8 @@
private boolean isScrollingOverlay() {
return mLauncherOverlay != null &&
- ((mIsRtl && getUnboundedScrollX() > mMaxScrollX)
- || (!mIsRtl && getUnboundedScrollX() < mMinScrollX));
+ ((mIsRtl && getUnboundedScroll() > mMaxScroll)
+ || (!mIsRtl && getUnboundedScroll() < mMinScroll));
}
@Override
@@ -1003,7 +936,7 @@
public void showPageIndicatorAtCurrentScroll() {
if (mPageIndicator != null) {
- mPageIndicator.setScroll(getScrollX(), computeMaxScrollX());
+ mPageIndicator.setScroll(getScrollX(), computeMaxScroll());
}
}
@@ -1054,7 +987,6 @@
if (!mOverlayShown) {
mLauncher.getUserEventDispatcher().logActionOnContainer(Action.Touch.SWIPE,
Action.Direction.LEFT, ContainerType.WORKSPACE, 0);
- mLauncher.getStatsLogManager().logSwipeOnContainer(true, 0);
}
mOverlayShown = true;
// Not announcing the overlay page for accessibility since it announces itself.
@@ -1064,7 +996,6 @@
if (!ued.isPreviousHomeGesture()) {
mLauncher.getUserEventDispatcher().logActionOnContainer(Action.Touch.SWIPE,
Action.Direction.RIGHT, ContainerType.WORKSPACE, -1);
- mLauncher.getStatsLogManager().logSwipeOnContainer(false, -1);
}
} else if (Float.compare(mOverlayTranslation, 0f) != 0) {
// When arriving to 0 overscroll from non-zero overscroll, announce page for
@@ -1236,10 +1167,8 @@
protected void onAttachedToWindow() {
super.onAttachedToWindow();
- IBinder windowToken = getWindowToken();
- mWallpaperOffset.setWindowToken(windowToken);
+ mWallpaperOffset.setWindowToken(getWindowToken());
computeScroll();
- mDragController.setWindowToken(windowToken);
}
protected void onDetachedFromWindow() {
@@ -1382,10 +1311,10 @@
* Sets the current workspace {@link LauncherState}, then animates the UI
*/
@Override
- public void setStateWithAnimation(LauncherState toState,
- AnimatorSetBuilder builder, AnimationConfig config) {
+ public void setStateWithAnimation(
+ LauncherState toState, StateAnimationConfig config, PendingAnimation animation) {
StateTransitionListener listener = new StateTransitionListener(toState);
- mStateTransitionAnimation.setStateWithAnimation(toState, builder, config);
+ mStateTransitionAnimation.setStateWithAnimation(toState, config, animation);
// Invalidate the pages now, so that we have the visible pages before the
// animation is started
@@ -1398,7 +1327,7 @@
stepAnimator.addUpdateListener(listener);
stepAnimator.setDuration(config.duration);
stepAnimator.addListener(listener);
- builder.play(stepAnimator);
+ animation.add(stepAnimator);
}
public WorkspaceStateTransitionAnimation getStateTransitionAnimation() {
@@ -1443,14 +1372,14 @@
child.setVisibility(INVISIBLE);
if (options.isAccessibleDrag) {
- mDragController.addDragListener(new AccessibleDragListenerAdapter(
- this, CellLayout.WORKSPACE_ACCESSIBILITY_DRAG) {
- @Override
- protected void enableAccessibleDrag(boolean enable) {
- super.enableAccessibleDrag(enable);
- setEnableForLayout(mLauncher.getHotseat(),enable);
- }
- });
+ mDragController.addDragListener(
+ new AccessibleDragListenerAdapter(this, WorkspaceAccessibilityHelper::new) {
+ @Override
+ protected void enableAccessibleDrag(boolean enable) {
+ super.enableAccessibleDrag(enable);
+ setEnableForLayout(mLauncher.getHotseat(), enable);
+ }
+ });
}
beginDragShared(child, this, options);
@@ -1464,12 +1393,17 @@
+ "View: " + child + " tag: " + child.getTag();
throw new IllegalStateException(msg);
}
- beginDragShared(child, source, (ItemInfo) dragObject,
+ beginDragShared(child, null, source, (ItemInfo) dragObject,
new DragPreviewProvider(child), options);
}
- public DragView beginDragShared(View child, DragSource source, ItemInfo dragObject,
- DragPreviewProvider previewProvider, DragOptions dragOptions) {
+ /**
+ * Core functionality for beginning a drag operation for an item that will be dropped within
+ * the workspace
+ */
+ public DragView beginDragShared(View child, DraggableView draggableView, DragSource source,
+ ItemInfo dragObject, DragPreviewProvider previewProvider, DragOptions dragOptions) {
+
float iconScale = 1f;
if (child instanceof BubbleTextView) {
Drawable icon = ((BubbleTextView) child).getIcon();
@@ -1478,41 +1412,36 @@
}
}
+ // Clear the pressed state if necessary
child.clearFocus();
child.setPressed(false);
+ if (child instanceof BubbleTextView) {
+ BubbleTextView icon = (BubbleTextView) child;
+ icon.clearPressedBackground();
+ }
+
mOutlineProvider = previewProvider;
// The drag bitmap follows the touch point around on the screen
final Bitmap b = previewProvider.createDragBitmap();
int halfPadding = previewProvider.previewPadding / 2;
-
float scale = previewProvider.getScaleAndPosition(b, mTempXY);
int dragLayerX = mTempXY[0];
int dragLayerY = mTempXY[1];
- DeviceProfile grid = mLauncher.getDeviceProfile();
Point dragVisualizeOffset = null;
- Rect dragRect = null;
- if (child instanceof BubbleTextView) {
- dragRect = new Rect();
- BubbleTextView.getIconBounds(child, dragRect, grid.iconSizePx);
+ Rect dragRect = new Rect();
+
+ if (draggableView == null && child instanceof DraggableView) {
+ draggableView = (DraggableView) child;
+ }
+
+ if (draggableView != null) {
+ draggableView.getVisualDragBounds(dragRect);
dragLayerY += dragRect.top;
- // Note: The dragRect is used to calculate drag layer offsets, but the
- // dragVisualizeOffset in addition to the dragRect (the size) to position the outline.
- dragVisualizeOffset = new Point(- halfPadding, halfPadding);
- } else if (child instanceof FolderIcon) {
- int previewSize = grid.folderIconSizePx;
- dragVisualizeOffset = new Point(- halfPadding, halfPadding - child.getPaddingTop());
- dragRect = new Rect(0, child.getPaddingTop(), child.getWidth(), previewSize);
- } else if (previewProvider instanceof ShortcutDragPreviewProvider) {
dragVisualizeOffset = new Point(- halfPadding, halfPadding);
}
- // Clear the pressed state if necessary
- if (child instanceof BubbleTextView) {
- BubbleTextView icon = (BubbleTextView) child;
- icon.clearPressedBackground();
- }
if (child.getParent() instanceof ShortcutAndWidgetContainer) {
mDragSourceInternal = (ShortcutAndWidgetContainer) child.getParent();
@@ -1523,13 +1452,13 @@
.showForIcon((BubbleTextView) child);
if (popupContainer != null) {
dragOptions.preDragCondition = popupContainer.createPreDragCondition();
-
mLauncher.getUserEventDispatcher().resetElapsedContainerMillis("dragging started");
}
}
- DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source,
- dragObject, dragVisualizeOffset, dragRect, scale * iconScale, scale, dragOptions);
+ DragView dv = mDragController.startDrag(b, draggableView, dragLayerX, dragLayerY, source,
+ dragObject, dragVisualizeOffset, dragRect, scale * iconScale,
+ scale, dragOptions);
dv.setIntrinsicIconScaleFactor(dragOptions.intrinsicIconScaleFactor);
return dv;
}
@@ -1858,7 +1787,7 @@
CellLayout parentCell = getParentCellLayoutForView(cell);
if (parentCell != null) {
parentCell.removeView(cell);
- } else if (FeatureFlags.IS_DOGFOOD_BUILD) {
+ } else if (FeatureFlags.IS_STUDIO_BUILD) {
throw new NullPointerException("mDragInfo.cell has null parent");
}
addInScreen(cell, container, screenId, mTargetCell[0], mTargetCell[1],
@@ -1882,12 +1811,10 @@
final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell;
AppWidgetProviderInfo pInfo = hostView.getAppWidgetInfo();
if (pInfo != null && pInfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE
- && !d.accessibleDrag) {
- onCompleteRunnable = new Runnable() {
- public void run() {
- if (!isPageInTransition()) {
- AppWidgetResizeFrame.showForWidget(hostView, cellLayout);
- }
+ && !options.isAccessibleDrag) {
+ onCompleteRunnable = () -> {
+ if (!isPageInTransition()) {
+ AppWidgetResizeFrame.showForWidget(hostView, cellLayout);
}
};
}
@@ -2087,8 +2014,6 @@
if (mFolderCreateBg != null) {
mFolderCreateBg.animateToRest();
}
- mFolderCreationAlarm.setOnAlarmListener(null);
- mFolderCreationAlarm.cancelAlarm();
}
private void cleanupAddToFolder() {
@@ -2153,7 +2078,7 @@
ItemInfo item = d.dragInfo;
if (item == null) {
- if (FeatureFlags.IS_DOGFOOD_BUILD) {
+ if (FeatureFlags.IS_STUDIO_BUILD) {
throw new NullPointerException("DragObject has null info");
}
return;
@@ -2195,14 +2120,14 @@
float targetCellDistance = mDragTargetLayout.getDistanceFromCell(
mDragViewVisualCenter[0], mDragViewVisualCenter[1], mTargetCell);
- manageFolderFeedback(mDragTargetLayout, mTargetCell, targetCellDistance, d);
+ manageFolderFeedback(targetCellDistance, d);
boolean nearestDropOccupied = mDragTargetLayout.isNearestDropLocationOccupied((int)
mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], item.spanX,
item.spanY, child, mTargetCell);
if (!nearestDropOccupied) {
- mDragTargetLayout.visualizeDropLocation(child, mOutlineProvider,
+ mDragTargetLayout.visualizeDropLocation(d.originalView, mOutlineProvider,
mTargetCell[0], mTargetCell[1], item.spanX, item.spanY, false, d);
} else if ((mDragMode == DRAG_MODE_NONE || mDragMode == DRAG_MODE_REORDER)
&& !mReorderAlarm.alarmPending() && (mLastReorderX != reorderX ||
@@ -2293,10 +2218,10 @@
return null;
}
- private void manageFolderFeedback(CellLayout targetLayout,
- int[] targetCell, float distance, DragObject dragObject) {
+ private void manageFolderFeedback(float distance, DragObject dragObject) {
if (distance > mMaxDistanceForFolderCreation) {
- if (mDragMode != DRAG_MODE_NONE) {
+ if ((mDragMode == DRAG_MODE_ADD_TO_FOLDER
+ || mDragMode == DRAG_MODE_CREATE_FOLDER)) {
setDragMode(DRAG_MODE_NONE);
}
return;
@@ -2305,18 +2230,18 @@
final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0], mTargetCell[1]);
ItemInfo info = dragObject.dragInfo;
boolean userFolderPending = willCreateUserFolder(info, dragOverView, false);
- if (mDragMode == DRAG_MODE_NONE && userFolderPending &&
- !mFolderCreationAlarm.alarmPending()) {
+ if (mDragMode == DRAG_MODE_NONE && userFolderPending) {
- FolderCreationAlarmListener listener = new
- FolderCreationAlarmListener(targetLayout, targetCell[0], targetCell[1]);
+ mFolderCreateBg = new PreviewBackground();
+ mFolderCreateBg.setup(mLauncher, mLauncher, null,
+ dragOverView.getMeasuredWidth(), dragOverView.getPaddingTop());
- if (!dragObject.accessibleDrag) {
- mFolderCreationAlarm.setOnAlarmListener(listener);
- mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT);
- } else {
- listener.onAlarm(mFolderCreationAlarm);
- }
+ // The full preview background should appear behind the icon
+ mFolderCreateBg.isClipping = false;
+
+ mFolderCreateBg.animateToAccept(mDragTargetLayout, mTargetCell[0], mTargetCell[1]);
+ mDragTargetLayout.clearDragOutlines();
+ setDragMode(DRAG_MODE_CREATE_FOLDER);
if (dragObject.stateAnnouncer != null) {
dragObject.stateAnnouncer.announce(WorkspaceAccessibilityHelper
@@ -2329,8 +2254,8 @@
if (willAddToFolder && mDragMode == DRAG_MODE_NONE) {
mDragOverFolderIcon = ((FolderIcon) dragOverView);
mDragOverFolderIcon.onDragEnter(info);
- if (targetLayout != null) {
- targetLayout.clearDragOutlines();
+ if (mDragTargetLayout != null) {
+ mDragTargetLayout.clearDragOutlines();
}
setDragMode(DRAG_MODE_ADD_TO_FOLDER);
@@ -2349,33 +2274,6 @@
}
}
- class FolderCreationAlarmListener implements OnAlarmListener {
- final CellLayout layout;
- final int cellX;
- final int cellY;
-
- final PreviewBackground bg = new PreviewBackground();
-
- public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) {
- this.layout = layout;
- this.cellX = cellX;
- this.cellY = cellY;
-
- BubbleTextView cell = (BubbleTextView) layout.getChildAt(cellX, cellY);
- bg.setup(mLauncher, mLauncher, null, cell.getMeasuredWidth(), cell.getPaddingTop());
-
- // The full preview background should appear behind the icon
- bg.isClipping = false;
- }
-
- public void onAlarm(Alarm alarm) {
- mFolderCreateBg = bg;
- mFolderCreateBg.animateToAccept(layout, cellX, cellY);
- layout.clearDragOutlines();
- setDragMode(DRAG_MODE_CREATE_FOLDER);
- }
- }
-
class ReorderAlarmListener implements OnAlarmListener {
final float[] dragViewCenter;
final int minSpanX, minSpanY, spanX, spanY;
@@ -2412,7 +2310,7 @@
}
boolean resize = resultSpan[0] != spanX || resultSpan[1] != spanY;
- mDragTargetLayout.visualizeDropLocation(child, mOutlineProvider,
+ mDragTargetLayout.visualizeDropLocation(dragObject.originalView, mOutlineProvider,
mTargetCell[0], mTargetCell[1], resultSpan[0], resultSpan[1], resize, dragObject);
}
}
@@ -2775,7 +2673,7 @@
mDragInfo.container, mDragInfo.screenId);
if (cellLayout != null) {
cellLayout.onDropChild(mDragInfo.cell);
- } else if (FeatureFlags.IS_DOGFOOD_BUILD) {
+ } else if (FeatureFlags.IS_STUDIO_BUILD) {
throw new RuntimeException("Invalid state: cellLayout == null in "
+ "Workspace#onDropCompleted. Please file a bug. ");
}
@@ -2794,7 +2692,7 @@
CellLayout parentCell = getParentCellLayoutForView(v);
if (parentCell != null) {
parentCell.removeView(v);
- } else if (FeatureFlags.IS_DOGFOOD_BUILD) {
+ } else if (FeatureFlags.IS_STUDIO_BUILD) {
// When an app is uninstalled using the drop target, we wait until resume to remove
// the icon. We also remove all the corresponding items from the workspace at
// {@link Launcher#bindComponentsRemoved}. That call can come before or after
@@ -3309,17 +3207,21 @@
}
@Override
- public void fillInLogContainerData(View v, ItemInfo info, Target target, Target targetParent) {
- target.gridX = info.cellX;
- target.gridY = info.cellY;
- target.pageIndex = getCurrentPage();
- targetParent.containerType = ContainerType.WORKSPACE;
- if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
- target.rank = info.rank;
- targetParent.containerType = ContainerType.HOTSEAT;
- } else if (info.container >= 0) {
- targetParent.containerType = ContainerType.FOLDER;
+ public void fillInLogContainerData(ItemInfo childInfo, Target child,
+ ArrayList<Target> parents) {
+ if (childInfo.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT
+ || childInfo.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT_PREDICTION) {
+ getHotseat().fillInLogContainerData(childInfo, child, parents);
+ return;
+ } else if (childInfo.container >= 0) {
+ FolderIcon icon = (FolderIcon) getHomescreenIconByItemId(childInfo.container);
+ icon.getFolder().fillInLogContainerData(childInfo, child, parents);
+ return;
}
+ child.gridX = childInfo.cellX;
+ child.gridY = childInfo.cellY;
+ child.pageIndex = getCurrentPage();
+ parents.add(newContainerTarget(ContainerType.WORKSPACE));
}
/**
diff --git a/src/com/android/launcher3/WorkspaceLayoutManager.java b/src/com/android/launcher3/WorkspaceLayoutManager.java
index 0b9d602..c3d4aeb 100644
--- a/src/com/android/launcher3/WorkspaceLayoutManager.java
+++ b/src/com/android/launcher3/WorkspaceLayoutManager.java
@@ -21,6 +21,7 @@
import com.android.launcher3.folder.Folder;
import com.android.launcher3.folder.FolderIcon;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.touch.ItemLongClickListener;
public interface WorkspaceLayoutManager {
diff --git a/src/com/android/launcher3/WorkspaceStateTransitionAnimation.java b/src/com/android/launcher3/WorkspaceStateTransitionAnimation.java
index c33392d..c4c4377 100644
--- a/src/com/android/launcher3/WorkspaceStateTransitionAnimation.java
+++ b/src/com/android/launcher3/WorkspaceStateTransitionAnimation.java
@@ -18,28 +18,31 @@
import static com.android.launcher3.LauncherAnimUtils.DRAWABLE_ALPHA;
import static com.android.launcher3.LauncherAnimUtils.SCALE_PROPERTY;
+import static com.android.launcher3.LauncherAnimUtils.VIEW_ALPHA;
+import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_X;
+import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_Y;
import static com.android.launcher3.LauncherState.HOTSEAT_ICONS;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_HOTSEAT_SCALE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_HOTSEAT_TRANSLATE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_WORKSPACE_FADE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_WORKSPACE_SCALE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_WORKSPACE_TRANSLATE;
import static com.android.launcher3.anim.Interpolators.LINEAR;
import static com.android.launcher3.anim.Interpolators.ZOOM_OUT;
import static com.android.launcher3.anim.PropertySetter.NO_ANIM_PROPERTY_SETTER;
import static com.android.launcher3.graphics.WorkspaceAndHotseatScrim.SCRIM_PROGRESS;
import static com.android.launcher3.graphics.WorkspaceAndHotseatScrim.SYSUI_PROGRESS;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_HOTSEAT_SCALE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_HOTSEAT_TRANSLATE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_WORKSPACE_FADE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_WORKSPACE_SCALE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_WORKSPACE_TRANSLATE;
import android.view.View;
import android.view.animation.Interpolator;
import com.android.launcher3.LauncherState.PageAlphaProvider;
import com.android.launcher3.LauncherState.ScaleAndTranslation;
-import com.android.launcher3.LauncherStateManager.AnimationConfig;
import com.android.launcher3.allapps.AllAppsContainerView;
-import com.android.launcher3.anim.AnimatorSetBuilder;
+import com.android.launcher3.anim.PendingAnimation;
import com.android.launcher3.anim.PropertySetter;
import com.android.launcher3.graphics.WorkspaceAndHotseatScrim;
+import com.android.launcher3.states.StateAnimationConfig;
/**
* Manages the animations between each of the workspace states.
@@ -57,13 +60,15 @@
}
public void setState(LauncherState toState) {
- setWorkspaceProperty(toState, NO_ANIM_PROPERTY_SETTER, new AnimatorSetBuilder(),
- new AnimationConfig());
+ setWorkspaceProperty(toState, NO_ANIM_PROPERTY_SETTER, new StateAnimationConfig());
}
- public void setStateWithAnimation(LauncherState toState, AnimatorSetBuilder builder,
- AnimationConfig config) {
- setWorkspaceProperty(toState, config.getPropertySetter(builder), builder, config);
+ /**
+ * @see com.android.launcher3.LauncherStateManager.StateHandler#setStateWithAnimation
+ */
+ public void setStateWithAnimation(
+ LauncherState toState, StateAnimationConfig config, PendingAnimation animation) {
+ setWorkspaceProperty(toState, animation, config);
}
public float getFinalScale() {
@@ -74,7 +79,7 @@
* Starts a transition animation for the workspace.
*/
private void setWorkspaceProperty(LauncherState state, PropertySetter propertySetter,
- AnimatorSetBuilder builder, AnimationConfig config) {
+ StateAnimationConfig config) {
ScaleAndTranslation scaleAndTranslation = state.getWorkspaceScaleAndTranslation(mLauncher);
ScaleAndTranslation hotseatScaleAndTranslation = state.getHotseatScaleAndTranslation(
mLauncher);
@@ -84,11 +89,11 @@
final int childCount = mWorkspace.getChildCount();
for (int i = 0; i < childCount; i++) {
applyChildState(state, (CellLayout) mWorkspace.getChildAt(i), i, pageAlphaProvider,
- propertySetter, builder, config);
+ propertySetter, config);
}
int elements = state.getVisibleElements(mLauncher);
- Interpolator fadeInterpolator = builder.getInterpolator(ANIM_WORKSPACE_FADE,
+ Interpolator fadeInterpolator = config.getInterpolator(ANIM_WORKSPACE_FADE,
pageAlphaProvider.interpolator);
boolean playAtomicComponent = config.playAtomicOverviewScaleComponent();
Hotseat hotseat = mWorkspace.getHotseat();
@@ -96,15 +101,13 @@
AllAppsContainerView qsbScaleView = mLauncher.getAppsView();
View qsbView = qsbScaleView.getSearchView();
if (playAtomicComponent) {
- Interpolator scaleInterpolator = builder.getInterpolator(ANIM_WORKSPACE_SCALE, ZOOM_OUT);
+ Interpolator scaleInterpolator = config.getInterpolator(ANIM_WORKSPACE_SCALE, ZOOM_OUT);
propertySetter.setFloat(mWorkspace, SCALE_PROPERTY, mNewScale, scaleInterpolator);
- if (!hotseat.getRotationMode().isTransposed) {
- setPivotToScaleWithWorkspace(hotseat);
- setPivotToScaleWithWorkspace(qsbScaleView);
- }
+ setPivotToScaleWithWorkspace(hotseat);
+ setPivotToScaleWithWorkspace(qsbScaleView);
float hotseatScale = hotseatScaleAndTranslation.scale;
- Interpolator hotseatScaleInterpolator = builder.getInterpolator(ANIM_HOTSEAT_SCALE,
+ Interpolator hotseatScaleInterpolator = config.getInterpolator(ANIM_HOTSEAT_SCALE,
scaleInterpolator);
propertySetter.setFloat(hotseat, SCALE_PROPERTY, hotseatScale,
hotseatScaleInterpolator);
@@ -117,26 +120,26 @@
hotseatIconsAlpha, fadeInterpolator);
}
- if (!config.playNonAtomicComponent()) {
+ if (config.onlyPlayAtomicComponent()) {
// Only the alpha and scale, handled above, are included in the atomic animation.
return;
}
Interpolator translationInterpolator = !playAtomicComponent
? LINEAR
- : builder.getInterpolator(ANIM_WORKSPACE_TRANSLATE, ZOOM_OUT);
- propertySetter.setFloat(mWorkspace, View.TRANSLATION_X,
+ : config.getInterpolator(ANIM_WORKSPACE_TRANSLATE, ZOOM_OUT);
+ propertySetter.setFloat(mWorkspace, VIEW_TRANSLATE_X,
scaleAndTranslation.translationX, translationInterpolator);
- propertySetter.setFloat(mWorkspace, View.TRANSLATION_Y,
+ propertySetter.setFloat(mWorkspace, VIEW_TRANSLATE_Y,
scaleAndTranslation.translationY, translationInterpolator);
- Interpolator hotseatTranslationInterpolator = builder.getInterpolator(
+ Interpolator hotseatTranslationInterpolator = config.getInterpolator(
ANIM_HOTSEAT_TRANSLATE, translationInterpolator);
- propertySetter.setFloat(hotseat, View.TRANSLATION_Y,
+ propertySetter.setFloat(hotseat, VIEW_TRANSLATE_Y,
hotseatScaleAndTranslation.translationY, hotseatTranslationInterpolator);
- propertySetter.setFloat(mWorkspace.getPageIndicator(), View.TRANSLATION_Y,
+ propertySetter.setFloat(mWorkspace.getPageIndicator(), VIEW_TRANSLATE_Y,
hotseatScaleAndTranslation.translationY, hotseatTranslationInterpolator);
- propertySetter.setFloat(qsbView, View.TRANSLATION_Y,
+ propertySetter.setFloat(qsbView, VIEW_TRANSLATE_Y,
qsbScaleAndTranslation.translationY, hotseatTranslationInterpolator);
setScrim(propertySetter, state);
@@ -163,23 +166,24 @@
public void applyChildState(LauncherState state, CellLayout cl, int childIndex) {
applyChildState(state, cl, childIndex, state.getWorkspacePageAlphaProvider(mLauncher),
- NO_ANIM_PROPERTY_SETTER, new AnimatorSetBuilder(), new AnimationConfig());
+ NO_ANIM_PROPERTY_SETTER, new StateAnimationConfig());
}
private void applyChildState(LauncherState state, CellLayout cl, int childIndex,
PageAlphaProvider pageAlphaProvider, PropertySetter propertySetter,
- AnimatorSetBuilder builder, AnimationConfig config) {
+ StateAnimationConfig config) {
float pageAlpha = pageAlphaProvider.getPageAlpha(childIndex);
int drawableAlpha = Math.round(pageAlpha * (state.hasWorkspacePageBackground ? 255 : 0));
- if (config.playNonAtomicComponent()) {
+ if (!config.onlyPlayAtomicComponent()) {
+ // Don't update the scrim during the atomic animation.
propertySetter.setInt(cl.getScrimBackground(),
DRAWABLE_ALPHA, drawableAlpha, ZOOM_OUT);
}
if (config.playAtomicOverviewScaleComponent()) {
- Interpolator fadeInterpolator = builder.getInterpolator(ANIM_WORKSPACE_FADE,
+ Interpolator fadeInterpolator = config.getInterpolator(ANIM_WORKSPACE_FADE,
pageAlphaProvider.interpolator);
- propertySetter.setFloat(cl.getShortcutsAndWidgets(), View.ALPHA,
+ propertySetter.setFloat(cl.getShortcutsAndWidgets(), VIEW_ALPHA,
pageAlpha, fadeInterpolator);
}
}
diff --git a/src/com/android/launcher3/accessibility/AccessibleDragListenerAdapter.java b/src/com/android/launcher3/accessibility/AccessibleDragListenerAdapter.java
index f8df5d7..0d7df2b 100644
--- a/src/com/android/launcher3/accessibility/AccessibleDragListenerAdapter.java
+++ b/src/com/android/launcher3/accessibility/AccessibleDragListenerAdapter.java
@@ -16,7 +16,9 @@
package com.android.launcher3.accessibility;
+import android.view.View;
import android.view.ViewGroup;
+import android.view.ViewGroup.OnHierarchyChangeListener;
import com.android.launcher3.CellLayout;
import com.android.launcher3.DropTarget.DragObject;
@@ -24,36 +26,55 @@
import com.android.launcher3.dragndrop.DragController.DragListener;
import com.android.launcher3.dragndrop.DragOptions;
+import java.util.function.Function;
+
/**
* Utility listener to enable/disable accessibility drag flags for a ViewGroup
* containing CellLayouts
*/
-public class AccessibleDragListenerAdapter implements DragListener {
+public class AccessibleDragListenerAdapter implements DragListener, OnHierarchyChangeListener {
private final ViewGroup mViewGroup;
- private final int mDragType;
+ private final Function<CellLayout, DragAndDropAccessibilityDelegate> mDelegateFactory;
/**
- * @param parent
- * @param dragType either {@link CellLayout#WORKSPACE_ACCESSIBILITY_DRAG} or
- * {@link CellLayout#FOLDER_ACCESSIBILITY_DRAG}
+ * @param parent the viewgroup containing all the children
+ * @param delegateFactory function to create no delegates
*/
- public AccessibleDragListenerAdapter(ViewGroup parent, int dragType) {
+ public AccessibleDragListenerAdapter(ViewGroup parent,
+ Function<CellLayout, DragAndDropAccessibilityDelegate> delegateFactory) {
mViewGroup = parent;
- mDragType = dragType;
+ mDelegateFactory = delegateFactory;
}
@Override
public void onDragStart(DragObject dragObject, DragOptions options) {
+ mViewGroup.setOnHierarchyChangeListener(this);
enableAccessibleDrag(true);
}
@Override
public void onDragEnd() {
+ mViewGroup.setOnHierarchyChangeListener(null);
enableAccessibleDrag(false);
Launcher.getLauncher(mViewGroup.getContext()).getDragController().removeDragListener(this);
}
+
+ @Override
+ public void onChildViewAdded(View parent, View child) {
+ if (parent == mViewGroup) {
+ setEnableForLayout((CellLayout) child, true);
+ }
+ }
+
+ @Override
+ public void onChildViewRemoved(View parent, View child) {
+ if (parent == mViewGroup) {
+ setEnableForLayout((CellLayout) child, false);
+ }
+ }
+
protected void enableAccessibleDrag(boolean enable) {
for (int i = 0; i < mViewGroup.getChildCount(); i++) {
setEnableForLayout((CellLayout) mViewGroup.getChildAt(i), enable);
@@ -61,6 +82,6 @@
}
protected final void setEnableForLayout(CellLayout layout, boolean enable) {
- layout.enableAccessibleDrag(enable, mDragType);
+ layout.setDragAndDropAccessibilityDelegate(enable ? mDelegateFactory.apply(layout) : null);
}
}
diff --git a/src/com/android/launcher3/accessibility/DragAndDropAccessibilityDelegate.java b/src/com/android/launcher3/accessibility/DragAndDropAccessibilityDelegate.java
index 117296d..ddb547f 100644
--- a/src/com/android/launcher3/accessibility/DragAndDropAccessibilityDelegate.java
+++ b/src/com/android/launcher3/accessibility/DragAndDropAccessibilityDelegate.java
@@ -19,24 +19,26 @@
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
+import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
+import android.view.View.OnHoverListener;
import android.view.accessibility.AccessibilityEvent;
+import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
+import androidx.customview.widget.ExploreByTouchHelper;
+
import com.android.launcher3.CellLayout;
import com.android.launcher3.Launcher;
import com.android.launcher3.R;
import java.util.List;
-import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
-import androidx.customview.widget.ExploreByTouchHelper;
-
/**
* Helper class to make drag-and-drop in a {@link CellLayout} accessible.
*/
public abstract class DragAndDropAccessibilityDelegate extends ExploreByTouchHelper
- implements OnClickListener {
+ implements OnClickListener, OnHoverListener {
protected static final int INVALID_POSITION = -1;
private static final int[] sTempArray = new int[2];
@@ -123,6 +125,11 @@
node.setFocusable(true);
}
+ @Override
+ public boolean onHover(View view, MotionEvent motionEvent) {
+ return dispatchHoverEvent(motionEvent);
+ }
+
protected abstract String getLocationDescriptionForIconDrop(int id);
protected abstract String getConfirmationForIconDrop(int id);
diff --git a/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java b/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java
index 0b439ec..136d43e 100644
--- a/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java
+++ b/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java
@@ -7,6 +7,7 @@
import android.app.AlertDialog;
import android.appwidget.AppWidgetProviderInfo;
import android.content.DialogInterface;
+import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
@@ -18,26 +19,26 @@
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
-import com.android.launcher3.AppInfo;
import com.android.launcher3.AppWidgetResizeFrame;
import com.android.launcher3.BubbleTextView;
import com.android.launcher3.ButtonDropTarget;
import com.android.launcher3.CellLayout;
import com.android.launcher3.DropTarget.DragObject;
-import com.android.launcher3.FolderInfo;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.Launcher;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.PendingAddItemInfo;
import com.android.launcher3.R;
import com.android.launcher3.Workspace;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.dragndrop.DragController.DragListener;
import com.android.launcher3.dragndrop.DragOptions;
import com.android.launcher3.folder.Folder;
import com.android.launcher3.keyboard.CustomActionsPopup;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.FolderInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.notification.NotificationListener;
import com.android.launcher3.popup.PopupContainerWithArrow;
import com.android.launcher3.touch.ItemLongClickListener;
@@ -55,6 +56,7 @@
public static final int REMOVE = R.id.action_remove;
public static final int UNINSTALL = R.id.action_uninstall;
public static final int DISMISS_PREDICTION = R.id.action_dismiss_prediction;
+ public static final int PIN_PREDICTION = R.id.action_pin_prediction;
public static final int RECONFIGURE = R.id.action_reconfigure;
protected static final int ADD_TO_WORKSPACE = R.id.action_add_to_workspace;
protected static final int MOVE = R.id.action_move;
@@ -119,6 +121,10 @@
if (!(host.getTag() instanceof ItemInfo)) return;
ItemInfo item = (ItemInfo) host.getTag();
+ if (host instanceof AccessibilityActionHandler) {
+ ((AccessibilityActionHandler) host).addSupportedAccessibilityActions(info);
+ }
+
// If the request came from keyboard, do not add custom shortcuts as that is already
// exposed as a direct shortcut
if (!fromKeyboard && ShortcutUtil.supportsShortcuts(item)) {
@@ -145,15 +151,25 @@
}
}
+ if (!fromKeyboard && !itemSupportsLongClick(host, item)) {
+ info.setLongClickable(false);
+ info.removeAction(AccessibilityAction.ACTION_LONG_CLICK);
+ }
+
if ((item instanceof AppInfo) || (item instanceof PendingAddItemInfo)) {
info.addAction(mActions.get(ADD_TO_WORKSPACE));
}
}
+ private boolean itemSupportsLongClick(View host, ItemInfo info) {
+ return PopupContainerWithArrow.canShow(host, info)
+ || new CustomActionsPopup(mLauncher, host).canShow();
+ }
+
private boolean itemSupportsAccessibleDrag(ItemInfo item) {
if (item instanceof WorkspaceItemInfo) {
// Support the action unless the item is in a context menu.
- return item.screenId >= 0;
+ return item.screenId >= 0 && item.container != Favorites.CONTAINER_HOTSEAT_PREDICTION;
}
return (item instanceof LauncherAppWidgetInfo)
|| (item instanceof FolderInfo);
@@ -170,21 +186,24 @@
public boolean performAction(final View host, final ItemInfo item, int action) {
if (action == ACTION_LONG_CLICK) {
- if (ShortcutUtil.isDeepShortcut(item)) {
- CustomActionsPopup popup = new CustomActionsPopup(mLauncher, host);
- if (popup.canShow()) {
- popup.show();
- return true;
- }
- } else if (host instanceof BubbleTextView) {
+ if (PopupContainerWithArrow.canShow(host, item)) {
// Long press should be consumed for workspace items, and it should invoke the
// Shortcuts / Notifications / Actions pop-up menu, and not start a drag as the
// standard long press path does.
PopupContainerWithArrow.showForIcon((BubbleTextView) host);
return true;
+ } else {
+ CustomActionsPopup popup = new CustomActionsPopup(mLauncher, host);
+ if (popup.canShow()) {
+ popup.show();
+ return true;
+ }
}
}
-
+ if (host instanceof AccessibilityActionHandler
+ && ((AccessibilityActionHandler) host).performAccessibilityAction(action, item)) {
+ return true;
+ }
if (action == MOVE) {
beginAccessibleDrag(host, item);
} else if (action == ADD_TO_WORKSPACE) {
@@ -400,11 +419,11 @@
Rect pos = new Rect();
mLauncher.getDragLayer().getDescendantRectRelativeToSelf(item, pos);
- mLauncher.getDragController().prepareAccessibleDrag(pos.centerX(), pos.centerY());
mLauncher.getDragController().addDragListener(this);
DragOptions options = new DragOptions();
options.isAccessibleDrag = true;
+ options.simulatedDndStartPoint = new Point(pos.centerX(), pos.centerY());
ItemLongClickListener.beginDrag(item, mLauncher, info, options);
}
@@ -455,4 +474,20 @@
}
return screenId;
}
+
+ /**
+ * An interface allowing views to handle their own action.
+ */
+ public interface AccessibilityActionHandler {
+
+ /**
+ * performs accessibility action and returns true on success
+ */
+ boolean performAccessibilityAction(int action, ItemInfo itemInfo);
+
+ /**
+ * adds all the accessibility actions that can be handled.
+ */
+ void addSupportedAccessibilityActions(AccessibilityNodeInfo accessibilityNodeInfo);
+ }
}
diff --git a/src/com/android/launcher3/accessibility/ShortcutMenuAccessibilityDelegate.java b/src/com/android/launcher3/accessibility/ShortcutMenuAccessibilityDelegate.java
index c0c0b37..d4ba11e 100644
--- a/src/com/android/launcher3/accessibility/ShortcutMenuAccessibilityDelegate.java
+++ b/src/com/android/launcher3/accessibility/ShortcutMenuAccessibilityDelegate.java
@@ -23,11 +23,11 @@
import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
import com.android.launcher3.AbstractFloatingView;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.R;
-import com.android.launcher3.WorkspaceItemInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.notification.NotificationMainView;
import com.android.launcher3.shortcuts.DeepShortcutView;
diff --git a/src/com/android/launcher3/accessibility/WorkspaceAccessibilityHelper.java b/src/com/android/launcher3/accessibility/WorkspaceAccessibilityHelper.java
index 17daeb8..65a261d 100644
--- a/src/com/android/launcher3/accessibility/WorkspaceAccessibilityHelper.java
+++ b/src/com/android/launcher3/accessibility/WorkspaceAccessibilityHelper.java
@@ -21,17 +21,17 @@
import android.text.TextUtils;
import android.view.View;
-import com.android.launcher3.AppInfo;
+import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
+
import com.android.launcher3.CellLayout;
-import com.android.launcher3.FolderInfo;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.Launcher;
import com.android.launcher3.R;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.accessibility.LauncherAccessibilityDelegate.DragType;
import com.android.launcher3.dragndrop.DragLayer;
-
-import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.FolderInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
/**
* Implementation of {@link DragAndDropAccessibilityDelegate} to support DnD on workspace.
diff --git a/src/com/android/launcher3/allapps/AllAppsContainerView.java b/src/com/android/launcher3/allapps/AllAppsContainerView.java
index 56bd1b6..a45c96c 100644
--- a/src/com/android/launcher3/allapps/AllAppsContainerView.java
+++ b/src/com/android/launcher3/allapps/AllAppsContainerView.java
@@ -15,8 +15,7 @@
*/
package com.android.launcher3.allapps;
-import static android.view.View.MeasureSpec.EXACTLY;
-import static android.view.View.MeasureSpec.makeMeasureSpec;
+import static com.android.launcher3.logging.LoggerUtils.newContainerTarget;
import android.animation.ValueAnimator;
import android.content.Context;
@@ -39,10 +38,10 @@
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.dynamicanimation.animation.DynamicAnimation;
+import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
-import com.android.launcher3.AppInfo;
import com.android.launcher3.BaseDraggingActivity;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.DeviceProfile.OnDeviceProfileChangeListener;
@@ -50,10 +49,11 @@
import com.android.launcher3.DropTarget.DragObject;
import com.android.launcher3.Insettable;
import com.android.launcher3.InsettableFrameLayout;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.keyboard.FocusedItemDecorator;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.pm.UserCache;
import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
@@ -63,7 +63,8 @@
import com.android.launcher3.util.Themes;
import com.android.launcher3.views.RecyclerViewFastScroller;
import com.android.launcher3.views.SpringRelativeLayout;
-import com.android.launcher3.views.WorkFooterContainer;
+
+import java.util.ArrayList;
/**
* The all apps view container.
@@ -90,7 +91,7 @@
private AllAppsPagedView mViewPager;
private FloatingHeaderView mHeader;
- private WorkFooterContainer mWorkFooterContainer;
+ private WorkModeSwitch mWorkModeSwitch;
private SpannableStringBuilder mSearchQueryBuilder = null;
@@ -98,11 +99,13 @@
protected boolean mUsingTabs;
private boolean mSearchModeWhileUsingTabs = false;
- private RecyclerViewFastScroller mTouchHandler;
- private final Point mFastScrollerOffset = new Point();
+ protected RecyclerViewFastScroller mTouchHandler;
+ protected final Point mFastScrollerOffset = new Point();
private final MultiValueAlpha mMultiValueAlpha;
+ Rect mInsets = new Rect();
+
public AllAppsContainerView(Context context) {
this(context, null);
}
@@ -153,6 +156,11 @@
return mMultiValueAlpha.getProperty(index);
}
+ public WorkModeSwitch getWorkModeSwitch() {
+ return mWorkModeSwitch;
+ }
+
+
@Override
protected void setDampedScrollShift(float shift) {
// Bound the shift amount to avoid content from drawing on top (Y-val) of the QSB.
@@ -187,7 +195,7 @@
}
private void resetWorkProfile() {
- mWorkFooterContainer.refresh();
+ mWorkModeSwitch.refresh();
mAH[AdapterHolder.WORK].setupOverlay();
mAH[AdapterHolder.WORK].applyPadding();
}
@@ -231,6 +239,16 @@
@Override
public boolean onTouchEvent(MotionEvent ev) {
+ if (ev.getAction() == MotionEvent.ACTION_DOWN) {
+ AllAppsRecyclerView rv = getActiveRecyclerView();
+ if (rv != null && rv.getScrollbar().isHitInParent(ev.getX(), ev.getY(),
+ mFastScrollerOffset)) {
+ mTouchHandler = rv.getScrollbar();
+ } else {
+ mTouchHandler = null;
+
+ }
+ }
if (mTouchHandler != null) {
mTouchHandler.handleTouchEvent(ev, mFastScrollerOffset);
return true;
@@ -310,16 +328,15 @@
}
@Override
- public void fillInLogContainerData(View v, ItemInfo info, Target target, Target targetParent) {
- if (getApps().hasFilter()) {
- targetParent.containerType = ContainerType.SEARCHRESULT;
- } else {
- targetParent.containerType = ContainerType.ALLAPPS;
- }
+ public void fillInLogContainerData(ItemInfo childInfo, Target child,
+ ArrayList<Target> parents) {
+ parents.add(newContainerTarget(
+ getApps().hasFilter() ? ContainerType.SEARCHRESULT : ContainerType.ALLAPPS));
}
@Override
public void setInsets(Rect insets) {
+ mInsets.set(insets);
DeviceProfile grid = mLauncher.getDeviceProfile();
int leftRightPadding = grid.desiredWorkspaceLeftRightMarginPx
+ grid.cellLayoutPaddingLeftRightPx;
@@ -375,7 +392,7 @@
rebindAdapters(showTabs, false /* force */);
}
- private void rebindAdapters(boolean showTabs, boolean force) {
+ protected void rebindAdapters(boolean showTabs, boolean force) {
if (showTabs == mUsingTabs && !force) {
return;
}
@@ -389,13 +406,18 @@
setupWorkToggle();
mAH[AdapterHolder.MAIN].setup(mViewPager.getChildAt(0), mPersonalMatcher);
mAH[AdapterHolder.WORK].setup(mViewPager.getChildAt(1), mWorkMatcher);
+ mViewPager.getPageIndicator().setActiveMarker(AdapterHolder.MAIN);
+ findViewById(R.id.tab_personal)
+ .setOnClickListener((View view) -> mViewPager.snapToPage(AdapterHolder.MAIN));
+ findViewById(R.id.tab_work)
+ .setOnClickListener((View view) -> mViewPager.snapToPage(AdapterHolder.WORK));
onTabChanged(mViewPager.getNextPage());
} else {
mAH[AdapterHolder.MAIN].setup(findViewById(R.id.apps_list_view), null);
mAH[AdapterHolder.WORK].recyclerView = null;
- if (mWorkFooterContainer != null) {
- ((ViewGroup) mWorkFooterContainer.getParent()).removeView(mWorkFooterContainer);
- mWorkFooterContainer = null;
+ if (mWorkModeSwitch != null) {
+ ((ViewGroup) mWorkModeSwitch.getParent()).removeView(mWorkModeSwitch);
+ mWorkModeSwitch = null;
}
}
setupHeader();
@@ -405,13 +427,11 @@
}
private void setupWorkToggle() {
- mWorkFooterContainer = (WorkFooterContainer) mLauncher.getLayoutInflater().inflate(
- R.layout.work_tab_footer, findViewById(R.id.work_toggle_container));
- mWorkFooterContainer.setLayoutParams(
- new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
- ViewGroup.LayoutParams.WRAP_CONTENT));
- this.addView(mWorkFooterContainer);
- mWorkFooterContainer.post(() -> mAH[AdapterHolder.WORK].applyPadding());
+ mWorkModeSwitch = (WorkModeSwitch) mLauncher.getLayoutInflater().inflate(
+ R.layout.work_mode_switch, this, false);
+ this.addView(mWorkModeSwitch);
+ mWorkModeSwitch.setInsets(mInsets);
+ mWorkModeSwitch.post(() -> mAH[AdapterHolder.WORK].applyPadding());
}
private void replaceRVContainer(boolean showTabs) {
@@ -441,17 +461,12 @@
public void onTabChanged(int pos) {
mHeader.setMainActive(pos == 0);
- reset(true /* animate */);
if (mAH[pos].recyclerView != null) {
mAH[pos].recyclerView.bindFastScrollbar();
-
- findViewById(R.id.tab_personal)
- .setOnClickListener((View view) -> mViewPager.snapToPage(AdapterHolder.MAIN));
- findViewById(R.id.tab_work)
- .setOnClickListener((View view) -> mViewPager.snapToPage(AdapterHolder.WORK));
}
- if (mWorkFooterContainer != null) {
- mWorkFooterContainer.setWorkTabVisible(pos == AdapterHolder.WORK);
+ reset(true /* animate */);
+ if (mWorkModeSwitch != null) {
+ mWorkModeSwitch.setWorkTabVisible(pos == AdapterHolder.WORK);
}
}
@@ -548,17 +563,6 @@
return mHeader != null && mHeader.getVisibility() == View.VISIBLE;
}
- public void onScrollUpEnd() {
- highlightWorkTabIfNecessary();
- }
-
- void highlightWorkTabIfNecessary() {
- if (mUsingTabs) {
- ((PersonalWorkSlidingTabStrip) findViewById(R.id.tabs))
- .highlightWorkTabIfNecessary();
- }
- }
-
/**
* Adds an update listener to {@param animator} that adds springs to the animation.
*/
@@ -598,6 +602,7 @@
public static final int MAIN = 0;
public static final int WORK = 1;
+ private ItemInfoMatcher mInfoMatcher;
private final boolean mIsWork;
public final AllAppsGridAdapter adapter;
final LinearLayoutManager layoutManager;
@@ -605,6 +610,7 @@
final Rect padding = new Rect();
AllAppsRecyclerView recyclerView;
boolean verticalFadingEdge;
+ private View mOverlay;
boolean mWorkDisabled;
@@ -617,6 +623,7 @@
}
void setup(@NonNull View rv, @Nullable ItemInfoMatcher matcher) {
+ mInfoMatcher = matcher;
appsList.updateItemFilter(matcher);
recyclerView = (AllAppsRecyclerView) rv;
recyclerView.setEdgeEffectFactory(createEdgeEffectFactory());
@@ -637,19 +644,23 @@
void setupOverlay() {
if (!mIsWork || recyclerView == null) return;
boolean workDisabled = UserCache.INSTANCE.get(mLauncher).isAnyProfileQuietModeEnabled();
- recyclerView.getOverlay().clear();
+ if (mWorkDisabled == workDisabled) return;
+ recyclerView.setContentDescription(workDisabled ? mLauncher.getString(
+ R.string.work_apps_paused_content_description) : null);
+ View overlayView = getOverlayView();
+ recyclerView.setItemAnimator(new DefaultItemAnimator());
if (workDisabled) {
- View pausedOverlay = mLauncher.getLayoutInflater().inflate(
- R.layout.work_apps_paused, null);
- recyclerView.post(() -> {
- int width = recyclerView.getWidth();
- int height = recyclerView.getHeight();
- pausedOverlay.measure(makeMeasureSpec(width, EXACTLY),
- makeMeasureSpec(height, EXACTLY));
- pausedOverlay.layout(0, 0, width, height);
- applyPadding();
- });
- recyclerView.getOverlay().add(pausedOverlay);
+ overlayView.setAlpha(0);
+ appsList.updateItemFilter((info, cn) -> false);
+ recyclerView.addAutoSizedOverlay(overlayView);
+ overlayView.animate().alpha(1).withEndAction(
+ () -> recyclerView.setItemAnimator(null)).start();
+ } else if (mInfoMatcher != null) {
+ appsList.updateItemFilter(mInfoMatcher);
+ overlayView.animate().alpha(0).withEndAction(() -> {
+ recyclerView.setItemAnimator(null);
+ recyclerView.clearAutoSizedOverlays();
+ }).start();
}
mWorkDisabled = workDisabled;
}
@@ -657,8 +668,7 @@
void applyPadding() {
if (recyclerView != null) {
int bottomOffset =
- mWorkFooterContainer != null && mIsWork ? mWorkFooterContainer.getHeight()
- : 0;
+ mWorkModeSwitch != null && mIsWork ? mWorkModeSwitch.getHeight() : 0;
recyclerView.setPadding(padding.left, padding.top, padding.right,
padding.bottom + bottomOffset);
}
@@ -669,5 +679,12 @@
mAH[AdapterHolder.MAIN].recyclerView.setVerticalFadingEdgeEnabled(!mUsingTabs
&& verticalFadingEdge);
}
+
+ private View getOverlayView() {
+ if (mOverlay == null) {
+ mOverlay = mLauncher.getLayoutInflater().inflate(R.layout.work_apps_paused, null);
+ }
+ return mOverlay;
+ }
}
}
diff --git a/src/com/android/launcher3/allapps/AllAppsGridAdapter.java b/src/com/android/launcher3/allapps/AllAppsGridAdapter.java
index 1f861bc..4aebec0 100644
--- a/src/com/android/launcher3/allapps/AllAppsGridAdapter.java
+++ b/src/com/android/launcher3/allapps/AllAppsGridAdapter.java
@@ -37,12 +37,12 @@
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
-import com.android.launcher3.AppInfo;
import com.android.launcher3.BaseDraggingActivity;
import com.android.launcher3.BubbleTextView;
import com.android.launcher3.R;
import com.android.launcher3.allapps.AlphabeticalAppsList.AdapterItem;
import com.android.launcher3.model.AppLaunchTracker;
+import com.android.launcher3.model.data.AppInfo;
import com.android.launcher3.util.PackageManagerHelper;
import java.util.List;
diff --git a/src/com/android/launcher3/allapps/AllAppsPagedView.java b/src/com/android/launcher3/allapps/AllAppsPagedView.java
index 5b73940..f640c3e 100644
--- a/src/com/android/launcher3/allapps/AllAppsPagedView.java
+++ b/src/com/android/launcher3/allapps/AllAppsPagedView.java
@@ -48,7 +48,7 @@
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
- mPageIndicator.setScroll(l, mMaxScrollX);
+ mPageIndicator.setScroll(l, mMaxScroll);
}
@Override
@@ -83,7 +83,7 @@
}
@Override
- protected boolean isVerticalScrollable() {
- return false;
+ protected boolean canScroll(float absVScroll, float absHScroll) {
+ return (absHScroll > absVScroll) && super.canScroll(absVScroll, absHScroll);
}
}
diff --git a/src/com/android/launcher3/allapps/AllAppsRecyclerView.java b/src/com/android/launcher3/allapps/AllAppsRecyclerView.java
index b6744cf..069472f 100644
--- a/src/com/android/launcher3/allapps/AllAppsRecyclerView.java
+++ b/src/com/android/launcher3/allapps/AllAppsRecyclerView.java
@@ -15,7 +15,11 @@
*/
package com.android.launcher3.allapps;
+import static android.view.View.MeasureSpec.EXACTLY;
import static android.view.View.MeasureSpec.UNSPECIFIED;
+import static android.view.View.MeasureSpec.makeMeasureSpec;
+
+import static com.android.launcher3.logging.LoggerUtils.newContainerTarget;
import android.content.Context;
import android.content.res.Resources;
@@ -31,15 +35,16 @@
import com.android.launcher3.BaseDraggingActivity;
import com.android.launcher3.BaseRecyclerView;
import com.android.launcher3.DeviceProfile;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.R;
import com.android.launcher3.allapps.AllAppsGridAdapter.AppsGridLayoutManager;
import com.android.launcher3.logging.StatsLogUtils.LogContainerProvider;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
import com.android.launcher3.views.RecyclerViewFastScroller;
+import java.util.ArrayList;
import java.util.List;
/**
@@ -59,6 +64,8 @@
private AllAppsBackgroundDrawable mEmptySearchBackground;
private int mEmptySearchBackgroundTopOffset;
+ private ArrayList<View> mAutoSizedOverlays = new ArrayList<>();
+
public AllAppsRecyclerView(Context context) {
this(context, null);
}
@@ -142,15 +149,37 @@
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
updateEmptySearchBackgroundBounds();
updatePoolSize();
+ for (int i = 0; i < mAutoSizedOverlays.size(); i++) {
+ View overlay = mAutoSizedOverlays.get(i);
+ overlay.measure(makeMeasureSpec(w, EXACTLY), makeMeasureSpec(w, EXACTLY));
+ overlay.layout(0, 0, w, h);
+ }
+ }
+
+ /**
+ * Adds an overlay that automatically rescales with the recyclerview.
+ */
+ public void addAutoSizedOverlay(View overlay) {
+ mAutoSizedOverlays.add(overlay);
+ getOverlay().add(overlay);
+ onSizeChanged(getWidth(), getHeight(), getWidth(), getHeight());
+ }
+
+ /**
+ * Clears auto scaling overlay views added by #addAutoSizedOverlay
+ */
+ public void clearAutoSizedOverlays() {
+ for (View v : mAutoSizedOverlays) {
+ getOverlay().remove(v);
+ }
+ mAutoSizedOverlays.clear();
}
@Override
- public void fillInLogContainerData(View v, ItemInfo info, Target target, Target targetParent) {
- if (mApps.hasFilter()) {
- targetParent.containerType = ContainerType.SEARCHRESULT;
- } else {
- targetParent.containerType = ContainerType.ALLAPPS;
- }
+ public void fillInLogContainerData(ItemInfo childInfo, Target child,
+ ArrayList<Target> parents) {
+ parents.add(newContainerTarget(
+ getApps().hasFilter() ? ContainerType.SEARCHRESULT : ContainerType.ALLAPPS));
}
public void onSearchResultsChanged() {
diff --git a/src/com/android/launcher3/allapps/AllAppsStore.java b/src/com/android/launcher3/allapps/AllAppsStore.java
index c4b2f68..d2dcfd2 100644
--- a/src/com/android/launcher3/allapps/AllAppsStore.java
+++ b/src/com/android/launcher3/allapps/AllAppsStore.java
@@ -15,16 +15,17 @@
*/
package com.android.launcher3.allapps;
-import static com.android.launcher3.AppInfo.COMPONENT_KEY_COMPARATOR;
-import static com.android.launcher3.AppInfo.EMPTY_ARRAY;
+import static com.android.launcher3.model.data.AppInfo.COMPONENT_KEY_COMPARATOR;
+import static com.android.launcher3.model.data.AppInfo.EMPTY_ARRAY;
+import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
-import com.android.launcher3.AppInfo;
import com.android.launcher3.BubbleTextView;
-import com.android.launcher3.ItemInfo;
-import com.android.launcher3.PromiseAppInfo;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.PromiseAppInfo;
import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.PackageUserKey;
@@ -55,6 +56,8 @@
private int mDeferUpdatesFlags = 0;
private boolean mUpdatePending = false;
+ private boolean mListenerUpdateInProgress = false;
+
public AppInfo[] getApps() {
return mApps;
}
@@ -99,10 +102,12 @@
mUpdatePending = true;
return;
}
+ mListenerUpdateInProgress = true;
int count = mUpdateListeners.size();
for (int i = 0; i < count; i++) {
mUpdateListeners.get(i).onAppsUpdated();
}
+ mListenerUpdateInProgress = false;
}
public void addUpdateListener(OnUpdateListener listener) {
@@ -110,6 +115,9 @@
}
public void removeUpdateListener(OnUpdateListener listener) {
+ if (mListenerUpdateInProgress) {
+ Log.e("AllAppsStore", "Trying to remove listener during update", new Exception());
+ }
mUpdateListeners.remove(listener);
}
diff --git a/src/com/android/launcher3/allapps/AllAppsTransitionController.java b/src/com/android/launcher3/allapps/AllAppsTransitionController.java
index 1bde138..68b0706 100644
--- a/src/com/android/launcher3/allapps/AllAppsTransitionController.java
+++ b/src/com/android/launcher3/allapps/AllAppsTransitionController.java
@@ -2,16 +2,16 @@
import static com.android.launcher3.LauncherState.ALL_APPS_CONTENT;
import static com.android.launcher3.LauncherState.ALL_APPS_HEADER_EXTRA;
+import static com.android.launcher3.LauncherState.APPS_VIEW_ITEM_MASK;
import static com.android.launcher3.LauncherState.OVERVIEW;
import static com.android.launcher3.LauncherState.VERTICAL_SWIPE_INDICATOR;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_ALL_APPS_FADE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_ALL_APPS_HEADER_FADE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_SCALE;
-import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_VERTICAL_PROGRESS;
import static com.android.launcher3.anim.Interpolators.FAST_OUT_SLOW_IN;
import static com.android.launcher3.anim.Interpolators.LINEAR;
import static com.android.launcher3.anim.PropertySetter.NO_ANIM_PROPERTY_SETTER;
-import static com.android.launcher3.config.FeatureFlags.QUICKSTEP_SPRINGS;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_ALL_APPS_FADE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_ALL_APPS_HEADER_FADE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_SCALE;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_VERTICAL_PROGRESS;
import static com.android.launcher3.util.SystemUiController.UI_STATE_ALL_APPS;
import android.animation.Animator;
@@ -24,13 +24,12 @@
import com.android.launcher3.DeviceProfile.OnDeviceProfileChangeListener;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherState;
-import com.android.launcher3.LauncherStateManager.AnimationConfig;
import com.android.launcher3.LauncherStateManager.StateHandler;
import com.android.launcher3.R;
import com.android.launcher3.anim.AnimationSuccessListener;
-import com.android.launcher3.anim.AnimatorSetBuilder;
+import com.android.launcher3.anim.PendingAnimation;
import com.android.launcher3.anim.PropertySetter;
-import com.android.launcher3.anim.SpringObjectAnimator;
+import com.android.launcher3.states.StateAnimationConfig;
import com.android.launcher3.util.Themes;
import com.android.launcher3.views.ScrimView;
@@ -46,9 +45,6 @@
*/
public class AllAppsTransitionController implements StateHandler, OnDeviceProfileChangeListener {
- private static final float SPRING_DAMPING_RATIO = 0.75f;
- private static final float SPRING_STIFFNESS = 600f;
-
public static final FloatProperty<AllAppsTransitionController> ALL_APPS_PROGRESS =
new FloatProperty<AllAppsTransitionController>("allAppsProgress") {
@@ -116,7 +112,7 @@
* @param progress value between 0 and 1, 0 shows all apps and 1 shows workspace
*
* @see #setState(LauncherState)
- * @see #setStateWithAnimation(LauncherState, AnimatorSetBuilder, AnimationConfig)
+ * @see #setStateWithAnimation(LauncherState, StateAnimationConfig, PendingAnimation)
*/
public void setProgress(float progress) {
mProgress = progress;
@@ -127,8 +123,8 @@
// Use a light system UI (dark icons) if all apps is behind at least half of the
// status bar.
- boolean forceChange = shiftCurrent - mScrimView.getDragHandleSize()
- <= mLauncher.getDeviceProfile().getInsets().top / 2;
+ boolean forceChange = Math.min(shiftCurrent, mScrimView.getVisualTop())
+ <= mLauncher.getDeviceProfile().getInsets().top / 2f;
if (forceChange) {
mLauncher.getSystemUiController().updateUiState(UI_STATE_ALL_APPS, !mIsDarkTheme);
} else {
@@ -147,7 +143,7 @@
@Override
public void setState(LauncherState state) {
setProgress(state.getVerticalProgress(mLauncher));
- setAlphas(state, null, new AnimatorSetBuilder());
+ setAlphas(state, new StateAnimationConfig(), NO_ANIM_PROPERTY_SETTER);
onProgressAnimationEnd();
}
@@ -157,7 +153,7 @@
*/
@Override
public void setStateWithAnimation(LauncherState toState,
- AnimatorSetBuilder builder, AnimationConfig config) {
+ StateAnimationConfig config, PendingAnimation builder) {
float targetProgress = toState.getVerticalProgress(mLauncher);
if (Float.compare(mProgress, targetProgress) == 0) {
setAlphas(toState, config, builder);
@@ -166,45 +162,40 @@
return;
}
- if (!config.playNonAtomicComponent()) {
+ if (config.onlyPlayAtomicComponent()) {
// There is no atomic component for the all apps transition, so just return early.
return;
}
Interpolator interpolator = config.userControlled ? LINEAR : toState == OVERVIEW
- ? builder.getInterpolator(ANIM_OVERVIEW_SCALE, FAST_OUT_SLOW_IN)
+ ? config.getInterpolator(ANIM_OVERVIEW_SCALE, FAST_OUT_SLOW_IN)
: FAST_OUT_SLOW_IN;
+
Animator anim = createSpringAnimation(mProgress, targetProgress);
anim.setDuration(config.duration);
- anim.setInterpolator(builder.getInterpolator(ANIM_VERTICAL_PROGRESS, interpolator));
+ anim.setInterpolator(config.getInterpolator(ANIM_VERTICAL_PROGRESS, interpolator));
anim.addListener(getProgressAnimatorListener());
-
- builder.play(anim);
+ builder.add(anim);
setAlphas(toState, config, builder);
}
public Animator createSpringAnimation(float... progressValues) {
- if (QUICKSTEP_SPRINGS.get()) {
- return new SpringObjectAnimator<>(this, ALL_APPS_PROGRESS, 1f / mShiftRange,
- SPRING_DAMPING_RATIO, SPRING_STIFFNESS, progressValues);
- }
return ObjectAnimator.ofFloat(this, ALL_APPS_PROGRESS, progressValues);
}
- private void setAlphas(LauncherState toState, AnimationConfig config,
- AnimatorSetBuilder builder) {
- setAlphas(toState.getVisibleElements(mLauncher), config, builder);
- }
-
- public void setAlphas(int visibleElements, AnimationConfig config, AnimatorSetBuilder builder) {
- PropertySetter setter = config == null ? NO_ANIM_PROPERTY_SETTER
- : config.getPropertySetter(builder);
+ /**
+ * Updates the property for the provided state
+ */
+ public void setAlphas(LauncherState state, StateAnimationConfig config, PropertySetter setter) {
+ int visibleElements = state.getVisibleElements(mLauncher);
boolean hasHeaderExtra = (visibleElements & ALL_APPS_HEADER_EXTRA) != 0;
boolean hasAllAppsContent = (visibleElements & ALL_APPS_CONTENT) != 0;
- Interpolator allAppsFade = builder.getInterpolator(ANIM_ALL_APPS_FADE, LINEAR);
- Interpolator headerFade = builder.getInterpolator(ANIM_ALL_APPS_HEADER_FADE, allAppsFade);
+ boolean hasAnyVisibleItem = (visibleElements & APPS_VIEW_ITEM_MASK) != 0;
+
+ Interpolator allAppsFade = config.getInterpolator(ANIM_ALL_APPS_FADE, LINEAR);
+ Interpolator headerFade = config.getInterpolator(ANIM_ALL_APPS_HEADER_FADE, allAppsFade);
setter.setViewAlpha(mAppsView.getContentView(), hasAllAppsContent ? 1 : 0, allAppsFade);
setter.setViewAlpha(mAppsView.getScrollBar(), hasAllAppsContent ? 1 : 0, allAppsFade);
mAppsView.getFloatingHeaderView().setContentVisibility(hasHeaderExtra, hasAllAppsContent,
@@ -213,20 +204,17 @@
setter.setInt(mScrimView, ScrimView.DRAG_HANDLE_ALPHA,
(visibleElements & VERTICAL_SWIPE_INDICATOR) != 0 ? 255 : 0, allAppsFade);
+
+ setter.setViewAlpha(mAppsView, hasAnyVisibleItem ? 1 : 0, allAppsFade);
}
public AnimatorListenerAdapter getProgressAnimatorListener() {
- return new AnimationSuccessListener() {
- @Override
- public void onAnimationSuccess(Animator animator) {
- onProgressAnimationEnd();
- }
- };
+ return AnimationSuccessListener.forRunnable(this::onProgressAnimationEnd);
}
- public void setupViews(AllAppsContainerView appsView) {
+ public void setupViews(AllAppsContainerView appsView, ScrimView scrimView) {
mAppsView = appsView;
- mScrimView = mLauncher.findViewById(R.id.scrim_view);
+ mScrimView = scrimView;
}
/**
@@ -248,18 +236,6 @@
private void onProgressAnimationEnd() {
if (Float.compare(mProgress, 1f) == 0) {
mAppsView.reset(false /* animate */);
- } else if (isAllAppsExpanded()) {
- mAppsView.onScrollUpEnd();
- }
- }
-
- private boolean isAllAppsExpanded() {
- return Float.compare(mProgress, 0f) == 0;
- }
-
- public void highlightWorkTabIfNecessary() {
- if (isAllAppsExpanded()) {
- mAppsView.highlightWorkTabIfNecessary();
}
}
}
diff --git a/src/com/android/launcher3/allapps/AlphabeticalAppsList.java b/src/com/android/launcher3/allapps/AlphabeticalAppsList.java
index b501c82..06209bb 100644
--- a/src/com/android/launcher3/allapps/AlphabeticalAppsList.java
+++ b/src/com/android/launcher3/allapps/AlphabeticalAppsList.java
@@ -18,8 +18,8 @@
import android.content.Context;
-import com.android.launcher3.AppInfo;
import com.android.launcher3.BaseDraggingActivity;
+import com.android.launcher3.model.data.AppInfo;
import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.ItemInfoMatcher;
import com.android.launcher3.util.LabelComparator;
diff --git a/src/com/android/launcher3/allapps/AppInfoComparator.java b/src/com/android/launcher3/allapps/AppInfoComparator.java
index 8baf56c..823f98e 100644
--- a/src/com/android/launcher3/allapps/AppInfoComparator.java
+++ b/src/com/android/launcher3/allapps/AppInfoComparator.java
@@ -19,7 +19,7 @@
import android.os.Process;
import android.os.UserHandle;
-import com.android.launcher3.AppInfo;
+import com.android.launcher3.model.data.AppInfo;
import com.android.launcher3.pm.UserCache;
import com.android.launcher3.util.LabelComparator;
diff --git a/src/com/android/launcher3/allapps/DiscoveryBounce.java b/src/com/android/launcher3/allapps/DiscoveryBounce.java
index e8035eb..fc29a30 100644
--- a/src/com/android/launcher3/allapps/DiscoveryBounce.java
+++ b/src/com/android/launcher3/allapps/DiscoveryBounce.java
@@ -24,7 +24,6 @@
import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.animation.AnimatorListenerAdapter;
-import android.content.SharedPreferences;
import android.os.Handler;
import android.os.UserManager;
import android.view.MotionEvent;
@@ -35,7 +34,7 @@
import com.android.launcher3.LauncherStateManager.StateListener;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
-import com.android.launcher3.pm.UserCache;
+import com.android.launcher3.util.OnboardingPrefs;
/**
* Abstract base class of floating view responsible for showing discovery bounce animation
@@ -44,13 +43,6 @@
private static final long DELAY_MS = 450;
- public static final String HOME_BOUNCE_SEEN = "launcher.apps_view_shown";
- public static final String SHELF_BOUNCE_SEEN = "launcher.shelf_bounce_seen";
- public static final String HOME_BOUNCE_COUNT = "launcher.home_bounce_count";
- public static final String SHELF_BOUNCE_COUNT = "launcher.shelf_bounce_count";
-
- public static final int BOUNCE_MAX_COUNT = 3;
-
private final Launcher mLauncher;
private final Animator mDiscoBounceAnimation;
@@ -143,9 +135,9 @@
}
private static void showForHomeIfNeeded(Launcher launcher, boolean withDelay) {
+ OnboardingPrefs onboardingPrefs = launcher.getOnboardingPrefs();
if (!launcher.isInState(NORMAL)
- || (launcher.getSharedPrefs().getBoolean(HOME_BOUNCE_SEEN, false)
- && !shouldShowForWorkProfile(launcher))
+ || onboardingPrefs.getBoolean(OnboardingPrefs.HOME_BOUNCE_SEEN)
|| AbstractFloatingView.getTopOpenView(launcher) != null
|| launcher.getSystemService(UserManager.class).isDemoUser()
|| Utilities.IS_RUNNING_IN_TEST_HARNESS) {
@@ -156,7 +148,7 @@
new Handler().postDelayed(() -> showForHomeIfNeeded(launcher, false), DELAY_MS);
return;
}
- incrementHomeBounceCount(launcher);
+ onboardingPrefs.incrementEventCount(OnboardingPrefs.HOME_BOUNCE_COUNT);
new DiscoveryBounce(launcher, 0).show(HOTSEAT);
}
@@ -166,12 +158,12 @@
}
private static void showForOverviewIfNeeded(Launcher launcher, boolean withDelay) {
+ OnboardingPrefs onboardingPrefs = launcher.getOnboardingPrefs();
if (!launcher.isInState(OVERVIEW)
|| !launcher.hasBeenResumed()
|| launcher.isForceInvisible()
|| launcher.getDeviceProfile().isVerticalBarLayout()
- || (launcher.getSharedPrefs().getBoolean(SHELF_BOUNCE_SEEN, false)
- && !shouldShowForWorkProfile(launcher))
+ || onboardingPrefs.getBoolean(OnboardingPrefs.SHELF_BOUNCE_SEEN)
|| launcher.getSystemService(UserManager.class).isDemoUser()
|| Utilities.IS_RUNNING_IN_TEST_HARNESS) {
return;
@@ -185,7 +177,7 @@
// TODO: Move these checks to the top and call this method after invalidate handler.
return;
}
- incrementShelfBounceCount(launcher);
+ onboardingPrefs.incrementEventCount(OnboardingPrefs.SHELF_BOUNCE_COUNT);
new DiscoveryBounce(launcher, (1 - OVERVIEW.getVerticalProgress(launcher)))
.show(PREDICTION);
@@ -212,28 +204,4 @@
mController.setProgress(progress - mDelta);
}
}
-
- private static boolean shouldShowForWorkProfile(Launcher launcher) {
- return !launcher.getSharedPrefs().getBoolean(
- PersonalWorkSlidingTabStrip.KEY_SHOWED_PEEK_WORK_TAB, false)
- && UserCache.INSTANCE.get(launcher).hasWorkProfile();
- }
-
- private static void incrementShelfBounceCount(Launcher launcher) {
- SharedPreferences sharedPrefs = launcher.getSharedPrefs();
- int count = sharedPrefs.getInt(SHELF_BOUNCE_COUNT, 0);
- if (count > BOUNCE_MAX_COUNT) {
- return;
- }
- sharedPrefs.edit().putInt(SHELF_BOUNCE_COUNT, count + 1).apply();
- }
-
- private static void incrementHomeBounceCount(Launcher launcher) {
- SharedPreferences sharedPrefs = launcher.getSharedPrefs();
- int count = sharedPrefs.getInt(HOME_BOUNCE_COUNT, 0);
- if (count > BOUNCE_MAX_COUNT) {
- return;
- }
- sharedPrefs.edit().putInt(HOME_BOUNCE_COUNT, count + 1).apply();
- }
}
diff --git a/src/com/android/launcher3/allapps/FloatingHeaderView.java b/src/com/android/launcher3/allapps/FloatingHeaderView.java
index cc33af9..81e1b94 100644
--- a/src/com/android/launcher3/allapps/FloatingHeaderView.java
+++ b/src/com/android/launcher3/allapps/FloatingHeaderView.java
@@ -15,6 +15,8 @@
*/
package com.android.launcher3.allapps;
+import static com.android.launcher3.LauncherAnimUtils.VIEW_ALPHA;
+
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Point;
@@ -370,7 +372,7 @@
}
allowTouchForwarding(hasAllAppsContent);
- setter.setFloat(mTabLayout, ALPHA, hasAllAppsContent ? 1 : 0, headerFade);
+ setter.setFloat(mTabLayout, VIEW_ALPHA, hasAllAppsContent ? 1 : 0, headerFade);
}
protected void allowTouchForwarding(boolean allow) {
diff --git a/src/com/android/launcher3/allapps/LauncherAllAppsContainerView.java b/src/com/android/launcher3/allapps/LauncherAllAppsContainerView.java
index 9d0ecd3..f6766c4 100644
--- a/src/com/android/launcher3/allapps/LauncherAllAppsContainerView.java
+++ b/src/com/android/launcher3/allapps/LauncherAllAppsContainerView.java
@@ -51,7 +51,10 @@
public boolean onInterceptTouchEvent(MotionEvent ev) {
// The AllAppsContainerView houses the QSB and is hence visible from the Workspace
// Overview states. We shouldn't intercept for the scrubber in these cases.
- if (!mLauncher.isInState(LauncherState.ALL_APPS)) return false;
+ if (!mLauncher.isInState(LauncherState.ALL_APPS)) {
+ mTouchHandler = null;
+ return false;
+ }
return super.onInterceptTouchEvent(ev);
}
@@ -64,6 +67,14 @@
}
@Override
+ public void setupHeader() {
+ super.setupHeader();
+ if (mWorkTabListener != null && !mUsingTabs) {
+ mLauncher.getStateManager().removeStateListener(mWorkTabListener);
+ }
+ }
+
+ @Override
public void onTabChanged(int pos) {
super.onTabChanged(pos);
if (mUsingTabs) {
diff --git a/src/com/android/launcher3/allapps/PersonalWorkSlidingTabStrip.java b/src/com/android/launcher3/allapps/PersonalWorkSlidingTabStrip.java
index 6204f31..2515c24 100644
--- a/src/com/android/launcher3/allapps/PersonalWorkSlidingTabStrip.java
+++ b/src/com/android/launcher3/allapps/PersonalWorkSlidingTabStrip.java
@@ -16,7 +16,6 @@
package com.android.launcher3.allapps;
import android.content.Context;
-import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
@@ -39,11 +38,8 @@
private static final int POSITION_PERSONAL = 0;
private static final int POSITION_WORK = 1;
- public static final String KEY_SHOWED_PEEK_WORK_TAB = "showed_peek_work_tab";
-
private final Paint mSelectedIndicatorPaint;
private final Paint mDividerPaint;
- private final SharedPreferences mSharedPreferences;
private int mSelectedIndicatorHeight;
private int mIndicatorLeft = -1;
@@ -72,16 +68,13 @@
mDividerPaint.setStrokeWidth(
getResources().getDimensionPixelSize(R.dimen.all_apps_divider_height));
- mSharedPreferences = Utilities.getPrefs(context);
mIsRtl = Utilities.isRtl(getResources());
}
- private void updateIndicatorPosition(float scrollOffset) {
- mScrollOffset = scrollOffset;
- updateIndicatorPosition();
- }
-
- private void updateTabTextColor(int pos) {
+ /**
+ * Highlights tab with index pos
+ */
+ public void updateTabTextColor(int pos) {
mSelectedPosition = pos;
for (int i = 0; i < getChildCount(); i++) {
Button tab = (Button) getChildAt(i);
@@ -89,6 +82,11 @@
}
}
+ private void updateIndicatorPosition(float scrollOffset) {
+ mScrollOffset = scrollOffset;
+ updateIndicatorPosition();
+ }
+
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
@@ -128,25 +126,6 @@
mIndicatorRight, getHeight(), mSelectedIndicatorPaint);
}
- public void highlightWorkTabIfNecessary() {
- if (mSharedPreferences.getBoolean(KEY_SHOWED_PEEK_WORK_TAB, false)) {
- return;
- }
- if (mLastActivePage != POSITION_PERSONAL) {
- return;
- }
- highlightWorkTab();
- mSharedPreferences.edit().putBoolean(KEY_SHOWED_PEEK_WORK_TAB, true).apply();
- }
-
- private void highlightWorkTab() {
- View v = getChildAt(POSITION_WORK);
- v.post(() -> {
- v.setPressed(true);
- v.setPressed(false);
- });
- }
-
@Override
public void setScroll(int currentScroll, int totalScroll) {
float scrollOffset = ((float) currentScroll) / totalScroll;
@@ -156,6 +135,7 @@
@Override
public void setActiveMarker(int activePage) {
updateTabTextColor(activePage);
+ updateIndicatorPosition(activePage);
if (mContainerView != null && mLastActivePage != activePage) {
mContainerView.onTabChanged(activePage);
}
diff --git a/src/com/android/launcher3/allapps/PluginHeaderRow.java b/src/com/android/launcher3/allapps/PluginHeaderRow.java
index 535ef54..3089b18 100644
--- a/src/com/android/launcher3/allapps/PluginHeaderRow.java
+++ b/src/com/android/launcher3/allapps/PluginHeaderRow.java
@@ -15,10 +15,11 @@
*/
package com.android.launcher3.allapps;
-import static android.view.View.ALPHA;
import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;
+import static com.android.launcher3.LauncherAnimUtils.VIEW_ALPHA;
+
import android.graphics.Rect;
import android.view.View;
import android.view.animation.Interpolator;
@@ -67,7 +68,7 @@
public void setContentVisibility(boolean hasHeaderExtra, boolean hasAllAppsContent,
PropertySetter setter, Interpolator headerFade, Interpolator allAppsFade) {
// Don't use setViewAlpha as we want to control the visibility ourselves.
- setter.setFloat(mView, ALPHA, hasAllAppsContent ? 1 : 0, headerFade);
+ setter.setFloat(mView, VIEW_ALPHA, hasAllAppsContent ? 1 : 0, headerFade);
}
@Override
diff --git a/src/com/android/launcher3/allapps/WorkModeSwitch.java b/src/com/android/launcher3/allapps/WorkModeSwitch.java
index aadb297..c1621b0 100644
--- a/src/com/android/launcher3/allapps/WorkModeSwitch.java
+++ b/src/com/android/launcher3/allapps/WorkModeSwitch.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2018 The Android Open Source Project
+ * 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.
@@ -15,21 +15,36 @@
*/
package com.android.launcher3.allapps;
+import static com.android.launcher3.util.PackageManagerHelper.hasShortcutsPermission;
+
import android.content.Context;
+import android.content.pm.PackageManager;
+import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Process;
import android.os.UserHandle;
import android.os.UserManager;
import android.util.AttributeSet;
-import android.view.MotionEvent;
import android.widget.Switch;
+import com.android.launcher3.Insettable;
+import com.android.launcher3.Launcher;
+import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.pm.UserCache;
+import com.android.launcher3.views.ArrowTipView;
import java.lang.ref.WeakReference;
-public class WorkModeSwitch extends Switch {
+/**
+ * Work profile toggle switch shown at the bottom of AllApps work tab
+ */
+public class WorkModeSwitch extends Switch implements Insettable {
+
+ private static final int WORK_TIP_THRESHOLD = 2;
+ public static final String KEY_WORK_TIP_COUNTER = "worked_tip_counter";
+
+ private Rect mInsets = new Rect();
public WorkModeSwitch(Context context) {
super(context);
@@ -45,33 +60,64 @@
@Override
public void setChecked(boolean checked) {
- // No-op, do not change the checked state until broadcast is received.
+
}
@Override
public void toggle() {
+ Launcher launcher = Launcher.getLauncher(getContext());
+ // don't show tip if user uses toggle
+ launcher.getSharedPrefs().edit().putInt(KEY_WORK_TIP_COUNTER, -1).apply();
trySetQuietModeEnabledToAllProfilesAsync(isChecked());
}
private void setCheckedInternal(boolean checked) {
super.setChecked(checked);
+ setCompoundDrawablesRelativeWithIntrinsicBounds(
+ checked ? R.drawable.ic_corp : R.drawable.ic_corp_off, 0, 0, 0);
}
public void refresh() {
+ if (!shouldShowWorkSwitch()) return;
UserCache userManager = UserCache.INSTANCE.get(getContext());
setCheckedInternal(!userManager.isAnyProfileQuietModeEnabled());
setEnabled(true);
}
@Override
- public boolean onTouchEvent(MotionEvent ev) {
- return ev.getActionMasked() == MotionEvent.ACTION_MOVE || super.onTouchEvent(ev);
+ protected void onLayout(boolean changed, int l, int t, int r, int b) {
+ super.onLayout(changed, l, t, r, b);
+ this.setVisibility(shouldShowWorkSwitch() ? VISIBLE : GONE);
}
private void trySetQuietModeEnabledToAllProfilesAsync(boolean enabled) {
new SetQuietModeEnabledAsyncTask(enabled, new WeakReference<>(this)).execute();
}
+ @Override
+ public void setInsets(Rect insets) {
+ int bottomInset = insets.bottom - mInsets.bottom;
+ mInsets.set(insets);
+ setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(),
+ getPaddingBottom() + bottomInset);
+ }
+
+ /**
+ * Animates in/out work profile toggle panel based on the tab user is on
+ */
+ public void setWorkTabVisible(boolean workTabVisible) {
+ if (!shouldShowWorkSwitch()) return;
+ clearAnimation();
+ if (workTabVisible) {
+ setVisibility(VISIBLE);
+ setAlpha(0);
+ animate().alpha(1).start();
+ showTipifNeeded();
+ } else {
+ animate().alpha(0).withEndAction(() -> this.setVisibility(GONE)).start();
+ }
+ }
+
private static final class SetQuietModeEnabledAsyncTask
extends AsyncTask<Void, Void, Boolean> {
@@ -122,4 +168,24 @@
}
}
}
+
+ private boolean shouldShowWorkSwitch() {
+ Launcher launcher = Launcher.getLauncher(getContext());
+ return Utilities.ATLEAST_P && (hasShortcutsPermission(launcher)
+ || launcher.checkSelfPermission("android.permission.MODIFY_QUIET_MODE")
+ == PackageManager.PERMISSION_GRANTED);
+ }
+
+ /**
+ * Shows a work tip on the Nth work tab open
+ */
+ public void showTipifNeeded() {
+ Launcher launcher = Launcher.getLauncher(getContext());
+ int tipCounter = launcher.getSharedPrefs().getInt(KEY_WORK_TIP_COUNTER, WORK_TIP_THRESHOLD);
+ if (tipCounter < 0) return;
+ if (tipCounter == 0) {
+ new ArrowTipView(launcher).show(launcher.getString(R.string.work_switch_tip), getTop());
+ }
+ launcher.getSharedPrefs().edit().putInt(KEY_WORK_TIP_COUNTER, tipCounter - 1).apply();
+ }
}
diff --git a/src/com/android/launcher3/allapps/search/AppsSearchContainerLayout.java b/src/com/android/launcher3/allapps/search/AppsSearchContainerLayout.java
index d497c3a..9e3a862 100644
--- a/src/com/android/launcher3/allapps/search/AppsSearchContainerLayout.java
+++ b/src/com/android/launcher3/allapps/search/AppsSearchContainerLayout.java
@@ -62,9 +62,8 @@
private AlphabeticalAppsList mApps;
private AllAppsContainerView mAppsView;
- // This value was used to position the QSB. We store it here for translationY animations.
- private final float mFixedTranslationY;
- private final float mMarginTopAdjusting;
+ // The amount of pixels to shift down and overlap with the rest of the content.
+ private final int mContentOverlap;
public AppsSearchContainerLayout(Context context) {
this(context, null);
@@ -82,11 +81,10 @@
mSearchQueryBuilder = new SpannableStringBuilder();
Selection.setSelection(mSearchQueryBuilder, 0);
-
- mFixedTranslationY = getTranslationY();
- mMarginTopAdjusting = mFixedTranslationY - getPaddingTop();
-
setHint(prefixTextWithIcon(getContext(), R.drawable.ic_allapps_search, getHint()));
+
+ mContentOverlap =
+ getResources().getDimensionPixelSize(R.dimen.all_apps_search_bar_field_height) / 2;
}
@Override
@@ -128,6 +126,8 @@
int expectedLeft = parent.getPaddingLeft() + (availableWidth - myWidth) / 2;
int shift = expectedLeft - left;
setTranslationX(shift);
+
+ offsetTopAndBottom(mContentOverlap);
}
@Override
@@ -196,7 +196,7 @@
@Override
public void setInsets(Rect insets) {
MarginLayoutParams mlp = (MarginLayoutParams) getLayoutParams();
- mlp.topMargin = Math.round(Math.max(-mFixedTranslationY, insets.top - mMarginTopAdjusting));
+ mlp.topMargin = insets.top;
requestLayout();
}
@@ -205,9 +205,7 @@
if (mLauncher.getDeviceProfile().isVerticalBarLayout()) {
return 0;
} else {
- int topMargin = Math.round(Math.max(
- -mFixedTranslationY, insets.top - mMarginTopAdjusting));
- return insets.bottom + topMargin + mFixedTranslationY;
+ return insets.bottom + insets.top;
}
}
diff --git a/src/com/android/launcher3/allapps/search/DefaultAppSearchAlgorithm.java b/src/com/android/launcher3/allapps/search/DefaultAppSearchAlgorithm.java
index 26f6ec3..f72a988 100644
--- a/src/com/android/launcher3/allapps/search/DefaultAppSearchAlgorithm.java
+++ b/src/com/android/launcher3/allapps/search/DefaultAppSearchAlgorithm.java
@@ -17,7 +17,7 @@
import android.os.Handler;
-import com.android.launcher3.AppInfo;
+import com.android.launcher3.model.data.AppInfo;
import com.android.launcher3.util.ComponentKey;
import java.text.Collator;
diff --git a/src/com/android/launcher3/anim/AnimationSuccessListener.java b/src/com/android/launcher3/anim/AnimationSuccessListener.java
index 9448632..9905e81 100644
--- a/src/com/android/launcher3/anim/AnimationSuccessListener.java
+++ b/src/com/android/launcher3/anim/AnimationSuccessListener.java
@@ -39,4 +39,25 @@
}
public abstract void onAnimationSuccess(Animator animator);
+
+ /**
+ * Returns an AnimationSuccessListener which runs the provided action on success
+ */
+ public static AnimationSuccessListener forRunnable(Runnable r) {
+ return new RunnableSuccessListener(r);
+ }
+
+ private static class RunnableSuccessListener extends AnimationSuccessListener {
+
+ private final Runnable mRunnable;
+
+ private RunnableSuccessListener(Runnable r) {
+ mRunnable = r;
+ }
+
+ @Override
+ public void onAnimationSuccess(Animator animator) {
+ mRunnable.run();
+ }
+ }
}
diff --git a/src/com/android/launcher3/anim/AnimatorPlaybackController.java b/src/com/android/launcher3/anim/AnimatorPlaybackController.java
index 1c277ab..f12789a 100644
--- a/src/com/android/launcher3/anim/AnimatorPlaybackController.java
+++ b/src/com/android/launcher3/anim/AnimatorPlaybackController.java
@@ -16,7 +16,9 @@
package com.android.launcher3.anim;
import static com.android.launcher3.anim.Interpolators.LINEAR;
-import static com.android.launcher3.config.FeatureFlags.QUICKSTEP_SPRINGS;
+import static com.android.launcher3.anim.Interpolators.clampToProgress;
+import static com.android.launcher3.anim.Interpolators.scrollInterpolatorForVelocity;
+import static com.android.launcher3.util.DefaultDisplay.getSingleFrameMs;
import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
@@ -24,17 +26,18 @@
import android.animation.AnimatorSet;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
-import android.util.Log;
+import android.content.Context;
+import android.util.FloatProperty;
import androidx.annotation.Nullable;
-import androidx.dynamicanimation.animation.DynamicAnimation;
-import androidx.dynamicanimation.animation.SpringAnimation;
+
+import com.android.launcher3.Utilities;
import java.util.ArrayList;
import java.util.Collections;
-import java.util.HashSet;
import java.util.List;
-import java.util.Set;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
/**
* Helper class to control the playback of an {@link AnimatorSet}, with custom interpolators
@@ -43,14 +46,7 @@
* Note: The implementation does not support start delays on child animations or
* sequential playbacks.
*/
-public abstract class AnimatorPlaybackController implements ValueAnimator.AnimatorUpdateListener {
-
- private static final String TAG = "AnimatorPlaybackCtrler";
- private static boolean DEBUG = false;
-
- public static AnimatorPlaybackController wrap(AnimatorSet anim, long duration) {
- return wrap(anim, duration, null);
- }
+public class AnimatorPlaybackController implements ValueAnimator.AnimatorUpdateListener {
/**
* Creates an animation controller for the provided animation.
@@ -58,20 +54,37 @@
* needs to be larger than the total number of pixels so that we don't have jittering due
* to float (animation-fraction * total duration) to int conversion.
*/
- public static AnimatorPlaybackController wrap(AnimatorSet anim, long duration,
- Runnable onCancelRunnable) {
-
+ public static AnimatorPlaybackController wrap(AnimatorSet anim, long duration) {
/**
* TODO: use {@link AnimatorSet#setCurrentPlayTime(long)} once b/68382377 is fixed.
*/
- return new AnimatorPlaybackControllerVL(anim, duration, onCancelRunnable);
+ ArrayList<Holder> childAnims = new ArrayList<>();
+ addAnimationHoldersRecur(anim, SpringProperty.DEFAULT, childAnims);
+
+ return new AnimatorPlaybackController(anim, duration, childAnims);
}
+ private static final FloatProperty<ValueAnimator> CURRENT_PLAY_TIME =
+ new FloatProperty<ValueAnimator>("current-play-time") {
+ @Override
+ public void setValue(ValueAnimator animator, float v) {
+ animator.setCurrentPlayTime((long) v);
+ }
+
+ @Override
+ public Float get(ValueAnimator animator) {
+ return (float) animator.getCurrentPlayTime();
+ }
+ };
+
+ // Progress factor after which an animation is considered almost completed.
+ private static final float ANIMATION_COMPLETE_THRESHOLD = 0.95f;
+
private final ValueAnimator mAnimationPlayer;
private final long mDuration;
- protected final AnimatorSet mAnim;
- private Set<SpringAnimation> mSprings;
+ private final AnimatorSet mAnim;
+ private final Holder[] mChildAnimations;
protected float mCurrentFraction;
private Runnable mEndAction;
@@ -79,22 +92,14 @@
protected boolean mTargetCancelled = false;
protected Runnable mOnCancelRunnable;
- private OnAnimationEndDispatcher mEndListener;
- private DynamicAnimation.OnAnimationEndListener mSpringEndListener;
- // We need this variable to ensure the end listener is called immediately, otherwise we run into
- // issues where the callback interferes with the states of the swipe detector.
- private boolean mSkipToEnd = false;
-
- protected AnimatorPlaybackController(AnimatorSet anim, long duration,
- Runnable onCancelRunnable) {
+ /** package private */
+ AnimatorPlaybackController(AnimatorSet anim, long duration, ArrayList<Holder> childAnims) {
mAnim = anim;
mDuration = duration;
- mOnCancelRunnable = onCancelRunnable;
mAnimationPlayer = ValueAnimator.ofFloat(0, 1);
mAnimationPlayer.setInterpolator(LINEAR);
- mEndListener = new OnAnimationEndDispatcher();
- mAnimationPlayer.addListener(mEndListener);
+ mAnimationPlayer.addListener(new OnAnimationEndDispatcher());
mAnimationPlayer.addUpdateListener(this);
mAnim.addListener(new AnimatorListenerAdapter() {
@@ -119,14 +124,7 @@
}
});
- mSprings = new HashSet<>();
- mSpringEndListener = (animation, canceled, value, velocity1) -> {
- if (canceled) {
- mEndListener.onAnimationCancel(mAnimationPlayer);
- } else {
- mEndListener.onAnimationEnd(mAnimationPlayer);
- }
- };
+ mChildAnimations = childAnims.toArray(new Holder[childAnims.size()]);
}
public AnimatorSet getTarget() {
@@ -160,9 +158,78 @@
}
/**
+ * Starts playing the animation with the provided velocity optionally playing any
+ * physics based animations
+ */
+ public void startWithVelocity(Context context, boolean goingToEnd,
+ float velocity, float scale, long animationDuration) {
+ float scaleInverse = 1 / Math.abs(scale);
+ float scaledVelocity = velocity * scaleInverse;
+
+ float nextFrameProgress = Utilities.boundToRange(getProgressFraction()
+ + scaledVelocity * getSingleFrameMs(context), 0f, 1f);
+
+ // Update setters for spring
+ int springFlag = goingToEnd
+ ? SpringProperty.FLAG_CAN_SPRING_ON_END
+ : SpringProperty.FLAG_CAN_SPRING_ON_START;
+
+ long springDuration = animationDuration;
+ for (Holder h : mChildAnimations) {
+ if ((h.springProperty.flags & springFlag) != 0) {
+ SpringAnimationBuilder s = new SpringAnimationBuilder(h.anim, CURRENT_PLAY_TIME)
+ .setStartValue(clampDuration(mCurrentFraction))
+ .setEndValue(goingToEnd ? h.anim.getDuration() : 0)
+ .setStartVelocity(scaledVelocity * h.anim.getDuration())
+ .setMinimumVisibleChange(scaleInverse)
+ .setDampingRatio(h.springProperty.mDampingRatio)
+ .setStiffness(h.springProperty.mStiffness);
+
+ long expectedDurationL = s.build(context).getDuration();
+ springDuration = Math.max(expectedDurationL, springDuration);
+
+ float expectedDuration = expectedDurationL;
+ h.setter = (a, l) ->
+ s.setValue(a, mAnimationPlayer.getCurrentPlayTime() / expectedDuration);
+ h.anim.setInterpolator(LINEAR);
+ }
+ }
+
+ mAnimationPlayer.setFloatValues(nextFrameProgress, goingToEnd ? 1f : 0f);
+
+ if (springDuration <= animationDuration) {
+ mAnimationPlayer.setDuration(animationDuration);
+ mAnimationPlayer.setInterpolator(scrollInterpolatorForVelocity(velocity));
+ } else {
+ // Since spring requires more time to run, we let the other animations play with
+ // current time and interpolation and by clamping the duration.
+ mAnimationPlayer.setDuration(springDuration);
+
+ float cutOff = animationDuration / (float) springDuration;
+ mAnimationPlayer.setInterpolator(
+ clampToProgress(scrollInterpolatorForVelocity(velocity), 0, cutOff));
+ }
+ mAnimationPlayer.start();
+ }
+
+ /**
+ * Tries to finish the running animation if it is close to completion.
+ */
+ public void forceFinishIfCloseToEnd() {
+ if (mAnimationPlayer.isRunning()
+ && mAnimationPlayer.getAnimatedFraction() > ANIMATION_COMPLETE_THRESHOLD) {
+ mAnimationPlayer.end();
+ }
+ }
+
+ /**
* Pauses the currently playing animation.
*/
public void pause() {
+ // Reset property setters
+ for (Holder h : mChildAnimations) {
+ h.reset();
+ }
mAnimationPlayer.cancel();
}
@@ -176,7 +243,18 @@
/**
* Sets the current animation position and updates all the child animators accordingly.
*/
- public abstract void setPlayFraction(float fraction);
+ public void setPlayFraction(float fraction) {
+ mCurrentFraction = fraction;
+ // Let the animator report the progress but don't apply the progress to child
+ // animations if it has been cancelled.
+ if (mTargetCancelled) {
+ return;
+ }
+ long playPos = clampDuration(fraction);
+ for (Holder holder : mChildAnimations) {
+ holder.setter.set(holder.anim, playPos);
+ }
+ }
public float getProgressFraction() {
return mCurrentFraction;
@@ -208,49 +286,6 @@
}
}
- /**
- * Starts playback and sets the spring.
- */
- public void dispatchOnStartWithVelocity(float end, float velocity) {
- if (!QUICKSTEP_SPRINGS.get()) {
- dispatchOnStart();
- return;
- }
-
- if (DEBUG) Log.d(TAG, "dispatchOnStartWithVelocity#end=" + end + ", velocity=" + velocity);
-
- for (Animator a : mAnim.getChildAnimations()) {
- if (a instanceof SpringObjectAnimator) {
- if (DEBUG) Log.d(TAG, "Found springAnimator=" + a);
- SpringObjectAnimator springAnimator = (SpringObjectAnimator) a;
- mSprings.add(springAnimator.getSpring());
- springAnimator.startSpring(end, velocity, mSpringEndListener);
- }
- }
-
- dispatchOnStart();
- }
-
- public void dispatchOnStart() {
- dispatchOnStartRecursively(mAnim);
- }
-
- private void dispatchOnStartRecursively(Animator animator) {
- List<AnimatorListener> listeners = animator instanceof SpringObjectAnimator
- ? nonNullList(((SpringObjectAnimator) animator).getObjectAnimatorListeners())
- : nonNullList(animator.getListeners());
-
- for (AnimatorListener l : listeners) {
- l.onAnimationStart(animator);
- }
-
- if (animator instanceof AnimatorSet) {
- for (Animator anim : nonNullList(((AnimatorSet) animator).getChildAnimations())) {
- dispatchOnStartRecursively(anim);
- }
- }
- }
-
/** @see #dispatchOnCancelWithoutCancelRunnable(Runnable) */
public void dispatchOnCancelWithoutCancelRunnable() {
dispatchOnCancelWithoutCancelRunnable(null);
@@ -272,115 +307,47 @@
setOnCancelRunnable(onCancel);
}
- public void dispatchOnCancel() {
- dispatchOnCancelRecursively(mAnim);
+
+ public AnimatorPlaybackController setOnCancelRunnable(Runnable runnable) {
+ mOnCancelRunnable = runnable;
+ return this;
}
- private void dispatchOnCancelRecursively(Animator animator) {
- for (AnimatorListener l : nonNullList(animator.getListeners())) {
- l.onAnimationCancel(animator);
- }
+ public void dispatchOnStart() {
+ callListenerCommandRecursively(mAnim, AnimatorListener::onAnimationStart);
+ }
- if (animator instanceof AnimatorSet) {
- for (Animator anim : nonNullList(((AnimatorSet) animator).getChildAnimations())) {
- dispatchOnCancelRecursively(anim);
- }
- }
+ public void dispatchOnCancel() {
+ callListenerCommandRecursively(mAnim, AnimatorListener::onAnimationCancel);
}
public void dispatchSetInterpolator(TimeInterpolator interpolator) {
- dispatchSetInterpolatorRecursively(mAnim, interpolator);
+ callAnimatorCommandRecursively(mAnim, a -> a.setInterpolator(interpolator));
}
- private void dispatchSetInterpolatorRecursively(Animator anim, TimeInterpolator interpolator) {
- anim.setInterpolator(interpolator);
+ private static void callListenerCommandRecursively(
+ Animator anim, BiConsumer<AnimatorListener, Animator> command) {
+ callAnimatorCommandRecursively(anim, a-> {
+ for (AnimatorListener l : nonNullList(a.getListeners())) {
+ command.accept(l, a);
+ }
+ });
+ }
+
+ private static void callAnimatorCommandRecursively(Animator anim, Consumer<Animator> command) {
+ command.accept(anim);
if (anim instanceof AnimatorSet) {
for (Animator child : nonNullList(((AnimatorSet) anim).getChildAnimations())) {
- dispatchSetInterpolatorRecursively(child, interpolator);
+ callAnimatorCommandRecursively(child, command);
}
}
}
- public void setOnCancelRunnable(Runnable runnable) {
- mOnCancelRunnable = runnable;
- }
-
- public void skipToEnd() {
- mSkipToEnd = true;
- for (SpringAnimation spring : mSprings) {
- if (spring.canSkipToEnd()) {
- spring.skipToEnd();
- }
- }
- mAnimationPlayer.end();
- mSkipToEnd = false;
- }
-
- public static class AnimatorPlaybackControllerVL extends AnimatorPlaybackController {
-
- private final ValueAnimator[] mChildAnimations;
-
- private AnimatorPlaybackControllerVL(AnimatorSet anim, long duration,
- Runnable onCancelRunnable) {
- super(anim, duration, onCancelRunnable);
-
- // Build animation list
- ArrayList<ValueAnimator> childAnims = new ArrayList<>();
- getAnimationsRecur(mAnim, childAnims);
- mChildAnimations = childAnims.toArray(new ValueAnimator[childAnims.size()]);
- }
-
- private void getAnimationsRecur(AnimatorSet anim, ArrayList<ValueAnimator> out) {
- long forceDuration = anim.getDuration();
- TimeInterpolator forceInterpolator = anim.getInterpolator();
- for (Animator child : anim.getChildAnimations()) {
- if (forceDuration > 0) {
- child.setDuration(forceDuration);
- }
- if (forceInterpolator != null) {
- child.setInterpolator(forceInterpolator);
- }
- if (child instanceof ValueAnimator) {
- out.add((ValueAnimator) child);
- } else if (child instanceof AnimatorSet) {
- getAnimationsRecur((AnimatorSet) child, out);
- } else {
- throw new RuntimeException("Unknown animation type " + child);
- }
- }
- }
-
- @Override
- public void setPlayFraction(float fraction) {
- mCurrentFraction = fraction;
- // Let the animator report the progress but don't apply the progress to child
- // animations if it has been cancelled.
- if (mTargetCancelled) {
- return;
- }
- long playPos = clampDuration(fraction);
- for (ValueAnimator anim : mChildAnimations) {
- anim.setCurrentPlayTime(Math.min(playPos, anim.getDuration()));
- }
- }
- }
-
- private boolean isAnySpringRunning() {
- for (SpringAnimation spring : mSprings) {
- if (spring.isRunning()) {
- return true;
- }
- }
- return false;
- }
-
/**
* Only dispatches the on end actions once the animator and all springs have completed running.
*/
private class OnAnimationEndDispatcher extends AnimationSuccessListener {
- boolean mAnimatorDone = false;
- boolean mSpringsDone = false;
boolean mDispatched = false;
@Override
@@ -391,39 +358,76 @@
@Override
public void onAnimationSuccess(Animator animator) {
- if (mSprings.isEmpty()) {
- mSpringsDone = mAnimatorDone = true;
- }
- if (isAnySpringRunning()) {
- mAnimatorDone = true;
- } else {
- mSpringsDone = true;
- }
-
// We wait for the spring (if any) to finish running before completing the end callback.
- if (!mDispatched && (mSkipToEnd || (mAnimatorDone && mSpringsDone))) {
- dispatchOnEndRecursively(mAnim);
+ if (!mDispatched) {
+ callListenerCommandRecursively(mAnim, AnimatorListener::onAnimationEnd);
if (mEndAction != null) {
mEndAction.run();
}
mDispatched = true;
}
}
-
- private void dispatchOnEndRecursively(Animator animator) {
- for (AnimatorListener l : nonNullList(animator.getListeners())) {
- l.onAnimationEnd(animator);
- }
-
- if (animator instanceof AnimatorSet) {
- for (Animator anim : nonNullList(((AnimatorSet) animator).getChildAnimations())) {
- dispatchOnEndRecursively(anim);
- }
- }
- }
}
private static <T> List<T> nonNullList(ArrayList<T> list) {
return list == null ? Collections.emptyList() : list;
}
+
+ /**
+ * Interface for setting position of value animator
+ */
+ private interface PositionSetter {
+
+ PositionSetter DEFAULT = (anim, playPos) ->
+ anim.setCurrentPlayTime(Math.min(playPos, anim.getDuration()));
+
+ void set(ValueAnimator anim, long position);
+ }
+
+ /**
+ * Holder class for various child animations
+ */
+ static class Holder {
+
+ public final ValueAnimator anim;
+
+ public final SpringProperty springProperty;
+
+ public final TimeInterpolator interpolator;
+
+ public PositionSetter setter;
+
+ Holder(Animator anim, SpringProperty springProperty) {
+ this.anim = (ValueAnimator) anim;
+ this.springProperty = springProperty;
+ this.interpolator = this.anim.getInterpolator();
+ this.setter = PositionSetter.DEFAULT;
+ }
+
+ public void reset() {
+ anim.setInterpolator(interpolator);
+ setter = PositionSetter.DEFAULT;
+ }
+ }
+
+ static void addAnimationHoldersRecur(
+ Animator anim, SpringProperty springProperty, ArrayList<Holder> out) {
+ long forceDuration = anim.getDuration();
+ TimeInterpolator forceInterpolator = anim.getInterpolator();
+ if (anim instanceof ValueAnimator) {
+ out.add(new Holder(anim, springProperty));
+ } else if (anim instanceof AnimatorSet) {
+ for (Animator child : ((AnimatorSet) anim).getChildAnimations()) {
+ if (forceDuration > 0) {
+ child.setDuration(forceDuration);
+ }
+ if (forceInterpolator != null) {
+ child.setInterpolator(forceInterpolator);
+ }
+ addAnimationHoldersRecur(child, springProperty, out);
+ }
+ } else {
+ throw new RuntimeException("Unknown animation type " + anim);
+ }
+ }
}
diff --git a/src/com/android/launcher3/anim/AnimatorSetBuilder.java b/src/com/android/launcher3/anim/AnimatorSetBuilder.java
deleted file mode 100644
index cd30dea..0000000
--- a/src/com/android/launcher3/anim/AnimatorSetBuilder.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * 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.launcher3.anim;
-
-import android.animation.Animator;
-import android.animation.AnimatorSet;
-import android.util.SparseArray;
-import android.view.animation.Interpolator;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Utility class for building animator set
- */
-public class AnimatorSetBuilder {
-
- public static final int ANIM_VERTICAL_PROGRESS = 0;
- public static final int ANIM_WORKSPACE_SCALE = 1;
- public static final int ANIM_WORKSPACE_TRANSLATE = 2;
- public static final int ANIM_WORKSPACE_FADE = 3;
- public static final int ANIM_HOTSEAT_SCALE = 4;
- public static final int ANIM_HOTSEAT_TRANSLATE = 5;
- public static final int ANIM_OVERVIEW_SCALE = 6;
- public static final int ANIM_OVERVIEW_TRANSLATE_X = 7;
- public static final int ANIM_OVERVIEW_TRANSLATE_Y = 8;
- public static final int ANIM_OVERVIEW_FADE = 9;
- public static final int ANIM_ALL_APPS_FADE = 10;
- public static final int ANIM_OVERVIEW_SCRIM_FADE = 11;
- public static final int ANIM_ALL_APPS_HEADER_FADE = 12; // e.g. predictions
-
- public static final int FLAG_DONT_ANIMATE_OVERVIEW = 1 << 0;
-
- protected final ArrayList<Animator> mAnims = new ArrayList<>();
-
- private final SparseArray<Interpolator> mInterpolators = new SparseArray<>();
- private List<Runnable> mOnFinishRunnables = new ArrayList<>();
- private int mFlags = 0;
-
- public void play(Animator anim) {
- mAnims.add(anim);
- }
-
- public void addOnFinishRunnable(Runnable onFinishRunnable) {
- mOnFinishRunnables.add(onFinishRunnable);
- }
-
- public AnimatorSet build() {
- AnimatorSet anim = new AnimatorSet();
- anim.playTogether(mAnims);
- if (!mOnFinishRunnables.isEmpty()) {
- anim.addListener(new AnimationSuccessListener() {
- @Override
- public void onAnimationSuccess(Animator animation) {
- for (Runnable onFinishRunnable : mOnFinishRunnables) {
- onFinishRunnable.run();
- }
- mOnFinishRunnables.clear();
- }
- });
- }
- return anim;
- }
-
- public Interpolator getInterpolator(int animId, Interpolator fallback) {
- return mInterpolators.get(animId, fallback);
- }
-
- public void setInterpolator(int animId, Interpolator interpolator) {
- mInterpolators.put(animId, interpolator);
- }
-
- public void addFlag(int flag) {
- mFlags |= flag;
- }
-
- public boolean hasFlag(int flag) {
- return (mFlags & flag) != 0;
- }
-}
diff --git a/src/com/android/launcher3/anim/FlingSpringAnim.java b/src/com/android/launcher3/anim/FlingSpringAnim.java
index eaf3b1c..06d0f1c 100644
--- a/src/com/android/launcher3/anim/FlingSpringAnim.java
+++ b/src/com/android/launcher3/anim/FlingSpringAnim.java
@@ -15,32 +15,40 @@
*/
package com.android.launcher3.anim;
+import android.content.Context;
+
import androidx.dynamicanimation.animation.DynamicAnimation.OnAnimationEndListener;
import androidx.dynamicanimation.animation.FlingAnimation;
import androidx.dynamicanimation.animation.FloatPropertyCompat;
import androidx.dynamicanimation.animation.SpringAnimation;
import androidx.dynamicanimation.animation.SpringForce;
+import com.android.launcher3.R;
+import com.android.launcher3.util.DynamicResource;
+import com.android.systemui.plugins.ResourceProvider;
+
/**
* Given a property to animate and a target value and starting velocity, first apply friction to
* the fling until we pass the target, then apply a spring force to pull towards the target.
*/
public class FlingSpringAnim {
- private static final float FLING_FRICTION = 1.5f;
- private static final float SPRING_STIFFNESS = 200;
- private static final float SPRING_DAMPING = 0.8f;
-
private final FlingAnimation mFlingAnim;
private SpringAnimation mSpringAnim;
private float mTargetPosition;
- public <K> FlingSpringAnim(K object, FloatPropertyCompat<K> property, float startPosition,
- float targetPosition, float startVelocity, float minVisChange, float minValue,
- float maxValue, float springVelocityFactor, OnAnimationEndListener onEndListener) {
+ public <K> FlingSpringAnim(K object, Context context, FloatPropertyCompat<K> property,
+ float startPosition, float targetPosition, float startVelocity, float minVisChange,
+ float minValue, float maxValue, float springVelocityFactor,
+ OnAnimationEndListener onEndListener) {
+ ResourceProvider rp = DynamicResource.provider(context);
+ float damping = rp.getFloat(R.dimen.swipe_up_rect_xy_damping_ratio);
+ float stiffness = rp.getFloat(R.dimen.swipe_up_rect_xy_stiffness);
+ float friction = rp.getFloat(R.dimen.swipe_up_rect_xy_fling_friction);
+
mFlingAnim = new FlingAnimation(object, property)
- .setFriction(FLING_FRICTION)
+ .setFriction(friction)
// Have the spring pull towards the target if we've slowed down too much before
// reaching it.
.setMinimumVisibleChange(minVisChange)
@@ -54,8 +62,8 @@
.setStartValue(value)
.setStartVelocity(velocity * springVelocityFactor)
.setSpring(new SpringForce(mTargetPosition)
- .setStiffness(SPRING_STIFFNESS)
- .setDampingRatio(SPRING_DAMPING));
+ .setStiffness(stiffness)
+ .setDampingRatio(damping));
mSpringAnim.addEndListener(onEndListener);
mSpringAnim.animateToFinalPosition(mTargetPosition);
}));
diff --git a/src/com/android/launcher3/anim/PendingAnimation.java b/src/com/android/launcher3/anim/PendingAnimation.java
new file mode 100644
index 0000000..a95a5e1
--- /dev/null
+++ b/src/com/android/launcher3/anim/PendingAnimation.java
@@ -0,0 +1,160 @@
+/*
+ * 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.launcher3.anim;
+
+import static com.android.launcher3.anim.AnimatorPlaybackController.addAnimationHoldersRecur;
+
+import android.animation.Animator;
+import android.animation.AnimatorSet;
+import android.animation.ObjectAnimator;
+import android.animation.TimeInterpolator;
+import android.animation.ValueAnimator;
+import android.util.FloatProperty;
+import android.util.IntProperty;
+import android.view.View;
+
+import com.android.launcher3.anim.AnimatorPlaybackController.Holder;
+
+import java.util.ArrayList;
+import java.util.function.Consumer;
+
+/**
+ * Utility class to keep track of a running animation.
+ *
+ * This class allows attaching end callbacks to an animation is intended to be used with
+ * {@link com.android.launcher3.anim.AnimatorPlaybackController}, since in that case
+ * AnimationListeners are not properly dispatched.
+ *
+ * TODO: Find a better name
+ */
+public class PendingAnimation implements PropertySetter {
+
+ private final ArrayList<Consumer<EndState>> mEndListeners = new ArrayList<>();
+
+ private final ArrayList<Holder> mAnimHolders = new ArrayList<>();
+ private final AnimatorSet mAnim;
+ private final long mDuration;
+
+ private ValueAnimator mProgressAnimator;
+
+ public PendingAnimation(long duration) {
+ this(duration, new AnimatorSet());
+ }
+
+ public PendingAnimation(long duration, AnimatorSet targetSet) {
+ mDuration = duration;
+ mAnim = targetSet;
+ }
+
+ /**
+ * Utility method to sent an interpolator on an animation and add it to the list
+ */
+ public void add(Animator anim, TimeInterpolator interpolator, SpringProperty springProperty) {
+ anim.setInterpolator(interpolator);
+ add(anim, springProperty);
+ }
+
+ public void add(Animator anim) {
+ add(anim, SpringProperty.DEFAULT);
+ }
+
+ public void add(Animator a, SpringProperty springProperty) {
+ mAnim.play(a);
+ addAnimationHoldersRecur(a, springProperty, mAnimHolders);
+ }
+
+ public void finish(boolean isSuccess, int logAction) {
+ for (Consumer<EndState> listeners : mEndListeners) {
+ listeners.accept(new EndState(isSuccess, logAction));
+ }
+ mEndListeners.clear();
+ }
+
+ @Override
+ public void setViewAlpha(View view, float alpha, TimeInterpolator interpolator) {
+ if (view == null || view.getAlpha() == alpha) {
+ return;
+ }
+ ObjectAnimator anim = ObjectAnimator.ofFloat(view, View.ALPHA, alpha);
+ anim.addListener(new AlphaUpdateListener(view));
+ anim.setDuration(mDuration).setInterpolator(interpolator);
+ add(anim);
+ }
+
+ @Override
+ public <T> void setFloat(T target, FloatProperty<T> property, float value,
+ TimeInterpolator interpolator) {
+ if (property.get(target) == value) {
+ return;
+ }
+ Animator anim = ObjectAnimator.ofFloat(target, property, value);
+ anim.setDuration(mDuration).setInterpolator(interpolator);
+ add(anim);
+ }
+
+ @Override
+ public <T> void setInt(T target, IntProperty<T> property, int value,
+ TimeInterpolator interpolator) {
+ if (property.get(target) == value) {
+ return;
+ }
+ Animator anim = ObjectAnimator.ofInt(target, property, value);
+ anim.setDuration(mDuration).setInterpolator(interpolator);
+ add(anim);
+ }
+
+ /**
+ * Adds a callback to be run on every frame of the animation
+ */
+ public void addOnFrameCallback(Runnable runnable) {
+ if (mProgressAnimator == null) {
+ mProgressAnimator = ValueAnimator.ofFloat(0, 1).setDuration(mDuration);
+ add(mProgressAnimator);
+ }
+
+ mProgressAnimator.addUpdateListener(anim -> runnable.run());
+ }
+
+ public AnimatorSet getAnim() {
+ return mAnim;
+ }
+
+ /**
+ * Creates a controller for this animation
+ */
+ public AnimatorPlaybackController createPlaybackController() {
+ return new AnimatorPlaybackController(mAnim, mDuration, mAnimHolders);
+ }
+
+ /**
+ * Add a listener of receiving the end state.
+ * Note that the listeners are called as a result of calling {@link #finish(boolean, int)}
+ * and not automatically
+ */
+ public void addEndListener(Consumer<EndState> listener) {
+ mEndListeners.add(listener);
+ }
+
+ public static class EndState {
+ public boolean isSuccess;
+ public int logAction;
+
+ public EndState(boolean isSuccess, int logAction) {
+ this.isSuccess = isSuccess;
+ this.logAction = logAction;
+ }
+ }
+}
diff --git a/src/com/android/launcher3/anim/PropertySetter.java b/src/com/android/launcher3/anim/PropertySetter.java
index 757edff..2ce620b 100644
--- a/src/com/android/launcher3/anim/PropertySetter.java
+++ b/src/com/android/launcher3/anim/PropertySetter.java
@@ -16,77 +16,43 @@
package com.android.launcher3.anim;
-import android.animation.Animator;
-import android.animation.ObjectAnimator;
import android.animation.TimeInterpolator;
-import android.util.Property;
+import android.util.FloatProperty;
+import android.util.IntProperty;
import android.view.View;
/**
* Utility class for setting a property with or without animation
*/
-public class PropertySetter {
+public interface PropertySetter {
- public static final PropertySetter NO_ANIM_PROPERTY_SETTER = new PropertySetter();
+ PropertySetter NO_ANIM_PROPERTY_SETTER = new PropertySetter() { };
- public void setViewAlpha(View view, float alpha, TimeInterpolator interpolator) {
+ /**
+ * Sets the view alpha using the provided interpolator.
+ * Unlike {@link #setFloat}, this also updates the visibility of the view as alpha changes
+ * between zero and non-zero.
+ */
+ default void setViewAlpha(View view, float alpha, TimeInterpolator interpolator) {
if (view != null) {
view.setAlpha(alpha);
AlphaUpdateListener.updateVisibility(view);
}
}
- public <T> void setFloat(T target, Property<T, Float> property, float value,
+ /**
+ * Updates the float property of the target using the provided interpolator
+ */
+ default <T> void setFloat(T target, FloatProperty<T> property, float value,
TimeInterpolator interpolator) {
- property.set(target, value);
+ property.setValue(target, value);
}
- public <T> void setInt(T target, Property<T, Integer> property, int value,
+ /**
+ * Updates the int property of the target using the provided interpolator
+ */
+ default <T> void setInt(T target, IntProperty<T> property, int value,
TimeInterpolator interpolator) {
- property.set(target, value);
- }
-
- public static class AnimatedPropertySetter extends PropertySetter {
-
- private final long mDuration;
- private final AnimatorSetBuilder mStateAnimator;
-
- public AnimatedPropertySetter(long duration, AnimatorSetBuilder builder) {
- mDuration = duration;
- mStateAnimator = builder;
- }
-
- @Override
- public void setViewAlpha(View view, float alpha, TimeInterpolator interpolator) {
- if (view == null || view.getAlpha() == alpha) {
- return;
- }
- ObjectAnimator anim = ObjectAnimator.ofFloat(view, View.ALPHA, alpha);
- anim.addListener(new AlphaUpdateListener(view));
- anim.setDuration(mDuration).setInterpolator(interpolator);
- mStateAnimator.play(anim);
- }
-
- @Override
- public <T> void setFloat(T target, Property<T, Float> property, float value,
- TimeInterpolator interpolator) {
- if (property.get(target) == value) {
- return;
- }
- Animator anim = ObjectAnimator.ofFloat(target, property, value);
- anim.setDuration(mDuration).setInterpolator(interpolator);
- mStateAnimator.play(anim);
- }
-
- @Override
- public <T> void setInt(T target, Property<T, Integer> property, int value,
- TimeInterpolator interpolator) {
- if (property.get(target) == value) {
- return;
- }
- Animator anim = ObjectAnimator.ofInt(target, property, value);
- anim.setDuration(mDuration).setInterpolator(interpolator);
- mStateAnimator.play(anim);
- }
+ property.setValue(target, value);
}
}
diff --git a/src/com/android/launcher3/anim/SpringAnimationBuilder.java b/src/com/android/launcher3/anim/SpringAnimationBuilder.java
index 0f34c1e..f22a9f0 100644
--- a/src/com/android/launcher3/anim/SpringAnimationBuilder.java
+++ b/src/com/android/launcher3/anim/SpringAnimationBuilder.java
@@ -15,16 +15,15 @@
*/
package com.android.launcher3.anim;
-import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.util.FloatProperty;
-import com.android.launcher3.util.DefaultDisplay;
-
import androidx.annotation.FloatRange;
import androidx.dynamicanimation.animation.SpringForce;
+import com.android.launcher3.util.DefaultDisplay;
+
/**
* Utility class to build an object animator which follows the same path as a spring animation for
* an underdamped spring.
@@ -192,12 +191,8 @@
long durationMs = (long) (1000.0 * duration);
ObjectAnimator animator = ObjectAnimator.ofFloat(mTarget, this, 0, (float) duration);
animator.setDuration(durationMs).setInterpolator(Interpolators.LINEAR);
- animator.addListener(new AnimationSuccessListener() {
- @Override
- public void onAnimationSuccess(Animator animator) {
- mProperty.setValue(mTarget, mEndValue);
- }
- });
+ animator.addListener(AnimationSuccessListener.forRunnable(
+ () -> mProperty.setValue(mTarget, mEndValue)));
return animator;
}
diff --git a/src/com/android/launcher3/anim/SpringObjectAnimator.java b/src/com/android/launcher3/anim/SpringObjectAnimator.java
deleted file mode 100644
index 27b9c18..0000000
--- a/src/com/android/launcher3/anim/SpringObjectAnimator.java
+++ /dev/null
@@ -1,308 +0,0 @@
-/*
- * 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.launcher3.anim;
-
-import static androidx.dynamicanimation.animation.FloatPropertyCompat.createFloatPropertyCompat;
-
-import static com.android.launcher3.config.FeatureFlags.QUICKSTEP_SPRINGS;
-
-import android.animation.Animator;
-import android.animation.AnimatorListenerAdapter;
-import android.animation.ObjectAnimator;
-import android.animation.TimeInterpolator;
-import android.animation.ValueAnimator;
-import android.os.Handler;
-import android.os.Looper;
-import android.util.FloatProperty;
-import android.util.Log;
-
-import androidx.dynamicanimation.animation.DynamicAnimation.OnAnimationEndListener;
-import androidx.dynamicanimation.animation.SpringAnimation;
-import androidx.dynamicanimation.animation.SpringForce;
-
-import java.util.ArrayList;
-
-
-/**
- * This animator allows for an object's property to be be controlled by an {@link ObjectAnimator} or
- * a {@link SpringAnimation}. It extends ValueAnimator so it can be used in an AnimatorSet.
- */
-public class SpringObjectAnimator<T> extends ValueAnimator {
-
- private static final String TAG = "SpringObjectAnimator";
- private static boolean DEBUG = false;
-
- private ObjectAnimator mObjectAnimator;
- private float[] mValues;
-
- private SpringAnimation mSpring;
- private SpringProperty<T> mProperty;
-
- private ArrayList<AnimatorListener> mListeners;
- private boolean mSpringEnded = true;
- private boolean mAnimatorEnded = true;
- private boolean mEnded = true;
-
- public SpringObjectAnimator(T object, FloatProperty<T> property, float minimumVisibleChange,
- float damping, float stiffness, float... values) {
- mSpring = new SpringAnimation(object, createFloatPropertyCompat(property));
- mSpring.setMinimumVisibleChange(minimumVisibleChange);
- mSpring.setSpring(new SpringForce(0)
- .setDampingRatio(damping)
- .setStiffness(stiffness));
- mSpring.setStartVelocity(0.01f);
- mProperty = new SpringProperty<>(property, mSpring);
- mObjectAnimator = ObjectAnimator.ofFloat(object, mProperty, values);
- mValues = values;
- mListeners = new ArrayList<>();
- setFloatValues(values);
-
- // We use this listener and track mListeners so that we can sync the animator and spring
- // listeners.
- mObjectAnimator.addListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationStart(Animator animation) {
- mAnimatorEnded = false;
- mEnded = false;
- for (AnimatorListener l : mListeners) {
- l.onAnimationStart(animation);
- }
- }
-
- @Override
- public void onAnimationEnd(Animator animation) {
- mAnimatorEnded = true;
- tryEnding();
- }
-
- @Override
- public void onAnimationCancel(Animator animation) {
- for (AnimatorListener l : mListeners) {
- l.onAnimationCancel(animation);
- }
- mSpring.cancel();
- }
- });
-
- mSpring.addUpdateListener((animation, value, velocity) -> {
- mSpringEnded = false;
- mEnded = false;
- });
- mSpring.addEndListener((animation, canceled, value, velocity) -> {
- mSpringEnded = true;
- tryEnding();
- });
- }
-
- private void tryEnding() {
- if (DEBUG) {
- Log.d(TAG, "tryEnding#mAnimatorEnded=" + mAnimatorEnded + ", mSpringEnded="
- + mSpringEnded + ", mEnded=" + mEnded);
- }
-
- // If springs are disabled, ignore value of mSpringEnded
- if (mAnimatorEnded && (mSpringEnded || !QUICKSTEP_SPRINGS.get()) && !mEnded) {
- for (AnimatorListener l : mListeners) {
- l.onAnimationEnd(this);
- }
- mEnded = true;
- }
- }
-
- public SpringAnimation getSpring() {
- return mSpring;
- }
-
- /**
- * Initializes and sets up the spring to take over controlling the object.
- */
- public void startSpring(float end, float velocity, OnAnimationEndListener endListener) {
- // Cancel the spring so we can set new start velocity and final position. We need to remove
- // the listener since the spring is not actually ending.
- mSpring.removeEndListener(endListener);
- mSpring.cancel();
- mSpring.addEndListener(endListener);
-
- mProperty.switchToSpring();
-
- float startValue = end == 0 ? mValues[1] : mValues[0];
- float endValue = end == 0 ? mValues[0] : mValues[1];
-
- // Ensures that the velocity matches the direction of the values.
- velocity = Math.signum(endValue - startValue) * Math.abs(velocity);
- mSpring.setStartVelocity(velocity);
-
- new Handler(Looper.getMainLooper()).postDelayed(() -> {
- mSpring.animateToFinalPosition(endValue);
- }, getStartDelay());
- }
-
- @Override
- public void addListener(AnimatorListener listener) {
- mListeners.add(listener);
- }
-
- public ArrayList<AnimatorListener> getObjectAnimatorListeners() {
- return mObjectAnimator.getListeners();
- }
-
- @Override
- public ArrayList<AnimatorListener> getListeners() {
- return mListeners;
- }
-
- @Override
- public void removeAllListeners() {
- mListeners.clear();
- }
-
- @Override
- public void removeListener(AnimatorListener listener) {
- mListeners.remove(listener);
- }
-
- @Override
- public void addPauseListener(AnimatorPauseListener listener) {
- mObjectAnimator.addPauseListener(listener);
- }
-
- @Override
- public void cancel() {
- mObjectAnimator.cancel();
- mSpring.cancel();
- }
-
- @Override
- public void end() {
- mObjectAnimator.end();
- }
-
- @Override
- public long getDuration() {
- return mObjectAnimator.getDuration();
- }
-
- @Override
- public TimeInterpolator getInterpolator() {
- return mObjectAnimator.getInterpolator();
- }
-
- @Override
- public long getStartDelay() {
- return mObjectAnimator.getStartDelay();
- }
-
- @Override
- public long getTotalDuration() {
- return mObjectAnimator.getTotalDuration();
- }
-
- @Override
- public boolean isPaused() {
- return mObjectAnimator.isPaused();
- }
-
- @Override
- public boolean isRunning() {
- return mObjectAnimator.isRunning();
- }
-
- @Override
- public boolean isStarted() {
- return mObjectAnimator.isStarted();
- }
-
- @Override
- public void pause() {
- mObjectAnimator.pause();
- }
-
- @Override
- public void removePauseListener(AnimatorPauseListener listener) {
- mObjectAnimator.removePauseListener(listener);
- }
-
- @Override
- public void resume() {
- mObjectAnimator.resume();
- }
-
- @Override
- public ValueAnimator setDuration(long duration) {
- return mObjectAnimator.setDuration(duration);
- }
-
- @Override
- public void setInterpolator(TimeInterpolator value) {
- mObjectAnimator.setInterpolator(value);
- }
-
- @Override
- public void setStartDelay(long startDelay) {
- mObjectAnimator.setStartDelay(startDelay);
- }
-
- @Override
- public void setTarget(Object target) {
- mObjectAnimator.setTarget(target);
- }
-
- @Override
- public void start() {
- mObjectAnimator.start();
- }
-
- @Override
- public void setCurrentFraction(float fraction) {
- mObjectAnimator.setCurrentFraction(fraction);
- }
-
- @Override
- public void setCurrentPlayTime(long playTime) {
- mObjectAnimator.setCurrentPlayTime(playTime);
- }
-
- public static class SpringProperty<T> extends FloatProperty<T> {
-
- boolean useSpring = false;
- final FloatProperty<T> mProperty;
- final SpringAnimation mSpring;
-
- public SpringProperty(FloatProperty<T> property, SpringAnimation spring) {
- super(property.getName());
- mProperty = property;
- mSpring = spring;
- }
-
- public void switchToSpring() {
- useSpring = true;
- }
-
- @Override
- public Float get(T object) {
- return mProperty.get(object);
- }
-
- @Override
- public void setValue(T object, float progress) {
- if (useSpring) {
- mSpring.animateToFinalPosition(progress);
- } else {
- mProperty.setValue(object, progress);
- }
- }
- }
-}
diff --git a/src/com/android/launcher3/anim/SpringProperty.java b/src/com/android/launcher3/anim/SpringProperty.java
new file mode 100644
index 0000000..caedd6c
--- /dev/null
+++ b/src/com/android/launcher3/anim/SpringProperty.java
@@ -0,0 +1,54 @@
+/*
+ * 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.launcher3.anim;
+
+import androidx.dynamicanimation.animation.SpringForce;
+
+/**
+ * Utility class to store configurations for spring animation
+ */
+public class SpringProperty {
+
+ public static final SpringProperty DEFAULT = new SpringProperty();
+
+ // Play spring when the animation is going towards the end
+ public static final int FLAG_CAN_SPRING_ON_END = 1 << 0;
+ // Play spring when animation is going towards the start (in reverse direction)
+ public static final int FLAG_CAN_SPRING_ON_START = 1 << 1;
+
+ public final int flags;
+
+ float mDampingRatio = SpringForce.DAMPING_RATIO_MEDIUM_BOUNCY;
+ float mStiffness = SpringForce.STIFFNESS_MEDIUM;
+
+ public SpringProperty() {
+ this(0);
+ }
+
+ public SpringProperty(int flags) {
+ this.flags = flags;
+ }
+
+ public SpringProperty setDampingRatio(float dampingRatio) {
+ mDampingRatio = dampingRatio;
+ return this;
+ }
+
+ public SpringProperty setStiffness(float stiffness) {
+ mStiffness = stiffness;
+ return this;
+ }
+}
diff --git a/src/com/android/launcher3/compat/AccessibilityManagerCompat.java b/src/com/android/launcher3/compat/AccessibilityManagerCompat.java
index 28579c1..737c97b 100644
--- a/src/com/android/launcher3/compat/AccessibilityManagerCompat.java
+++ b/src/com/android/launcher3/compat/AccessibilityManagerCompat.java
@@ -18,11 +18,14 @@
import android.content.Context;
import android.os.Bundle;
+import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
+import androidx.annotation.Nullable;
+
import com.android.launcher3.Utilities;
import com.android.launcher3.testing.TestProtocol;
@@ -37,11 +40,21 @@
return isAccessibilityEnabled(context);
}
- public static void sendCustomAccessibilityEvent(View target, int type, String text) {
- if (isObservedEventType(target.getContext(), type)) {
+ /**
+ *
+ * @param target The view the accessibility event is initialized on.
+ * If null, this method has no effect.
+ * @param type See TYPE_ constants defined in {@link AccessibilityEvent}.
+ * @param text Optional text to add to the event, which will be announced to the user.
+ */
+ public static void sendCustomAccessibilityEvent(@Nullable View target, int type,
+ @Nullable String text) {
+ if (target != null && isObservedEventType(target.getContext(), type)) {
AccessibilityEvent event = AccessibilityEvent.obtain(type);
target.onInitializeAccessibilityEvent(event);
- event.getText().add(text);
+ if (!TextUtils.isEmpty(text)) {
+ event.getText().add(text);
+ }
getManager(target.getContext()).sendAccessibilityEvent(event);
}
}
@@ -62,6 +75,9 @@
}
public static void sendScrollFinishedEventToTest(Context context) {
+ if (TestProtocol.sDebugTracing) {
+ Log.d(TestProtocol.NO_SCROLL_END_WIDGETS, "sendScrollFinishedEventToTest");
+ }
final AccessibilityManager accessibilityManager = getAccessibilityManagerForTest(context);
if (accessibilityManager == null) return;
diff --git a/src/com/android/launcher3/config/FeatureFlags.java b/src/com/android/launcher3/config/FeatureFlags.java
index cc33965..bcd91da 100644
--- a/src/com/android/launcher3/config/FeatureFlags.java
+++ b/src/com/android/launcher3/config/FeatureFlags.java
@@ -22,6 +22,7 @@
import com.android.launcher3.Utilities;
import com.android.launcher3.uioverrides.DeviceFlag;
+import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
@@ -35,6 +36,8 @@
private static final List<DebugFlag> sDebugFlags = new ArrayList<>();
public static final String FLAGS_PREF_NAME = "featureFlags";
+ public static final String FLAG_ENABLE_FIXED_ROTATION_TRANSFORM =
+ "ENABLE_FIXED_ROTATION_TRANSFORM";
private FeatureFlags() { }
@@ -42,7 +45,10 @@
return Utilities.IS_DEBUG_DEVICE && Utilities.isDevelopersOptionsEnabled(context);
}
- public static final boolean IS_DOGFOOD_BUILD = BuildConfig.DEBUG;
+ /**
+ * True when the build has come from Android Studio and is being used for local debugging.
+ */
+ public static final boolean IS_STUDIO_BUILD = BuildConfig.DEBUG;
/**
* Enable moving the QSB on the 0th screen of the workspace. This is not a configuration feature
@@ -77,23 +83,24 @@
public static final BooleanFlag UNSTABLE_SPRINGS = getDebugFlag(
"UNSTABLE_SPRINGS", false, "Enable unstable springs for quickstep animations");
+ public static final BooleanFlag KEYGUARD_ANIMATION = getDebugFlag(
+ "KEYGUARD_ANIMATION", false, "Enable animation for keyguard going away on wallpaper");
+
public static final BooleanFlag ADAPTIVE_ICON_WINDOW_ANIM = getDebugFlag(
"ADAPTIVE_ICON_WINDOW_ANIM", true, "Use adaptive icons for window animations.");
public static final BooleanFlag ENABLE_QUICKSTEP_LIVE_TILE = getDebugFlag(
"ENABLE_QUICKSTEP_LIVE_TILE", false, "Enable live tile in Quickstep overview");
- public static final BooleanFlag ENABLE_HINTS_IN_OVERVIEW = getDebugFlag(
- "ENABLE_HINTS_IN_OVERVIEW", false, "Show chip hints and gleams on the overview screen");
+ public static final BooleanFlag ENABLE_SUGGESTED_ACTIONS_OVERVIEW = new DeviceFlag(
+ "ENABLE_SUGGESTED_ACTIONS_OVERVIEW", false, "Show chip hints on the overview screen");
- public static final BooleanFlag FAKE_LANDSCAPE_UI = getDebugFlag(
- "FAKE_LANDSCAPE_UI", false, "Rotate launcher UI instead of using transposed layout");
-
- public static final BooleanFlag FOLDER_NAME_SUGGEST = getDebugFlag(
- "FOLDER_NAME_SUGGEST", false, "Suggests folder names instead of blank text.");
+ public static final BooleanFlag FOLDER_NAME_SUGGEST = new DeviceFlag(
+ "FOLDER_NAME_SUGGEST", true,
+ "Suggests folder names instead of blank text.");
public static final BooleanFlag APP_SEARCH_IMPROVEMENTS = new DeviceFlag(
- "APP_SEARCH_IMPROVEMENTS", false,
+ "APP_SEARCH_IMPROVEMENTS", true,
"Adds localized title and keyword search and ranking");
public static final BooleanFlag ENABLE_PREDICTION_DISMISS = getDebugFlag(
@@ -102,13 +109,20 @@
public static final BooleanFlag ENABLE_QUICK_CAPTURE_GESTURE = getDebugFlag(
"ENABLE_QUICK_CAPTURE_GESTURE", true, "Swipe from right to left to quick capture");
+ public static final BooleanFlag FORCE_LOCAL_OVERSCROLL_PLUGIN = getDebugFlag(
+ "FORCE_LOCAL_OVERSCROLL_PLUGIN", false,
+ "Use a launcher-provided OverscrollPlugin if available");
+
public static final BooleanFlag ASSISTANT_GIVES_LAUNCHER_FOCUS = getDebugFlag(
"ASSISTANT_GIVES_LAUNCHER_FOCUS", false,
"Allow Launcher to handle nav bar gestures while Assistant is running over it");
- public static final BooleanFlag ENABLE_HYBRID_HOTSEAT = getDebugFlag(
+ public static final BooleanFlag ENABLE_HYBRID_HOTSEAT = new DeviceFlag(
"ENABLE_HYBRID_HOTSEAT", false, "Fill gaps in hotseat with predicted apps");
+ public static final BooleanFlag HOTSEAT_MIGRATE_TO_FOLDER = new DeviceFlag(
+ "HOTSEAT_MIGRATE_TO_FOLDER", false, "Should move hotseat items into a folder");
+
public static final BooleanFlag ENABLE_DEEP_SHORTCUT_ICON_CACHE = getDebugFlag(
"ENABLE_DEEP_SHORTCUT_ICON_CACHE", true, "R/W deep shortcut in IconCache");
@@ -116,13 +130,18 @@
"MULTI_DB_GRID_MIRATION_ALGO", false, "Use the multi-db grid migration algorithm");
public static final BooleanFlag ENABLE_LAUNCHER_PREVIEW_IN_GRID_PICKER = getDebugFlag(
- "ENABLE_LAUNCHER_PREVIEW_IN_GRID_PICKER", false,
- "Show launcher preview in grid picker");
+ "ENABLE_LAUNCHER_PREVIEW_IN_GRID_PICKER", true, "Show launcher preview in grid picker");
+
+ public static final BooleanFlag USE_SURFACE_VIEW_FOR_GRID_PREVIEW = getDebugFlag(
+ "USE_SURFACE_VIEW_FOR_GRID_PREVIEW", true, "Use surface view for grid preview");
public static final BooleanFlag ENABLE_OVERVIEW_ACTIONS = getDebugFlag(
- "ENABLE_OVERVIEW_ACTIONS", false, "Show app actions instead of the shelf in Overview."
+ "ENABLE_OVERVIEW_ACTIONS", true, "Show app actions instead of the shelf in Overview."
+ " As part of this decoupling, also distinguish swipe up from nav bar vs above it.");
+ public static final BooleanFlag ENABLE_SELECT_MODE = getDebugFlag(
+ "ENABLE_SELECT_MODE", true, "Show Select Mode button in Overview Actions");
+
public static final BooleanFlag ENABLE_DATABASE_RESTORE = getDebugFlag(
"ENABLE_DATABASE_RESTORE", true,
"Enable database restore when new restore session is created");
@@ -131,6 +150,19 @@
"ENABLE_UNIVERSAL_SMARTSPACE", false,
"Replace Smartspace with a version rendered by System UI.");
+ public static final BooleanFlag ENABLE_LSQ_VELOCITY_PROVIDER = getDebugFlag(
+ "ENABLE_LSQ_VELOCITY_PROVIDER", true,
+ "Use Least Square algorithm for motion pause detection.");
+
+ public static final BooleanFlag ALWAYS_USE_HARDWARE_OPTIMIZATION_FOR_FOLDER_ANIMATIONS =
+ getDebugFlag(
+ "ALWAYS_USE_HARDWARE_OPTIMIZATION_FOR_FOLDER_ANIMATIONS", false,
+ "Always use hardware optimization for folder animations.");
+
+ public static final BooleanFlag ENABLE_FIXED_ROTATION_TRANSFORM = getDebugFlag(
+ FLAG_ENABLE_FIXED_ROTATION_TRANSFORM, true,
+ "Launch/close apps without rotation animation. Fix Launcher to portrait");
+
public static void initialize(Context context) {
synchronized (sDebugFlags) {
for (DebugFlag flag : sDebugFlags) {
@@ -145,6 +177,15 @@
}
}
+ public static void dump(PrintWriter pw) {
+ pw.println("FeatureFlags:");
+ synchronized (sDebugFlags) {
+ for (DebugFlag flag : sDebugFlags) {
+ pw.println(" " + flag.key + "=" + flag.get());
+ }
+ }
+ }
+
public static class BooleanFlag {
public final String key;
diff --git a/src/com/android/launcher3/dot/DotInfo.java b/src/com/android/launcher3/dot/DotInfo.java
index 4ff0539..fc180d1 100644
--- a/src/com/android/launcher3/dot/DotInfo.java
+++ b/src/com/android/launcher3/dot/DotInfo.java
@@ -16,6 +16,8 @@
package com.android.launcher3.dot;
+import androidx.annotation.NonNull;
+
import com.android.launcher3.notification.NotificationInfo;
import com.android.launcher3.notification.NotificationKeyData;
@@ -83,4 +85,10 @@
public int getNotificationCount() {
return Math.min(mTotalCount, MAX_COUNT);
}
+
+ @NonNull
+ @Override
+ public String toString() {
+ return Integer.toString(mTotalCount);
+ }
}
diff --git a/src/com/android/launcher3/dragndrop/BaseItemDragListener.java b/src/com/android/launcher3/dragndrop/BaseItemDragListener.java
index 75693c6..9b91a1d 100644
--- a/src/com/android/launcher3/dragndrop/BaseItemDragListener.java
+++ b/src/com/android/launcher3/dragndrop/BaseItemDragListener.java
@@ -26,7 +26,6 @@
import android.graphics.Rect;
import android.os.Handler;
import android.os.Looper;
-import android.os.SystemClock;
import android.util.Log;
import android.view.DragEvent;
import android.view.View;
@@ -63,7 +62,6 @@
protected Launcher mLauncher;
private DragController mDragController;
- private long mDragStartTime;
public BaseItemDragListener(Rect previewRect, int previewBitmapWidth, int previewViewWidth) {
mPreviewRect = previewRect;
@@ -102,7 +100,7 @@
return false;
}
}
- return mDragController.onDragEvent(mDragStartTime, event);
+ return mDragController.onDragEvent(event);
}
protected boolean onDragStart(DragEvent event) {
@@ -118,7 +116,7 @@
Point downPos = new Point((int) event.getX(), (int) event.getY());
DragOptions options = new DragOptions();
- options.systemDndStartPoint = downPos;
+ options.simulatedDndStartPoint = downPos;
options.preDragCondition = preDragCondition;
// We use drag event position as the screenPos for the preview image. Since mPreviewRect
@@ -128,7 +126,6 @@
// to source window.
createDragHelper().startDrag(new Rect(mPreviewRect),
mPreviewBitmapWidth, mPreviewViewWidth, downPos, this, options);
- mDragStartTime = SystemClock.uptimeMillis();
return true;
}
diff --git a/src/com/android/launcher3/dragndrop/DragController.java b/src/com/android/launcher3/dragndrop/DragController.java
index 1b7b015..d93fb1a 100644
--- a/src/com/android/launcher3/dragndrop/DragController.java
+++ b/src/com/android/launcher3/dragndrop/DragController.java
@@ -20,6 +20,7 @@
import static com.android.launcher3.LauncherAnimUtils.SPRING_LOADED_EXIT_DELAY;
import static com.android.launcher3.LauncherState.NORMAL;
import static com.android.launcher3.Utilities.ATLEAST_Q;
+import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
import android.animation.ValueAnimator;
import android.content.ComponentName;
@@ -27,7 +28,6 @@
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Rect;
-import android.os.IBinder;
import android.view.DragEvent;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
@@ -37,15 +37,13 @@
import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.DragSource;
import com.android.launcher3.DropTarget;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.Launcher;
import com.android.launcher3.R;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.accessibility.DragViewStateAnnouncer;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.util.ItemInfoMatcher;
-import com.android.launcher3.util.Thunk;
import com.android.launcher3.util.TouchController;
-import com.android.launcher3.util.UiThreadHelper;
import java.util.ArrayList;
@@ -61,11 +59,11 @@
*/
private static final int DEEP_PRESS_DISTANCE_FACTOR = 3;
- @Thunk Launcher mLauncher;
- private FlingToDeleteHelper mFlingToDeleteHelper;
+ private final Launcher mLauncher;
+ private final FlingToDeleteHelper mFlingToDeleteHelper;
// temporaries to avoid gc thrash
- private Rect mRectTemp = new Rect();
+ private final Rect mRectTemp = new Rect();
private final int[] mCoordinatesTemp = new int[2];
/**
@@ -77,33 +75,24 @@
/** Options controlling the drag behavior. */
private DragOptions mOptions;
- /** X coordinate of the down event. */
- private int mMotionDownX;
+ /** Coordinate for motion down event */
+ private final Point mMotionDown = new Point();
+ /** Coordinate for last touch event **/
+ private final Point mLastTouch = new Point();
- /** Y coordinate of the down event. */
- private int mMotionDownY;
+ private final Point mTmpPoint = new Point();
private DropTarget.DragObject mDragObject;
/** Who can receive drop events */
- private ArrayList<DropTarget> mDropTargets = new ArrayList<>();
- private ArrayList<DragListener> mListeners = new ArrayList<>();
-
- /** The window token used as the parent for the DragView. */
- private IBinder mWindowToken;
-
- private View mMoveTarget;
+ private final ArrayList<DropTarget> mDropTargets = new ArrayList<>();
+ private final ArrayList<DragListener> mListeners = new ArrayList<>();
private DropTarget mLastDropTarget;
- private final int[] mLastTouch = new int[2];
- private long mLastTouchUpTime = -1;
private int mLastTouchClassification;
private int mDistanceSinceScroll = 0;
- private int mTmpPoint[] = new int[2];
- private Rect mDragLayerRect = new Rect();
-
private boolean mIsInPreDrag;
/**
@@ -140,6 +129,8 @@
*
* @param b The bitmap to display as the drag image. It will be re-scaled to the
* enlarged size.
+ * @param originalView The source view (ie. icon, widget etc.) that is being dragged
+ * and which the DragView represents
* @param dragLayerX The x position in the DragLayer of the left-top of the bitmap.
* @param dragLayerY The y position in the DragLayer of the left-top of the bitmap.
* @param source An object representing where the drag originated
@@ -147,25 +138,24 @@
* @param dragRegion Coordinates within the bitmap b for the position of item being dragged.
* Makes dragging feel more precise, e.g. you can clip out a transparent border
*/
- public DragView startDrag(Bitmap b, int dragLayerX, int dragLayerY,
+ public DragView startDrag(Bitmap b, DraggableView originalView, int dragLayerX, int dragLayerY,
DragSource source, ItemInfo dragInfo, Point dragOffset, Rect dragRegion,
float initialDragViewScale, float dragViewScaleOnDrop, DragOptions options) {
if (PROFILE_DRAWING_DURING_DRAG) {
android.os.Debug.startMethodTracing("Launcher");
}
- // Hide soft keyboard, if visible
- UiThreadHelper.hideKeyboardAsync(mLauncher, mWindowToken);
+ mLauncher.hideKeyboard();
AbstractFloatingView.closeOpenViews(mLauncher, false, TYPE_DISCOVERY_BOUNCE);
mOptions = options;
- if (mOptions.systemDndStartPoint != null) {
- mMotionDownX = mOptions.systemDndStartPoint.x;
- mMotionDownY = mOptions.systemDndStartPoint.y;
+ if (mOptions.simulatedDndStartPoint != null) {
+ mLastTouch.x = mMotionDown.x = mOptions.simulatedDndStartPoint.x;
+ mLastTouch.y = mMotionDown.y = mOptions.simulatedDndStartPoint.y;
}
- final int registrationX = mMotionDownX - dragLayerX;
- final int registrationY = mMotionDownY - dragLayerY;
+ final int registrationX = mMotionDown.x - dragLayerX;
+ final int registrationY = mMotionDown.y - dragLayerY;
final int dragRegionLeft = dragRegion == null ? 0 : dragRegion.left;
final int dragRegionTop = dragRegion == null ? 0 : dragRegion.top;
@@ -173,6 +163,7 @@
mLastDropTarget = null;
mDragObject = new DropTarget.DragObject(mLauncher.getApplicationContext());
+ mDragObject.originalView = originalView;
mIsInPreDrag = mOptions.preDragCondition != null
&& !mOptions.preDragCondition.shouldStartDrag(0);
@@ -184,17 +175,13 @@
registrationY, initialDragViewScale, dragViewScaleOnDrop, scaleDps);
dragView.setItemInfo(dragInfo);
mDragObject.dragComplete = false;
- if (mOptions.isAccessibleDrag) {
- // For an accessible drag, we assume the view is being dragged from the center.
- mDragObject.xOffset = b.getWidth() / 2;
- mDragObject.yOffset = b.getHeight() / 2;
- mDragObject.accessibleDrag = true;
- } else {
- mDragObject.xOffset = mMotionDownX - (dragLayerX + dragRegionLeft);
- mDragObject.yOffset = mMotionDownY - (dragLayerY + dragRegionTop);
- mDragObject.stateAnnouncer = DragViewStateAnnouncer.createFor(dragView);
- mDragDriver = DragDriver.create(mLauncher, this, mDragObject, mOptions);
+ mDragObject.xOffset = mMotionDown.x - (dragLayerX + dragRegionLeft);
+ mDragObject.yOffset = mMotionDown.y - (dragLayerY + dragRegionTop);
+
+ mDragDriver = DragDriver.create(this, mOptions, mFlingToDeleteHelper::recordMotionEvent);
+ if (!mOptions.isAccessibleDrag) {
+ mDragObject.stateAnnouncer = DragViewStateAnnouncer.createFor(dragView);
}
mDragObject.dragSource = source;
@@ -210,7 +197,7 @@
}
mLauncher.getDragLayer().performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
- dragView.show(mLastTouch[0], mLastTouch[1]);
+ dragView.show(mLastTouch.x, mLastTouch.y);
mDistanceSinceScroll = 0;
if (!mIsInPreDrag) {
@@ -219,8 +206,13 @@
mOptions.preDragCondition.onPreDragStart(mDragObject);
}
- handleMoveEvent(mLastTouch[0], mLastTouch[1]);
+ handleMoveEvent(mLastTouch.x, mLastTouch.y);
mLauncher.getUserEventDispatcher().resetActionDurationMillis();
+
+ if (!mLauncher.isTouchInProgress() && options.simulatedDndStartPoint == null) {
+ // If it is an internal drag and the touch is already complete, cancel immediately
+ MAIN_EXECUTOR.submit(this::cancelDrag);
+ }
return dragView;
}
@@ -336,7 +328,7 @@
}
}
};
- mDragObject.dragView.animateTo(mMotionDownX, mMotionDownY, onCompleteRunnable, duration);
+ mDragObject.dragView.animateTo(mMotionDown.x, mMotionDown.y, onCompleteRunnable, duration);
}
private void callOnDragEnd() {
@@ -365,30 +357,17 @@
/**
* Clamps the position to the drag layer bounds.
*/
- private int[] getClampedDragLayerPos(float x, float y) {
- mLauncher.getDragLayer().getLocalVisibleRect(mDragLayerRect);
- mTmpPoint[0] = (int) Math.max(mDragLayerRect.left, Math.min(x, mDragLayerRect.right - 1));
- mTmpPoint[1] = (int) Math.max(mDragLayerRect.top, Math.min(y, mDragLayerRect.bottom - 1));
+ private Point getClampedDragLayerPos(float x, float y) {
+ mLauncher.getDragLayer().getLocalVisibleRect(mRectTemp);
+ mTmpPoint.x = (int) Math.max(mRectTemp.left, Math.min(x, mRectTemp.right - 1));
+ mTmpPoint.y = (int) Math.max(mRectTemp.top, Math.min(y, mRectTemp.bottom - 1));
return mTmpPoint;
}
- public long getLastGestureUpTime() {
- if (mDragDriver != null) {
- return System.currentTimeMillis();
- } else {
- return mLastTouchUpTime;
- }
- }
-
- public void resetLastGestureUpTime() {
- mLastTouchUpTime = -1;
- }
-
@Override
public void onDriverDragMove(float x, float y) {
- final int[] dragLayerPos = getClampedDragLayerPos(x, y);
-
- handleMoveEvent(dragLayerPos[0], dragLayerPos[1]);
+ Point dragLayerPos = getClampedDragLayerPos(x, y);
+ handleMoveEvent(dragLayerPos.x, dragLayerPos.y);
}
@Override
@@ -422,66 +401,40 @@
/**
* Call this from a drag source view.
*/
+ @Override
public boolean onControllerInterceptTouchEvent(MotionEvent ev) {
if (mOptions != null && mOptions.isAccessibleDrag) {
return false;
}
- // Update the velocity tracker
- mFlingToDeleteHelper.recordMotionEvent(ev);
+ Point dragLayerPos = getClampedDragLayerPos(ev.getX(), ev.getY());
+ mLastTouch.set(dragLayerPos.x, dragLayerPos.y);
+ if (ev.getAction() == MotionEvent.ACTION_DOWN) {
+ // Remember location of down touch
+ mMotionDown.set(dragLayerPos.x, dragLayerPos.y);
+ }
- final int action = ev.getAction();
- final int[] dragLayerPos = getClampedDragLayerPos(ev.getX(), ev.getY());
- final int dragLayerX = dragLayerPos[0];
- final int dragLayerY = dragLayerPos[1];
- mLastTouch[0] = dragLayerX;
- mLastTouch[1] = dragLayerY;
if (ATLEAST_Q) {
mLastTouchClassification = ev.getClassification();
}
-
- switch (action) {
- case MotionEvent.ACTION_DOWN:
- // Remember location of down touch
- mMotionDownX = dragLayerX;
- mMotionDownY = dragLayerY;
- break;
- case MotionEvent.ACTION_UP:
- mLastTouchUpTime = System.currentTimeMillis();
- break;
- }
-
return mDragDriver != null && mDragDriver.onInterceptTouchEvent(ev);
}
/**
* Call this from a drag source view.
*/
- public boolean onDragEvent(long dragStartTime, DragEvent event) {
- mFlingToDeleteHelper.recordDragEvent(dragStartTime, event);
+ @Override
+ public boolean onControllerTouchEvent(MotionEvent ev) {
+ return mDragDriver != null && mDragDriver.onTouchEvent(ev);
+ }
+
+ /**
+ * Call this from a drag source view.
+ */
+ public boolean onDragEvent(DragEvent event) {
return mDragDriver != null && mDragDriver.onDragEvent(event);
}
- /**
- * Call this from a drag view.
- */
- public void onDragViewAnimationEnd() {
- if (mDragDriver != null) {
- mDragDriver.onDragViewAnimationEnd();
- }
- }
-
- /**
- * Sets the view that should handle move events.
- */
- public void setMoveTarget(View view) {
- mMoveTarget = view;
- }
-
- public boolean dispatchUnhandledMove(View focused, int direction) {
- return mMoveTarget != null && mMoveTarget.dispatchUnhandledMove(focused, direction);
- }
-
private void handleMoveEvent(int x, int y) {
mDragObject.dragView.move(x, y);
@@ -493,9 +446,8 @@
checkTouchMove(dropTarget);
// Check if we are hovering over the scroll areas
- mDistanceSinceScroll += Math.hypot(mLastTouch[0] - x, mLastTouch[1] - y);
- mLastTouch[0] = x;
- mLastTouch[1] = y;
+ mDistanceSinceScroll += Math.hypot(mLastTouch.x - x, mLastTouch.y - y);
+ mLastTouch.set(x, y);
int distanceDragged = mDistanceSinceScroll;
if (ATLEAST_Q && mLastTouchClassification == MotionEvent.CLASSIFICATION_DEEP_PRESS) {
@@ -513,7 +465,7 @@
public void forceTouchMove() {
int[] dummyCoordinates = mCoordinatesTemp;
- DropTarget dropTarget = findDropTarget(mLastTouch[0], mLastTouch[1], dummyCoordinates);
+ DropTarget dropTarget = findDropTarget(mLastTouch.x, mLastTouch.y, dummyCoordinates);
mDragObject.x = dummyCoordinates[0];
mDragObject.y = dummyCoordinates[1];
checkTouchMove(dropTarget);
@@ -537,44 +489,6 @@
}
/**
- * Call this from a drag source view.
- */
- public boolean onControllerTouchEvent(MotionEvent ev) {
- if (mDragDriver == null || mOptions == null || mOptions.isAccessibleDrag) {
- return false;
- }
-
- // Update the velocity tracker
- mFlingToDeleteHelper.recordMotionEvent(ev);
-
- final int action = ev.getAction();
- final int[] dragLayerPos = getClampedDragLayerPos(ev.getX(), ev.getY());
- final int dragLayerX = dragLayerPos[0];
- final int dragLayerY = dragLayerPos[1];
-
- switch (action) {
- case MotionEvent.ACTION_DOWN:
- // Remember where the motion event started
- mMotionDownX = dragLayerX;
- mMotionDownY = dragLayerY;
- break;
- }
-
- return mDragDriver.onTouchEvent(ev);
- }
-
- /**
- * Since accessible drag and drop won't cause the same sequence of touch events, we manually
- * inject the appropriate state which would have been otherwise initiated via touch events.
- */
- public void prepareAccessibleDrag(int x, int y) {
- mMotionDownX = x;
- mMotionDownY = y;
- mLastTouch[0] = x;
- mLastTouch[1] = y;
- }
-
- /**
* As above, since accessible drag and drop won't cause the same sequence of touch events,
* we manually ensure appropriate drag and drop events get emulated for accessible drag.
*/
@@ -664,10 +578,6 @@
return mLauncher.getWorkspace();
}
- public void setWindowToken(IBinder token) {
- mWindowToken = token;
- }
-
/**
* Sets the drag listener which will be notified when a drag starts or ends.
*/
diff --git a/src/com/android/launcher3/dragndrop/DragDriver.java b/src/com/android/launcher3/dragndrop/DragDriver.java
index 87461d5..d4ce308 100644
--- a/src/com/android/launcher3/dragndrop/DragDriver.java
+++ b/src/com/android/launcher3/dragndrop/DragDriver.java
@@ -16,19 +16,19 @@
package com.android.launcher3.dragndrop;
-import android.content.Context;
-import android.util.Log;
+import android.os.SystemClock;
import android.view.DragEvent;
import android.view.MotionEvent;
-import com.android.launcher3.DropTarget.DragObject;
-import com.android.launcher3.testing.TestProtocol;
+import java.util.function.Consumer;
/**
* Base class for driving a drag/drop operation.
*/
public abstract class DragDriver {
+
protected final EventListener mEventListener;
+ protected final Consumer<MotionEvent> mSecondaryEventConsumer;
public interface EventListener {
void onDriverDragMove(float x, float y);
@@ -37,131 +37,175 @@
void onDriverDragCancel();
}
- public DragDriver(EventListener eventListener) {
+ public DragDriver(EventListener eventListener, Consumer<MotionEvent> sec) {
mEventListener = eventListener;
+ mSecondaryEventConsumer = sec;
}
/**
- * Handles ending of the DragView animation.
+ * Called to handle system touch event
*/
- public void onDragViewAnimationEnd() { }
-
public boolean onTouchEvent(MotionEvent ev) {
- final int action = ev.getAction();
-
- switch (action) {
- case MotionEvent.ACTION_MOVE:
- mEventListener.onDriverDragMove(ev.getX(), ev.getY());
- break;
- case MotionEvent.ACTION_UP:
- mEventListener.onDriverDragMove(ev.getX(), ev.getY());
- mEventListener.onDriverDragEnd(ev.getX(), ev.getY());
- break;
- case MotionEvent.ACTION_CANCEL:
- mEventListener.onDriverDragCancel();
- break;
- }
-
- return true;
+ return false;
}
- public abstract boolean onDragEvent (DragEvent event);
-
-
+ /**
+ * Called to handle system touch intercept event
+ */
public boolean onInterceptTouchEvent(MotionEvent ev) {
- final int action = ev.getAction();
-
- switch (action) {
- case MotionEvent.ACTION_UP:
- mEventListener.onDriverDragEnd(ev.getX(), ev.getY());
- break;
- case MotionEvent.ACTION_CANCEL:
- mEventListener.onDriverDragCancel();
- break;
- }
-
- return true;
+ return false;
}
- public static DragDriver create(Context context, DragController dragController,
- DragObject dragObject, DragOptions options) {
- if (options.systemDndStartPoint != null) {
- return new SystemDragDriver(dragController, context, dragObject);
+ /**
+ * Called to handle system drag event
+ */
+ public boolean onDragEvent(DragEvent event) {
+ return false;
+ }
+
+ /**
+ * Created a driver for handing the actual events
+ */
+ public static DragDriver create(DragController dragController, DragOptions options,
+ Consumer<MotionEvent> sec) {
+ if (options.simulatedDndStartPoint != null) {
+ if (options.isAccessibleDrag) {
+ return null;
+ }
+ return new SystemDragDriver(dragController, sec);
} else {
- return new InternalDragDriver(dragController);
+ return new InternalDragDriver(dragController, sec);
+ }
+ }
+
+ /**
+ * Class for driving a system (i.e. framework) drag/drop operation.
+ */
+ static class SystemDragDriver extends DragDriver {
+
+ private final long mDragStartTime;
+ float mLastX = 0;
+ float mLastY = 0;
+
+ SystemDragDriver(DragController dragController, Consumer<MotionEvent> sec) {
+ super(dragController, sec);
+ mDragStartTime = SystemClock.uptimeMillis();
+ }
+
+ @Override
+ public boolean onInterceptTouchEvent(MotionEvent ev) {
+ return false;
+ }
+
+ /**
+ * It creates a temporary {@link MotionEvent} object for secondary consumer
+ */
+ private void simulateSecondaryMotionEvent(DragEvent event) {
+ final int motionAction;
+ switch (event.getAction()) {
+ case DragEvent.ACTION_DRAG_STARTED:
+ motionAction = MotionEvent.ACTION_DOWN;
+ break;
+ case DragEvent.ACTION_DRAG_LOCATION:
+ motionAction = MotionEvent.ACTION_MOVE;
+ break;
+ case DragEvent.ACTION_DRAG_ENDED:
+ motionAction = MotionEvent.ACTION_UP;
+ break;
+ default:
+ return;
+ }
+ MotionEvent emulatedEvent = MotionEvent.obtain(mDragStartTime,
+ SystemClock.uptimeMillis(), motionAction, event.getX(), event.getY(), 0);
+ mSecondaryEventConsumer.accept(emulatedEvent);
+ emulatedEvent.recycle();
+ }
+
+ @Override
+ public boolean onDragEvent(DragEvent event) {
+ simulateSecondaryMotionEvent(event);
+ final int action = event.getAction();
+
+ switch (action) {
+ case DragEvent.ACTION_DRAG_STARTED:
+ mLastX = event.getX();
+ mLastY = event.getY();
+ return true;
+
+ case DragEvent.ACTION_DRAG_ENTERED:
+ return true;
+
+ case DragEvent.ACTION_DRAG_LOCATION:
+ mLastX = event.getX();
+ mLastY = event.getY();
+ mEventListener.onDriverDragMove(event.getX(), event.getY());
+ return true;
+
+ case DragEvent.ACTION_DROP:
+ mLastX = event.getX();
+ mLastY = event.getY();
+ mEventListener.onDriverDragMove(event.getX(), event.getY());
+ mEventListener.onDriverDragEnd(mLastX, mLastY);
+ return true;
+ case DragEvent.ACTION_DRAG_EXITED:
+ mEventListener.onDriverDragExitWindow();
+ return true;
+
+ case DragEvent.ACTION_DRAG_ENDED:
+ mEventListener.onDriverDragCancel();
+ return true;
+
+ default:
+ return false;
+ }
+ }
+ }
+
+ /**
+ * Class for driving an internal (i.e. not using framework) drag/drop operation.
+ */
+ static class InternalDragDriver extends DragDriver {
+ InternalDragDriver(DragController dragController, Consumer<MotionEvent> sec) {
+ super(dragController, sec);
+ }
+
+ @Override
+ public boolean onTouchEvent(MotionEvent ev) {
+ mSecondaryEventConsumer.accept(ev);
+ final int action = ev.getAction();
+
+ switch (action) {
+ case MotionEvent.ACTION_MOVE:
+ mEventListener.onDriverDragMove(ev.getX(), ev.getY());
+ break;
+ case MotionEvent.ACTION_UP:
+ mEventListener.onDriverDragMove(ev.getX(), ev.getY());
+ mEventListener.onDriverDragEnd(ev.getX(), ev.getY());
+ break;
+ case MotionEvent.ACTION_CANCEL:
+ mEventListener.onDriverDragCancel();
+ break;
+ }
+
+ return true;
+ }
+
+
+ public boolean onInterceptTouchEvent(MotionEvent ev) {
+ mSecondaryEventConsumer.accept(ev);
+ final int action = ev.getAction();
+
+ switch (action) {
+ case MotionEvent.ACTION_UP:
+ mEventListener.onDriverDragEnd(ev.getX(), ev.getY());
+ break;
+ case MotionEvent.ACTION_CANCEL:
+ mEventListener.onDriverDragCancel();
+ break;
+ }
+ return true;
}
}
}
-/**
- * Class for driving a system (i.e. framework) drag/drop operation.
- */
-class SystemDragDriver extends DragDriver {
- float mLastX = 0;
- float mLastY = 0;
-
- SystemDragDriver(DragController dragController, Context context, DragObject dragObject) {
- super(dragController);
- }
-
- @Override
- public boolean onTouchEvent(MotionEvent ev) {
- return false;
- }
-
- @Override
- public boolean onInterceptTouchEvent(MotionEvent ev) {
- return false;
- }
-
- @Override
- public boolean onDragEvent (DragEvent event) {
- final int action = event.getAction();
-
- switch (action) {
- case DragEvent.ACTION_DRAG_STARTED:
- mLastX = event.getX();
- mLastY = event.getY();
- return true;
-
- case DragEvent.ACTION_DRAG_ENTERED:
- return true;
-
- case DragEvent.ACTION_DRAG_LOCATION:
- mLastX = event.getX();
- mLastY = event.getY();
- mEventListener.onDriverDragMove(event.getX(), event.getY());
- return true;
-
- case DragEvent.ACTION_DROP:
- mLastX = event.getX();
- mLastY = event.getY();
- mEventListener.onDriverDragMove(event.getX(), event.getY());
- mEventListener.onDriverDragEnd(mLastX, mLastY);
- return true;
- case DragEvent.ACTION_DRAG_EXITED:
- mEventListener.onDriverDragExitWindow();
- return true;
-
- case DragEvent.ACTION_DRAG_ENDED:
- mEventListener.onDriverDragCancel();
- return true;
-
- default:
- return false;
- }
- }
-}
-
-/**
- * Class for driving an internal (i.e. not using framework) drag/drop operation.
- */
-class InternalDragDriver extends DragDriver {
- InternalDragDriver(DragController dragController) {
- super(dragController);
- }
-
- @Override
- public boolean onDragEvent (DragEvent event) { return false; }
-}
diff --git a/src/com/android/launcher3/dragndrop/DragLayer.java b/src/com/android/launcher3/dragndrop/DragLayer.java
index 92f35e2..970c5a0 100644
--- a/src/com/android/launcher3/dragndrop/DragLayer.java
+++ b/src/com/android/launcher3/dragndrop/DragLayer.java
@@ -17,10 +17,7 @@
package com.android.launcher3.dragndrop;
-import static android.view.View.MeasureSpec.EXACTLY;
-import static android.view.View.MeasureSpec.getMode;
-import static android.view.View.MeasureSpec.getSize;
-
+import static com.android.launcher3.anim.Interpolators.DEACCEL_1_5;
import static com.android.launcher3.compat.AccessibilityManagerCompat.sendCustomAccessibilityEvent;
import android.animation.Animator;
@@ -33,15 +30,12 @@
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
-import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.animation.Interpolator;
-import android.widget.FrameLayout;
-import android.widget.TextView;
import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.CellLayout;
@@ -50,16 +44,12 @@
import com.android.launcher3.R;
import com.android.launcher3.ShortcutAndWidgetContainer;
import com.android.launcher3.Workspace;
-import com.android.launcher3.anim.Interpolators;
import com.android.launcher3.folder.Folder;
-import com.android.launcher3.folder.FolderIcon;
import com.android.launcher3.graphics.OverviewScrim;
-import com.android.launcher3.graphics.RotationMode;
import com.android.launcher3.graphics.WorkspaceAndHotseatScrim;
import com.android.launcher3.keyboard.ViewGroupFocusHelper;
import com.android.launcher3.util.Thunk;
import com.android.launcher3.views.BaseDragLayer;
-import com.android.launcher3.views.Transposable;
import java.util.ArrayList;
@@ -76,11 +66,11 @@
public static final int ANIMATION_END_DISAPPEAR = 0;
public static final int ANIMATION_END_REMAIN_VISIBLE = 2;
- @Thunk DragController mDragController;
+ private DragController mDragController;
// Variables relating to animation of views after drop
private ValueAnimator mDropAnim = null;
- private final TimeInterpolator mCubicEaseOutInterpolator = Interpolators.DEACCEL_1_5;
+
@Thunk DragView mDropView = null;
@Thunk int mAnchorViewInitialScrollX = 0;
@Thunk View mAnchorView = null;
@@ -95,6 +85,9 @@
private final WorkspaceAndHotseatScrim mWorkspaceScrim;
private final OverviewScrim mOverviewScrim;
+ // View that should handle move events
+ private View mMoveTarget;
+
/**
* Used to create a new DragLayer from XML.
*
@@ -116,9 +109,11 @@
public void setup(DragController dragController, Workspace workspace) {
mDragController = dragController;
mWorkspaceScrim.setWorkspace(workspace);
+ mMoveTarget = workspace;
recreateControllers();
}
+ @Override
public void recreateControllers() {
mControllers = mActivity.createTouchControllers();
}
@@ -222,7 +217,7 @@
@Override
public boolean dispatchUnhandledMove(View focused, int direction) {
return super.dispatchUnhandledMove(focused, direction)
- || mDragController.dispatchUnhandledMove(focused, direction);
+ || mMoveTarget.dispatchUnhandledMove(focused, direction);
}
@Override
@@ -253,59 +248,47 @@
public void animateViewIntoPosition(DragView dragView, final View child, int duration,
View anchorView) {
+
ShortcutAndWidgetContainer parentChildren = (ShortcutAndWidgetContainer) child.getParent();
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
parentChildren.measureChild(child);
+ parentChildren.layoutChild(child);
- Rect r = new Rect();
- getViewRectRelativeToSelf(dragView, r);
+ Rect dragViewBounds = new Rect();
+ getViewRectRelativeToSelf(dragView, dragViewBounds);
+ final int fromX = dragViewBounds.left;
+ final int fromY = dragViewBounds.top;
float coord[] = new float[2];
float childScale = child.getScaleX();
+
coord[0] = lp.x + (child.getMeasuredWidth() * (1 - childScale) / 2);
coord[1] = lp.y + (child.getMeasuredHeight() * (1 - childScale) / 2);
// Since the child hasn't necessarily been laid out, we force the lp to be updated with
// the correct coordinates (above) and use these to determine the final location
float scale = getDescendantCoordRelativeToSelf((View) child.getParent(), coord);
+
// We need to account for the scale of the child itself, as the above only accounts for
// for the scale in parents.
scale *= childScale;
int toX = Math.round(coord[0]);
int toY = Math.round(coord[1]);
float toScale = scale;
- if (child instanceof TextView) {
- TextView tv = (TextView) child;
- // Account for the source scale of the icon (ie. from AllApps to Workspace, in which
- // the workspace may have smaller icon bounds).
- toScale = scale / dragView.getIntrinsicIconScaleFactor();
- // The child may be scaled (always about the center of the view) so to account for it,
- // we have to offset the position by the scaled size. Once we do that, we can center
- // the drag view about the scaled child view.
- // padding will remain constant (does not scale with size)
- toY += tv.getPaddingTop();
- toY -= dragView.getMeasuredHeight() * (1 - toScale) / 2;
- if (dragView.getDragVisualizeOffset() != null) {
- toY -= Math.round(toScale * dragView.getDragVisualizeOffset().y);
- }
+ if (child instanceof DraggableView) {
+ DraggableView d = (DraggableView) child;
+ d.getVisualDragBounds(dragViewBounds);
- toX -= (dragView.getMeasuredWidth() - Math.round(scale * child.getMeasuredWidth())) / 2;
- } else if (child instanceof FolderIcon) {
- // Account for holographic blur padding on the drag view
- toY += Math.round(scale * (child.getPaddingTop() - dragView.getDragRegionTop()));
- toY -= scale * dragView.getBlurSizeOutline() / 2;
- toY -= (1 - scale) * dragView.getMeasuredHeight() / 2;
- // Center in the x coordinate about the target's drawable
- toX -= (dragView.getMeasuredWidth() - Math.round(scale * child.getMeasuredWidth())) / 2;
- } else {
- toY -= (Math.round(scale * (dragView.getHeight() - child.getMeasuredHeight()))) / 2;
- toX -= (Math.round(scale * (dragView.getMeasuredWidth()
- - child.getMeasuredWidth()))) / 2;
+ // This accounts for the offset of the DragView created by scaling it about its
+ // center as it animates into place.
+ float scaleShiftX = dragView.getMeasuredWidth() * (1 - scale) / 2;
+ float scaleShiftY = dragView.getMeasuredHeight() * (1 - scale) / 2;
+
+ toX += scale * (dragViewBounds.left - dragView.getBlurSizeOutline() / 2) - scaleShiftX;
+ toY += scale * (dragViewBounds.top - dragView.getBlurSizeOutline() / 2) - scaleShiftY;
}
- final int fromX = r.left;
- final int fromY = r.top;
child.setVisibility(INVISIBLE);
Runnable onCompleteRunnable = () -> child.setVisibility(VISIBLE);
animateViewIntoPosition(dragView, fromX, fromY, toX, toY, 1, 1, 1, toScale, toScale,
@@ -360,7 +343,7 @@
if (duration < 0) {
duration = res.getInteger(R.integer.config_dropAnimMaxDuration);
if (dist < maxDist) {
- duration *= mCubicEaseOutInterpolator.getInterpolation(dist / maxDist);
+ duration *= DEACCEL_1_5.getInterpolation(dist / maxDist);
}
duration = Math.max(duration, res.getInteger(R.integer.config_dropAnimMinDuration));
}
@@ -368,7 +351,7 @@
// Fall back to cubic ease out interpolator for the animation if none is specified
TimeInterpolator interpolator = null;
if (alphaInterpolator == null || motionInterpolator == null) {
- interpolator = mCubicEaseOutInterpolator;
+ interpolator = DEACCEL_1_5;
}
// Animate the view
@@ -558,7 +541,7 @@
@Override
public void setInsets(Rect insets) {
super.setInsets(insets);
- mWorkspaceScrim.onInsetsChanged(insets);
+ mWorkspaceScrim.onInsetsChanged(insets, mAllowSysuiScrims);
mOverviewScrim.onInsetsChanged(insets);
}
@@ -569,145 +552,4 @@
public OverviewScrim getOverviewScrim() {
return mOverviewScrim;
}
-
- @Override
- protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- RotationMode rotation = mActivity.getRotationMode();
- int count = getChildCount();
-
- if (!rotation.isTransposed
- || getMode(widthMeasureSpec) != EXACTLY
- || getMode(heightMeasureSpec) != EXACTLY) {
-
- for (int i = 0; i < count; i++) {
- final View child = getChildAt(i);
- child.setRotation(rotation.surfaceRotation);
- }
- super.onMeasure(widthMeasureSpec, heightMeasureSpec);
- } else {
-
- for (int i = 0; i < count; i++) {
- final View child = getChildAt(i);
- if (child.getVisibility() == GONE) {
- continue;
- }
- if (!(child instanceof Transposable)) {
- measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
- } else {
- measureChildWithMargins(child, heightMeasureSpec, 0, widthMeasureSpec, 0);
-
- child.setPivotX(child.getMeasuredWidth() / 2);
- child.setPivotY(child.getMeasuredHeight() / 2);
- child.setRotation(rotation.surfaceRotation);
- }
- }
- setMeasuredDimension(getSize(widthMeasureSpec), getSize(heightMeasureSpec));
- }
- }
-
- @Override
- protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
- RotationMode rotation = mActivity.getRotationMode();
- if (!rotation.isTransposed) {
- super.onLayout(changed, left, top, right, bottom);
- return;
- }
-
- final int count = getChildCount();
-
- final int parentWidth = right - left;
- final int parentHeight = bottom - top;
-
- for (int i = 0; i < count; i++) {
- final View child = getChildAt(i);
- if (child.getVisibility() == GONE) {
- continue;
- }
-
- final FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) child.getLayoutParams();
-
- if (lp instanceof LayoutParams) {
- final LayoutParams dlp = (LayoutParams) lp;
- if (dlp.customPosition) {
- child.layout(dlp.x, dlp.y, dlp.x + dlp.width, dlp.y + dlp.height);
- continue;
- }
- }
-
- final int width = child.getMeasuredWidth();
- final int height = child.getMeasuredHeight();
-
- int childLeft;
- int childTop;
-
- int gravity = lp.gravity;
- if (gravity == -1) {
- gravity = Gravity.TOP | Gravity.START;
- }
-
- final int layoutDirection = getLayoutDirection();
-
- int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
-
- if (child instanceof Transposable) {
- absoluteGravity = rotation.toNaturalGravity(absoluteGravity);
-
- switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
- case Gravity.CENTER_HORIZONTAL:
- childTop = (parentHeight - height) / 2 +
- lp.topMargin - lp.bottomMargin;
- break;
- case Gravity.RIGHT:
- childTop = width / 2 + lp.rightMargin - height / 2;
- break;
- case Gravity.LEFT:
- default:
- childTop = parentHeight - lp.leftMargin - width / 2 - height / 2;
- }
-
- switch (absoluteGravity & Gravity.VERTICAL_GRAVITY_MASK) {
- case Gravity.CENTER_VERTICAL:
- childLeft = (parentWidth - width) / 2 +
- lp.leftMargin - lp.rightMargin;
- break;
- case Gravity.BOTTOM:
- childLeft = parentWidth - width / 2 - height / 2 - lp.bottomMargin;
- break;
- case Gravity.TOP:
- default:
- childLeft = height / 2 - width / 2 + lp.topMargin;
- }
- } else {
- switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
- case Gravity.CENTER_HORIZONTAL:
- childLeft = (parentWidth - width) / 2 +
- lp.leftMargin - lp.rightMargin;
- break;
- case Gravity.RIGHT:
- childLeft = parentWidth - width - lp.rightMargin;
- break;
- case Gravity.LEFT:
- default:
- childLeft = lp.leftMargin;
- }
-
- switch (absoluteGravity & Gravity.VERTICAL_GRAVITY_MASK) {
- case Gravity.TOP:
- childTop = lp.topMargin;
- break;
- case Gravity.CENTER_VERTICAL:
- childTop = (parentHeight - height) / 2 +
- lp.topMargin - lp.bottomMargin;
- break;
- case Gravity.BOTTOM:
- childTop = parentHeight - height - lp.bottomMargin;
- break;
- default:
- childTop = lp.topMargin;
- }
- }
-
- child.layout(childLeft, childTop, childLeft + width, childTop + height);
- }
- }
}
diff --git a/src/com/android/launcher3/dragndrop/DragOptions.java b/src/com/android/launcher3/dragndrop/DragOptions.java
index 2d19f36..959602b 100644
--- a/src/com/android/launcher3/dragndrop/DragOptions.java
+++ b/src/com/android/launcher3/dragndrop/DragOptions.java
@@ -28,8 +28,11 @@
/** Whether or not an accessible drag operation is in progress. */
public boolean isAccessibleDrag = false;
- /** Specifies the start location for the system DnD, null when using internal DnD */
- public Point systemDndStartPoint = null;
+ /**
+ * Specifies the start location for a simulated DnD (like system drag or accessibility drag),
+ * null when using internal DnD
+ */
+ public Point simulatedDndStartPoint = null;
/** Determines when a pre-drag should transition to a drag. By default, this is immediate. */
public PreDragCondition preDragCondition = null;
diff --git a/src/com/android/launcher3/dragndrop/DragView.java b/src/com/android/launcher3/dragndrop/DragView.java
index 145885a..d07635b 100644
--- a/src/com/android/launcher3/dragndrop/DragView.java
+++ b/src/com/android/launcher3/dragndrop/DragView.java
@@ -19,8 +19,6 @@
import static com.android.launcher3.Utilities.getBadge;
import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
-import android.animation.Animator;
-import android.animation.AnimatorListenerAdapter;
import android.animation.FloatArrayEvaluator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
@@ -48,7 +46,6 @@
import com.android.launcher3.FastBitmapDrawable;
import com.android.launcher3.FirstFrameAnimatorHelper;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.LauncherState;
@@ -57,6 +54,7 @@
import com.android.launcher3.Utilities;
import com.android.launcher3.anim.Interpolators;
import com.android.launcher3.icons.LauncherIcons;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.util.Themes;
import com.android.launcher3.util.Thunk;
@@ -146,15 +144,6 @@
}
});
- mAnim.addListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationEnd(Animator animation) {
- if (!mAnimationCancelled) {
- mDragController.onDragViewAnimationEnd();
- }
- }
- });
-
mBitmap = bitmap;
setDragRegion(new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()));
diff --git a/src/com/android/launcher3/dragndrop/DraggableView.java b/src/com/android/launcher3/dragndrop/DraggableView.java
new file mode 100644
index 0000000..df99902
--- /dev/null
+++ b/src/com/android/launcher3/dragndrop/DraggableView.java
@@ -0,0 +1,57 @@
+/*
+ * 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.launcher3.dragndrop;
+
+import android.graphics.Rect;
+
+/**
+ * Interface defining methods required for drawing and previewing DragViews, drag previews, and
+ * related animations
+ */
+public interface DraggableView {
+ int DRAGGABLE_ICON = 0;
+ int DRAGGABLE_WIDGET = 1;
+
+ /**
+ * Static ctr for a simple instance which just returns the view type.
+ */
+ static DraggableView ofType(int type) {
+ return () -> type;
+ }
+
+ /**
+ * Certain handling of DragViews depend only on whether this is an Icon Type item or a Widget
+ * Type item.
+ *
+ * @return DRAGGABLE_ICON or DRAGGABLE_WIDGET as appropriate
+ */
+ int getViewType();
+
+ /**
+ * Before rendering as a DragView bitmap, some views need a preparation step.
+ */
+ default void prepareDrawDragView() { }
+
+ /**
+ * If an actual View subclass, this method returns the rectangle (within the View's coordinates)
+ * of the visual region that should get dragged. This is used to extract exactly that element
+ * as well as to offset that element as appropriate for various animations
+ *
+ * @param bounds Visual bounds in the views coordinates will be written here.
+ */
+ default void getVisualDragBounds(Rect bounds) { }
+}
diff --git a/src/com/android/launcher3/dragndrop/FlingToDeleteHelper.java b/src/com/android/launcher3/dragndrop/FlingToDeleteHelper.java
index 06b5c40..7788f93 100644
--- a/src/com/android/launcher3/dragndrop/FlingToDeleteHelper.java
+++ b/src/com/android/launcher3/dragndrop/FlingToDeleteHelper.java
@@ -17,8 +17,6 @@
package com.android.launcher3.dragndrop;
import android.graphics.PointF;
-import android.os.SystemClock;
-import android.view.DragEvent;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.ViewConfiguration;
@@ -55,31 +53,6 @@
mVelocityTracker.addMovement(ev);
}
- /**
- * Same as {@link #recordMotionEvent}. It creates a temporary {@link MotionEvent} object
- * using {@param event} for tracking velocity.
- */
- public void recordDragEvent(long dragStartTime, DragEvent event) {
- final int motionAction;
- switch (event.getAction()) {
- case DragEvent.ACTION_DRAG_STARTED:
- motionAction = MotionEvent.ACTION_DOWN;
- break;
- case DragEvent.ACTION_DRAG_LOCATION:
- motionAction = MotionEvent.ACTION_MOVE;
- break;
- case DragEvent.ACTION_DRAG_ENDED:
- motionAction = MotionEvent.ACTION_UP;
- break;
- default:
- return;
- }
- MotionEvent emulatedEvent = MotionEvent.obtain(dragStartTime, SystemClock.uptimeMillis(),
- motionAction, event.getX(), event.getY(), 0);
- recordMotionEvent(emulatedEvent);
- emulatedEvent.recycle();
- }
-
public void releaseVelocityTracker() {
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
diff --git a/src/com/android/launcher3/dragndrop/FolderAdaptiveIcon.java b/src/com/android/launcher3/dragndrop/FolderAdaptiveIcon.java
index 0bb3fba..ea1fbdb 100644
--- a/src/com/android/launcher3/dragndrop/FolderAdaptiveIcon.java
+++ b/src/com/android/launcher3/dragndrop/FolderAdaptiveIcon.java
@@ -20,10 +20,10 @@
import android.annotation.TargetApi;
import android.graphics.Bitmap;
-import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Path;
import android.graphics.Point;
+import android.graphics.Rect;
import android.graphics.drawable.AdaptiveIconDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
@@ -33,7 +33,6 @@
import androidx.annotation.Nullable;
import com.android.launcher3.Launcher;
-import com.android.launcher3.R;
import com.android.launcher3.folder.FolderIcon;
import com.android.launcher3.folder.PreviewBackground;
import com.android.launcher3.graphics.ShiftedBitmapDrawable;
@@ -50,6 +49,7 @@
private final Drawable mBadge;
private final Path mMask;
private final ConstantState mConstantState;
+ private static final Rect sTmpRect = new Rect();
private FolderAdaptiveIcon(Drawable bg, Drawable fg, Drawable badge, Path mask) {
super(bg, fg);
@@ -72,23 +72,14 @@
public static @Nullable FolderAdaptiveIcon createFolderAdaptiveIcon(
Launcher launcher, int folderId, Point dragViewSize) {
Preconditions.assertNonUiThread();
- int margin = launcher.getResources()
- .getDimensionPixelSize(R.dimen.blur_size_medium_outline);
-
- // Allocate various bitmaps on the background thread, because why not!
- int width = dragViewSize.x - margin;
- int height = dragViewSize.y - margin;
- if (width <= 0 || height <= 0) {
- return null;
- }
- final Bitmap badge = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// Create the actual drawable on the UI thread to avoid race conditions with
// FolderIcon draw pass
try {
return MAIN_EXECUTOR.submit(() -> {
FolderIcon icon = launcher.findFolderIcon(folderId);
- return icon == null ? null : createDrawableOnUiThread(icon, badge, dragViewSize);
+ return icon == null ? null : createDrawableOnUiThread(icon, dragViewSize);
+
}).get();
} catch (Exception e) {
Log.e(TAG, "Unable to create folder icon", e);
@@ -96,49 +87,50 @@
}
}
- /**
- * Initializes various bitmaps on the UI thread and returns the final drawable.
- */
private static FolderAdaptiveIcon createDrawableOnUiThread(FolderIcon icon,
- Bitmap badgeBitmap, Point dragViewSize) {
+ Point dragViewSize) {
Preconditions.assertUIThread();
- float margin = icon.getResources().getDimension(R.dimen.blur_size_medium_outline) / 2;
- Canvas c = new Canvas();
+ icon.getPreviewBounds(sTmpRect);
+
PreviewBackground bg = icon.getFolderBackground();
- // Initialize badge
- c.setBitmap(badgeBitmap);
- bg.drawShadow(c);
- bg.drawBackgroundStroke(c);
- icon.drawDot(c);
+ // assume square
+ assert (dragViewSize.x == dragViewSize.y);
+ final int previewSize = sTmpRect.width();
- // Initialize preview
- final float sizeScaleFactor = 1 + 2 * AdaptiveIconDrawable.getExtraInsetFraction();
- final int previewWidth = (int) (dragViewSize.x * sizeScaleFactor);
- final int previewHeight = (int) (dragViewSize.y * sizeScaleFactor);
+ final int margin = (dragViewSize.x - previewSize) / 2;
+ final float previewShiftX = -sTmpRect.left + margin;
+ final float previewShiftY = -sTmpRect.top + margin;
- final float shiftFactor = AdaptiveIconDrawable.getExtraInsetFraction() / sizeScaleFactor;
- final float previewShiftX = shiftFactor * previewWidth;
- final float previewShiftY = shiftFactor * previewHeight;
-
- Bitmap previewBitmap = BitmapRenderer.createHardwareBitmap(previewWidth, previewHeight,
+ // Initialize badge, which consists of the outline stroke, shadow and dot; these
+ // must be rendered above the foreground
+ Bitmap badgeBmp = BitmapRenderer.createHardwareBitmap(dragViewSize.x, dragViewSize.y,
(canvas) -> {
- int count = canvas.save();
+ canvas.save();
canvas.translate(previewShiftX, previewShiftY);
- icon.getPreviewItemManager().draw(canvas);
- canvas.restoreToCount(count);
+ bg.drawShadow(canvas);
+ bg.drawBackgroundStroke(canvas);
+ icon.drawDot(canvas);
+ canvas.restore();
});
// Initialize mask
Path mask = new Path();
Matrix m = new Matrix();
- m.setTranslate(margin, margin);
+ m.setTranslate(previewShiftX, previewShiftY);
bg.getClipPath().transform(m, mask);
- ShiftedBitmapDrawable badge = new ShiftedBitmapDrawable(badgeBitmap, margin, margin);
- ShiftedBitmapDrawable foreground = new ShiftedBitmapDrawable(previewBitmap,
- margin - previewShiftX, margin - previewShiftY);
+ Bitmap previewBitmap = BitmapRenderer.createHardwareBitmap(dragViewSize.x, dragViewSize.y,
+ (canvas) -> {
+ canvas.save();
+ canvas.translate(previewShiftX, previewShiftY);
+ icon.getPreviewItemManager().draw(canvas);
+ canvas.restore();
+ });
+
+ ShiftedBitmapDrawable badge = new ShiftedBitmapDrawable(badgeBmp, 0, 0);
+ ShiftedBitmapDrawable foreground = new ShiftedBitmapDrawable(previewBitmap, 0, 0);
return new FolderAdaptiveIcon(new ColorDrawable(bg.getBgColor()), foreground, badge, mask);
}
diff --git a/src/com/android/launcher3/dragndrop/PinItemDragListener.java b/src/com/android/launcher3/dragndrop/PinItemDragListener.java
index 869dd94..bf3aa7f 100644
--- a/src/com/android/launcher3/dragndrop/PinItemDragListener.java
+++ b/src/com/android/launcher3/dragndrop/PinItemDragListener.java
@@ -16,6 +16,8 @@
package com.android.launcher3.dragndrop;
+import static com.android.launcher3.logging.LoggerUtils.newContainerTarget;
+
import android.annotation.TargetApi;
import android.appwidget.AppWidgetManager;
import android.content.pm.LauncherApps.PinItemRequest;
@@ -28,16 +30,18 @@
import android.widget.RemoteViews;
import com.android.launcher3.DragSource;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherAppWidgetProviderInfo;
import com.android.launcher3.PendingAddItemInfo;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.userevent.nano.LauncherLogProto;
import com.android.launcher3.widget.PendingAddShortcutInfo;
import com.android.launcher3.widget.PendingAddWidgetInfo;
import com.android.launcher3.widget.PendingItemDragHelper;
import com.android.launcher3.widget.WidgetAddFlowHandler;
+import java.util.ArrayList;
+
/**
* {@link DragSource} for handling drop from a different window. This object is initialized
* in the source window and is passed on to the Launcher activity as an Intent extra.
@@ -103,9 +107,9 @@
}
@Override
- public void fillInLogContainerData(View v, ItemInfo info, LauncherLogProto.Target target,
- LauncherLogProto.Target targetParent) {
- targetParent.containerType = LauncherLogProto.ContainerType.PINITEM;
+ public void fillInLogContainerData(ItemInfo childInfo, LauncherLogProto.Target child,
+ ArrayList<LauncherLogProto.Target> parents) {
+ parents.add(newContainerTarget(LauncherLogProto.ContainerType.PINITEM));
}
@Override
diff --git a/src/com/android/launcher3/dragndrop/PinShortcutRequestActivityInfo.java b/src/com/android/launcher3/dragndrop/PinShortcutRequestActivityInfo.java
index f71cfb8..9982b39 100644
--- a/src/com/android/launcher3/dragndrop/PinShortcutRequestActivityInfo.java
+++ b/src/com/android/launcher3/dragndrop/PinShortcutRequestActivityInfo.java
@@ -35,8 +35,8 @@
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.LauncherState;
import com.android.launcher3.R;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.icons.IconCache;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.pm.PinRequestHelper;
import com.android.launcher3.pm.ShortcutConfigActivityInfo;
diff --git a/src/com/android/launcher3/dragndrop/PinWidgetFlowHandler.java b/src/com/android/launcher3/dragndrop/PinWidgetFlowHandler.java
index 9f617e4..c501ab5 100644
--- a/src/com/android/launcher3/dragndrop/PinWidgetFlowHandler.java
+++ b/src/com/android/launcher3/dragndrop/PinWidgetFlowHandler.java
@@ -25,8 +25,8 @@
import android.os.Parcel;
import android.os.Parcelable;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.Launcher;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.widget.WidgetAddFlowHandler;
/**
diff --git a/src/com/android/launcher3/folder/Folder.java b/src/com/android/launcher3/folder/Folder.java
index 8e80916..4fe1d1a 100644
--- a/src/com/android/launcher3/folder/Folder.java
+++ b/src/com/android/launcher3/folder/Folder.java
@@ -16,9 +16,26 @@
package com.android.launcher3.folder;
+import static android.text.TextUtils.isEmpty;
+
+import static androidx.core.util.Preconditions.checkNotNull;
+
import static com.android.launcher3.LauncherAnimUtils.SPRING_LOADED_EXIT_DELAY;
+import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_DESKTOP;
+import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_HOTSEAT;
import static com.android.launcher3.LauncherState.NORMAL;
import static com.android.launcher3.compat.AccessibilityManagerCompat.sendCustomAccessibilityEvent;
+import static com.android.launcher3.config.FeatureFlags.ALWAYS_USE_HARDWARE_OPTIMIZATION_FOR_FOLDER_ANIMATIONS;
+import static com.android.launcher3.logging.LoggerUtils.newContainerTarget;
+import static com.android.launcher3.model.data.FolderInfo.FLAG_MANUAL_FOLDER_NAME;
+import static com.android.launcher3.userevent.LauncherLogProto.Target.FromFolderLabelState.FROM_CUSTOM;
+import static com.android.launcher3.userevent.LauncherLogProto.Target.FromFolderLabelState.FROM_EMPTY;
+import static com.android.launcher3.userevent.LauncherLogProto.Target.FromFolderLabelState.FROM_FOLDER_LABEL_STATE_UNSPECIFIED;
+import static com.android.launcher3.userevent.LauncherLogProto.Target.FromFolderLabelState.FROM_SUGGESTED;
+
+import static java.util.Arrays.asList;
+import static java.util.Arrays.stream;
+import static java.util.Optional.ofNullable;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
@@ -48,47 +65,55 @@
import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.Alarm;
-import com.android.launcher3.AppInfo;
import com.android.launcher3.BubbleTextView;
import com.android.launcher3.CellLayout;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.DragSource;
import com.android.launcher3.DropTarget;
import com.android.launcher3.ExtendedEditText;
-import com.android.launcher3.FolderInfo;
-import com.android.launcher3.FolderInfo.FolderListener;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.OnAlarmListener;
import com.android.launcher3.PagedView;
import com.android.launcher3.R;
import com.android.launcher3.ShortcutAndWidgetContainer;
+import com.android.launcher3.Utilities;
import com.android.launcher3.Workspace;
import com.android.launcher3.Workspace.ItemOperator;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.accessibility.AccessibleDragListenerAdapter;
+import com.android.launcher3.accessibility.FolderAccessibilityHelper;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.dragndrop.DragController;
import com.android.launcher3.dragndrop.DragController.DragListener;
import com.android.launcher3.dragndrop.DragLayer;
import com.android.launcher3.dragndrop.DragOptions;
-import com.android.launcher3.logging.LoggerUtils;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.FolderInfo;
+import com.android.launcher3.model.data.FolderInfo.FolderListener;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.pageindicators.PageIndicatorDots;
-import com.android.launcher3.userevent.nano.LauncherLogProto.Action.Direction;
-import com.android.launcher3.userevent.nano.LauncherLogProto.Action.Touch;
-import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
-import com.android.launcher3.userevent.nano.LauncherLogProto.ItemType;
-import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
+import com.android.launcher3.userevent.LauncherLogProto.Action;
+import com.android.launcher3.userevent.LauncherLogProto.ContainerType;
+import com.android.launcher3.userevent.LauncherLogProto.ItemType;
+import com.android.launcher3.userevent.LauncherLogProto.LauncherEvent;
+import com.android.launcher3.userevent.LauncherLogProto.Target;
+import com.android.launcher3.userevent.LauncherLogProto.Target.ToFolderLabelState;
+import com.android.launcher3.userevent.nano.LauncherLogProto;
+import com.android.launcher3.util.Executors;
import com.android.launcher3.util.Thunk;
import com.android.launcher3.views.ClipPathView;
import com.android.launcher3.widget.PendingAddShortcutInfo;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
/**
* Represents a set of icons chosen by the user or generated by the system.
@@ -186,6 +211,9 @@
@Thunk int mScrollHintDir = SCROLL_NONE;
@Thunk int mCurrentScrollDir = SCROLL_NONE;
+ private String mPreviousLabel;
+ private boolean mIsPreviousLabelSuggested;
+
/**
* Used to inflate the Workspace from XML.
*
@@ -247,16 +275,15 @@
mDragController.addDragListener(this);
if (options.isAccessibleDrag) {
mDragController.addDragListener(new AccessibleDragListenerAdapter(
- mContent, CellLayout.FOLDER_ACCESSIBILITY_DRAG) {
-
- @Override
- protected void enableAccessibleDrag(boolean enable) {
- super.enableAccessibleDrag(enable);
- mFooter.setImportantForAccessibility(enable
- ? IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
- : IMPORTANT_FOR_ACCESSIBILITY_AUTO);
- }
- });
+ mContent, FolderAccessibilityHelper::new) {
+ @Override
+ protected void enableAccessibleDrag(boolean enable) {
+ super.enableAccessibleDrag(enable);
+ mFooter.setImportantForAccessibility(enable
+ ? IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
+ : IMPORTANT_FOR_ACCESSIBILITY_AUTO);
+ }
+ });
}
mLauncher.getWorkspace().beginDragShared(v, this, options);
@@ -300,14 +327,11 @@
public void startEditingFolderName() {
post(() -> {
if (FeatureFlags.FOLDER_NAME_SUGGEST.get()) {
- if (TextUtils.isEmpty(mFolderName.getText())) {
- String[] suggestedNames =
- mInfo.suggestedFolderNames.getStringArrayExtra("suggest");
- mFolderName.setText(suggestedNames[0]);
- mFolderName.displayCompletions(Arrays.asList(suggestedNames).subList(1,
- suggestedNames.length));
- mFolderName.setEnteredCompose(false);
- }
+ ofNullable(mInfo)
+ .map(info -> info.suggestedFolderNames)
+ .map(folderNames -> (FolderNameInfo[]) folderNames
+ .getParcelableArrayExtra(FolderInfo.EXTRA_FOLDER_SUGGESTIONS))
+ .ifPresent(nameInfos -> showLabelSuggestions(nameInfos));
}
mFolderName.setHint("");
mIsEditingName = true;
@@ -324,23 +348,16 @@
}
mInfo.title = newTitle;
- mInfo.setOption(FolderInfo.FLAG_MANUAL_FOLDER_NAME, mFolderName.isEnteredCompose(),
+ mInfo.setOption(FLAG_MANUAL_FOLDER_NAME, !getAcceptedSuggestionIndex().isPresent(),
mLauncher.getModelWriter());
mFolderIcon.onTitleChanged(newTitle);
mLauncher.getModelWriter().updateItemInDatabase(mInfo);
- if (FeatureFlags.FOLDER_NAME_SUGGEST.get()) {
- mFolderName.setText(mInfo.title);
- // TODO: depending on whether the title was manually edited or automatically
- // suggested, apply different hint.
- mFolderName.setHint("");
+ if (TextUtils.isEmpty(mInfo.title)) {
+ mFolderName.setHint(R.string.folder_hint_text);
+ mFolderName.setText("");
} else {
- if (TextUtils.isEmpty(mInfo.title)) {
- mFolderName.setHint(R.string.folder_hint_text);
- mFolderName.setText("");
- } else {
- mFolderName.setHint(null);
- }
+ mFolderName.setHint(null);
}
sendCustomAccessibilityEvent(
@@ -412,7 +429,7 @@
mInfo = info;
ArrayList<WorkspaceItemInfo> children = info.contents;
Collections.sort(children, ITEM_POS_COMPARATOR);
- updateItemLocationsInDatabaseBatch();
+ updateItemLocationsInDatabaseBatch(true);
DragLayer.LayoutParams lp = (DragLayer.LayoutParams) getLayoutParams();
if (lp == null) {
@@ -422,17 +439,15 @@
}
mItemsInvalidated = true;
mInfo.addListener(this);
+ Optional.ofNullable(mInfo.title).ifPresent(title -> mPreviousLabel = title.toString());
+ mIsPreviousLabelSuggested = !mInfo.hasOption(FLAG_MANUAL_FOLDER_NAME);
- if (!TextUtils.isEmpty(mInfo.title)) {
+ if (!isEmpty(mInfo.title)) {
mFolderName.setText(mInfo.title);
mFolderName.setHint(null);
} else {
mFolderName.setText("");
- if (FeatureFlags.FOLDER_NAME_SUGGEST.get()) {
- mFolderName.setHint("");
- } else {
- mFolderName.setHint(R.string.folder_hint_text);
- }
+ mFolderName.setHint(R.string.folder_hint_text);
}
// In case any children didn't come across during loading, clean up the folder accordingly
mFolderIcon.post(() -> {
@@ -442,24 +457,39 @@
});
}
+
/**
- * Show suggested folder title.
+ * Show suggested folder title in FolderEditText if the first suggestion is non-empty, push
+ * rest of the suggestions to InputMethodManager.
*/
- public void showSuggestedTitle(String[] suggestName) {
- if (FeatureFlags.FOLDER_NAME_SUGGEST.get()) {
- mInfo.suggestedFolderNames = new Intent().putExtra("suggest", suggestName);
- if (TextUtils.isEmpty(mFolderName.getText().toString())
- && !mInfo.hasOption(FolderInfo.FLAG_MANUAL_FOLDER_NAME)) {
- if (suggestName.length > 0 && !TextUtils.isEmpty(suggestName[0])) {
+ private void showLabelSuggestions(FolderNameInfo[] nameInfos) {
+ if (nameInfos == null) {
+ return;
+ }
+ // Open the Folder and Keyboard when the first or second suggestion is valid non-empty
+ // string.
+ boolean shouldOpen = nameInfos.length > 0 && nameInfos[0] != null && !isEmpty(
+ nameInfos[0].getLabel())
+ || nameInfos.length > 1 && nameInfos[1] != null && !isEmpty(
+ nameInfos[1].getLabel());
+
+ if (shouldOpen) {
+ // update the primary suggestion if the folder name is empty.
+ if (isEmpty(mFolderName.getText())) {
+ CharSequence firstLabel = nameInfos[0] == null ? "" : nameInfos[0].getLabel();
+ if (!isEmpty(firstLabel)) {
mFolderName.setHint("");
- mFolderName.setText(suggestName[0]);
- mInfo.title = suggestName[0];
- animateOpen(mInfo.contents, 0, true);
- mFolderName.showKeyboard();
- mFolderName.displayCompletions(
- Arrays.asList(suggestName).subList(1, suggestName.length));
+ mFolderName.setText(firstLabel);
}
}
+ mFolderName.showKeyboard();
+ mFolderName.displayCompletions(
+ asList(nameInfos).subList(0, nameInfos.length).stream()
+ .filter(Objects::nonNull)
+ .map(s -> s.getLabel().toString())
+ .filter(s -> !s.isEmpty())
+ .filter(s -> !s.equalsIgnoreCase(mFolderName.getText().toString()))
+ .collect(Collectors.toList()));
}
}
@@ -477,9 +507,6 @@
}
private void startAnimation(final AnimatorSet a) {
- if (mCurrentAnimator != null && mCurrentAnimator.isRunning()) {
- mCurrentAnimator.cancel();
- }
final Workspace workspace = mLauncher.getWorkspace();
final CellLayout currentCellLayout =
(CellLayout) workspace.getChildAt(workspace.getCurrentPage());
@@ -508,6 +535,8 @@
}
private boolean shouldUseHardwareLayerForAnimation(CellLayout currentCellLayout) {
+ if (ALWAYS_USE_HARDWARE_OPTIMIZATION_FOR_FOLDER_ANIMATIONS.get()) return true;
+
int folderCount = 0;
final ShortcutAndWidgetContainer container = currentCellLayout.getShortcutsAndWidgets();
for (int i = container.getChildCount() - 1; i >= 0; --i) {
@@ -580,7 +609,7 @@
dragLayer.addView(this);
mDragController.addDropTarget(this);
} else {
- if (FeatureFlags.IS_DOGFOOD_BUILD) {
+ if (FeatureFlags.IS_STUDIO_BUILD) {
Log.e(TAG, "Opening folder (" + this + ") which already has a parent:"
+ getParent());
}
@@ -594,6 +623,9 @@
// dropping. One resulting issue is that replaceFolderWithFinalItem() can be called twice.
mDeleteFolderOnDropCompleted = false;
+ if (mCurrentAnimator != null && mCurrentAnimator.isRunning()) {
+ mCurrentAnimator.cancel();
+ }
AnimatorSet anim = new FolderAnimationManager(this, true /* isOpening */).getAnimator();
anim.addListener(new AnimatorListenerAdapter() {
@Override
@@ -608,9 +640,9 @@
if (!skipUserEventLog) {
mLauncher.getUserEventDispatcher().logActionOnItem(
- Touch.TAP,
- Direction.NONE,
- ItemType.FOLDER_ICON, mInfo.cellX, mInfo.cellY);
+ LauncherLogProto.Action.Touch.TAP,
+ LauncherLogProto.Action.Direction.NONE,
+ LauncherLogProto.ItemType.FOLDER_ICON, mInfo.cellX, mInfo.cellY);
}
@@ -697,6 +729,9 @@
}
private void animateClosed() {
+ if (mCurrentAnimator != null && mCurrentAnimator.isRunning()) {
+ mCurrentAnimator.cancel();
+ }
AnimatorSet a = new FolderAnimationManager(this, false /* isOpening */).getAnimator();
a.addListener(new AnimatorListenerAdapter() {
@Override
@@ -915,6 +950,7 @@
View icon = (mCurrentDragView != null && mCurrentDragView.getTag() == info)
? mCurrentDragView : mContent.createNewView(info);
ArrayList<View> views = getIconsInReadingOrder();
+ info.rank = Utilities.boundToRange(info.rank, 0, views.size());
views.add(info.rank, icon);
mContent.arrangeChildren(views);
mItemsInvalidated = true;
@@ -942,7 +978,7 @@
// Reordering may have occured, and we need to save the new item locations. We do this once
// at the end to prevent unnecessary database operations.
- updateItemLocationsInDatabaseBatch();
+ updateItemLocationsInDatabaseBatch(false);
// Use the item count to check for multi-page as the folder UI may not have
// been refreshed yet.
if (getItemCount() <= mContent.itemsPerPage()) {
@@ -952,7 +988,7 @@
}
}
- private void updateItemLocationsInDatabaseBatch() {
+ private void updateItemLocationsInDatabaseBatch(boolean isBind) {
FolderGridOrganizer verifier = new FolderGridOrganizer(
mLauncher.getDeviceProfile().inv).setFolderInfo(mInfo);
@@ -968,6 +1004,18 @@
if (!items.isEmpty()) {
mLauncher.getModelWriter().moveItemsInDatabase(items, mInfo.id, 0);
}
+ if (FeatureFlags.FOLDER_NAME_SUGGEST.get() && !isBind) {
+ Executors.MODEL_EXECUTOR.post(() -> {
+ FolderNameInfo[] nameInfos =
+ new FolderNameInfo[FolderNameProvider.SUGGEST_MAX];
+ FolderNameProvider fnp = FolderNameProvider.newInstance(getContext());
+ fnp.getSuggestedFolderName(
+ getContext(), mInfo.contents, nameInfos);
+ mInfo.suggestedFolderNames = new Intent().putExtra(
+ FolderInfo.EXTRA_FOLDER_SUGGESTIONS,
+ nameInfos);
+ });
+ }
}
public void notifyDrop() {
@@ -1272,7 +1320,7 @@
// We only need to update the locations if it doesn't get handled in
// #onDropCompleted.
if (d.dragSource != this) {
- updateItemLocationsInDatabaseBatch();
+ updateItemLocationsInDatabaseBatch(false);
}
}
@@ -1313,7 +1361,7 @@
verifier.updateRankAndPos(item, rank);
mLauncher.getModelWriter().addOrMoveItemInDatabase(item, mInfo.id, 0, item.cellX,
item.cellY);
- updateItemLocationsInDatabaseBatch();
+ updateItemLocationsInDatabaseBatch(false);
if (mContent.areViewsBound()) {
mContent.createAndAddViewForRank(item, rank);
@@ -1392,6 +1440,7 @@
if (hasFocus) {
startEditingFolderName();
} else {
+ logEditFolderLabel();
mFolderName.dispatchBackKey();
}
}
@@ -1405,11 +1454,24 @@
}
@Override
- public void fillInLogContainerData(View v, ItemInfo info, Target target, Target targetParent) {
- target.gridX = info.cellX;
- target.gridY = info.cellY;
- target.pageIndex = mContent.getCurrentPage();
- targetParent.containerType = ContainerType.FOLDER;
+ public void fillInLogContainerData(ItemInfo childInfo, LauncherLogProto.Target child,
+ ArrayList<LauncherLogProto.Target> targets) {
+ child.gridX = childInfo.cellX;
+ child.gridY = childInfo.cellY;
+ child.pageIndex = mContent.getCurrentPage();
+
+ LauncherLogProto.Target target = newContainerTarget(LauncherLogProto.ContainerType.FOLDER);
+ target.pageIndex = mInfo.screenId;
+ target.gridX = mInfo.cellX;
+ target.gridY = mInfo.cellY;
+ targets.add(target);
+
+ // continue to parent
+ if (mInfo.container == CONTAINER_HOTSEAT) {
+ mLauncher.getHotseat().fillInLogContainerData(mInfo, target, targets);
+ } else {
+ mLauncher.getWorkspace().fillInLogContainerData(mInfo, target, targets);
+ }
}
private class OnScrollHintListener implements OnAlarmListener {
@@ -1507,7 +1569,7 @@
@Override
public int getLogContainerType() {
- return ContainerType.FOLDER;
+ return LauncherLogProto.ContainerType.FOLDER;
}
/**
@@ -1542,7 +1604,7 @@
}
} else {
mLauncher.getUserEventDispatcher().logActionTapOutside(
- LoggerUtils.newContainerTarget(ContainerType.FOLDER));
+ newContainerTarget(LauncherLogProto.ContainerType.FOLDER));
close(true);
return true;
}
@@ -1572,4 +1634,152 @@
super.draw(canvas);
}
}
+
+ public FolderPagedView getContent() {
+ return mContent;
+ }
+
+ private void logEditFolderLabel() {
+ LauncherEvent launcherEvent = LauncherEvent.newBuilder()
+ .setAction(Action.newBuilder().setType(Action.Type.SOFT_KEYBOARD))
+ .addSrcTarget(newEditTextTargetBuilder()
+ .setFromFolderLabelState(getFromFolderLabelState())
+ .setToFolderLabelState(getToFolderLabelState()))
+ .addSrcTarget(newFolderTargetBuilder())
+ .addSrcTarget(newParentContainerTarget())
+ .build();
+ mLauncher.getUserEventDispatcher().logLauncherEvent(launcherEvent);
+ mPreviousLabel = mFolderName.getText().toString();
+ mIsPreviousLabelSuggested = !mInfo.hasOption(FLAG_MANUAL_FOLDER_NAME);
+ }
+
+ private Target.FromFolderLabelState getFromFolderLabelState() {
+ return mPreviousLabel == null
+ ? FROM_FOLDER_LABEL_STATE_UNSPECIFIED
+ : mPreviousLabel.isEmpty()
+ ? FROM_EMPTY
+ : mIsPreviousLabelSuggested
+ ? FROM_SUGGESTED
+ : FROM_CUSTOM;
+ }
+
+ private Target.ToFolderLabelState getToFolderLabelState() {
+ String newLabel =
+ checkNotNull(mFolderName.getText().toString(),
+ "Expected valid folder label, but found null");
+ if (newLabel.equals(mPreviousLabel)) {
+ return Target.ToFolderLabelState.UNCHANGED;
+ }
+
+ if (!FeatureFlags.FOLDER_NAME_SUGGEST.get()) {
+ return newLabel.isEmpty()
+ ? ToFolderLabelState.TO_EMPTY_WITH_SUGGESTIONS_DISABLED
+ : ToFolderLabelState.TO_CUSTOM_WITH_SUGGESTIONS_DISABLED;
+ }
+
+ Optional<String[]> suggestedLabels = getSuggestedLabels();
+ boolean isEmptySuggestions = suggestedLabels
+ .map(labels -> stream(labels).allMatch(TextUtils::isEmpty))
+ .orElse(true);
+ if (isEmptySuggestions) {
+ return newLabel.isEmpty()
+ ? ToFolderLabelState.TO_EMPTY_WITH_EMPTY_SUGGESTIONS
+ : ToFolderLabelState.TO_CUSTOM_WITH_EMPTY_SUGGESTIONS;
+ }
+
+ boolean hasValidPrimary = suggestedLabels
+ .map(labels -> !isEmpty(labels[0]))
+ .orElse(false);
+ if (newLabel.isEmpty()) {
+ return hasValidPrimary ? ToFolderLabelState.TO_EMPTY_WITH_VALID_PRIMARY
+ : ToFolderLabelState.TO_EMPTY_WITH_VALID_SUGGESTIONS_AND_EMPTY_PRIMARY;
+ }
+
+ OptionalInt accepted_suggestion_index = getAcceptedSuggestionIndex();
+ if (!accepted_suggestion_index.isPresent()) {
+ return hasValidPrimary ? ToFolderLabelState.TO_CUSTOM_WITH_VALID_PRIMARY
+ : ToFolderLabelState.TO_CUSTOM_WITH_VALID_SUGGESTIONS_AND_EMPTY_PRIMARY;
+ }
+
+ switch (accepted_suggestion_index.getAsInt()) {
+ case 0:
+ return ToFolderLabelState.TO_SUGGESTION0_WITH_VALID_PRIMARY;
+ case 1:
+ return hasValidPrimary ? ToFolderLabelState.TO_SUGGESTION1_WITH_VALID_PRIMARY
+ : ToFolderLabelState.TO_SUGGESTION1_WITH_EMPTY_PRIMARY;
+ case 2:
+ return hasValidPrimary ? ToFolderLabelState.TO_SUGGESTION2_WITH_VALID_PRIMARY
+ : ToFolderLabelState.TO_SUGGESTION2_WITH_EMPTY_PRIMARY;
+ case 3:
+ return hasValidPrimary ? ToFolderLabelState.TO_SUGGESTION3_WITH_VALID_PRIMARY
+ : ToFolderLabelState.TO_SUGGESTION3_WITH_EMPTY_PRIMARY;
+ default:
+ // fall through
+ }
+ return ToFolderLabelState.TO_FOLDER_LABEL_STATE_UNSPECIFIED;
+
+ }
+
+ private Optional<String[]> getSuggestedLabels() {
+ return ofNullable(mInfo)
+ .map(info -> info.suggestedFolderNames)
+ .map(
+ folderNames ->
+ (FolderNameInfo[])
+ folderNames.getParcelableArrayExtra(FolderInfo.EXTRA_FOLDER_SUGGESTIONS))
+ .map(
+ folderNameInfoArray ->
+ stream(folderNameInfoArray)
+ .filter(Objects::nonNull)
+ .map(FolderNameInfo::getLabel)
+ .filter(Objects::nonNull)
+ .map(CharSequence::toString)
+ .toArray(String[]::new));
+ }
+
+ private OptionalInt getAcceptedSuggestionIndex() {
+ String newLabel = checkNotNull(mFolderName.getText().toString(),
+ "Expected valid folder label, but found null");
+ return getSuggestedLabels()
+ .map(suggestionsArray ->
+ IntStream.range(0, suggestionsArray.length)
+ .filter(
+ index -> !isEmpty(suggestionsArray[index])
+ && newLabel.equalsIgnoreCase(suggestionsArray[index]))
+ .sequential()
+ .findFirst()
+ ).orElse(OptionalInt.empty());
+
+ }
+
+
+ private Target.Builder newEditTextTargetBuilder() {
+ return Target.newBuilder().setType(Target.Type.ITEM).setItemType(ItemType.EDITTEXT);
+ }
+
+ private Target.Builder newFolderTargetBuilder() {
+ return Target.newBuilder()
+ .setType(Target.Type.CONTAINER)
+ .setContainerType(ContainerType.FOLDER)
+ .setPageIndex(mInfo.screenId)
+ .setGridX(mInfo.cellX)
+ .setGridY(mInfo.cellY)
+ .setCardinality(mInfo.contents.size());
+ }
+
+ private Target.Builder newParentContainerTarget() {
+ Target.Builder builder = Target.newBuilder().setType(Target.Type.CONTAINER);
+ switch (mInfo.container) {
+ case CONTAINER_HOTSEAT:
+ return builder.setContainerType(ContainerType.HOTSEAT);
+ case CONTAINER_DESKTOP:
+ return builder.setContainerType(ContainerType.WORKSPACE);
+ default:
+ throw new AssertionError(String
+ .format("Expected container to be either %s or %s but found %s.",
+ CONTAINER_HOTSEAT,
+ CONTAINER_DESKTOP,
+ mInfo.container));
+ }
+ }
}
diff --git a/src/com/android/launcher3/folder/FolderAnimationManager.java b/src/com/android/launcher3/folder/FolderAnimationManager.java
index 1310d37..3d72b49 100644
--- a/src/com/android/launcher3/folder/FolderAnimationManager.java
+++ b/src/com/android/launcher3/folder/FolderAnimationManager.java
@@ -115,6 +115,7 @@
*/
public AnimatorSet getAnimator() {
final DragLayer.LayoutParams lp = (DragLayer.LayoutParams) mFolder.getLayoutParams();
+ mFolderIcon.getPreviewItemManager().recomputePreviewDrawingParams();
ClippedFolderIconLayoutRule rule = mFolderIcon.getLayoutRule();
final List<BubbleTextView> itemsInPreview = getPreviewIconsOnPage(0);
@@ -220,7 +221,6 @@
Animator z = getAnimator(mFolder, View.TRANSLATION_Z, -mFolder.getElevation(), 0);
play(a, z, mIsOpening ? midDuration : 0, midDuration);
-
// Store clip variables
CellLayout cellLayout = mContent.getCurrentCellLayout();
boolean folderClipChildren = mFolder.getClipChildren();
diff --git a/src/com/android/launcher3/folder/FolderGridOrganizer.java b/src/com/android/launcher3/folder/FolderGridOrganizer.java
index 9d14a5f..4be82ed 100644
--- a/src/com/android/launcher3/folder/FolderGridOrganizer.java
+++ b/src/com/android/launcher3/folder/FolderGridOrganizer.java
@@ -20,9 +20,9 @@
import android.graphics.Point;
-import com.android.launcher3.FolderInfo;
import com.android.launcher3.InvariantDeviceProfile;
-import com.android.launcher3.ItemInfo;
+import com.android.launcher3.model.data.FolderInfo;
+import com.android.launcher3.model.data.ItemInfo;
import java.util.ArrayList;
import java.util.List;
diff --git a/src/com/android/launcher3/folder/FolderIcon.java b/src/com/android/launcher3/folder/FolderIcon.java
index 6a47b98..e29971e 100644
--- a/src/com/android/launcher3/folder/FolderIcon.java
+++ b/src/com/android/launcher3/folder/FolderIcon.java
@@ -16,6 +16,8 @@
package com.android.launcher3.folder;
+import static android.text.TextUtils.isEmpty;
+
import static com.android.launcher3.folder.ClippedFolderIconLayoutRule.MAX_NUM_ITEMS_IN_PREVIEW;
import static com.android.launcher3.folder.PreviewItemManager.INITIAL_ITEM_ANIMATION_DURATION;
@@ -31,7 +33,6 @@
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
-import android.view.ViewConfiguration;
import android.view.ViewDebug;
import android.view.ViewGroup;
import android.widget.FrameLayout;
@@ -39,31 +40,30 @@
import androidx.annotation.NonNull;
import com.android.launcher3.Alarm;
-import com.android.launcher3.AppInfo;
import com.android.launcher3.BubbleTextView;
import com.android.launcher3.CellLayout;
import com.android.launcher3.CheckLongPressHelper;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.DropTarget.DragObject;
-import com.android.launcher3.FolderInfo;
-import com.android.launcher3.FolderInfo.FolderListener;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.OnAlarmListener;
import com.android.launcher3.R;
-import com.android.launcher3.SimpleOnStylusPressListener;
-import com.android.launcher3.StylusEventHelper;
import com.android.launcher3.Utilities;
import com.android.launcher3.Workspace;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.anim.Interpolators;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.dot.FolderDotInfo;
import com.android.launcher3.dragndrop.BaseItemDragListener;
import com.android.launcher3.dragndrop.DragLayer;
import com.android.launcher3.dragndrop.DragView;
+import com.android.launcher3.dragndrop.DraggableView;
import com.android.launcher3.icons.DotRenderer;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.FolderInfo;
+import com.android.launcher3.model.data.FolderInfo.FolderListener;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.touch.ItemClickHandler;
import com.android.launcher3.util.Executors;
import com.android.launcher3.util.Thunk;
@@ -78,14 +78,14 @@
/**
* An icon that can appear on in the workspace representing an {@link Folder}.
*/
-public class FolderIcon extends FrameLayout implements FolderListener, IconLabelDotView {
+public class FolderIcon extends FrameLayout implements FolderListener, IconLabelDotView,
+ DraggableView {
@Thunk ActivityContext mActivity;
@Thunk Folder mFolder;
private FolderInfo mInfo;
private CheckLongPressHelper mLongPressHelper;
- private StylusEventHelper mStylusEventHelper;
static final int DROP_IN_ANIMATION_DURATION = 400;
@@ -108,8 +108,6 @@
boolean mAnimating = false;
- private float mSlop;
-
private Alarm mOpenAlarm = new Alarm();
private boolean mForceHideDot;
@@ -147,9 +145,7 @@
private void init() {
mLongPressHelper = new CheckLongPressHelper(this);
- mStylusEventHelper = new StylusEventHelper(new SimpleOnStylusPressListener(this), this);
mPreviewLayoutRule = new ClippedFolderIconLayoutRule();
- mSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
mPreviewItemManager = new PreviewItemManager(this);
mDotParams = new DotRenderer.DrawParams();
}
@@ -178,7 +174,7 @@
"is dependent on this");
}
- DeviceProfile grid = activity.getWallpaperDeviceProfile();
+ DeviceProfile grid = activity.getDeviceProfile();
FolderIcon icon = (FolderIcon) LayoutInflater.from(group.getContext())
.inflate(resId, group, false);
@@ -230,6 +226,16 @@
mBackground.getBounds(outBounds);
}
+ @Override
+ public int getViewType() {
+ return DRAGGABLE_ICON;
+ }
+
+ @Override
+ public void getVisualDragBounds(Rect bounds) {
+ getPreviewBounds(bounds);
+ }
+
public float getBackgroundStrokeWidth() {
return mBackground.getStrokeWidth();
}
@@ -393,15 +399,16 @@
if (!itemAdded) mPreviewItemManager.hidePreviewItem(index, true);
final int finalIndex = index;
- String[] suggestedNameOut = new String[FolderNameProvider.SUGGEST_MAX];
+ FolderNameInfo[] nameInfos =
+ new FolderNameInfo[FolderNameProvider.SUGGEST_MAX];
if (FeatureFlags.FOLDER_NAME_SUGGEST.get()) {
Executors.UI_HELPER_EXECUTOR.post(() -> {
d.folderNameProvider.getSuggestedFolderName(
- getContext(), mInfo.contents, suggestedNameOut);
- showFinalView(finalIndex, item, suggestedNameOut);
+ getContext(), mInfo.contents, nameInfos);
+ showFinalView(finalIndex, item, nameInfos);
});
} else {
- showFinalView(finalIndex, item, suggestedNameOut);
+ showFinalView(finalIndex, item, nameInfos);
}
} else {
addItem(item);
@@ -409,15 +416,37 @@
}
private void showFinalView(int finalIndex, final WorkspaceItemInfo item,
- String[] suggestedNameOut) {
+ FolderNameInfo[] nameInfos) {
postDelayed(() -> {
mPreviewItemManager.hidePreviewItem(finalIndex, false);
mFolder.showItem(item);
+ setLabelSuggestion(nameInfos);
invalidate();
- mFolder.showSuggestedTitle(suggestedNameOut);
}, DROP_IN_ANIMATION_DURATION);
}
+ /**
+ * Set the suggested folder name.
+ */
+ public void setLabelSuggestion(FolderNameInfo[] nameInfos) {
+ if (!FeatureFlags.FOLDER_NAME_SUGGEST.get()) {
+ return;
+ }
+ if (!isEmpty(mFolderName.getText().toString())
+ || mInfo.hasOption(FolderInfo.FLAG_MANUAL_FOLDER_NAME)) {
+ return;
+ }
+ if (nameInfos == null || nameInfos[0] == null || isEmpty(nameInfos[0].getLabel())) {
+ return;
+ }
+ mInfo.title = nameInfos[0].getLabel();
+ onTitleChanged(mInfo.title);
+ mFolder.mFolderName.setText(mInfo.title);
+ mFolder.mLauncher.getModelWriter().updateItemInDatabase(mInfo);
+ // TODO: Add logging while folder creation.
+ }
+
+
public void onDrop(DragObject d, boolean itemReturnedOnFailedDrop) {
WorkspaceItemInfo item;
if (d.dragInfo instanceof AppInfo) {
@@ -524,6 +553,10 @@
invalidate();
}
+ public boolean getIconVisible() {
+ return mBackgroundIsVisible;
+ }
+
public PreviewBackground getFolderBackground() {
return mBackground;
}
@@ -561,8 +594,7 @@
public void drawDot(Canvas canvas) {
if (!mForceHideDot && ((mDotInfo != null && mDotInfo.hasDot()) || mDotScale > 0)) {
Rect iconBounds = mDotParams.iconBounds;
- BubbleTextView.getIconBounds(this, iconBounds,
- mActivity.getWallpaperDeviceProfile().iconSizePx);
+ BubbleTextView.getIconBounds(this, iconBounds, mActivity.getDeviceProfile().iconSizePx);
float iconScale = (float) mBackground.previewSize / iconBounds.width();
Utilities.scaleRectAboutCenter(iconBounds, iconScale);
@@ -646,29 +678,10 @@
public boolean onTouchEvent(MotionEvent event) {
// Call the superclass onTouchEvent first, because sometimes it changes the state to
// isPressed() on an ACTION_UP
- boolean result = super.onTouchEvent(event);
-
- // Check for a stylus button press, if it occurs cancel any long press checks.
- if (mStylusEventHelper.onMotionEvent(event)) {
- mLongPressHelper.cancelLongPress();
- return true;
- }
-
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:
- mLongPressHelper.postCheckForLongPress();
- break;
- case MotionEvent.ACTION_CANCEL:
- case MotionEvent.ACTION_UP:
- mLongPressHelper.cancelLongPress();
- break;
- case MotionEvent.ACTION_MOVE:
- if (!Utilities.pointInView(this, event.getX(), event.getY(), mSlop)) {
- mLongPressHelper.cancelLongPress();
- }
- break;
- }
- return result;
+ super.onTouchEvent(event);
+ mLongPressHelper.onTouchEvent(event);
+ // Keep receiving the rest of the events
+ return true;
}
@Override
diff --git a/src/com/android/launcher3/folder/FolderNameEditText.java b/src/com/android/launcher3/folder/FolderNameEditText.java
index 7e11b18..edf2c70 100644
--- a/src/com/android/launcher3/folder/FolderNameEditText.java
+++ b/src/com/android/launcher3/folder/FolderNameEditText.java
@@ -102,13 +102,6 @@
mEnteredCompose = value;
}
- protected boolean isEnteredCompose() {
- if (DEBUG) {
- Log.d(TAG, "isEnteredCompose " + mEnteredCompose);
- }
- return mEnteredCompose;
- }
-
private class FolderNameEditTextInputConnection extends InputConnectionWrapper {
FolderNameEditTextInputConnection(InputConnection target, boolean mutable) {
diff --git a/src/com/android/launcher3/folder/FolderNameInfo.java b/src/com/android/launcher3/folder/FolderNameInfo.java
new file mode 100644
index 0000000..1287219
--- /dev/null
+++ b/src/com/android/launcher3/folder/FolderNameInfo.java
@@ -0,0 +1,89 @@
+/*
+ * 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.launcher3.folder;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.text.TextUtils;
+
+import androidx.annotation.NonNull;
+
+/**
+ * Information about a single label suggestions of the Folder.
+ */
+
+public final class FolderNameInfo implements Parcelable {
+ private final double mScore;
+ private final CharSequence mLabel;
+
+ /**
+ * Create a simple completion with label.
+ *
+ * @param label The text that should be inserted into the editor and pushed to
+ * InputMethodManager suggestions.
+ * @param score The score for the label between 0.0 and 1.0.
+ */
+ public FolderNameInfo(CharSequence label, double score) {
+ mScore = score;
+ mLabel = label;
+ }
+
+ private FolderNameInfo(Parcel source) {
+ mScore = source.readDouble();
+ mLabel = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
+ }
+
+ public CharSequence getLabel() {
+ return mLabel;
+ }
+
+ /**
+ * Used to package this object into a {@link Parcel}.
+ *
+ * @param dest The {@link Parcel} to be written.
+ * @param flags The flags used for parceling.
+ */
+ public void writeToParcel(Parcel dest, int flags) {
+ dest.writeDouble(mScore);
+ TextUtils.writeToParcel(mLabel, dest, flags);
+ }
+
+ /**
+ * Used to make this class parcelable.
+ */
+ @NonNull
+ public static final Parcelable.Creator<FolderNameInfo> CREATOR =
+ new Parcelable.Creator<FolderNameInfo>() {
+ public FolderNameInfo createFromParcel(Parcel source) {
+ return new FolderNameInfo(source);
+ }
+
+ public FolderNameInfo[] newArray(int size) {
+ return new FolderNameInfo[size];
+ }
+ };
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ @NonNull
+ public String toString() {
+ return String.format("%s:%.2f", mLabel, mScore);
+ }
+}
diff --git a/src/com/android/launcher3/folder/FolderNameProvider.java b/src/com/android/launcher3/folder/FolderNameProvider.java
index 957e636..7731e6e 100644
--- a/src/com/android/launcher3/folder/FolderNameProvider.java
+++ b/src/com/android/launcher3/folder/FolderNameProvider.java
@@ -15,25 +15,30 @@
*/
package com.android.launcher3.folder;
+import android.content.ComponentName;
import android.content.Context;
import android.os.Process;
+import android.os.UserHandle;
import android.text.TextUtils;
import android.util.Log;
-import com.android.launcher3.AppInfo;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.R;
-import com.android.launcher3.WorkspaceItemInfo;
+import com.android.launcher3.model.AllAppsList;
+import com.android.launcher3.model.BaseModelUpdateTask;
+import com.android.launcher3.model.BgDataModel;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.FolderInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
+import com.android.launcher3.util.IntSparseArrayMap;
import com.android.launcher3.util.ResourceBasedOverride;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import java.util.Map;
+import java.util.Objects;
import java.util.Optional;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.function.Function;
-import java.util.function.Predicate;
+import java.util.Set;
import java.util.stream.Collectors;
/**
@@ -49,6 +54,8 @@
* name edit box can also be used to provide suggestion.
*/
public static final int SUGGEST_MAX = 4;
+ protected IntSparseArrayMap<FolderInfo> mFolderInfos;
+ protected List<AppInfo> mAppInfos;
/**
* Retrieve instance of this object that can be overridden in runtime based on the build
@@ -57,83 +64,118 @@
public static FolderNameProvider newInstance(Context context) {
FolderNameProvider fnp = Overrides.getObject(FolderNameProvider.class,
context.getApplicationContext(), R.string.folder_name_provider_class);
+ fnp.load(context);
+
return fnp;
}
- public CharSequence getSuggestedFolderName(Context context,
- ArrayList<WorkspaceItemInfo> workspaceItemInfos, CharSequence[] candidates) {
+ public static FolderNameProvider newInstance(Context context, List<AppInfo> appInfos,
+ IntSparseArrayMap<FolderInfo> folderInfos) {
+ FolderNameProvider fnp = Overrides.getObject(FolderNameProvider.class,
+ context.getApplicationContext(), R.string.folder_name_provider_class);
+ fnp.load(appInfos, folderInfos);
+
+ return fnp;
+ }
+
+ private void load(Context context) {
+ LauncherAppState.getInstance(context).getModel().enqueueModelUpdateTask(
+ new FolderNameWorker());
+ }
+
+ private void load(List<AppInfo> appInfos, IntSparseArrayMap<FolderInfo> folderInfos) {
+ mAppInfos = appInfos;
+ mFolderInfos = folderInfos;
+ }
+
+ /**
+ * Generate and rank the suggested Folder names.
+ */
+ public void getSuggestedFolderName(Context context,
+ ArrayList<WorkspaceItemInfo> workspaceItemInfos,
+ FolderNameInfo[] nameInfos) {
if (DEBUG) {
- Log.d(TAG, "getSuggestedFolderName:" + Arrays.toString(candidates));
+ Log.d(TAG, "getSuggestedFolderName:" + Arrays.toString(nameInfos));
}
// If all the icons are from work profile,
// Then, suggest "Work" as the folder name
- List<WorkspaceItemInfo> distinctItemInfos = workspaceItemInfos.stream()
- .filter(distinctByKey(p-> p.user))
- .collect(Collectors.toList());
-
- if (distinctItemInfos.size() == 1
- && !distinctItemInfos.get(0).user.equals(Process.myUserHandle())) {
- // Place it as last viable suggestion
- setAsLastSuggestion(candidates,
+ Set<UserHandle> users = workspaceItemInfos.stream().map(w -> w.user)
+ .collect(Collectors.toSet());
+ if (users.size() == 1 && !users.contains(Process.myUserHandle())) {
+ setAsLastSuggestion(nameInfos,
context.getResources().getString(R.string.work_folder_name));
}
// If all the icons are from same package (e.g., main icon, shortcut, shortcut)
// Then, suggest the package's title as the folder name
- distinctItemInfos = workspaceItemInfos.stream()
- .filter(distinctByKey(p-> p.getTargetComponent() != null
- ? p.getTargetComponent().getPackageName() : ""))
- .collect(Collectors.toList());
+ Set<String> packageNames = workspaceItemInfos.stream()
+ .map(WorkspaceItemInfo::getTargetComponent)
+ .filter(Objects::nonNull)
+ .map(ComponentName::getPackageName)
+ .collect(Collectors.toSet());
- if (distinctItemInfos.size() == 1) {
- Optional<AppInfo> info = LauncherAppState.getInstance(context).getModel()
- .getAppInfoByPackageName(distinctItemInfos.get(0).getTargetComponent()
- .getPackageName());
+ if (packageNames.size() == 1) {
+ Optional<AppInfo> info = getAppInfoByPackageName(packageNames.iterator().next());
// Place it as first viable suggestion and shift everything else
- info.ifPresent(i -> setAsFirstSuggestion(candidates, i.title.toString()));
+ info.ifPresent(i -> setAsFirstSuggestion(nameInfos, i.title.toString()));
}
if (DEBUG) {
- Log.d(TAG, "getSuggestedFolderName:" + Arrays.toString(candidates));
+ Log.d(TAG, "getSuggestedFolderName:" + Arrays.toString(nameInfos));
}
- return candidates[0];
}
- private void setAsFirstSuggestion(CharSequence[] candidatesOut, CharSequence candidate) {
- if (contains(candidatesOut, candidate)) {
+ private Optional<AppInfo> getAppInfoByPackageName(String packageName) {
+ if (mAppInfos == null || mAppInfos.isEmpty()) {
+ return Optional.empty();
+ }
+ return mAppInfos.stream()
+ .filter(info -> info.componentName != null)
+ .filter(info -> info.componentName.getPackageName().equals(packageName))
+ .findAny();
+ }
+
+ private void setAsFirstSuggestion(FolderNameInfo[] nameInfos, CharSequence label) {
+ if (nameInfos.length == 0 || contains(nameInfos, label)) {
return;
}
- for (int i = candidatesOut.length - 1; i > 0; i--) {
- if (!TextUtils.isEmpty(candidatesOut[i - 1])) {
- candidatesOut[i] = candidatesOut[i - 1];
+ for (int i = nameInfos.length - 1; i > 0; i--) {
+ if (nameInfos[i - 1] != null && !TextUtils.isEmpty(nameInfos[i - 1].getLabel())) {
+ nameInfos[i] = nameInfos[i - 1];
}
}
- candidatesOut[0] = candidate;
+ nameInfos[0] = new FolderNameInfo(label, 1.0);
}
- private void setAsLastSuggestion(CharSequence[] candidatesOut, CharSequence candidate) {
- if (contains(candidatesOut, candidate)) {
+ private void setAsLastSuggestion(FolderNameInfo[] nameInfos, CharSequence label) {
+ if (nameInfos.length == 0 || contains(nameInfos, label)) {
return;
}
- for (int i = 0; i < candidate.length(); i++) {
- if (TextUtils.isEmpty(candidatesOut[i])) {
- candidatesOut[i] = candidate;
+ for (int i = 0; i < nameInfos.length; i++) {
+ if (nameInfos[i] == null || TextUtils.isEmpty(nameInfos[i].getLabel())) {
+ nameInfos[i] = new FolderNameInfo(label, 1.0);
return;
}
}
- candidatesOut[candidate.length() - 1] = candidate;
+ // Overwrite the last suggestion.
+ int lastIndex = nameInfos.length - 1;
+ nameInfos[lastIndex] = new FolderNameInfo(label, 1.0);
}
- private boolean contains(CharSequence[] list, CharSequence key) {
- return Arrays.asList(list).stream()
- .filter(s -> s != null)
- .anyMatch(s -> s.toString().equalsIgnoreCase(key.toString()));
+ private boolean contains(FolderNameInfo[] nameInfos, CharSequence label) {
+ return Arrays.stream(nameInfos)
+ .filter(Objects::nonNull)
+ .anyMatch(nameInfo -> nameInfo.getLabel().toString().equalsIgnoreCase(
+ label.toString()));
}
- // This method can be moved to some Utility class location.
- private static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
- Map<Object, Boolean> map = new ConcurrentHashMap<>();
- return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
+ private class FolderNameWorker extends BaseModelUpdateTask {
+ @Override
+ public void execute(LauncherAppState app, BgDataModel dataModel, AllAppsList apps) {
+ mFolderInfos = dataModel.folders.clone();
+ mAppInfos = Arrays.asList(apps.copyData());
+ }
}
+
}
diff --git a/src/com/android/launcher3/folder/FolderPagedView.java b/src/com/android/launcher3/folder/FolderPagedView.java
index 3b5fd59..96ddd57 100644
--- a/src/com/android/launcher3/folder/FolderPagedView.java
+++ b/src/com/android/launcher3/folder/FolderPagedView.java
@@ -16,6 +16,9 @@
package com.android.launcher3.folder;
+import static com.android.launcher3.AbstractFloatingView.TYPE_ALL;
+import static com.android.launcher3.AbstractFloatingView.TYPE_FOLDER;
+
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
@@ -27,12 +30,12 @@
import android.view.View;
import android.view.ViewDebug;
+import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.BaseActivity;
import com.android.launcher3.BubbleTextView;
import com.android.launcher3.CellLayout;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.InvariantDeviceProfile;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.PagedView;
@@ -40,9 +43,10 @@
import com.android.launcher3.ShortcutAndWidgetContainer;
import com.android.launcher3.Utilities;
import com.android.launcher3.Workspace.ItemOperator;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.anim.Interpolators;
import com.android.launcher3.keyboard.ViewGroupFocusHelper;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.pageindicators.PageIndicatorDots;
import com.android.launcher3.touch.ItemClickHandler;
import com.android.launcher3.util.Thunk;
@@ -258,7 +262,7 @@
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
- mPageIndicator.setScroll(l, mMaxScrollX);
+ if (mMaxScroll > 0) mPageIndicator.setScroll(l, mMaxScroll);
}
/**
@@ -614,6 +618,12 @@
}
}
+ @Override
+ protected boolean canScroll(float absVScroll, float absHScroll) {
+ return AbstractFloatingView.getTopOpenViewWithType(mFolder.mLauncher,
+ TYPE_ALL & ~TYPE_FOLDER) == null;
+ }
+
public int itemsPerPage() {
return mOrganizer.getMaxItemsPerPage();
}
diff --git a/src/com/android/launcher3/folder/PreviewBackground.java b/src/com/android/launcher3/folder/PreviewBackground.java
index 2d177d2..27b906b 100644
--- a/src/com/android/launcher3/folder/PreviewBackground.java
+++ b/src/com/android/launcher3/folder/PreviewBackground.java
@@ -153,7 +153,7 @@
mBgColor = ta.getColor(R.styleable.FolderIconPreview_folderFillColor, 0);
ta.recycle();
- DeviceProfile grid = activity.getWallpaperDeviceProfile();
+ DeviceProfile grid = activity.getDeviceProfile();
previewSize = grid.folderIconSizePx;
basePreviewOffsetX = (availableSpaceX - previewSize) / 2;
diff --git a/src/com/android/launcher3/folder/PreviewItemDrawingParams.java b/src/com/android/launcher3/folder/PreviewItemDrawingParams.java
index caf6e55..a14a0d8 100644
--- a/src/com/android/launcher3/folder/PreviewItemDrawingParams.java
+++ b/src/com/android/launcher3/folder/PreviewItemDrawingParams.java
@@ -17,7 +17,7 @@
import android.graphics.drawable.Drawable;
-import com.android.launcher3.WorkspaceItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
/**
* Manages the parameters used to draw a Folder preview item.
diff --git a/src/com/android/launcher3/folder/PreviewItemManager.java b/src/com/android/launcher3/folder/PreviewItemManager.java
index 27aa43e..7f8a15c 100644
--- a/src/com/android/launcher3/folder/PreviewItemManager.java
+++ b/src/com/android/launcher3/folder/PreviewItemManager.java
@@ -38,8 +38,8 @@
import androidx.annotation.NonNull;
import com.android.launcher3.Utilities;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.graphics.PreloadIconDrawable;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.views.ActivityContext;
import java.util.ArrayList;
diff --git a/src/com/android/launcher3/graphics/DragPreviewProvider.java b/src/com/android/launcher3/graphics/DragPreviewProvider.java
index f579451..848c04a 100644
--- a/src/com/android/launcher3/graphics/DragPreviewProvider.java
+++ b/src/com/android/launcher3/graphics/DragPreviewProvider.java
@@ -30,14 +30,12 @@
import android.view.View;
import com.android.launcher3.BubbleTextView;
-import com.android.launcher3.FastBitmapDrawable;
import com.android.launcher3.Launcher;
import com.android.launcher3.R;
import com.android.launcher3.config.FeatureFlags;
-import com.android.launcher3.folder.FolderIcon;
+import com.android.launcher3.dragndrop.DraggableView;
import com.android.launcher3.icons.BitmapRenderer;
import com.android.launcher3.widget.LauncherAppWidgetHostView;
-import com.android.launcher3.widget.PendingAppWidgetHostView;
import java.nio.ByteBuffer;
@@ -53,7 +51,7 @@
// The padding added to the drag view during the preview generation.
public final int previewPadding;
- protected final int blurSizeOutline;
+ public final int blurSizeOutline;
private OutlineGeneratorCallback mOutlineGeneratorCallback;
public Bitmap generatedDragOutline;
@@ -66,56 +64,25 @@
mView = view;
blurSizeOutline =
context.getResources().getDimensionPixelSize(R.dimen.blur_size_medium_outline);
-
- if (mView instanceof BubbleTextView) {
- Drawable d = ((BubbleTextView) mView).getIcon();
- Rect bounds = getDrawableBounds(d);
- previewPadding = blurSizeOutline - bounds.left - bounds.top;
- } else {
- previewPadding = blurSizeOutline;
- }
+ previewPadding = blurSizeOutline;
}
/**
* Draws the {@link #mView} into the given {@param destCanvas}.
*/
protected void drawDragView(Canvas destCanvas, float scale) {
- destCanvas.save();
+ int saveCount = destCanvas.save();
destCanvas.scale(scale, scale);
- if (mView instanceof BubbleTextView) {
- Drawable d = ((BubbleTextView) mView).getIcon();
- Rect bounds = getDrawableBounds(d);
- destCanvas.translate(blurSizeOutline / 2 - bounds.left,
- blurSizeOutline / 2 - bounds.top);
- if (d instanceof FastBitmapDrawable) {
- ((FastBitmapDrawable) d).setScale(1);
- }
- d.draw(destCanvas);
- } else {
- final Rect clipRect = mTempRect;
- mView.getDrawingRect(clipRect);
-
- boolean textVisible = false;
- if (mView instanceof FolderIcon) {
- // For FolderIcons the text can bleed into the icon area, and so we need to
- // hide the text completely (which can't be achieved by clipping).
- if (((FolderIcon) mView).getTextVisible()) {
- ((FolderIcon) mView).setTextVisible(false);
- textVisible = true;
- }
- }
- destCanvas.translate(-mView.getScrollX() + blurSizeOutline / 2,
- -mView.getScrollY() + blurSizeOutline / 2);
- destCanvas.clipRect(clipRect);
+ if (mView instanceof DraggableView) {
+ DraggableView dv = (DraggableView) mView;
+ dv.prepareDrawDragView();
+ dv.getVisualDragBounds(mTempRect);
+ destCanvas.translate(blurSizeOutline / 2 - mTempRect.left,
+ blurSizeOutline / 2 - mTempRect.top);
mView.draw(destCanvas);
-
- // Restore text visibility of FolderIcon if necessary
- if (textVisible) {
- ((FolderIcon) mView).setTextVisible(true);
- }
}
- destCanvas.restore();
+ destCanvas.restoreToCount(saveCount);
}
/**
@@ -123,36 +90,25 @@
* Responsibility for the bitmap is transferred to the caller.
*/
public Bitmap createDragBitmap() {
- int width = mView.getWidth();
- int height = mView.getHeight();
-
- if (mView instanceof BubbleTextView) {
- Drawable d = ((BubbleTextView) mView).getIcon();
- Rect bounds = getDrawableBounds(d);
- width = bounds.width();
- height = bounds.height();
- } else if (mView instanceof LauncherAppWidgetHostView) {
- float scale = ((LauncherAppWidgetHostView) mView).getScaleToFit();
- width = (int) (mView.getWidth() * scale);
- height = (int) (mView.getHeight() * scale);
-
- if (mView instanceof PendingAppWidgetHostView) {
- // Use hardware renderer as the icon for the pending app widget may be a hw bitmap
- return BitmapRenderer.createHardwareBitmap(width + blurSizeOutline,
- height + blurSizeOutline, (c) -> drawDragView(c, scale));
- } else {
- // Use software renderer for widgets as we know that they already work
- return BitmapRenderer.createSoftwareBitmap(width + blurSizeOutline,
- height + blurSizeOutline, (c) -> drawDragView(c, scale));
- }
+ int width = 0;
+ int height = 0;
+ // Assume scaleX == scaleY, which is always the case for workspace items.
+ float scale = mView.getScaleX();
+ if (mView instanceof DraggableView) {
+ ((DraggableView) mView).getVisualDragBounds(mTempRect);
+ width = mTempRect.width();
+ height = mTempRect.height();
+ } else {
+ width = mView.getWidth();
+ height = mView.getHeight();
}
return BitmapRenderer.createHardwareBitmap(width + blurSizeOutline,
- height + blurSizeOutline, (c) -> drawDragView(c, 1));
+ height + blurSizeOutline, (c) -> drawDragView(c, scale));
}
public final void generateDragOutline(Bitmap preview) {
- if (FeatureFlags.IS_DOGFOOD_BUILD && mOutlineGeneratorCallback != null) {
+ if (FeatureFlags.IS_STUDIO_BUILD && mOutlineGeneratorCallback != null) {
throw new RuntimeException("Drag outline generated twice");
}
diff --git a/src/com/android/launcher3/graphics/GridOptionsProvider.java b/src/com/android/launcher3/graphics/GridOptionsProvider.java
index 71b4366..af974f8 100644
--- a/src/com/android/launcher3/graphics/GridOptionsProvider.java
+++ b/src/com/android/launcher3/graphics/GridOptionsProvider.java
@@ -1,5 +1,6 @@
package com.android.launcher3.graphics;
+import static com.android.launcher3.config.FeatureFlags.USE_SURFACE_VIEW_FOR_GRID_PREVIEW;
import static com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR;
import android.content.ContentProvider;
@@ -62,6 +63,11 @@
private static final String KEY_PREVIEW = "preview";
private static final String MIME_TYPE_PNG = "image/png";
+ private static final String METHOD_GET_PREVIEW = "get_preview";
+ private static final String METADATA_KEY_PREVIEW_VERSION = "preview_version";
+
+
+
public static final PipeDataWriter<Future<Bitmap>> BITMAP_WRITER =
new PipeDataWriter<Future<Bitmap>>() {
@Override
@@ -98,6 +104,10 @@
.add(KEY_IS_DEFAULT, idp.numColumns == gridOption.numColumns
&& idp.numRows == gridOption.numRows);
}
+ Bundle metadata = new Bundle();
+ metadata.putString(METADATA_KEY_PREVIEW_VERSION,
+ USE_SURFACE_VIEW_FOR_GRID_PREVIEW.get() ? "V2" : "V1");
+ cursor.setExtras(metadata);
return cursor;
}
@@ -188,4 +198,13 @@
throw new FileNotFoundException(e.getMessage());
}
}
+
+ @Override
+ public Bundle call(String method, String arg, Bundle extras) {
+ if (!METHOD_GET_PREVIEW.equals(method)) {
+ return null;
+ }
+
+ return new PreviewSurfaceRenderer(getContext(), extras).render();
+ }
}
diff --git a/src/com/android/launcher3/graphics/LauncherPreviewRenderer.java b/src/com/android/launcher3/graphics/LauncherPreviewRenderer.java
index def76e8..6e91d70 100644
--- a/src/com/android/launcher3/graphics/LauncherPreviewRenderer.java
+++ b/src/com/android/launcher3/graphics/LauncherPreviewRenderer.java
@@ -20,13 +20,18 @@
import static android.view.View.VISIBLE;
import static com.android.launcher3.config.FeatureFlags.ENABLE_LAUNCHER_PREVIEW_IN_GRID_PICKER;
+import static com.android.launcher3.config.FeatureFlags.MULTI_DB_GRID_MIRATION_ALGO;
import static com.android.launcher3.model.ModelUtils.filterCurrentWorkspaceItems;
import static com.android.launcher3.model.ModelUtils.sortWorkspaceItemsSpatially;
+import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
import android.annotation.TargetApi;
import android.app.Fragment;
+import android.appwidget.AppWidgetHostView;
import android.content.Context;
+import android.content.ContextWrapper;
import android.content.Intent;
+import android.content.pm.ShortcutInfo;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
@@ -49,18 +54,15 @@
import com.android.launcher3.BubbleTextView;
import com.android.launcher3.CellLayout;
import com.android.launcher3.DeviceProfile;
-import com.android.launcher3.FolderInfo;
import com.android.launcher3.Hotseat;
import com.android.launcher3.InsettableFrameLayout;
import com.android.launcher3.InvariantDeviceProfile;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherModel;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.WorkspaceLayoutManager;
import com.android.launcher3.allapps.SearchUiManager;
import com.android.launcher3.config.FeatureFlags;
@@ -68,15 +70,37 @@
import com.android.launcher3.icons.BaseIconFactory;
import com.android.launcher3.icons.BitmapInfo;
import com.android.launcher3.icons.BitmapRenderer;
+import com.android.launcher3.icons.LauncherIcons;
import com.android.launcher3.model.AllAppsList;
import com.android.launcher3.model.BgDataModel;
import com.android.launcher3.model.BgDataModel.Callbacks;
+import com.android.launcher3.model.GridSizeMigrationTask;
+import com.android.launcher3.model.GridSizeMigrationTaskV2;
import com.android.launcher3.model.LoaderResults;
+import com.android.launcher3.model.LoaderTask;
+import com.android.launcher3.model.WidgetItem;
+import com.android.launcher3.model.WidgetsModel;
+import com.android.launcher3.model.data.FolderInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
+import com.android.launcher3.pm.InstallSessionHelper;
+import com.android.launcher3.pm.UserCache;
+import com.android.launcher3.uioverrides.plugins.PluginManagerWrapper;
+import com.android.launcher3.util.MainThreadInitializedObject;
import com.android.launcher3.views.ActivityContext;
import com.android.launcher3.views.BaseDragLayer;
+import com.android.launcher3.widget.custom.CustomWidgetManager;
import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
@@ -97,6 +121,90 @@
private static final String TAG = "LauncherPreviewRenderer";
+ /**
+ * Context used just for preview. It also provides a few objects (e.g. UserCache) just for
+ * preview purposes.
+ */
+ public static class PreviewContext extends ContextWrapper {
+
+ private static final Set<MainThreadInitializedObject> WHITELIST = new HashSet<>(
+ Arrays.asList(UserCache.INSTANCE, InstallSessionHelper.INSTANCE,
+ LauncherAppState.INSTANCE, InvariantDeviceProfile.INSTANCE,
+ CustomWidgetManager.INSTANCE, PluginManagerWrapper.INSTANCE));
+
+ private final InvariantDeviceProfile mIdp;
+ private final Map<MainThreadInitializedObject, Object> mObjectMap = new HashMap<>();
+ private final ConcurrentLinkedQueue<LauncherIconsForPreview> mIconPool =
+ new ConcurrentLinkedQueue<>();
+
+ public PreviewContext(Context base, InvariantDeviceProfile idp) {
+ super(base);
+ mIdp = idp;
+ }
+
+ @Override
+ public Context getApplicationContext() {
+ return this;
+ }
+
+ public void onDestroy() {
+ CustomWidgetManager customWidgetManager = (CustomWidgetManager) mObjectMap.get(
+ CustomWidgetManager.INSTANCE);
+ if (customWidgetManager != null) {
+ customWidgetManager.onDestroy();
+ }
+ }
+
+ /**
+ * Find a cached object from mObjectMap if we have already created one. If not, generate
+ * an object using the provider.
+ */
+ public <T> T getObject(MainThreadInitializedObject<T> mainThreadInitializedObject,
+ MainThreadInitializedObject.ObjectProvider<T> provider) {
+ if (!WHITELIST.contains(mainThreadInitializedObject)) {
+ throw new IllegalStateException("Leaking unknown objects");
+ }
+ if (mainThreadInitializedObject == LauncherAppState.INSTANCE) {
+ throw new IllegalStateException(
+ "Should not use MainThreadInitializedObject to initialize this with "
+ + "PreviewContext");
+ }
+ if (mainThreadInitializedObject == InvariantDeviceProfile.INSTANCE) {
+ return (T) mIdp;
+ }
+ if (mObjectMap.containsKey(mainThreadInitializedObject)) {
+ return (T) mObjectMap.get(mainThreadInitializedObject);
+ }
+ T t = provider.get(this);
+ mObjectMap.put(mainThreadInitializedObject, t);
+ return t;
+ }
+
+ public LauncherIcons newLauncherIcons(Context context, boolean shapeDetection) {
+ LauncherIconsForPreview launcherIconsForPreview = mIconPool.poll();
+ if (launcherIconsForPreview != null) {
+ return launcherIconsForPreview;
+ }
+ return new LauncherIconsForPreview(context, mIdp.fillResIconDpi, mIdp.iconBitmapSize,
+ -1 /* poolId */, shapeDetection);
+ }
+
+ private final class LauncherIconsForPreview extends LauncherIcons {
+
+ private LauncherIconsForPreview(Context context, int fillResIconDpi, int iconBitmapSize,
+ int poolId, boolean shapeDetection) {
+ super(context, fillResIconDpi, iconBitmapSize, poolId, shapeDetection);
+ }
+
+ @Override
+ public void recycle() {
+ // Clear any temporary state variables
+ clear();
+ mIconPool.offer(this);
+ }
+ }
+ }
+
private final Handler mUiHandler;
private final Context mContext;
private final InvariantDeviceProfile mIdp;
@@ -153,6 +261,13 @@
});
}
+ /** Populate preview and render it. */
+ public View getRenderedView() {
+ MainThreadRenderer renderer = new MainThreadRenderer(mContext);
+ renderer.populate();
+ return renderer.mRootView;
+ }
+
private class MainThreadRenderer extends ContextThemeWrapper
implements ActivityContext, WorkspaceLayoutManager, LayoutInflater.Factory2 {
@@ -248,6 +363,19 @@
addInScreenFromBind(folderIcon, info);
}
+ private void inflateAndAddWidgets(LauncherAppWidgetInfo info, WidgetsModel widgetsModel) {
+ WidgetItem widgetItem = widgetsModel.getWidgetProviderInfoByProviderName(
+ info.providerName);
+ if (widgetItem == null) {
+ return;
+ }
+ AppWidgetHostView view = new AppWidgetHostView(mContext);
+ view.setAppWidget(-1, widgetItem.widgetInfo);
+ view.updateAppWidget(null);
+ view.setTag(info);
+ addInScreenFromBind(view, info);
+ }
+
private void dispatchVisibilityAggregated(View view, boolean isVisible) {
// Similar to View.dispatchVisibilityAggregated implementation.
final boolean thisVisible = view.getVisibility() == VISIBLE;
@@ -266,17 +394,38 @@
}
}
- private void renderScreenShot(Canvas canvas) {
+ private void populate() {
if (ENABLE_LAUNCHER_PREVIEW_IN_GRID_PICKER.get()) {
- final LauncherModel launcherModel = LauncherAppState.getInstance(
- mContext).getModel();
- final WorkspaceItemsInfoFetcher fetcher = new WorkspaceItemsInfoFetcher();
- launcherModel.enqueueModelUpdateTask(fetcher);
- ArrayList<ItemInfo> workspaceItems;
- try {
- workspaceItems = fetcher.mTask.get(5, TimeUnit.SECONDS);
- } catch (InterruptedException | ExecutionException | TimeoutException e) {
- Log.d(TAG, "Error fetching workspace items info", e);
+ boolean needsToMigrate =
+ MULTI_DB_GRID_MIRATION_ALGO.get()
+ ? GridSizeMigrationTaskV2.needsToMigrate(mContext, mIdp)
+ : GridSizeMigrationTask.needsToMigrate(mContext, mIdp);
+ boolean success = false;
+ if (needsToMigrate) {
+ success = MULTI_DB_GRID_MIRATION_ALGO.get()
+ ? GridSizeMigrationTaskV2.migrateGridIfNeeded(mContext, mIdp)
+ : GridSizeMigrationTask.migrateGridIfNeeded(mContext, mIdp);
+ }
+
+ WorkspaceFetcher fetcher;
+ PreviewContext previewContext = null;
+ if (needsToMigrate && success) {
+ previewContext = new PreviewContext(mContext, mIdp);
+ LauncherAppState appForPreview = new LauncherAppState(
+ previewContext, null /* iconCacheFileName */);
+ fetcher = new WorkspaceItemsInfoFromPreviewFetcher(appForPreview);
+ MODEL_EXECUTOR.execute(fetcher);
+ } else {
+ fetcher = new WorkspaceItemsInfoFetcher();
+ LauncherAppState.getInstance(mContext).getModel().enqueueModelUpdateTask(
+ (LauncherModel.ModelUpdateTask) fetcher);
+ }
+ WorkspaceResult workspaceResult = fetcher.get();
+ if (previewContext != null) {
+ previewContext.onDestroy();
+ }
+
+ if (workspaceResult == null) {
return;
}
@@ -284,9 +433,14 @@
// items
ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<>();
ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<>();
+ ArrayList<LauncherAppWidgetInfo> currentAppWidgets = new ArrayList<>();
+ ArrayList<LauncherAppWidgetInfo> otherAppWidgets = new ArrayList<>();
- filterCurrentWorkspaceItems(0 /* currentScreenId */, workspaceItems,
- currentWorkspaceItems, otherWorkspaceItems);
+ filterCurrentWorkspaceItems(0 /* currentScreenId */,
+ workspaceResult.mWorkspaceItems, currentWorkspaceItems,
+ otherWorkspaceItems);
+ filterCurrentWorkspaceItems(0 /* currentScreenId */, workspaceResult.mAppWidgets,
+ currentAppWidgets, otherAppWidgets);
sortWorkspaceItemsSpatially(mIdp, currentWorkspaceItems);
for (ItemInfo itemInfo : currentWorkspaceItems) {
@@ -303,6 +457,17 @@
break;
}
}
+ for (ItemInfo itemInfo : currentAppWidgets) {
+ switch (itemInfo.itemType) {
+ case Favorites.ITEM_TYPE_APPWIDGET:
+ case Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
+ inflateAndAddWidgets((LauncherAppWidgetInfo) itemInfo,
+ workspaceResult.mWidgetsModel);
+ break;
+ default:
+ break;
+ }
+ }
} else {
// Add hotseat icons
for (int i = 0; i < mIdp.numHotseatIcons; i++) {
@@ -343,16 +508,24 @@
measureView(mRootView, mDp.widthPx, mDp.heightPx);
// Additional measure for views which use auto text size API
measureView(mRootView, mDp.widthPx, mDp.heightPx);
+ }
+ private void renderScreenShot(Canvas canvas) {
+ populate();
mRootView.draw(canvas);
dispatchVisibilityAggregated(mRootView, false);
}
}
- private static class WorkspaceItemsInfoFetcher implements Callable<ArrayList<ItemInfo>>,
- LauncherModel.ModelUpdateTask {
+ private static void measureView(View view, int width, int height) {
+ view.measure(makeMeasureSpec(width, EXACTLY), makeMeasureSpec(height, EXACTLY));
+ view.layout(0, 0, width, height);
+ }
- private final FutureTask<ArrayList<ItemInfo>> mTask = new FutureTask<>(this);
+ private static class WorkspaceItemsInfoFetcher implements LauncherModel.ModelUpdateTask,
+ WorkspaceFetcher {
+
+ private final FutureTask<WorkspaceResult> mTask = new FutureTask<>(this);
private LauncherAppState mApp;
private LauncherModel mModel;
@@ -369,24 +542,81 @@
}
@Override
+ public FutureTask<WorkspaceResult> getTask() {
+ return mTask;
+ }
+
+ @Override
public void run() {
mTask.run();
}
@Override
- public ArrayList<ItemInfo> call() throws Exception {
+ public WorkspaceResult call() throws Exception {
if (!mModel.isModelLoaded()) {
Log.d(TAG, "Workspace not loaded, loading now");
mModel.startLoaderForResults(
new LoaderResults(mApp, mBgDataModel, mAllAppsList, new Callbacks[0]));
- return new ArrayList<>();
+ return null;
}
- return mBgDataModel.workspaceItems;
+
+ return new WorkspaceResult(mBgDataModel.workspaceItems, mBgDataModel.appWidgets,
+ mBgDataModel.widgetsModel);
}
}
- private static void measureView(View view, int width, int height) {
- view.measure(makeMeasureSpec(width, EXACTLY), makeMeasureSpec(height, EXACTLY));
- view.layout(0, 0, width, height);
+ private static class WorkspaceItemsInfoFromPreviewFetcher extends LoaderTask implements
+ WorkspaceFetcher {
+
+ private final FutureTask<WorkspaceResult> mTask = new FutureTask<>(this);
+
+ WorkspaceItemsInfoFromPreviewFetcher(LauncherAppState app) {
+ super(app, null, new BgDataModel(), null);
+ }
+
+ @Override
+ public FutureTask<WorkspaceResult> getTask() {
+ return mTask;
+ }
+
+ @Override
+ public void run() {
+ mTask.run();
+ }
+
+ @Override
+ public WorkspaceResult call() throws Exception {
+ List<ShortcutInfo> allShortcuts = new ArrayList<>();
+ loadWorkspace(allShortcuts, LauncherSettings.Favorites.PREVIEW_CONTENT_URI);
+ mBgDataModel.widgetsModel.update(mApp, null);
+ return new WorkspaceResult(mBgDataModel.workspaceItems, mBgDataModel.appWidgets,
+ mBgDataModel.widgetsModel);
+ }
+ }
+
+ private interface WorkspaceFetcher extends Runnable, Callable<WorkspaceResult> {
+ FutureTask<WorkspaceResult> getTask();
+
+ default WorkspaceResult get() {
+ try {
+ return getTask().get(5, TimeUnit.SECONDS);
+ } catch (InterruptedException | ExecutionException | TimeoutException e) {
+ Log.d(TAG, "Error fetching workspace items info", e);
+ return null;
+ }
+ }
+ }
+
+ private static class WorkspaceResult {
+ private final ArrayList<ItemInfo> mWorkspaceItems;
+ private final ArrayList<LauncherAppWidgetInfo> mAppWidgets;
+ private final WidgetsModel mWidgetsModel;
+
+ private WorkspaceResult(ArrayList<ItemInfo> workspaceItems,
+ ArrayList<LauncherAppWidgetInfo> appWidgets, WidgetsModel widgetsModel) {
+ mWorkspaceItems = workspaceItems;
+ mAppWidgets = appWidgets;
+ mWidgetsModel = widgetsModel;
+ }
}
}
diff --git a/src/com/android/launcher3/graphics/PreloadIconDrawable.java b/src/com/android/launcher3/graphics/PreloadIconDrawable.java
index b0e1db1..4439284 100644
--- a/src/com/android/launcher3/graphics/PreloadIconDrawable.java
+++ b/src/com/android/launcher3/graphics/PreloadIconDrawable.java
@@ -35,8 +35,8 @@
import android.util.SparseArray;
import com.android.launcher3.FastBitmapDrawable;
-import com.android.launcher3.ItemInfoWithIcon;
import com.android.launcher3.anim.Interpolators;
+import com.android.launcher3.model.data.ItemInfoWithIcon;
import java.lang.ref.WeakReference;
diff --git a/src/com/android/launcher3/graphics/PreviewSurfaceRenderer.java b/src/com/android/launcher3/graphics/PreviewSurfaceRenderer.java
new file mode 100644
index 0000000..20eec9a
--- /dev/null
+++ b/src/com/android/launcher3/graphics/PreviewSurfaceRenderer.java
@@ -0,0 +1,128 @@
+/*
+ * 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.launcher3.graphics;
+
+import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
+
+import android.content.Context;
+import android.hardware.display.DisplayManager;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.IBinder;
+import android.os.Looper;
+import android.os.Message;
+import android.os.Messenger;
+import android.view.Display;
+import android.view.SurfaceControlViewHost;
+import android.view.View;
+
+import com.android.launcher3.InvariantDeviceProfile;
+
+import java.util.concurrent.TimeUnit;
+
+/** Render preview using surface view. */
+public class PreviewSurfaceRenderer implements IBinder.DeathRecipient {
+
+ private static final String KEY_HOST_TOKEN = "host_token";
+ private static final String KEY_VIEW_WIDTH = "width";
+ private static final String KEY_VIEW_HEIGHT = "height";
+ private static final String KEY_DISPLAY_ID = "display_id";
+ private static final String KEY_SURFACE_PACKAGE = "surface_package";
+ private static final String KEY_CALLBACK = "callback";
+
+ private final Context mContext;
+ private final InvariantDeviceProfile mIdp;
+ private final IBinder mHostToken;
+ private final int mWidth;
+ private final int mHeight;
+ private final Display mDisplay;
+
+ private SurfaceControlViewHost mSurfaceControlViewHost;
+
+ PreviewSurfaceRenderer(Context context, Bundle bundle) {
+ mContext = context;
+
+ String gridName = bundle.getString("name");
+ bundle.remove("name");
+ if (gridName == null) {
+ gridName = InvariantDeviceProfile.getCurrentGridName(context);
+ }
+ mIdp = new InvariantDeviceProfile(context, gridName);
+
+ mHostToken = bundle.getBinder(KEY_HOST_TOKEN);
+ mWidth = bundle.getInt(KEY_VIEW_WIDTH);
+ mHeight = bundle.getInt(KEY_VIEW_HEIGHT);
+
+ final DisplayManager displayManager = (DisplayManager) context.getSystemService(
+ Context.DISPLAY_SERVICE);
+ mDisplay = displayManager.getDisplay(bundle.getInt(KEY_DISPLAY_ID));
+ }
+
+ /** Handle a received surface view request. */
+ Bundle render() {
+ if (mSurfaceControlViewHost != null) {
+ binderDied();
+ }
+
+ try {
+ mSurfaceControlViewHost = MAIN_EXECUTOR
+ .submit(() -> new SurfaceControlViewHost(mContext, mDisplay, mHostToken))
+ .get(5, TimeUnit.SECONDS);
+ mHostToken.linkToDeath(this, 0);
+ } catch (Exception e) {
+ e.printStackTrace();
+ return null;
+ }
+
+ MAIN_EXECUTOR.execute(() -> {
+ View view = new LauncherPreviewRenderer(mContext, mIdp).getRenderedView();
+ // This aspect scales the view to fit in the surface and centers it
+ final float scale = Math.min(mWidth / (float) view.getMeasuredWidth(),
+ mHeight / (float) view.getMeasuredHeight());
+ view.setScaleX(scale);
+ view.setScaleY(scale);
+ view.setPivotX(0);
+ view.setPivotY(0);
+ view.setTranslationX((mWidth - scale * view.getWidth()) / 2);
+ view.setTranslationY((mHeight - scale * view.getHeight()) / 2);
+ mSurfaceControlViewHost.setView(view, view.getMeasuredWidth(),
+ view.getMeasuredHeight());
+ });
+
+ Bundle result = new Bundle();
+ result.putParcelable(KEY_SURFACE_PACKAGE, mSurfaceControlViewHost.getSurfacePackage());
+
+ Handler handler = new Handler(Looper.getMainLooper(), Loopermessage -> {
+ binderDied();
+ return true;
+ });
+ Messenger messenger = new Messenger(handler);
+ Message msg = Message.obtain();
+ msg.replyTo = messenger;
+ result.putParcelable(KEY_CALLBACK, msg);
+ return result;
+ }
+
+ @Override
+ public void binderDied() {
+ if (mSurfaceControlViewHost != null) {
+ mSurfaceControlViewHost.release();
+ mSurfaceControlViewHost = null;
+ }
+ mHostToken.unlinkToDeath(this, 0);
+ }
+}
diff --git a/src/com/android/launcher3/graphics/RotationMode.java b/src/com/android/launcher3/graphics/RotationMode.java
deleted file mode 100644
index 6dd356a..0000000
--- a/src/com/android/launcher3/graphics/RotationMode.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * 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.launcher3.graphics;
-
-import android.content.Context;
-import android.graphics.Rect;
-
-public abstract class RotationMode {
-
- public static final RotationMode NORMAL = new RotationMode(0) { };
-
- public final float surfaceRotation;
- public final boolean isTransposed;
-
- public RotationMode(float surfaceRotation) {
- this.surfaceRotation = surfaceRotation;
- isTransposed = surfaceRotation != 0;
- }
-
- public final void mapRect(Rect rect, Rect out) {
- mapRect(rect.left, rect.top, rect.right, rect.bottom, out);
- }
-
- public void mapRect(int left, int top, int right, int bottom, Rect out) {
- out.set(left, top, right, bottom);
- }
-
- public void mapInsets(Context context, Rect insets, Rect out) {
- out.set(insets);
- }
-
- public int toNaturalGravity(int absoluteGravity) {
- return absoluteGravity;
- }
-}
diff --git a/src/com/android/launcher3/graphics/Scrim.java b/src/com/android/launcher3/graphics/Scrim.java
index 67b2b6d..f90962d 100644
--- a/src/com/android/launcher3/graphics/Scrim.java
+++ b/src/com/android/launcher3/graphics/Scrim.java
@@ -19,7 +19,7 @@
import static com.android.launcher3.icons.GraphicsUtils.setColorAlphaBound;
import android.graphics.Canvas;
-import android.util.Property;
+import android.util.FloatProperty;
import android.view.View;
import com.android.launcher3.Launcher;
@@ -31,16 +31,16 @@
public class Scrim implements View.OnAttachStateChangeListener,
WallpaperColorInfo.OnChangeListener {
- public static final Property<Scrim, Float> SCRIM_PROGRESS =
- new Property<Scrim, Float>(Float.TYPE, "scrimProgress") {
+ public static final FloatProperty<Scrim> SCRIM_PROGRESS =
+ new FloatProperty<Scrim>("scrimProgress") {
@Override
public Float get(Scrim scrim) {
return scrim.mScrimProgress;
}
@Override
- public void set(Scrim scrim, Float value) {
- scrim.setScrimProgress(value);
+ public void setValue(Scrim scrim, float v) {
+ scrim.setScrimProgress(v);
}
};
diff --git a/src/com/android/launcher3/graphics/WorkspaceAndHotseatScrim.java b/src/com/android/launcher3/graphics/WorkspaceAndHotseatScrim.java
index 5a1dcab..7b7ab5e 100644
--- a/src/com/android/launcher3/graphics/WorkspaceAndHotseatScrim.java
+++ b/src/com/android/launcher3/graphics/WorkspaceAndHotseatScrim.java
@@ -19,6 +19,7 @@
import static android.content.Intent.ACTION_SCREEN_OFF;
import static android.content.Intent.ACTION_USER_PRESENT;
+import static com.android.launcher3.config.FeatureFlags.KEYGUARD_ANIMATION;
import static com.android.launcher3.icons.GraphicsUtils.setColorAlphaBound;
import android.animation.ObjectAnimator;
@@ -37,14 +38,16 @@
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
-import android.util.Property;
+import android.util.FloatProperty;
import android.view.View;
+import android.view.WindowInsets;
import androidx.core.graphics.ColorUtils;
import com.android.launcher3.CellLayout;
import com.android.launcher3.R;
import com.android.launcher3.ResourceUtils;
+import com.android.launcher3.Utilities;
import com.android.launcher3.Workspace;
import com.android.launcher3.uioverrides.WallpaperColorInfo;
import com.android.launcher3.util.Themes;
@@ -54,33 +57,37 @@
*/
public class WorkspaceAndHotseatScrim extends Scrim {
- public static final Property<WorkspaceAndHotseatScrim, Float> SYSUI_PROGRESS =
- new Property<WorkspaceAndHotseatScrim, Float>(Float.TYPE, "sysUiProgress") {
+ public static final FloatProperty<WorkspaceAndHotseatScrim> SYSUI_PROGRESS =
+ new FloatProperty<WorkspaceAndHotseatScrim>("sysUiProgress") {
@Override
public Float get(WorkspaceAndHotseatScrim scrim) {
return scrim.mSysUiProgress;
}
@Override
- public void set(WorkspaceAndHotseatScrim scrim, Float value) {
+ public void setValue(WorkspaceAndHotseatScrim scrim, float value) {
scrim.setSysUiProgress(value);
}
};
- private static final Property<WorkspaceAndHotseatScrim, Float> SYSUI_ANIM_MULTIPLIER =
- new Property<WorkspaceAndHotseatScrim, Float>(Float.TYPE, "sysUiAnimMultiplier") {
+ private static final FloatProperty<WorkspaceAndHotseatScrim> SYSUI_ANIM_MULTIPLIER =
+ new FloatProperty<WorkspaceAndHotseatScrim>("sysUiAnimMultiplier") {
@Override
public Float get(WorkspaceAndHotseatScrim scrim) {
return scrim.mSysUiAnimMultiplier;
}
@Override
- public void set(WorkspaceAndHotseatScrim scrim, Float value) {
+ public void setValue(WorkspaceAndHotseatScrim scrim, float value) {
scrim.mSysUiAnimMultiplier = value;
scrim.reapplySysUiAlpha();
}
};
+ /**
+ * Receiver used to get a signal that the user unlocked their device.
+ * @see KEYGUARD_ANIMATION For proper signal.
+ */
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
@@ -164,8 +171,10 @@
mSysUiAnimMultiplier = 0;
reapplySysUiAlphaNoInvalidate();
- animateToSysuiMultiplier(1, 600,
- mLauncher.getWindow().getTransitionBackgroundFadeDuration());
+ ObjectAnimator oa = createSysuiMultiplierAnim(1);
+ oa.setDuration(600);
+ oa.setStartDelay(mLauncher.getWindow().getTransitionBackgroundFadeDuration());
+ oa.start();
mAnimateScrimOnNextDraw = false;
}
@@ -178,26 +187,42 @@
}
}
- public void animateToSysuiMultiplier(float toMultiplier, long duration,
- long startDelay) {
- ObjectAnimator anim = ObjectAnimator.ofFloat(this, SYSUI_ANIM_MULTIPLIER, toMultiplier);
+ /**
+ * @return an ObjectAnimator that controls the fade in/out of the sys ui scrim.
+ */
+ public ObjectAnimator createSysuiMultiplierAnim(float... values) {
+ ObjectAnimator anim = ObjectAnimator.ofFloat(this, SYSUI_ANIM_MULTIPLIER, values);
anim.setAutoCancel(true);
- anim.setDuration(duration);
- anim.setStartDelay(startDelay);
- anim.start();
+ return anim;
}
- public void onInsetsChanged(Rect insets) {
- mDrawTopScrim = mTopScrim != null && insets.top > 0;
- mDrawBottomScrim = mBottomMask != null &&
- !mLauncher.getDeviceProfile().isVerticalBarLayout();
+ /**
+ * Determines whether to draw the top and/or bottom scrim based on new insets.
+ */
+ public void onInsetsChanged(Rect insets, boolean allowSysuiScrims) {
+ mDrawTopScrim = allowSysuiScrims
+ && mTopScrim != null
+ && insets.top > 0;
+ mDrawBottomScrim = allowSysuiScrims
+ && mBottomMask != null
+ && !mLauncher.getDeviceProfile().isVerticalBarLayout()
+ && hasBottomNavButtons();
+ }
+
+ private boolean hasBottomNavButtons() {
+ if (Utilities.ATLEAST_Q && mLauncher.getRootView() != null
+ && mLauncher.getRootView().getRootWindowInsets() != null) {
+ WindowInsets windowInsets = mLauncher.getRootView().getRootWindowInsets();
+ return windowInsets.getTappableElementInsets().bottom > 0;
+ }
+ return true;
}
@Override
public void onViewAttachedToWindow(View view) {
super.onViewAttachedToWindow(view);
- if (mTopScrim != null) {
+ if (!KEYGUARD_ANIMATION.get() && mTopScrim != null) {
IntentFilter filter = new IntentFilter(ACTION_SCREEN_OFF);
filter.addAction(ACTION_USER_PRESENT); // When the device wakes up + keyguard is gone
mRoot.getContext().registerReceiver(mReceiver, filter);
@@ -207,7 +232,7 @@
@Override
public void onViewDetachedFromWindow(View view) {
super.onViewDetachedFromWindow(view);
- if (mTopScrim != null) {
+ if (!KEYGUARD_ANIMATION.get() && mTopScrim != null) {
mRoot.getContext().unregisterReceiver(mReceiver);
}
}
@@ -229,14 +254,6 @@
}
}
- public void hideSysUiScrim(boolean hideSysUiScrim) {
- mHideSysUiScrim = hideSysUiScrim || (mTopScrim == null);
- if (!hideSysUiScrim) {
- mAnimateScrimOnNextDraw = true;
- }
- invalidate();
- }
-
private void setSysUiProgress(float progress) {
if (progress != mSysUiProgress) {
mSysUiProgress = progress;
diff --git a/src/com/android/launcher3/icons/IconCache.java b/src/com/android/launcher3/icons/IconCache.java
index 804acc3..ff0f773 100644
--- a/src/com/android/launcher3/icons/IconCache.java
+++ b/src/com/android/launcher3/icons/IconCache.java
@@ -38,18 +38,18 @@
import androidx.annotation.NonNull;
-import com.android.launcher3.AppInfo;
import com.android.launcher3.InvariantDeviceProfile;
-import com.android.launcher3.ItemInfoWithIcon;
import com.android.launcher3.LauncherFiles;
import com.android.launcher3.Utilities;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.icons.ComponentWithLabel.ComponentCachingLogic;
import com.android.launcher3.icons.cache.BaseIconCache;
import com.android.launcher3.icons.cache.CachingLogic;
import com.android.launcher3.icons.cache.HandlerRunnable;
-import com.android.launcher3.model.PackageItemInfo;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.ItemInfoWithIcon;
+import com.android.launcher3.model.data.PackageItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.pm.UserCache;
import com.android.launcher3.shortcuts.ShortcutKey;
import com.android.launcher3.util.ComponentKey;
@@ -81,9 +81,13 @@
private int mPendingIconRequestCount = 0;
- public IconCache(Context context, InvariantDeviceProfile inv) {
- super(context, LauncherFiles.APP_ICONS_DB, MODEL_EXECUTOR.getLooper(),
- inv.fillResIconDpi, inv.iconBitmapSize, true /* inMemoryCache */);
+ public IconCache(Context context, InvariantDeviceProfile idp) {
+ this(context, idp, LauncherFiles.APP_ICONS_DB);
+ }
+
+ public IconCache(Context context, InvariantDeviceProfile idp, String dbFileName) {
+ super(context, dbFileName, MODEL_EXECUTOR.getLooper(),
+ idp.fillResIconDpi, idp.iconBitmapSize, true /* inMemoryCache */);
mComponentWithLabelCachingLogic = new ComponentCachingLogic(context, false);
mLauncherActivityInfoCachingLogic = LauncherActivityCachingLogic.newInstance(context);
mShortcutCachingLogic = new ShortcutCachingLogic();
diff --git a/src/com/android/launcher3/icons/LauncherIcons.java b/src/com/android/launcher3/icons/LauncherIcons.java
index cbd7c53..bf7897e 100644
--- a/src/com/android/launcher3/icons/LauncherIcons.java
+++ b/src/com/android/launcher3/icons/LauncherIcons.java
@@ -19,8 +19,8 @@
import android.content.Context;
import com.android.launcher3.InvariantDeviceProfile;
-import com.android.launcher3.LauncherAppState;
import com.android.launcher3.graphics.IconShape;
+import com.android.launcher3.graphics.LauncherPreviewRenderer;
/**
* Wrapper class to provide access to {@link BaseIconFactory} and also to provide pool of this class
@@ -41,6 +41,11 @@
* avoid allocating new objects in many cases.
*/
public static LauncherIcons obtain(Context context, boolean shapeDetection) {
+ if (context instanceof LauncherPreviewRenderer.PreviewContext) {
+ return ((LauncherPreviewRenderer.PreviewContext) context).newLauncherIcons(context,
+ shapeDetection);
+ }
+
int poolId;
synchronized (sPoolSync) {
if (sPool != null) {
@@ -52,7 +57,7 @@
poolId = sPoolId;
}
- InvariantDeviceProfile idp = LauncherAppState.getIDP(context);
+ InvariantDeviceProfile idp = InvariantDeviceProfile.INSTANCE.get(context);
return new LauncherIcons(context, idp.fillResIconDpi, idp.iconBitmapSize, poolId,
shapeDetection);
}
@@ -68,7 +73,7 @@
private LauncherIcons next;
- private LauncherIcons(Context context, int fillResIconDpi, int iconBitmapSize, int poolId,
+ protected LauncherIcons(Context context, int fillResIconDpi, int iconBitmapSize, int poolId,
boolean shapeDetection) {
super(context, fillResIconDpi, iconBitmapSize, shapeDetection);
mPoolId = poolId;
diff --git a/src/com/android/launcher3/keyboard/CustomActionsPopup.java b/src/com/android/launcher3/keyboard/CustomActionsPopup.java
index 938955c..800598e 100644
--- a/src/com/android/launcher3/keyboard/CustomActionsPopup.java
+++ b/src/com/android/launcher3/keyboard/CustomActionsPopup.java
@@ -24,9 +24,9 @@
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.Launcher;
import com.android.launcher3.accessibility.LauncherAccessibilityDelegate;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.popup.PopupContainerWithArrow;
import java.util.ArrayList;
diff --git a/src/com/android/launcher3/logging/DumpTargetWrapper.java b/src/com/android/launcher3/logging/DumpTargetWrapper.java
deleted file mode 100644
index 067bdfd..0000000
--- a/src/com/android/launcher3/logging/DumpTargetWrapper.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * 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.launcher3.logging;
-
-import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT;
-
-import android.content.ComponentName;
-import android.os.Process;
-import android.text.TextUtils;
-
-import com.android.launcher3.ItemInfo;
-import com.android.launcher3.LauncherAppWidgetInfo;
-import com.android.launcher3.LauncherSettings;
-import com.android.launcher3.WorkspaceItemInfo;
-import com.android.launcher3.model.nano.LauncherDumpProto;
-import com.android.launcher3.model.nano.LauncherDumpProto.ContainerType;
-import com.android.launcher3.model.nano.LauncherDumpProto.DumpTarget;
-import com.android.launcher3.model.nano.LauncherDumpProto.ItemType;
-import com.android.launcher3.model.nano.LauncherDumpProto.UserType;
-import com.android.launcher3.util.ShortcutUtil;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * This class can be used when proto definition doesn't support nesting.
- */
-public class DumpTargetWrapper {
- DumpTarget node;
- ArrayList<DumpTargetWrapper> children;
-
- public DumpTargetWrapper() {
- children = new ArrayList<>();
- }
-
- public DumpTargetWrapper(int containerType, int id) {
- this();
- node = newContainerTarget(containerType, id);
- }
-
- public DumpTargetWrapper(ItemInfo info) {
- this();
- node = newItemTarget(info);
- }
-
- public DumpTarget getDumpTarget() {
- return node;
- }
-
- public void add(DumpTargetWrapper child) {
- children.add(child);
- }
-
- public List<DumpTarget> getFlattenedList() {
- ArrayList<DumpTarget> list = new ArrayList<>();
- list.add(node);
- if (!children.isEmpty()) {
- for(DumpTargetWrapper t: children) {
- list.addAll(t.getFlattenedList());
- }
- list.add(node); // add a delimiter empty object
- }
- return list;
- }
- public DumpTarget newItemTarget(ItemInfo info) {
- DumpTarget dt = new DumpTarget();
- dt.type = DumpTarget.Type.ITEM;
- if (info == null) {
- return dt;
- }
- switch (info.itemType) {
- case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
- dt.itemType = ItemType.APP_ICON;
- break;
- case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
- dt.itemType = ItemType.WIDGET;
- break;
- case ITEM_TYPE_DEEP_SHORTCUT:
- case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
- dt.itemType = ItemType.SHORTCUT;
- break;
- default:
- dt.itemType = ItemType.UNKNOWN_ITEMTYPE;
- break;
- }
- return dt;
- }
-
- public DumpTarget newContainerTarget(int type, int id) {
- DumpTarget dt = new DumpTarget();
- dt.type = DumpTarget.Type.CONTAINER;
- dt.containerType = type;
- dt.pageId = id;
- return dt;
- }
-
- public static String getDumpTargetStr(DumpTarget t) {
- if (t == null){
- return "";
- }
- switch (t.type) {
- case LauncherDumpProto.DumpTarget.Type.ITEM:
- return getItemStr(t);
- case LauncherDumpProto.DumpTarget.Type.CONTAINER:
- String str = LoggerUtils.getFieldName(t.containerType, ContainerType.class);
- if (t.containerType == ContainerType.WORKSPACE) {
- str += " id=" + t.pageId;
- } else if (t.containerType == ContainerType.FOLDER) {
- str += " grid(" + t.gridX + "," + t.gridY+ ")";
- }
- return str;
- default:
- return "UNKNOWN TARGET TYPE";
- }
- }
-
- private static String getItemStr(DumpTarget t) {
- if (t == null) {
- return "";
- }
- String typeStr = LoggerUtils.getFieldName(t.itemType, ItemType.class);
- if (!TextUtils.isEmpty(t.packageName)) {
- typeStr += ", package=" + t.packageName;
- }
- if (!TextUtils.isEmpty(t.component)) {
- typeStr += ", component=" + t.component;
- }
- return typeStr + ", grid(" + t.gridX + "," + t.gridY + "), span(" + t.spanX + "," + t.spanY
- + "), pageIdx=" + t.pageId + " user=" + t.userType;
- }
-
- public DumpTarget writeToDumpTarget(ItemInfo info) {
- if (info == null) {
- return node;
- }
- if (ShortcutUtil.isDeepShortcut(info)) {
- node.component = ((WorkspaceItemInfo) info).getDeepShortcutId();
- } else {
- ComponentName cmp = info.getTargetComponent();
- node.component = cmp == null ? "" : cmp.flattenToString();
- }
- node.packageName = info.getTargetComponent() == null? "":
- info.getTargetComponent().getPackageName();
- if (info instanceof LauncherAppWidgetInfo) {
- node.component = ((LauncherAppWidgetInfo) info).providerName.flattenToString();
- node.packageName = ((LauncherAppWidgetInfo) info).providerName.getPackageName();
- }
-
- node.gridX = info.cellX;
- node.gridY = info.cellY;
- node.spanX = info.spanX;
- node.spanY = info.spanY;
- node.userType = (info.user.equals(Process.myUserHandle()))? UserType.DEFAULT : UserType.WORK;
- return node;
- }
-}
diff --git a/src/com/android/launcher3/logging/FileLog.java b/src/com/android/launcher3/logging/FileLog.java
index 2c972a0..bfeb1dc 100644
--- a/src/com/android/launcher3/logging/FileLog.java
+++ b/src/com/android/launcher3/logging/FileLog.java
@@ -10,6 +10,7 @@
import androidx.annotation.VisibleForTesting;
+import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.util.IOUtils;
import java.io.BufferedReader;
@@ -37,12 +38,12 @@
private static final DateFormat DATE_FORMAT =
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
- private static final long MAX_LOG_FILE_SIZE = 4 << 20; // 4 mb
+ private static final long MAX_LOG_FILE_SIZE = 8 << 20; // 4 mb
private static Handler sHandler = null;
private static File sLogsDirectory = null;
- private static final int LOG_DAYS = 2;
+ public static final int LOG_DAYS = FeatureFlags.ENABLE_HYBRID_HOTSEAT.get() ? 10 : 4;
public static void setDir(File logsDir) {
if (ENABLED) {
diff --git a/src/com/android/launcher3/logging/LauncherUiEvent.java b/src/com/android/launcher3/logging/LauncherUiEvent.java
new file mode 100644
index 0000000..4507ff7
--- /dev/null
+++ b/src/com/android/launcher3/logging/LauncherUiEvent.java
@@ -0,0 +1,30 @@
+/*
+ * 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.launcher3.logging;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.RetentionPolicy.SOURCE;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+@Retention(SOURCE)
+@Target(FIELD)
+public @interface LauncherUiEvent {
+ /** An explanation, suitable for Android analysts, of the UI event that this log represents. */
+ String doc();
+}
+
diff --git a/src/com/android/launcher3/logging/LoggerUtils.java b/src/com/android/launcher3/logging/LoggerUtils.java
index b004edf..0f79bd6 100644
--- a/src/com/android/launcher3/logging/LoggerUtils.java
+++ b/src/com/android/launcher3/logging/LoggerUtils.java
@@ -15,28 +15,24 @@
*/
package com.android.launcher3.logging;
-import static com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType.NAVBAR;
-
import android.util.ArrayMap;
import android.util.SparseArray;
import android.view.View;
-import com.android.launcher3.AppInfo;
import com.android.launcher3.ButtonDropTarget;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherSettings;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.userevent.nano.LauncherLogExtensions.TargetExtension;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action;
-import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
-import com.android.launcher3.userevent.nano.LauncherLogProto.ControlType;
import com.android.launcher3.userevent.nano.LauncherLogProto.ItemType;
import com.android.launcher3.userevent.nano.LauncherLogProto.LauncherEvent;
import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
-import com.android.launcher3.userevent.nano.LauncherLogProto.TipType;
import com.android.launcher3.util.InstantAppResolver;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
+import java.util.ArrayList;
/**
* Helper methods for logging.
@@ -69,93 +65,6 @@
return result != null ? result : UNKNOWN;
}
- public static String getActionStr(Action action) {
- String str = "";
- switch (action.type) {
- case Action.Type.TOUCH:
- str += getFieldName(action.touch, Action.Touch.class);
- if (action.touch == Action.Touch.SWIPE || action.touch == Action.Touch.FLING) {
- str += " direction=" + getFieldName(action.dir, Action.Direction.class);
- }
- break;
- case Action.Type.COMMAND:
- str += getFieldName(action.command, Action.Command.class);
- break;
- default: return getFieldName(action.type, Action.Type.class);
- }
- if (action.touch == Action.Touch.SWIPE || action.touch == Action.Touch.FLING ||
- (action.command == Action.Command.BACK && action.dir != Action.Direction.NONE)) {
- str += " direction=" + getFieldName(action.dir, Action.Direction.class);
- }
- return str;
- }
-
- public static String getTargetStr(Target t) {
- if (t == null) {
- return "";
- }
- String str = "";
- switch (t.type) {
- case Target.Type.ITEM:
- str = getItemStr(t);
- break;
- case Target.Type.CONTROL:
- str = getFieldName(t.controlType, ControlType.class);
- break;
- case Target.Type.CONTAINER:
- str = getFieldName(t.containerType, ContainerType.class);
- if (t.containerType == ContainerType.WORKSPACE ||
- t.containerType == ContainerType.HOTSEAT ||
- t.containerType == NAVBAR) {
- str += " id=" + t.pageIndex;
- } else if (t.containerType == ContainerType.FOLDER) {
- str += " grid(" + t.gridX + "," + t.gridY + ")";
- }
- break;
- default:
- str += "UNKNOWN TARGET TYPE";
- }
-
- if (t.spanX != 1 || t.spanY != 1) {
- str += " span(" + t.spanX + "," + t.spanY + ")";
- }
-
- if (t.tipType != TipType.DEFAULT_NONE) {
- str += " " + getFieldName(t.tipType, TipType.class);
- }
-
- return str;
- }
-
- private static String getItemStr(Target t) {
- String typeStr = getFieldName(t.itemType, ItemType.class);
- if (t.packageNameHash != 0) {
- typeStr += ", packageHash=" + t.packageNameHash;
- }
- if (t.componentHash != 0) {
- typeStr += ", componentHash=" + t.componentHash;
- }
- if (t.intentHash != 0) {
- typeStr += ", intentHash=" + t.intentHash;
- }
- if (t.itemType == ItemType.FOLDER_ICON) {
- typeStr += ", grid(" + t.gridX + "," + t.gridY + ")";
- } else if ((t.packageNameHash != 0 || t.componentHash != 0 || t.intentHash != 0)
- && t.itemType != ItemType.TASK) {
- typeStr +=
- ", isWorkApp=" + t.isWorkApp + ", predictiveRank=" + t.predictedRank + ", grid("
- + t.gridX + "," + t.gridY + "), span(" + t.spanX + "," + t.spanY
- + "), pageIdx=" + t.pageIndex;
- }
- if (t.searchQueryLength != 0) {
- typeStr += ", searchQueryLength=" + t.searchQueryLength;
- }
- if (t.itemType == ItemType.TASK) {
- typeStr += ", pageIdx=" + t.pageIndex;
- }
- return typeStr;
- }
-
public static Target newItemTarget(int itemType) {
Target t = newTarget(Target.Type.ITEM);
t.itemType = itemType;
@@ -255,4 +164,13 @@
event.action = action;
return event;
}
+
+ /**
+ * Creates LauncherEvent using Action and ArrayList of Targets
+ */
+ public static LauncherEvent newLauncherEvent(Action action, ArrayList<Target> targets) {
+ Target[] targetsArray = new Target[targets.size()];
+ targets.toArray(targetsArray);
+ return newLauncherEvent(action, targetsArray);
+ }
}
diff --git a/src/com/android/launcher3/logging/StatsLogManager.java b/src/com/android/launcher3/logging/StatsLogManager.java
index 9dfd7ab..2829951 100644
--- a/src/com/android/launcher3/logging/StatsLogManager.java
+++ b/src/com/android/launcher3/logging/StatsLogManager.java
@@ -16,23 +16,44 @@
package com.android.launcher3.logging;
import android.content.Context;
-import android.content.Intent;
-import android.os.UserHandle;
-import android.view.View;
-
-import androidx.annotation.Nullable;
import com.android.launcher3.R;
+import com.android.launcher3.logger.LauncherAtom;
+import com.android.launcher3.logger.LauncherAtom.ItemInfo;
import com.android.launcher3.logging.StatsLogUtils.LogStateProvider;
-import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.ResourceBasedOverride;
/**
- * Handles the user event logging in Q.
+ * Handles the user event logging in R+.
*/
public class StatsLogManager implements ResourceBasedOverride {
+ interface EventEnum {
+ int getId();
+ }
+
+ public enum LauncherEvent implements EventEnum {
+ @LauncherUiEvent(doc = "App launched from workspace, hotseat or folder in launcher")
+ APP_LAUNCH_TAP(1),
+ @LauncherUiEvent(doc = "Task launched from overview using TAP")
+ TASK_LAUNCH_TAP(2),
+ @LauncherUiEvent(doc = "Task launched from overview using SWIPE DOWN")
+ TASK_LAUNCH_SWIPE_DOWN(2),
+ @LauncherUiEvent(doc = "TASK dismissed from overview using SWIPE UP")
+ TASK_DISMISS_SWIPE_UP(3);
+ // ADD MORE
+
+ private final int mId;
+ LauncherEvent(int id) {
+ mId = id;
+ }
+ public int getId() {
+ return mId;
+ }
+ }
+
protected LogStateProvider mStateProvider;
+
public static StatsLogManager newInstance(Context context, LogStateProvider stateProvider) {
StatsLogManager mgr = Overrides.getObject(StatsLogManager.class,
context.getApplicationContext(), R.string.stats_log_manager_class);
@@ -42,11 +63,14 @@
}
/**
- * Logs app launches
+ * Logs an event and accompanying {@link ItemInfo}
*/
- public void logAppLaunch(View v, Intent intent, @Nullable UserHandle userHandle) { }
- public void logTaskLaunch(View v, ComponentKey key) { }
- public void logTaskDismiss(View v, ComponentKey key) { }
- public void logSwipeOnContainer(boolean isSwipingToLeft, int pageId) { }
+ public void log(LauncherEvent eventId, LauncherAtom.ItemInfo itemInfo) { }
+
+ /**
+ * Logs snapshot, or impression of the current workspace.
+ */
+ public void logSnapshot() { }
+
public void verify() {} // TODO: should move into robo tests
}
diff --git a/src/com/android/launcher3/logging/StatsLogUtils.java b/src/com/android/launcher3/logging/StatsLogUtils.java
index b02a050..97aaf84 100644
--- a/src/com/android/launcher3/logging/StatsLogUtils.java
+++ b/src/com/android/launcher3/logging/StatsLogUtils.java
@@ -5,11 +5,13 @@
import android.view.View;
import android.view.ViewParent;
-import com.android.launcher3.ItemInfo;
+import androidx.annotation.Nullable;
+
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
-import androidx.annotation.Nullable;
+import java.util.ArrayList;
public class StatsLogUtils {
@@ -35,14 +37,9 @@
public interface LogContainerProvider {
/**
- * Copies data from the source to the destination proto.
- *
- * @param v source of the data
- * @param info source of the data
- * @param target dest of the data
- * @param targetParent dest of the data
+ * Populates parent container targets for an item
*/
- void fillInLogContainerData(View v, ItemInfo info, Target target, Target targetParent);
+ void fillInLogContainerData(ItemInfo childInfo, Target child, ArrayList<Target> parents);
}
/**
diff --git a/src/com/android/launcher3/logging/UserEventDispatcher.java b/src/com/android/launcher3/logging/UserEventDispatcher.java
index 8289da9..da081a0 100644
--- a/src/com/android/launcher3/logging/UserEventDispatcher.java
+++ b/src/com/android/launcher3/logging/UserEventDispatcher.java
@@ -25,6 +25,9 @@
import static com.android.launcher3.logging.LoggerUtils.newLauncherEvent;
import static com.android.launcher3.logging.LoggerUtils.newTarget;
import static com.android.launcher3.logging.LoggerUtils.newTouchAction;
+import static com.android.launcher3.userevent.nano.LauncherLogProto.ControlType;
+import static com.android.launcher3.userevent.nano.LauncherLogProto.ItemType;
+import static com.android.launcher3.userevent.nano.LauncherLogProto.TipType;
import static java.util.Optional.ofNullable;
@@ -43,12 +46,12 @@
import androidx.annotation.Nullable;
import com.android.launcher3.DropTarget;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.logging.StatsLogUtils.LogContainerProvider;
-import com.android.launcher3.userevent.nano.LauncherLogProto;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.userevent.LauncherLogProto;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action;
import com.android.launcher3.userevent.nano.LauncherLogProto.LauncherEvent;
import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
@@ -57,7 +60,11 @@
import com.android.launcher3.util.LogConfig;
import com.android.launcher3.util.ResourceBasedOverride;
-import java.util.Locale;
+import com.google.protobuf.InvalidProtocolBufferException;
+import com.google.protobuf.nano.InvalidProtocolBufferNanoException;
+import com.google.protobuf.nano.MessageNano;
+
+import java.util.ArrayList;
import java.util.UUID;
/**
@@ -69,12 +76,13 @@
public class UserEventDispatcher implements ResourceBasedOverride {
private static final String TAG = "UserEvent";
- private static final boolean IS_VERBOSE =
- FeatureFlags.IS_DOGFOOD_BUILD && Utilities.isPropertyEnabled(LogConfig.USEREVENT);
+ private static final boolean IS_VERBOSE = Utilities.isPropertyEnabled(LogConfig.USEREVENT);
private static final String UUID_STORAGE = "uuid";
- public static UserEventDispatcher newInstance(Context context,
- UserEventDelegate delegate) {
+ /**
+ * A factory method for UserEventDispatcher
+ */
+ public static UserEventDispatcher newInstance(Context context) {
SharedPreferences sharedPrefs = Utilities.getDevicePrefs(context);
String uuidStr = sharedPrefs.getString(UUID_STORAGE, null);
if (uuidStr == null) {
@@ -83,41 +91,31 @@
}
UserEventDispatcher ued = Overrides.getObject(UserEventDispatcher.class,
context.getApplicationContext(), R.string.user_event_dispatcher_class);
- ued.mDelegate = delegate;
ued.mUuidStr = uuidStr;
ued.mInstantAppResolver = InstantAppResolver.newInstance(context);
return ued;
}
- public static UserEventDispatcher newInstance(Context context) {
- return newInstance(context, null);
- }
-
- public interface UserEventDelegate {
- void modifyUserEvent(LauncherEvent event);
- }
/**
* Fills in the container data on the given event if the given view is not null.
*
* @return whether container data was added.
*/
- public boolean fillInLogContainerData(LauncherLogProto.LauncherEvent event, @Nullable View v) {
- // Fill in grid(x,y), pageIndex of the child and container type of the parent
- LogContainerProvider provider = StatsLogUtils.getLaunchProviderRecursive(v);
- if (v == null || !(v.getTag() instanceof ItemInfo) || provider == null) {
+ public boolean fillLogContainer(@Nullable View v, Target child,
+ @Nullable ArrayList<Target> targets) {
+ LogContainerProvider firstParent = StatsLogUtils.getLaunchProviderRecursive(v);
+ if (v == null || !(v.getTag() instanceof ItemInfo) || firstParent == null) {
return false;
}
final ItemInfo itemInfo = (ItemInfo) v.getTag();
- final Target target = event.srcTarget[0];
- final Target targetParent = event.srcTarget[1];
- onFillInLogContainerData(itemInfo, target, targetParent);
- provider.fillInLogContainerData(v, itemInfo, target, targetParent);
+ firstParent.fillInLogContainerData(itemInfo, child, targets);
return true;
}
- protected void onFillInLogContainerData(
- @NonNull ItemInfo itemInfo, @NonNull Target target, @NonNull Target targetParent) { }
+ protected void onFillInLogContainerData(@NonNull ItemInfo itemInfo, @NonNull Target target,
+ @NonNull ArrayList<Target> targets) {
+ }
private boolean mSessionStarted;
private long mElapsedContainerMillis;
@@ -126,7 +124,6 @@
private String mUuidStr;
protected InstantAppResolver mInstantAppResolver;
private boolean mAppOrTaskLaunch;
- private UserEventDelegate mDelegate;
private boolean mPreviousHomeGesture;
// APP_ICON SHORTCUT WIDGET
@@ -137,18 +134,17 @@
// --------------------------------------------------------------
@Deprecated
- public void logAppLaunch(View v, Intent intent, @Nullable UserHandle userHandle) {
- LauncherEvent event = newLauncherEvent(newTouchAction(Action.Touch.TAP),
- newItemTarget(v, mInstantAppResolver), newTarget(Target.Type.CONTAINER));
-
- if (fillInLogContainerData(event, v)) {
- if (mDelegate != null) {
- mDelegate.modifyUserEvent(event);
- }
- fillIntentInfo(event.srcTarget[0], intent, userHandle);
+ public void logAppLaunch(View v, Intent intent, @Nullable UserHandle userHandle) {
+ Target itemTarget = newItemTarget(v, mInstantAppResolver);
+ Action action = newTouchAction(Action.Touch.TAP);
+ ArrayList<Target> targets = makeTargetsList(itemTarget);
+ if (fillLogContainer(v, itemTarget, targets)) {
+ onFillInLogContainerData((ItemInfo) v.getTag(), itemTarget, targets);
+ fillIntentInfo(itemTarget, intent, userHandle);
}
- ItemInfo info = (ItemInfo) v.getTag();
- if (Utilities.IS_DEBUG_DEVICE && FeatureFlags.ENABLE_HYBRID_HOTSEAT.get()) {
+ LauncherEvent event = newLauncherEvent(action, targets);
+ ItemInfo info = v == null ? null : (ItemInfo) v.getTag();
+ if (info != null && Utilities.IS_DEBUG_DEVICE && FeatureFlags.ENABLE_HYBRID_HOTSEAT.get()) {
FileLog.d(TAG, "appLaunch: packageName:" + info.getTargetComponent().getPackageName()
+ ",isWorkApp:" + (info.user != null && !Process.myUserHandle().equals(
userHandle)) + ",launchLocation:" + info.container);
@@ -172,7 +168,7 @@
// Direction DOWN means the task was launched, UP means it was dismissed.
event.action.dir = direction;
}
- event.srcTarget[0].itemType = LauncherLogProto.ItemType.TASK;
+ event.srcTarget[0].itemType = ItemType.TASK;
event.srcTarget[0].pageIndex = taskIndex;
fillComponentInfo(event.srcTarget[0], componentKey.componentName);
dispatchUserEvent(event, null);
@@ -195,8 +191,11 @@
public void logNotificationLaunch(View v, PendingIntent intent) {
LauncherEvent event = newLauncherEvent(newTouchAction(Action.Touch.TAP),
newItemTarget(v, mInstantAppResolver), newTarget(Target.Type.CONTAINER));
- if (fillInLogContainerData(event, v)) {
- event.srcTarget[0].packageNameHash = (mUuidStr + intent.getCreatorPackage()).hashCode();
+ Target itemTarget = newItemTarget(v, mInstantAppResolver);
+ ArrayList<Target> targets = makeTargetsList(itemTarget);
+
+ if (fillLogContainer(v, itemTarget, targets)) {
+ itemTarget.packageNameHash = (mUuidStr + intent.getCreatorPackage()).hashCode();
}
dispatchUserEvent(event, null);
}
@@ -242,50 +241,45 @@
LauncherEvent event = newLauncherEvent(newCommandAction(command),
newItemTarget(itemView, mInstantAppResolver), newTarget(Target.Type.CONTAINER));
- if (fillInLogContainerData(event, itemView)) {
+ Target itemTarget = newItemTarget(itemView, mInstantAppResolver);
+ ArrayList<Target> targets = makeTargetsList(itemTarget);
+
+ if (fillLogContainer(itemView, itemTarget, targets)) {
// TODO: Remove the following two lines once fillInLogContainerData can take in a
// container view.
- event.srcTarget[0].type = Target.Type.CONTAINER;
- event.srcTarget[0].containerType = srcContainerType;
+ itemTarget.type = Target.Type.CONTAINER;
+ itemTarget.containerType = srcContainerType;
}
dispatchUserEvent(event, null);
}
public void logActionOnControl(int action, int controlType) {
- logActionOnControl(action, controlType, null, -1);
+ logActionOnControl(action, controlType, null);
}
public void logActionOnControl(int action, int controlType, int parentContainerType) {
logActionOnControl(action, controlType, null, parentContainerType);
}
- public void logActionOnControl(int action, int controlType, @Nullable View controlInContainer) {
- logActionOnControl(action, controlType, controlInContainer, -1);
- }
+ /**
+ * Logs control action with proper parent hierarchy
+ */
+ public void logActionOnControl(int actionType, int controlType,
+ @Nullable View controlInContainer, int... parentTypes) {
+ Target control = newTarget(Target.Type.CONTROL);
+ control.controlType = controlType;
+ Action action = newAction(actionType);
- public void logActionOnControl(int action, int controlType, int parentContainer,
- int grandParentContainer) {
- LauncherEvent event = newLauncherEvent(newTouchAction(action),
- newControlTarget(controlType),
- newContainerTarget(parentContainer),
- newContainerTarget(grandParentContainer));
- dispatchUserEvent(event, null);
- }
-
- public void logActionOnControl(int action, int controlType, @Nullable View controlInContainer,
- int parentContainerType) {
- final LauncherEvent event = (controlInContainer == null && parentContainerType < 0)
- ? newLauncherEvent(newTouchAction(action), newTarget(Target.Type.CONTROL))
- : newLauncherEvent(newTouchAction(action), newTarget(Target.Type.CONTROL),
- newTarget(Target.Type.CONTAINER));
- event.srcTarget[0].controlType = controlType;
+ ArrayList<Target> targets = makeTargetsList(control);
if (controlInContainer != null) {
- fillInLogContainerData(event, controlInContainer);
+ fillLogContainer(controlInContainer, control, targets);
}
- if (parentContainerType >= 0) {
- event.srcTarget[1].containerType = parentContainerType;
+ for (int parentContainerType : parentTypes) {
+ if (parentContainerType < 0) continue;
+ targets.add(newContainerTarget(parentContainerType));
}
- if (action == Action.Touch.DRAGDROP) {
+ LauncherEvent event = newLauncherEvent(action, targets);
+ if (actionType == Action.Touch.DRAGDROP) {
event.actionDurationMillis = SystemClock.uptimeMillis() - mActionDurationMillis;
}
dispatchUserEvent(event, null);
@@ -301,7 +295,7 @@
public void logActionBounceTip(int containerType) {
LauncherEvent event = newLauncherEvent(newAction(Action.Type.TIP),
newContainerTarget(containerType));
- event.srcTarget[0].tipType = LauncherLogProto.TipType.BOUNCE;
+ event.srcTarget[0].tipType = TipType.BOUNCE;
dispatchUserEvent(event, null);
}
@@ -328,7 +322,7 @@
int srcChildTargetType, int srcParentContainerType, int dstContainerType,
int pageIndex) {
LauncherEvent event;
- if (srcChildTargetType == LauncherLogProto.ItemType.TASK) {
+ if (srcChildTargetType == ItemType.TASK) {
event = newLauncherEvent(newTouchAction(action),
newItemTarget(srcChildTargetType),
newContainerTarget(srcParentContainerType));
@@ -372,37 +366,57 @@
dispatchUserEvent(event, null);
}
- public void logDeepShortcutsOpen(View icon) {
- LogContainerProvider provider = StatsLogUtils.getLaunchProviderRecursive(icon);
- if (icon == null || !(icon.getTag() instanceof ItemInfo || provider == null)) {
- return;
- }
- ItemInfo info = (ItemInfo) icon.getTag();
- LauncherEvent event = newLauncherEvent(newTouchAction(Action.Touch.LONGPRESS),
- newItemTarget(info, mInstantAppResolver), newTarget(Target.Type.CONTAINER));
- provider.fillInLogContainerData(icon, info, event.srcTarget[0], event.srcTarget[1]);
- dispatchUserEvent(event, null);
+ /**
+ * Logs proto lite version of LauncherEvent object to clearcut.
+ */
+ public void logLauncherEvent(
+ com.android.launcher3.userevent.LauncherLogProto.LauncherEvent launcherEvent) {
+ if (mPreviousHomeGesture) {
+ mPreviousHomeGesture = false;
+ }
+ mAppOrTaskLaunch = false;
+ launcherEvent.toBuilder()
+ .setElapsedContainerMillis(SystemClock.uptimeMillis() - mElapsedContainerMillis)
+ .setElapsedSessionMillis(
+ SystemClock.uptimeMillis() - mElapsedSessionMillis).build();
+ try {
+ dispatchUserEvent(LauncherEvent.parseFrom(launcherEvent.toByteArray()), null);
+ } catch (InvalidProtocolBufferNanoException e) {
+ throw new RuntimeException("Cannot convert LauncherEvent from Lite to Nano version.");
+ }
+ }
+
+ public void logDeepShortcutsOpen(View icon) {
+ ItemInfo info = (ItemInfo) icon.getTag();
+ Target child = newItemTarget(info, mInstantAppResolver);
+ ArrayList<Target> targets = makeTargetsList(child);
+ fillLogContainer(icon, child, targets);
+ dispatchUserEvent(newLauncherEvent(newTouchAction(Action.Touch.TAP), targets), null);
resetElapsedContainerMillis("deep shortcut open");
}
public void logDragNDrop(DropTarget.DragObject dragObj, View dropTargetAsView) {
- LauncherEvent event = newLauncherEvent(newTouchAction(Action.Touch.DRAGDROP),
- newItemTarget(dragObj.originalDragInfo, mInstantAppResolver),
- newTarget(Target.Type.CONTAINER));
- event.destTarget = new Target[]{
- newItemTarget(dragObj.originalDragInfo, mInstantAppResolver),
- newDropTarget(dropTargetAsView)
- };
+ Target srcChild = newItemTarget(dragObj.originalDragInfo, mInstantAppResolver);
+ ArrayList<Target> srcTargets = makeTargetsList(srcChild);
- dragObj.dragSource.fillInLogContainerData(null, dragObj.originalDragInfo,
- event.srcTarget[0], event.srcTarget[1]);
+ Target destChild = newItemTarget(dragObj.originalDragInfo, mInstantAppResolver);
+ ArrayList<Target> destTargets = makeTargetsList(destChild);
+
+ dragObj.dragSource.fillInLogContainerData(dragObj.originalDragInfo, srcChild, srcTargets);
if (dropTargetAsView instanceof LogContainerProvider) {
- ((LogContainerProvider) dropTargetAsView).fillInLogContainerData(null,
- dragObj.dragInfo, event.destTarget[0], event.destTarget[1]);
-
+ ((LogContainerProvider) dropTargetAsView).fillInLogContainerData(dragObj.dragInfo,
+ destChild, destTargets);
}
+ else {
+ destTargets.add(newDropTarget(dropTargetAsView));
+ }
+ LauncherEvent event = newLauncherEvent(newTouchAction(Action.Touch.DRAGDROP), srcTargets);
+ Target[] destTargetsArray = new Target[destTargets.size()];
+ destTargets.toArray(destTargetsArray);
+ event.destTarget = destTargetsArray;
+
event.actionDurationMillis = SystemClock.uptimeMillis() - mActionDurationMillis;
dispatchUserEvent(event, null);
}
@@ -414,8 +428,8 @@
action.command = Action.Command.BACK;
action.dir = isButton ? Action.Direction.NONE :
gestureSwipeLeft ? Action.Direction.LEFT : Action.Direction.RIGHT;
- Target target = newControlTarget(isButton ? LauncherLogProto.ControlType.BACK_BUTTON :
- LauncherLogProto.ControlType.BACK_GESTURE);
+ Target target = newControlTarget(isButton ? ControlType.BACK_BUTTON :
+ ControlType.BACK_GESTURE);
target.spanX = downX;
target.spanY = downY;
target.cardinality = completed ? 1 : 0;
@@ -426,8 +440,6 @@
/**
* Currently logs following containers: workspace, allapps, widget tray.
- *
- * @param reason
*/
public final void resetElapsedContainerMillis(String reason) {
mElapsedContainerMillis = SystemClock.uptimeMillis();
@@ -466,34 +478,23 @@
if (!IS_VERBOSE) {
return;
}
- Log.d(TAG, generateLog(ev));
+ LauncherLogProto.LauncherEvent liteLauncherEvent;
+ try {
+ liteLauncherEvent =
+ LauncherLogProto.LauncherEvent.parseFrom(MessageNano.toByteArray(ev));
+ } catch (InvalidProtocolBufferException e) {
+ throw new RuntimeException("Cannot parse LauncherEvent from Nano to Lite version");
+ }
+ Log.d(TAG, liteLauncherEvent.toString());
}
/**
- * Returns a human-readable log for given user event.
+ * Constructs an ArrayList with targets
*/
- public static String generateLog(LauncherEvent ev) {
- String log = "\n-----------------------------------------------------"
- + "\naction:" + LoggerUtils.getActionStr(ev.action);
- if (ev.srcTarget != null && ev.srcTarget.length > 0) {
- log += "\n Source " + getTargetsStr(ev.srcTarget);
- }
- if (ev.destTarget != null && ev.destTarget.length > 0) {
- log += "\n Destination " + getTargetsStr(ev.destTarget);
- }
- log += String.format(Locale.US,
- "\n Elapsed container %d ms, session %d ms, action %d ms",
- ev.elapsedContainerMillis,
- ev.elapsedSessionMillis,
- ev.actionDurationMillis);
- log += "\n\n";
- return log;
- }
-
- private static String getTargetsStr(Target[] targets) {
- String result = "child:" + LoggerUtils.getTargetStr(targets[0]);
- for (int i = 1; i < targets.length; i++) {
- result += "\tparent:" + LoggerUtils.getTargetStr(targets[i]);
+ public static ArrayList<Target> makeTargetsList(Target... targets) {
+ ArrayList<Target> result = new ArrayList<>();
+ for (Target target : targets) {
+ result.add(target);
}
return result;
}
diff --git a/src/com/android/launcher3/model/AddWorkspaceItemsTask.java b/src/com/android/launcher3/model/AddWorkspaceItemsTask.java
index eb95395..c236fa6 100644
--- a/src/com/android/launcher3/model/AddWorkspaceItemsTask.java
+++ b/src/com/android/launcher3/model/AddWorkspaceItemsTask.java
@@ -23,16 +23,16 @@
import android.util.LongSparseArray;
import android.util.Pair;
-import com.android.launcher3.AppInfo;
-import com.android.launcher3.FolderInfo;
import com.android.launcher3.InvariantDeviceProfile;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppState;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherModel.CallbackTask;
import com.android.launcher3.LauncherSettings;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.model.BgDataModel.Callbacks;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.FolderInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.pm.InstallSessionHelper;
import com.android.launcher3.util.GridOccupancy;
import com.android.launcher3.util.IntArray;
diff --git a/src/com/android/launcher3/model/AllAppsList.java b/src/com/android/launcher3/model/AllAppsList.java
index 9f1843f..4f349ca 100644
--- a/src/com/android/launcher3/model/AllAppsList.java
+++ b/src/com/android/launcher3/model/AllAppsList.java
@@ -16,8 +16,8 @@
package com.android.launcher3.model;
-import static com.android.launcher3.AppInfo.COMPONENT_KEY_COMPARATOR;
-import static com.android.launcher3.AppInfo.EMPTY_ARRAY;
+import static com.android.launcher3.model.data.AppInfo.COMPONENT_KEY_COMPARATOR;
+import static com.android.launcher3.model.data.AppInfo.EMPTY_ARRAY;
import android.content.ComponentName;
import android.content.Context;
@@ -33,10 +33,10 @@
import androidx.annotation.Nullable;
import com.android.launcher3.AppFilter;
-import com.android.launcher3.AppInfo;
-import com.android.launcher3.PromiseAppInfo;
import com.android.launcher3.compat.AlphabeticIndexCompat;
import com.android.launcher3.icons.IconCache;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.PromiseAppInfo;
import com.android.launcher3.pm.PackageInstallInfo;
import com.android.launcher3.util.FlagOp;
import com.android.launcher3.util.ItemInfoMatcher;
diff --git a/src/com/android/launcher3/model/BaseLoaderResults.java b/src/com/android/launcher3/model/BaseLoaderResults.java
index 0d12183..c98be56 100644
--- a/src/com/android/launcher3/model/BaseLoaderResults.java
+++ b/src/com/android/launcher3/model/BaseLoaderResults.java
@@ -21,14 +21,14 @@
import android.util.Log;
-import com.android.launcher3.AppInfo;
import com.android.launcher3.InvariantDeviceProfile;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppState;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherModel.CallbackTask;
import com.android.launcher3.PagedView;
import com.android.launcher3.model.BgDataModel.Callbacks;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.LooperExecutor;
import com.android.launcher3.util.LooperIdleLock;
diff --git a/src/com/android/launcher3/model/BaseModelUpdateTask.java b/src/com/android/launcher3/model/BaseModelUpdateTask.java
index 5a7b4d3..7ce970d 100644
--- a/src/com/android/launcher3/model/BaseModelUpdateTask.java
+++ b/src/com/android/launcher3/model/BaseModelUpdateTask.java
@@ -17,13 +17,13 @@
import android.util.Log;
-import com.android.launcher3.AppInfo;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherModel;
import com.android.launcher3.LauncherModel.CallbackTask;
import com.android.launcher3.LauncherModel.ModelUpdateTask;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.model.BgDataModel.Callbacks;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.ItemInfoMatcher;
import com.android.launcher3.widget.WidgetListRowEntry;
diff --git a/src/com/android/launcher3/model/BgDataModel.java b/src/com/android/launcher3/model/BgDataModel.java
index c24b939..f79a9d1 100644
--- a/src/com/android/launcher3/model/BgDataModel.java
+++ b/src/com/android/launcher3/model/BgDataModel.java
@@ -26,20 +26,16 @@
import android.util.Log;
import android.util.MutableInt;
-import com.android.launcher3.AppInfo;
-import com.android.launcher3.FolderInfo;
import com.android.launcher3.InstallShortcutReceiver;
-import com.android.launcher3.ItemInfo;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherSettings;
-import com.android.launcher3.PromiseAppInfo;
import com.android.launcher3.Workspace;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.config.FeatureFlags;
-import com.android.launcher3.logging.DumpTargetWrapper;
-import com.android.launcher3.model.nano.LauncherDumpProto;
-import com.android.launcher3.model.nano.LauncherDumpProto.ContainerType;
-import com.android.launcher3.model.nano.LauncherDumpProto.DumpTarget;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.FolderInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
+import com.android.launcher3.model.data.PromiseAppInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.shortcuts.ShortcutKey;
import com.android.launcher3.shortcuts.ShortcutRequest;
import com.android.launcher3.util.ComponentKey;
@@ -50,11 +46,7 @@
import com.android.launcher3.util.ViewOnDrawExecutor;
import com.android.launcher3.widget.WidgetListRowEntry;
-import com.google.protobuf.nano.MessageNano;
-
import java.io.FileDescriptor;
-import java.io.FileOutputStream;
-import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
@@ -150,10 +142,6 @@
public synchronized void dump(String prefix, FileDescriptor fd, PrintWriter writer,
String[] args) {
- if (Arrays.asList(args).contains("--proto")) {
- dumpProto(prefix, fd, writer, args);
- return;
- }
writer.println(prefix + "Data Model:");
writer.println(prefix + " ---- workspace items ");
for (int i = 0; i < workspaceItems.size(); i++) {
@@ -181,89 +169,6 @@
}
}
- private synchronized void dumpProto(String prefix, FileDescriptor fd, PrintWriter writer,
- String[] args) {
-
- // Add top parent nodes. (L1)
- DumpTargetWrapper hotseat = new DumpTargetWrapper(ContainerType.HOTSEAT, 0);
- IntSparseArrayMap<DumpTargetWrapper> workspaces = new IntSparseArrayMap<>();
- IntArray workspaceScreens = collectWorkspaceScreens();
- for (int i = 0; i < workspaceScreens.size(); i++) {
- workspaces.put(workspaceScreens.get(i),
- new DumpTargetWrapper(ContainerType.WORKSPACE, i));
- }
- DumpTargetWrapper dtw;
- // Add non leaf / non top nodes (L2)
- for (int i = 0; i < folders.size(); i++) {
- FolderInfo fInfo = folders.valueAt(i);
- dtw = new DumpTargetWrapper(ContainerType.FOLDER, folders.size());
- dtw.writeToDumpTarget(fInfo);
- for(WorkspaceItemInfo sInfo: fInfo.contents) {
- DumpTargetWrapper child = new DumpTargetWrapper(sInfo);
- child.writeToDumpTarget(sInfo);
- dtw.add(child);
- }
- if (fInfo.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
- hotseat.add(dtw);
- } else if (fInfo.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
- workspaces.get(fInfo.screenId).add(dtw);
- }
- }
- // Add leaf nodes (L3): *Info
- for (int i = 0; i < workspaceItems.size(); i++) {
- ItemInfo info = workspaceItems.get(i);
- if (info instanceof FolderInfo) {
- continue;
- }
- dtw = new DumpTargetWrapper(info);
- dtw.writeToDumpTarget(info);
- if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
- hotseat.add(dtw);
- } else if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
- workspaces.get(info.screenId).add(dtw);
- }
- }
- for (int i = 0; i < appWidgets.size(); i++) {
- ItemInfo info = appWidgets.get(i);
- dtw = new DumpTargetWrapper(info);
- dtw.writeToDumpTarget(info);
- if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
- hotseat.add(dtw);
- } else if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
- workspaces.get(info.screenId).add(dtw);
- }
- }
-
-
- // Traverse target wrapper
- ArrayList<DumpTarget> targetList = new ArrayList<>();
- targetList.addAll(hotseat.getFlattenedList());
- for (int i = 0; i < workspaces.size(); i++) {
- targetList.addAll(workspaces.valueAt(i).getFlattenedList());
- }
-
- if (Arrays.asList(args).contains("--debug")) {
- for (int i = 0; i < targetList.size(); i++) {
- writer.println(prefix + DumpTargetWrapper.getDumpTargetStr(targetList.get(i)));
- }
- return;
- } else {
- LauncherDumpProto.LauncherImpression proto = new LauncherDumpProto.LauncherImpression();
- proto.targets = new DumpTarget[targetList.size()];
- for (int i = 0; i < targetList.size(); i++) {
- proto.targets[i] = targetList.get(i);
- }
- FileOutputStream fos = new FileOutputStream(fd);
- try {
-
- fos.write(MessageNano.toByteArray(proto));
- Log.d(TAG, MessageNano.toByteArray(proto).length + "Bytes");
- } catch (IOException e) {
- Log.e(TAG, "Exception writing dumpsys --proto", e);
- }
- }
- }
-
public synchronized void removeItem(Context context, ItemInfo... items) {
removeItem(context, Arrays.asList(items));
}
@@ -273,7 +178,7 @@
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
folders.remove(item.id);
- if (FeatureFlags.IS_DOGFOOD_BUILD) {
+ if (FeatureFlags.IS_STUDIO_BUILD) {
for (ItemInfo info : itemsIdMap) {
if (info.container == item.id) {
// We are deleting a folder which still contains items that
@@ -424,7 +329,8 @@
// Now add the new shortcuts to the map.
for (ShortcutInfo shortcut : shortcuts) {
boolean shouldShowInContainer = shortcut.isEnabled()
- && (shortcut.isDeclaredInManifest() || shortcut.isDynamic());
+ && (shortcut.isDeclaredInManifest() || shortcut.isDynamic())
+ && shortcut.getActivity() != null;
if (shouldShowInContainer) {
ComponentKey targetComponent
= new ComponentKey(shortcut.getActivity(), shortcut.getUserHandle());
diff --git a/src/com/android/launcher3/model/CacheDataUpdatedTask.java b/src/com/android/launcher3/model/CacheDataUpdatedTask.java
index c1c8be3..8e6b064 100644
--- a/src/com/android/launcher3/model/CacheDataUpdatedTask.java
+++ b/src/com/android/launcher3/model/CacheDataUpdatedTask.java
@@ -18,11 +18,11 @@
import android.content.ComponentName;
import android.os.UserHandle;
-import com.android.launcher3.WorkspaceItemInfo;
-import com.android.launcher3.icons.IconCache;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherSettings;
+import com.android.launcher3.icons.IconCache;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import java.util.ArrayList;
import java.util.HashSet;
diff --git a/src/com/android/launcher3/model/FirstScreenBroadcast.java b/src/com/android/launcher3/model/FirstScreenBroadcast.java
index a0b7177..5112304 100644
--- a/src/com/android/launcher3/model/FirstScreenBroadcast.java
+++ b/src/com/android/launcher3/model/FirstScreenBroadcast.java
@@ -15,16 +15,18 @@
*/
package com.android.launcher3.model;
+import static android.os.Process.myUserHandle;
+
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInstaller.SessionInfo;
import android.util.Log;
-import com.android.launcher3.FolderInfo;
-import com.android.launcher3.ItemInfo;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherSettings;
+import com.android.launcher3.model.data.FolderInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
import com.android.launcher3.util.MultiHashMap;
import com.android.launcher3.util.PackageUserKey;
@@ -35,8 +37,6 @@
import java.util.Map;
import java.util.Set;
-import static android.os.Process.myUserHandle;
-
/**
* Helper class to send broadcasts to package installers that have:
* - Items on the first screen
diff --git a/src/com/android/launcher3/model/GridBackupTable.java b/src/com/android/launcher3/model/GridBackupTable.java
index eb99af5..4a1bc4d 100644
--- a/src/com/android/launcher3/model/GridBackupTable.java
+++ b/src/com/android/launcher3/model/GridBackupTable.java
@@ -33,8 +33,6 @@
import com.android.launcher3.LauncherSettings.Settings;
import com.android.launcher3.pm.UserCache;
-import java.util.Objects;
-
/**
* Helper class to backup and restore Favorites table into a separate table
* within the same data base.
@@ -63,8 +61,7 @@
private static final int STATE_SANITIZED = 2;
private final Context mContext;
- private final SQLiteDatabase mFavoritesDb;
- private final SQLiteDatabase mBackupDb;
+ private final SQLiteDatabase mDb;
private final int mOldHotseatSize;
private final int mOldGridX;
@@ -77,11 +74,10 @@
@IntDef({STATE_NOT_FOUND, STATE_RAW, STATE_SANITIZED})
private @interface BackupState { }
- public GridBackupTable(Context context, SQLiteDatabase favoritesDb, SQLiteDatabase backupDb,
- int hotseatSize, int gridX, int gridY) {
+ public GridBackupTable(Context context, SQLiteDatabase db, int hotseatSize, int gridX,
+ int gridY) {
mContext = context;
- mFavoritesDb = favoritesDb;
- mBackupDb = backupDb;
+ mDb = db;
mOldHotseatSize = hotseatSize;
mOldGridX = gridX;
@@ -94,7 +90,7 @@
*/
public boolean backupOrRestoreAsNeeded() {
// Check if backup table exists
- if (!tableExists(mBackupDb, BACKUP_TABLE_NAME)) {
+ if (!tableExists(mDb, BACKUP_TABLE_NAME)) {
if (Settings.call(mContext.getContentResolver(), Settings.METHOD_WAS_EMPTY_DB_CREATED)
.getBoolean(Settings.EXTRA_VALUE, false)) {
// No need to copy if empty DB was created.
@@ -104,12 +100,24 @@
Process.myUserHandle()), 0);
return false;
}
+ return restoreIfBackupExists(Favorites.TABLE_NAME);
+ }
+
+ public boolean restoreToPreviewIfBackupExists() {
+ if (!tableExists(mDb, BACKUP_TABLE_NAME)) {
+ return false;
+ }
+
+ return restoreIfBackupExists(Favorites.PREVIEW_TABLE_NAME);
+ }
+
+ private boolean restoreIfBackupExists(String toTableName) {
if (loadDBProperties() != STATE_SANITIZED) {
return false;
}
long userSerial = UserCache.INSTANCE.get(mContext).getSerialNumberForUser(
Process.myUserHandle());
- copyTable(mBackupDb, BACKUP_TABLE_NAME, mFavoritesDb, Favorites.TABLE_NAME, userSerial);
+ copyTable(mDb, BACKUP_TABLE_NAME, toTableName, userSerial);
Log.d(TAG, "Backup table found");
return true;
}
@@ -122,37 +130,28 @@
/**
* Copy valid grid entries from one table to another.
*/
- private static void copyTable(SQLiteDatabase fromDb, String fromTable, SQLiteDatabase toDb,
- String toTable, long userSerial) {
- dropTable(toDb, toTable);
- Favorites.addTableToDb(toDb, userSerial, false, toTable);
- if (fromDb != toDb) {
- toDb.execSQL("ATTACH DATABASE '" + fromDb.getPath() + "' AS from_db");
- toDb.execSQL(
- "INSERT INTO " + toTable + " SELECT * FROM from_db." + fromTable
- + " where _id > " + ID_PROPERTY);
- } else {
- toDb.execSQL("INSERT INTO " + toTable + " SELECT * FROM " + fromTable + " where _id > "
- + ID_PROPERTY);
- }
+ private static void copyTable(SQLiteDatabase db, String from, String to, long userSerial) {
+ dropTable(db, to);
+ Favorites.addTableToDb(db, userSerial, false, to);
+ db.execSQL("INSERT INTO " + to + " SELECT * FROM " + from + " where _id > " + ID_PROPERTY);
}
private void encodeDBProperties(int options) {
ContentValues values = new ContentValues();
values.put(Favorites._ID, ID_PROPERTY);
- values.put(KEY_DB_VERSION, mFavoritesDb.getVersion());
+ values.put(KEY_DB_VERSION, mDb.getVersion());
values.put(KEY_GRID_X_SIZE, mOldGridX);
values.put(KEY_GRID_Y_SIZE, mOldGridY);
values.put(KEY_HOTSEAT_SIZE, mOldHotseatSize);
values.put(Favorites.OPTIONS, options);
- mBackupDb.insert(BACKUP_TABLE_NAME, null, values);
+ mDb.insert(BACKUP_TABLE_NAME, null, values);
}
/**
* Load DB properties from grid backup table.
*/
public @BackupState int loadDBProperties() {
- try (Cursor c = mBackupDb.query(BACKUP_TABLE_NAME, new String[] {
+ try (Cursor c = mDb.query(BACKUP_TABLE_NAME, new String[] {
KEY_DB_VERSION, // 0
KEY_GRID_X_SIZE, // 1
KEY_GRID_Y_SIZE, // 2
@@ -163,7 +162,7 @@
Log.e(TAG, "Meta data not found in backup table");
return STATE_NOT_FOUND;
}
- if (!validateDBVersion(mBackupDb.getVersion(), c.getInt(0))) {
+ if (!validateDBVersion(mDb.getVersion(), c.getInt(0))) {
return STATE_NOT_FOUND;
}
@@ -179,7 +178,7 @@
* Restore workspace from raw backup if available.
*/
public boolean restoreFromRawBackupIfAvailable(long oldProfileId) {
- if (!tableExists(mBackupDb, Favorites.BACKUP_TABLE_NAME)
+ if (!tableExists(mDb, Favorites.BACKUP_TABLE_NAME)
|| loadDBProperties() != STATE_RAW
|| mOldHotseatSize != mRestoredHotseatSize
|| mOldGridX != mRestoredGridX
@@ -187,8 +186,7 @@
// skip restore if dimensions in backup table differs from current setup.
return false;
}
- copyTable(mBackupDb, Favorites.BACKUP_TABLE_NAME, mFavoritesDb, Favorites.TABLE_NAME,
- oldProfileId);
+ copyTable(mDb, Favorites.BACKUP_TABLE_NAME, Favorites.TABLE_NAME, oldProfileId);
Log.d(TAG, "Backup restored");
return true;
}
@@ -197,8 +195,7 @@
* Performs a backup on the workspace layout.
*/
public void doBackup(long profileId, int options) {
- copyTable(mFavoritesDb, Favorites.TABLE_NAME, mBackupDb, Favorites.BACKUP_TABLE_NAME,
- profileId);
+ copyTable(mDb, Favorites.TABLE_NAME, Favorites.BACKUP_TABLE_NAME, profileId);
encodeDBProperties(options);
}
diff --git a/src/com/android/launcher3/model/GridSizeMigrationTask.java b/src/com/android/launcher3/model/GridSizeMigrationTask.java
index 4f92066..b27e4ea 100644
--- a/src/com/android/launcher3/model/GridSizeMigrationTask.java
+++ b/src/com/android/launcher3/model/GridSizeMigrationTask.java
@@ -3,6 +3,7 @@
import static com.android.launcher3.LauncherSettings.Settings.EXTRA_VALUE;
import static com.android.launcher3.Utilities.getPointString;
import static com.android.launcher3.Utilities.parsePoint;
+import static com.android.launcher3.provider.LauncherDbUtils.copyTable;
import android.content.ComponentName;
import android.content.ContentValues;
@@ -14,13 +15,13 @@
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Point;
+import android.os.SystemClock;
import android.util.Log;
import android.util.SparseArray;
import androidx.annotation.VisibleForTesting;
import com.android.launcher3.InvariantDeviceProfile;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherAppWidgetProviderInfo;
import com.android.launcher3.LauncherSettings;
@@ -29,6 +30,8 @@
import com.android.launcher3.Utilities;
import com.android.launcher3.Workspace;
import com.android.launcher3.config.FeatureFlags;
+import com.android.launcher3.graphics.LauncherPreviewRenderer;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.pm.InstallSessionHelper;
import com.android.launcher3.provider.LauncherDbUtils;
import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
@@ -69,6 +72,7 @@
private final SparseArray<ContentValues> mUpdateOperations = new SparseArray<>();
private final HashSet<String> mValidPackages;
+ private final String mTableName;
private final int mSrcX, mSrcY;
private final int mTrgX, mTrgY;
@@ -78,10 +82,12 @@
private final int mDestHotseatSize;
protected GridSizeMigrationTask(Context context, SQLiteDatabase db,
- HashSet<String> validPackages, Point sourceSize, Point targetSize) {
+ HashSet<String> validPackages, boolean usePreviewTable, Point sourceSize,
+ Point targetSize) {
mContext = context;
mDb = db;
mValidPackages = validPackages;
+ mTableName = usePreviewTable ? Favorites.PREVIEW_TABLE_NAME : Favorites.TABLE_NAME;
mSrcX = sourceSize.x;
mSrcY = sourceSize.y;
@@ -97,10 +103,12 @@
}
protected GridSizeMigrationTask(Context context, SQLiteDatabase db,
- HashSet<String> validPackages, int srcHotseatSize, int destHotseatSize) {
+ HashSet<String> validPackages, boolean usePreviewTable, int srcHotseatSize,
+ int destHotseatSize) {
mContext = context;
mDb = db;
mValidPackages = validPackages;
+ mTableName = usePreviewTable ? Favorites.PREVIEW_TABLE_NAME : Favorites.TABLE_NAME;
mSrcHotseatSize = srcHotseatSize;
@@ -120,7 +128,7 @@
// Update items
int updateCount = mUpdateOperations.size();
for (int i = 0; i < updateCount; i++) {
- mDb.update(Favorites.TABLE_NAME, mUpdateOperations.valueAt(i),
+ mDb.update(mTableName, mUpdateOperations.valueAt(i),
"_id=" + mUpdateOperations.keyAt(i), null);
}
@@ -128,8 +136,8 @@
if (DEBUG) {
Log.d(TAG, "Removing items: " + mEntryToRemove.toConcatString());
}
- mDb.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
- Favorites._ID, mEntryToRemove), null);
+ mDb.delete(mTableName, Utilities.createDbSelectionQuery(Favorites._ID, mEntryToRemove),
+ null);
}
return updateCount > 0 || !mEntryToRemove.isEmpty();
@@ -182,8 +190,8 @@
}
@VisibleForTesting
- static IntArray getWorkspaceScreenIds(SQLiteDatabase db) {
- return LauncherDbUtils.queryIntArray(db, Favorites.TABLE_NAME, Favorites.SCREEN,
+ static IntArray getWorkspaceScreenIds(SQLiteDatabase db, String tableName) {
+ return LauncherDbUtils.queryIntArray(db, tableName, Favorites.SCREEN,
Favorites.CONTAINER + " = " + Favorites.CONTAINER_DESKTOP,
Favorites.SCREEN, Favorites.SCREEN);
}
@@ -192,7 +200,7 @@
* @return true if any DB change was made
*/
protected boolean migrateWorkspace() throws Exception {
- IntArray allScreens = getWorkspaceScreenIds(mDb);
+ IntArray allScreens = getWorkspaceScreenIds(mDb, mTableName);
if (allScreens.isEmpty()) {
throw new Exception("Unable to get workspace screens");
}
@@ -244,12 +252,12 @@
/**
* Migrate a particular screen id.
* Strategy:
- * 1) For all possible combinations of row and column, pick the one which causes the least
- * data loss: {@link #tryRemove(int, int, int, ArrayList, float[])}
- * 2) Maintain a list of all lost items before this screen, and add any new item lost from
- * this screen to that list as well.
- * 3) If all those items from the above list can be placed on this screen, place them
- * (otherwise they are placed on a new screen).
+ * 1) For all possible combinations of row and column, pick the one which causes the least
+ * data loss: {@link #tryRemove(int, int, int, ArrayList, float[])}
+ * 2) Maintain a list of all lost items before this screen, and add any new item lost from
+ * this screen to that list as well.
+ * 3) If all those items from the above list can be placed on this screen, place them
+ * (otherwise they are placed on a new screen).
*/
protected void migrateScreen(int screenId) {
// If we are migrating the first screen, do not touch the first row.
@@ -362,9 +370,9 @@
/**
* Tries the remove the provided row and column.
*
- * @param items all the items on the screen under operation
+ * @param items all the items on the screen under operation
* @param outLoss array of size 2. The first entry is filled with weight loss, and the second
- * with the overall item movement.
+ * with the overall item movement.
*/
private ArrayList<DbEntry> tryRemove(int col, int row, int startY,
ArrayList<DbEntry> items, float[] outLoss) {
@@ -379,13 +387,13 @@
for (DbEntry item : items) {
if ((item.cellX <= col && (item.spanX + item.cellX) > col)
- || (item.cellY <= row && (item.spanY + item.cellY) > row)) {
+ || (item.cellY <= row && (item.spanY + item.cellY) > row)) {
removedItems.add(item);
- if (item.cellX >= col) item.cellX --;
- if (item.cellY >= row) item.cellY --;
+ if (item.cellX >= col) item.cellX--;
+ if (item.cellY >= row) item.cellY--;
} else {
- if (item.cellX > col) item.cellX --;
- if (item.cellY > row) item.cellY --;
+ if (item.cellX > col) item.cellX--;
+ if (item.cellY > row) item.cellY--;
finalItems.add(item);
occupied.markCells(item, true);
}
@@ -438,9 +446,9 @@
/**
* Recursively finds a placement for the provided items.
*
- * @param index the position in {@link #itemsToPlace} to start looking at.
- * @param weightLoss total weight loss upto this point
- * @param moveCost total move cost upto this point
+ * @param index the position in {@link #itemsToPlace} to start looking at.
+ * @param weightLoss total weight loss upto this point
+ * @param moveCost total move cost upto this point
* @param itemsPlaced all the items already placed upto this point
*/
public void find(int index, float weightLoss, float moveCost,
@@ -481,11 +489,11 @@
float newMoveCost = moveCost;
if (x != myX) {
me.cellX = x;
- newMoveCost ++;
+ newMoveCost++;
}
if (y != myY) {
me.cellY = y;
- newMoveCost ++;
+ newMoveCost++;
}
if (ignoreMove) {
newMoveCost = moveCost;
@@ -500,35 +508,35 @@
// Try resizing horizontally
if (myW > me.minSpanX && occupied.isRegionVacant(x, y, myW - 1, myH)) {
- me.spanX --;
+ me.spanX--;
occupied.markCells(me, true);
// 1 extra move cost
find(index + 1, weightLoss, newMoveCost + 1, itemsIncludingMe);
occupied.markCells(me, false);
- me.spanX ++;
+ me.spanX++;
}
// Try resizing vertically
if (myH > me.minSpanY && occupied.isRegionVacant(x, y, myW, myH - 1)) {
- me.spanY --;
+ me.spanY--;
occupied.markCells(me, true);
// 1 extra move cost
find(index + 1, weightLoss, newMoveCost + 1, itemsIncludingMe);
occupied.markCells(me, false);
- me.spanY ++;
+ me.spanY++;
}
// Try resizing horizontally & vertically
if (myH > me.minSpanY && myW > me.minSpanX &&
occupied.isRegionVacant(x, y, myW - 1, myH - 1)) {
- me.spanX --;
- me.spanY --;
+ me.spanX--;
+ me.spanY--;
occupied.markCells(me, true);
// 2 extra move cost
find(index + 1, weightLoss, newMoveCost + 2, itemsIncludingMe);
occupied.markCells(me, false);
- me.spanX ++;
- me.spanY ++;
+ me.spanX++;
+ me.spanY++;
}
me.cellX = myX;
me.cellY = myY;
@@ -565,11 +573,11 @@
float newMoveCost = moveCost;
if (newX != myX) {
me.cellX = newX;
- newMoveCost ++;
+ newMoveCost++;
}
if (newY != myY) {
me.cellY = newY;
- newMoveCost ++;
+ newMoveCost++;
}
if (ignoreMove) {
newMoveCost = moveCost;
@@ -602,7 +610,7 @@
}
private ArrayList<DbEntry> loadHotseatEntries() {
- Cursor c = queryWorkspace(
+ Cursor c = queryWorkspace(
new String[]{
Favorites._ID, // 0
Favorites.ITEM_TYPE, // 1
@@ -787,7 +795,7 @@
}
protected Cursor queryWorkspace(String[] columns, String where) {
- return mDb.query(Favorites.TABLE_NAME, columns, where, null, null, null, null);
+ return mDb.query(mTableName, columns, where, null, null, null, null);
}
/**
@@ -879,24 +887,44 @@
}
/**
- * Migrates the workspace and hotseat in case their sizes changed.
+ * Check given a new IDP, if migration is necessary.
+ */
+ public static boolean needsToMigrate(Context context, InvariantDeviceProfile idp) {
+ SharedPreferences prefs = Utilities.getPrefs(context);
+ String gridSizeString = getPointString(idp.numColumns, idp.numRows);
+
+ return !gridSizeString.equals(prefs.getString(KEY_MIGRATION_SRC_WORKSPACE_SIZE, ""))
+ || idp.numHotseatIcons != prefs.getInt(KEY_MIGRATION_SRC_HOTSEAT_COUNT,
+ idp.numHotseatIcons);
+ }
+
+ /** See {@link #migrateGridIfNeeded(Context, InvariantDeviceProfile)} */
+ public static boolean migrateGridIfNeeded(Context context) {
+ if (context instanceof LauncherPreviewRenderer.PreviewContext) {
+ return true;
+ }
+ return migrateGridIfNeeded(context, null);
+ }
+
+ /**
+ * Run the migration algorithm if needed. For preview, we provide the intended idp because it
+ * has not been changed. If idp is null, we read it from the context, for actual grid migration.
*
* @return false if the migration failed.
*/
- public static boolean migrateGridIfNeeded(Context context) {
- SharedPreferences prefs = Utilities.getPrefs(context);
- InvariantDeviceProfile idp = LauncherAppState.getIDP(context);
+ public static boolean migrateGridIfNeeded(Context context, InvariantDeviceProfile idp) {
+ boolean migrateForPreview = idp != null;
+ if (!migrateForPreview) {
+ idp = LauncherAppState.getIDP(context);
+ }
- String gridSizeString = getPointString(idp.numColumns, idp.numRows);
-
- if (gridSizeString.equals(prefs.getString(KEY_MIGRATION_SRC_WORKSPACE_SIZE, "")) &&
- idp.numHotseatIcons == prefs.getInt(KEY_MIGRATION_SRC_HOTSEAT_COUNT,
- idp.numHotseatIcons)) {
- // Skip if workspace and hotseat sizes have not changed.
+ if (!needsToMigrate(context, idp)) {
return true;
}
- long migrationStartTime = System.currentTimeMillis();
+ SharedPreferences prefs = Utilities.getPrefs(context);
+ String gridSizeString = getPointString(idp.numColumns, idp.numRows);
+ long migrationStartTime = SystemClock.elapsedRealtime();
try (SQLiteTransaction transaction = (SQLiteTransaction) Settings.call(
context.getContentResolver(), Settings.METHOD_NEW_TRANSACTION)
.getBinder(Settings.EXTRA_VALUE)) {
@@ -907,33 +935,40 @@
KEY_MIGRATION_SRC_WORKSPACE_SIZE, gridSizeString));
boolean dbChanged = false;
+ if (migrateForPreview) {
+ copyTable(transaction.getDb(), Favorites.TABLE_NAME, transaction.getDb(),
+ Favorites.PREVIEW_TABLE_NAME, context);
+ }
GridBackupTable backupTable = new GridBackupTable(context, transaction.getDb(),
- transaction.getDb(), srcHotseatCount, sourceSize.x, sourceSize.y);
- if (backupTable.backupOrRestoreAsNeeded()) {
+ srcHotseatCount, sourceSize.x, sourceSize.y);
+ if (migrateForPreview ? backupTable.restoreToPreviewIfBackupExists()
+ : backupTable.backupOrRestoreAsNeeded()) {
dbChanged = true;
srcHotseatCount = backupTable.getRestoreHotseatAndGridSize(sourceSize);
}
HashSet<String> validPackages = getValidPackages(context);
- // Hotseat
- if (srcHotseatCount != idp.numHotseatIcons) {
- // Migrate hotseat.
- dbChanged = new GridSizeMigrationTask(context, transaction.getDb(),
- validPackages, srcHotseatCount, idp.numHotseatIcons).migrateHotseat();
+ // Hotseat.
+ if (srcHotseatCount != idp.numHotseatIcons
+ && new GridSizeMigrationTask(context, transaction.getDb(), validPackages,
+ migrateForPreview, srcHotseatCount,
+ idp.numHotseatIcons).migrateHotseat()) {
+ dbChanged = true;
}
// Grid size
Point targetSize = new Point(idp.numColumns, idp.numRows);
- if (new MultiStepMigrationTask(validPackages, context, transaction.getDb())
- .migrate(sourceSize, targetSize)) {
+ if (new MultiStepMigrationTask(validPackages, context, transaction.getDb(),
+ migrateForPreview).migrate(sourceSize, targetSize)) {
dbChanged = true;
}
if (dbChanged) {
// Make sure we haven't removed everything.
final Cursor c = context.getContentResolver().query(
- Favorites.CONTENT_URI, null, null, null, null);
+ migrateForPreview ? Favorites.PREVIEW_CONTENT_URI : Favorites.CONTENT_URI,
+ null, null, null, null);
boolean hasData = c.moveToNext();
c.close();
if (!hasData) {
@@ -942,21 +977,25 @@
}
transaction.commit();
- Settings.call(context.getContentResolver(), Settings.METHOD_REFRESH_BACKUP_TABLE);
+ if (!migrateForPreview) {
+ Settings.call(context.getContentResolver(), Settings.METHOD_REFRESH_BACKUP_TABLE);
+ }
return true;
} catch (Exception e) {
- Log.e(TAG, "Error during grid migration", e);
+ Log.e(TAG, "Error during preview grid migration", e);
return false;
} finally {
- Log.v(TAG, "Workspace migration completed in "
- + (System.currentTimeMillis() - migrationStartTime));
+ Log.v(TAG, "Preview workspace migration completed in "
+ + (SystemClock.elapsedRealtime() - migrationStartTime));
- // Save current configuration, so that the migration does not run again.
- prefs.edit()
- .putString(KEY_MIGRATION_SRC_WORKSPACE_SIZE, gridSizeString)
- .putInt(KEY_MIGRATION_SRC_HOTSEAT_COUNT, idp.numHotseatIcons)
- .apply();
+ if (!migrateForPreview) {
+ // Save current configuration, so that the migration does not run again.
+ prefs.edit()
+ .putString(KEY_MIGRATION_SRC_WORKSPACE_SIZE, gridSizeString)
+ .putInt(KEY_MIGRATION_SRC_HOTSEAT_COUNT, idp.numHotseatIcons)
+ .apply();
+ }
}
}
@@ -989,7 +1028,7 @@
.getBinder(Settings.EXTRA_VALUE)) {
GridSizeMigrationTask task = new GridSizeMigrationTask(
context, transaction.getDb(), getValidPackages(context),
- Integer.MAX_VALUE, Integer.MAX_VALUE);
+ false /* usePreviewTable */, Integer.MAX_VALUE, Integer.MAX_VALUE);
// Load all the valid entries
ArrayList<DbEntry> items = task.loadHotseatEntries();
@@ -1011,12 +1050,14 @@
private final HashSet<String> mValidPackages;
private final Context mContext;
private final SQLiteDatabase mDb;
+ private final boolean mUsePreviewTable;
public MultiStepMigrationTask(HashSet<String> validPackages, Context context,
- SQLiteDatabase db) {
+ SQLiteDatabase db, boolean usePreviewTable) {
mValidPackages = validPackages;
mContext = context;
mDb = db;
+ mUsePreviewTable = usePreviewTable;
}
public boolean migrate(Point sourceSize, Point targetSize) throws Exception {
@@ -1052,8 +1093,8 @@
}
protected boolean runStepTask(Point sourceSize, Point nextSize) throws Exception {
- return new GridSizeMigrationTask(mContext, mDb,
- mValidPackages, sourceSize, nextSize).migrateWorkspace();
+ return new GridSizeMigrationTask(mContext, mDb, mValidPackages, mUsePreviewTable,
+ sourceSize, nextSize).migrateWorkspace();
}
}
}
diff --git a/src/com/android/launcher3/model/GridSizeMigrationTaskV2.java b/src/com/android/launcher3/model/GridSizeMigrationTaskV2.java
index 63b7191..1c44fc3 100644
--- a/src/com/android/launcher3/model/GridSizeMigrationTaskV2.java
+++ b/src/com/android/launcher3/model/GridSizeMigrationTaskV2.java
@@ -16,7 +16,46 @@
package com.android.launcher3.model;
+import static com.android.launcher3.Utilities.getPointString;
+import static com.android.launcher3.provider.LauncherDbUtils.dropTable;
+
+import android.content.ComponentName;
+import android.content.ContentValues;
import android.content.Context;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.database.Cursor;
+import android.database.DatabaseUtils;
+import android.database.sqlite.SQLiteDatabase;
+import android.graphics.Point;
+import android.text.TextUtils;
+import android.util.Log;
+
+import androidx.annotation.VisibleForTesting;
+
+import com.android.launcher3.InvariantDeviceProfile;
+import com.android.launcher3.LauncherAppState;
+import com.android.launcher3.LauncherAppWidgetProviderInfo;
+import com.android.launcher3.LauncherSettings;
+import com.android.launcher3.Utilities;
+import com.android.launcher3.graphics.LauncherPreviewRenderer;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.pm.InstallSessionHelper;
+import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
+import com.android.launcher3.util.GridOccupancy;
+import com.android.launcher3.util.IntArray;
+import com.android.launcher3.widget.WidgetManagerHelper;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
/**
* This class takes care of shrinking the workspace (by maximum of one row and one column), as a
@@ -24,17 +63,706 @@
*/
public class GridSizeMigrationTaskV2 {
- private GridSizeMigrationTaskV2(Context context) {
+ public static final String KEY_MIGRATION_SRC_WORKSPACE_SIZE = "migration_src_workspace_size";
+ public static final String KEY_MIGRATION_SRC_HOTSEAT_COUNT = "migration_src_hotseat_count";
+ private static final String TAG = "GridSizeMigrationTaskV2";
+ private static final boolean DEBUG = true;
+
+ private final Context mContext;
+ private final SQLiteDatabase mDb;
+ private final DbReader mSrcReader;
+ private final DbReader mDestReader;
+
+ private final List<DbEntry> mHotseatItems;
+ private final List<DbEntry> mWorkspaceItems;
+
+ private final List<DbEntry> mHotseatDiff;
+ private final List<DbEntry> mWorkspaceDiff;
+
+ private final int mDestHotseatSize;
+ private final int mTrgX, mTrgY;
+
+ @VisibleForTesting
+ protected GridSizeMigrationTaskV2(Context context, SQLiteDatabase db, DbReader srcReader,
+ DbReader destReader, int destHotseatSize, Point targetSize) {
+ mContext = context;
+ mDb = db;
+ mSrcReader = srcReader;
+ mDestReader = destReader;
+
+ mHotseatItems = destReader.loadHotseatEntries();
+ mWorkspaceItems = destReader.loadAllWorkspaceEntries();
+
+ mHotseatDiff = calcDiff(mSrcReader.loadHotseatEntries(), mHotseatItems);
+ mWorkspaceDiff = calcDiff(mSrcReader.loadAllWorkspaceEntries(), mWorkspaceItems);
+ mDestHotseatSize = destHotseatSize;
+
+ mTrgX = targetSize.x;
+ mTrgY = targetSize.y;
}
/**
- * Migrates the workspace and hotseat in case their sizes changed.
+ * Check given a new IDP, if migration is necessary.
+ */
+ public static boolean needsToMigrate(Context context, InvariantDeviceProfile idp) {
+ SharedPreferences prefs = Utilities.getPrefs(context);
+ String gridSizeString = getPointString(idp.numColumns, idp.numRows);
+
+ return !gridSizeString.equals(prefs.getString(KEY_MIGRATION_SRC_WORKSPACE_SIZE, ""))
+ || idp.numHotseatIcons != prefs.getInt(KEY_MIGRATION_SRC_HOTSEAT_COUNT,
+ idp.numHotseatIcons);
+ }
+
+ /** See {@link #migrateGridIfNeeded(Context, InvariantDeviceProfile)} */
+ public static boolean migrateGridIfNeeded(Context context) {
+ if (context instanceof LauncherPreviewRenderer.PreviewContext) {
+ return true;
+ }
+ return migrateGridIfNeeded(context, null);
+ }
+
+ /**
+ * When migrating the grid for preview, we copy the table
+ * {@link LauncherSettings.Favorites.TABLE_NAME} into
+ * {@link LauncherSettings.Favorites.PREVIEW_TABLE_NAME}, run grid size migration from the
+ * former to the later, then use the later table for preview.
+ *
+ * Similarly when doing the actual grid migration, the former grid option's table
+ * {@link LauncherSettings.Favorites.TABLE_NAME} is copied into the new grid option's
+ * {@link LauncherSettings.Favorites.TMP_TABLE}, we then run the grid size migration algorithm
+ * to migrate the later to the former, and load the workspace from the default
+ * {@link LauncherSettings.Favorites.TABLE_NAME}.
*
* @return false if the migration failed.
*/
- public static boolean migrateGridIfNeeded(Context context) {
- // To be implemented.
+ public static boolean migrateGridIfNeeded(Context context, InvariantDeviceProfile idp) {
+ boolean migrateForPreview = idp != null;
+ if (!migrateForPreview) {
+ idp = LauncherAppState.getIDP(context);
+ }
+
+ if (!needsToMigrate(context, idp)) {
+ return true;
+ }
+
+ SharedPreferences prefs = Utilities.getPrefs(context);
+ String gridSizeString = getPointString(idp.numColumns, idp.numRows);
+
+ if (gridSizeString.equals(prefs.getString(KEY_MIGRATION_SRC_WORKSPACE_SIZE, ""))
+ && idp.numHotseatIcons == prefs.getInt(KEY_MIGRATION_SRC_HOTSEAT_COUNT,
+ idp.numHotseatIcons)) {
+ // Skip if workspace and hotseat sizes have not changed.
+ return true;
+ }
+
+ HashSet<String> validPackages = getValidPackages(context);
+ int srcHotseatCount = prefs.getInt(KEY_MIGRATION_SRC_HOTSEAT_COUNT, idp.numHotseatIcons);
+
+ if (migrateForPreview) {
+ if (!LauncherSettings.Settings.call(
+ context.getContentResolver(),
+ LauncherSettings.Settings.METHOD_PREP_FOR_PREVIEW, idp.dbFile).getBoolean(
+ LauncherSettings.Settings.EXTRA_VALUE)) {
+ return false;
+ }
+ } else if (!LauncherSettings.Settings.call(
+ context.getContentResolver(),
+ LauncherSettings.Settings.METHOD_UPDATE_CURRENT_OPEN_HELPER).getBoolean(
+ LauncherSettings.Settings.EXTRA_VALUE)) {
+ return false;
+ }
+
+ long migrationStartTime = System.currentTimeMillis();
+ try (SQLiteTransaction t = (SQLiteTransaction) LauncherSettings.Settings.call(
+ context.getContentResolver(),
+ LauncherSettings.Settings.METHOD_NEW_TRANSACTION).getBinder(
+ LauncherSettings.Settings.EXTRA_VALUE)) {
+
+ DbReader srcReader = new DbReader(t.getDb(),
+ migrateForPreview ? LauncherSettings.Favorites.TABLE_NAME
+ : LauncherSettings.Favorites.TMP_TABLE,
+ context, validPackages, srcHotseatCount);
+ DbReader destReader = new DbReader(t.getDb(),
+ migrateForPreview ? LauncherSettings.Favorites.PREVIEW_TABLE_NAME
+ : LauncherSettings.Favorites.TABLE_NAME,
+ context, validPackages, idp.numHotseatIcons);
+
+ Point targetSize = new Point(idp.numColumns, idp.numRows);
+ GridSizeMigrationTaskV2 task = new GridSizeMigrationTaskV2(context, t.getDb(),
+ srcReader, destReader, idp.numHotseatIcons, targetSize);
+ task.migrate();
+
+ if (!migrateForPreview) {
+ dropTable(t.getDb(), LauncherSettings.Favorites.TMP_TABLE);
+ }
+
+ t.commit();
+ return true;
+ } catch (Exception e) {
+ Log.e(TAG, "Error during grid migration", e);
+
+ return false;
+ } finally {
+ Log.v(TAG, "Workspace migration completed in "
+ + (System.currentTimeMillis() - migrationStartTime));
+
+ if (!migrateForPreview) {
+ // Save current configuration, so that the migration does not run again.
+ prefs.edit()
+ .putString(KEY_MIGRATION_SRC_WORKSPACE_SIZE, gridSizeString)
+ .putInt(KEY_MIGRATION_SRC_HOTSEAT_COUNT, idp.numHotseatIcons)
+ .apply();
+ }
+ }
+ }
+
+ @VisibleForTesting
+ protected boolean migrate() {
+ if (mHotseatDiff.isEmpty() && mWorkspaceDiff.isEmpty()) {
+ return false;
+ }
+
+ // Migrate hotseat
+ HotseatPlacementSolution hotseatSolution = new HotseatPlacementSolution(mDb, mSrcReader,
+ mDestReader, mContext, mDestHotseatSize, mHotseatItems, mHotseatDiff);
+ hotseatSolution.find();
+
+ // Sort the items by the reading order.
+ Collections.sort(mWorkspaceDiff);
+
+ // Migrate workspace.
+ for (int screenId = 0; screenId <= mDestReader.mLastScreenId; screenId++) {
+ if (DEBUG) {
+ Log.d(TAG, "Migrating " + screenId);
+ }
+ List<DbEntry> entries = mDestReader.loadWorkspaceEntries(screenId);
+ GridPlacementSolution workspaceSolution = new GridPlacementSolution(mDb, mSrcReader,
+ mDestReader, mContext, entries, screenId, mTrgX, mTrgY, mWorkspaceDiff);
+ workspaceSolution.find();
+ if (mWorkspaceDiff.isEmpty()) {
+ break;
+ }
+ }
+
+ int screenId = mDestReader.mLastScreenId + 1;
+ while (!mWorkspaceDiff.isEmpty()) {
+ GridPlacementSolution workspaceSolution = new GridPlacementSolution(mDb, mSrcReader,
+ mDestReader, mContext, new ArrayList<>(), screenId, mTrgX, mTrgY,
+ mWorkspaceDiff);
+ workspaceSolution.find();
+ screenId++;
+ }
return true;
}
+
+ /** Return what's in the src but not in the dest */
+ private static List<DbEntry> calcDiff(List<DbEntry> src, List<DbEntry> dest) {
+ Set<String> destSet = dest.parallelStream().map(DbEntry::getIntentStr).collect(
+ Collectors.toSet());
+ List<DbEntry> diff = new ArrayList<>();
+ for (DbEntry entry : src) {
+ if (!destSet.contains(entry.mIntent)) {
+ diff.add(entry);
+ }
+ }
+ return diff;
+ }
+
+ private static void insertEntryInDb(SQLiteDatabase db, Context context,
+ ArrayList<DbEntry> entriesFromSrcDb, DbEntry entry, String srcTableName,
+ String destTableName) {
+ int id = -1;
+ switch (entry.itemType) {
+ case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
+ case LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT:
+ case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: {
+ for (DbEntry e : entriesFromSrcDb) {
+ if (TextUtils.equals(e.mIntent, entry.mIntent)) {
+ id = e.id;
+ }
+ }
+
+ break;
+ }
+ case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: {
+ for (DbEntry e : entriesFromSrcDb) {
+ if (e.mFolderItems.size() == entry.mFolderItems.size()
+ && e.mFolderItems.containsAll(entry.mFolderItems)) {
+ id = e.id;
+ }
+ }
+ break;
+ }
+ case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
+ case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET: {
+ for (DbEntry e : entriesFromSrcDb) {
+ if (TextUtils.equals(e.mProvider, entry.mProvider)) {
+ id = e.id;
+ break;
+ }
+ }
+ break;
+ }
+ default:
+ return;
+ }
+
+ Cursor c = db.query(srcTableName, null, LauncherSettings.Favorites._ID + " = '" + id + "'",
+ null, null, null, null);
+
+ while (c.moveToNext()) {
+ ContentValues values = new ContentValues();
+ DatabaseUtils.cursorRowToContentValues(c, values);
+ entry.updateContentValues(values);
+ values.put(LauncherSettings.Favorites._ID,
+ LauncherSettings.Settings.call(context.getContentResolver(),
+ LauncherSettings.Settings.METHOD_NEW_ITEM_ID).getInt(
+ LauncherSettings.Settings.EXTRA_VALUE));
+ db.insert(destTableName, null, values);
+ }
+ c.close();
+ }
+
+ private static void removeEntryFromDb(SQLiteDatabase db, String tableName, IntArray entryId) {
+ db.delete(tableName,
+ Utilities.createDbSelectionQuery(LauncherSettings.Favorites._ID, entryId), null);
+ }
+
+ private static HashSet<String> getValidPackages(Context context) {
+ // Initialize list of valid packages. This contain all the packages which are already on
+ // the device and packages which are being installed. Any item which doesn't belong to
+ // this set is removed.
+ // Since the loader removes such items anyway, removing these items here doesn't cause
+ // any extra data loss and gives us more free space on the grid for better migration.
+ HashSet<String> validPackages = new HashSet<>();
+ for (PackageInfo info : context.getPackageManager()
+ .getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES)) {
+ validPackages.add(info.packageName);
+ }
+ InstallSessionHelper.INSTANCE.get(context)
+ .getActiveSessions().keySet()
+ .forEach(packageUserKey -> validPackages.add(packageUserKey.mPackageName));
+ return validPackages;
+ }
+
+ protected static class GridPlacementSolution {
+
+ private final SQLiteDatabase mDb;
+ private final DbReader mSrcReader;
+ private final DbReader mDestReader;
+ private final Context mContext;
+ private final GridOccupancy mOccupied;
+ private final int mScreenId;
+ private final int mTrgX;
+ private final int mTrgY;
+ private final List<DbEntry> mItemsToPlace;
+
+ private int mNextStartX;
+ private int mNextStartY;
+
+ GridPlacementSolution(SQLiteDatabase db, DbReader srcReader, DbReader destReader,
+ Context context, List<DbEntry> placedWorkspaceItems, int screenId, int trgX,
+ int trgY, List<DbEntry> itemsToPlace) {
+ mDb = db;
+ mSrcReader = srcReader;
+ mDestReader = destReader;
+ mContext = context;
+ mOccupied = new GridOccupancy(trgX, trgY);
+ mScreenId = screenId;
+ mTrgX = trgX;
+ mTrgY = trgY;
+ mNextStartX = 0;
+ mNextStartY = mTrgY - 1;
+ for (DbEntry entry : placedWorkspaceItems) {
+ mOccupied.markCells(entry, true);
+ }
+ mItemsToPlace = itemsToPlace;
+ }
+
+ public void find() {
+ Iterator<DbEntry> iterator = mItemsToPlace.iterator();
+ while (iterator.hasNext()) {
+ final DbEntry entry = iterator.next();
+ if (entry.minSpanX > mTrgX || entry.minSpanY > mTrgY) {
+ iterator.remove();
+ continue;
+ }
+ if (findPlacement(entry)) {
+ insertEntryInDb(mDb, mContext, mSrcReader.mWorkspaceEntries, entry,
+ mSrcReader.mTableName, mDestReader.mTableName);
+ iterator.remove();
+ }
+ }
+ }
+
+ private boolean findPlacement(DbEntry entry) {
+ for (int y = mNextStartY; y >= 0; y--) {
+ for (int x = mNextStartX; x < mTrgX; x++) {
+ boolean fits = mOccupied.isRegionVacant(x, y, entry.spanX, entry.spanY);
+ boolean minFits = mOccupied.isRegionVacant(x, y, entry.minSpanX,
+ entry.minSpanY);
+ if (minFits) {
+ entry.spanX = entry.minSpanX;
+ entry.spanY = entry.minSpanY;
+ }
+ if (fits || minFits) {
+ entry.screenId = mScreenId;
+ entry.cellX = x;
+ entry.cellY = y;
+ mOccupied.markCells(entry, true);
+ mNextStartX = x + entry.spanX;
+ mNextStartY = y;
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ }
+
+ protected static class HotseatPlacementSolution {
+
+ private final SQLiteDatabase mDb;
+ private final DbReader mSrcReader;
+ private final DbReader mDestReader;
+ private final Context mContext;
+ private final HotseatOccupancy mOccupied;
+ private final List<DbEntry> mItemsToPlace;
+
+ HotseatPlacementSolution(SQLiteDatabase db, DbReader srcReader, DbReader destReader,
+ Context context, int hotseatSize, List<DbEntry> placedHotseatItems,
+ List<DbEntry> itemsToPlace) {
+ mDb = db;
+ mSrcReader = srcReader;
+ mDestReader = destReader;
+ mContext = context;
+ mOccupied = new HotseatOccupancy(hotseatSize);
+ for (DbEntry entry : placedHotseatItems) {
+ mOccupied.markCells(entry, true);
+ }
+ mItemsToPlace = itemsToPlace;
+ }
+
+ public void find() {
+ for (int i = 0; i < mOccupied.mCells.length; i++) {
+ if (!mOccupied.mCells[i] && !mItemsToPlace.isEmpty()) {
+ DbEntry entry = mItemsToPlace.remove(0);
+ entry.screenId = i;
+ // These values does not affect the item position, but we should set them
+ // to something other than -1.
+ entry.cellX = i;
+ entry.cellY = 0;
+ insertEntryInDb(mDb, mContext, mSrcReader.mHotseatEntries, entry,
+ mSrcReader.mTableName, mDestReader.mTableName);
+ mOccupied.markCells(entry, true);
+ }
+ }
+ }
+
+ private class HotseatOccupancy {
+
+ private final boolean[] mCells;
+
+ private HotseatOccupancy(int hotseatSize) {
+ mCells = new boolean[hotseatSize];
+ }
+
+ private void markCells(ItemInfo item, boolean value) {
+ mCells[item.screenId] = value;
+ }
+ }
+ }
+
+ protected static class DbReader {
+
+ private final SQLiteDatabase mDb;
+ private final String mTableName;
+ private final Context mContext;
+ private final HashSet<String> mValidPackages;
+ private final int mHotseatSize;
+ private int mLastScreenId = -1;
+
+ private final ArrayList<DbEntry> mHotseatEntries = new ArrayList<>();
+ private final ArrayList<DbEntry> mWorkspaceEntries = new ArrayList<>();
+
+ DbReader(SQLiteDatabase db, String tableName, Context context,
+ HashSet<String> validPackages, int hotseatSize) {
+ mDb = db;
+ mTableName = tableName;
+ mContext = context;
+ mValidPackages = validPackages;
+ mHotseatSize = hotseatSize;
+ }
+
+ protected ArrayList<DbEntry> loadHotseatEntries() {
+ Cursor c = queryWorkspace(
+ new String[]{
+ LauncherSettings.Favorites._ID, // 0
+ LauncherSettings.Favorites.ITEM_TYPE, // 1
+ LauncherSettings.Favorites.INTENT, // 2
+ LauncherSettings.Favorites.SCREEN}, // 3
+ LauncherSettings.Favorites.CONTAINER + " = "
+ + LauncherSettings.Favorites.CONTAINER_HOTSEAT);
+
+ final int indexId = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
+ final int indexItemType = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
+ final int indexIntent = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
+ final int indexScreen = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
+
+ IntArray entriesToRemove = new IntArray();
+ while (c.moveToNext()) {
+ DbEntry entry = new DbEntry();
+ entry.id = c.getInt(indexId);
+ entry.itemType = c.getInt(indexItemType);
+ entry.screenId = c.getInt(indexScreen);
+
+ if (entry.screenId >= mHotseatSize) {
+ entriesToRemove.add(entry.id);
+ continue;
+ }
+
+ try {
+ // calculate weight
+ switch (entry.itemType) {
+ case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
+ case LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT:
+ case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: {
+ entry.mIntent = c.getString(indexIntent);
+ verifyIntent(c.getString(indexIntent));
+ break;
+ }
+ case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: {
+ int total = getFolderItemsCount(entry);
+ if (total == 0) {
+ throw new Exception("Folder is empty");
+ }
+ break;
+ }
+ default:
+ throw new Exception("Invalid item type");
+ }
+ } catch (Exception e) {
+ if (DEBUG) {
+ Log.d(TAG, "Removing item " + entry.id, e);
+ }
+ entriesToRemove.add(entry.id);
+ continue;
+ }
+ mHotseatEntries.add(entry);
+ }
+ removeEntryFromDb(mDb, mTableName, entriesToRemove);
+ c.close();
+ return mHotseatEntries;
+ }
+
+ protected ArrayList<DbEntry> loadAllWorkspaceEntries() {
+ Cursor c = queryWorkspace(
+ new String[]{
+ LauncherSettings.Favorites._ID, // 0
+ LauncherSettings.Favorites.ITEM_TYPE, // 1
+ LauncherSettings.Favorites.SCREEN, // 2
+ LauncherSettings.Favorites.CELLX, // 3
+ LauncherSettings.Favorites.CELLY, // 4
+ LauncherSettings.Favorites.SPANX, // 5
+ LauncherSettings.Favorites.SPANY, // 6
+ LauncherSettings.Favorites.INTENT, // 7
+ LauncherSettings.Favorites.APPWIDGET_PROVIDER, // 8
+ LauncherSettings.Favorites.APPWIDGET_ID}, // 9
+ LauncherSettings.Favorites.CONTAINER + " = "
+ + LauncherSettings.Favorites.CONTAINER_DESKTOP);
+ return loadWorkspaceEntries(c);
+ }
+
+ protected ArrayList<DbEntry> loadWorkspaceEntries(int screen) {
+ Cursor c = queryWorkspace(
+ new String[]{
+ LauncherSettings.Favorites._ID, // 0
+ LauncherSettings.Favorites.ITEM_TYPE, // 1
+ LauncherSettings.Favorites.SCREEN, // 2
+ LauncherSettings.Favorites.CELLX, // 3
+ LauncherSettings.Favorites.CELLY, // 4
+ LauncherSettings.Favorites.SPANX, // 5
+ LauncherSettings.Favorites.SPANY, // 6
+ LauncherSettings.Favorites.INTENT, // 7
+ LauncherSettings.Favorites.APPWIDGET_PROVIDER, // 8
+ LauncherSettings.Favorites.APPWIDGET_ID}, // 9
+ LauncherSettings.Favorites.CONTAINER + " = "
+ + LauncherSettings.Favorites.CONTAINER_DESKTOP
+ + " AND " + LauncherSettings.Favorites.SCREEN + " = " + screen);
+ return loadWorkspaceEntries(c);
+ }
+
+ private ArrayList<DbEntry> loadWorkspaceEntries(Cursor c) {
+ final int indexId = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
+ final int indexItemType = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
+ final int indexScreen = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
+ final int indexCellX = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
+ final int indexCellY = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
+ final int indexSpanX = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
+ final int indexSpanY = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
+ final int indexIntent = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
+ final int indexAppWidgetProvider = c.getColumnIndexOrThrow(
+ LauncherSettings.Favorites.APPWIDGET_PROVIDER);
+ final int indexAppWidgetId = c.getColumnIndexOrThrow(
+ LauncherSettings.Favorites.APPWIDGET_ID);
+
+ IntArray entriesToRemove = new IntArray();
+ WidgetManagerHelper widgetManagerHelper = new WidgetManagerHelper(mContext);
+ while (c.moveToNext()) {
+ DbEntry entry = new DbEntry();
+ entry.id = c.getInt(indexId);
+ entry.itemType = c.getInt(indexItemType);
+ entry.screenId = c.getInt(indexScreen);
+ mLastScreenId = Math.max(mLastScreenId, entry.screenId);
+ entry.cellX = c.getInt(indexCellX);
+ entry.cellY = c.getInt(indexCellY);
+ entry.spanX = c.getInt(indexSpanX);
+ entry.spanY = c.getInt(indexSpanY);
+
+ try {
+ // calculate weight
+ switch (entry.itemType) {
+ case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
+ case LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT:
+ case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: {
+ entry.mIntent = c.getString(indexIntent);
+ verifyIntent(entry.mIntent);
+ break;
+ }
+ case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: {
+ entry.mProvider = c.getString(indexAppWidgetProvider);
+ ComponentName cn = ComponentName.unflattenFromString(entry.mProvider);
+ verifyPackage(cn.getPackageName());
+
+ int widgetId = c.getInt(indexAppWidgetId);
+ LauncherAppWidgetProviderInfo pInfo =
+ widgetManagerHelper.getLauncherAppWidgetInfo(widgetId);
+ Point spans = null;
+ if (pInfo != null) {
+ spans = pInfo.getMinSpans();
+ }
+ if (spans != null) {
+ entry.minSpanX = spans.x > 0 ? spans.x : entry.spanX;
+ entry.minSpanY = spans.y > 0 ? spans.y : entry.spanY;
+ } else {
+ // Assume that the widget be resized down to 2x2
+ entry.minSpanX = entry.minSpanY = 2;
+ }
+
+ break;
+ }
+ case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: {
+ int total = getFolderItemsCount(entry);
+ if (total == 0) {
+ throw new Exception("Folder is empty");
+ }
+ break;
+ }
+ default:
+ throw new Exception("Invalid item type");
+ }
+ } catch (Exception e) {
+ if (DEBUG) {
+ Log.d(TAG, "Removing item " + entry.id, e);
+ }
+ entriesToRemove.add(entry.id);
+ continue;
+ }
+ mWorkspaceEntries.add(entry);
+ }
+ removeEntryFromDb(mDb, mTableName, entriesToRemove);
+ c.close();
+ return mWorkspaceEntries;
+ }
+
+ private int getFolderItemsCount(DbEntry entry) {
+ Cursor c = queryWorkspace(
+ new String[]{LauncherSettings.Favorites._ID, LauncherSettings.Favorites.INTENT},
+ LauncherSettings.Favorites.CONTAINER + " = " + entry.id);
+
+ int total = 0;
+ while (c.moveToNext()) {
+ try {
+ String intent = c.getString(1);
+ verifyIntent(intent);
+ total++;
+ entry.mFolderItems.add(intent);
+ } catch (Exception e) {
+ removeEntryFromDb(mDb, mTableName, IntArray.wrap(c.getInt(0)));
+ }
+ }
+ c.close();
+ return total;
+ }
+
+ private Cursor queryWorkspace(String[] columns, String where) {
+ return mDb.query(mTableName, columns, where, null, null, null, null);
+ }
+
+ /** Verifies if the mIntent should be restored. */
+ private void verifyIntent(String intentStr)
+ throws Exception {
+ Intent intent = Intent.parseUri(intentStr, 0);
+ if (intent.getComponent() != null) {
+ verifyPackage(intent.getComponent().getPackageName());
+ } else if (intent.getPackage() != null) {
+ // Only verify package if the component was null.
+ verifyPackage(intent.getPackage());
+ }
+ }
+
+ /** Verifies if the package should be restored */
+ private void verifyPackage(String packageName)
+ throws Exception {
+ if (!mValidPackages.contains(packageName)) {
+ // TODO(b/151468819): Handle promise app icon restoration during grid migration.
+ throw new Exception("Package not available");
+ }
+ }
+ }
+
+ protected static class DbEntry extends ItemInfo implements Comparable<DbEntry> {
+
+ private String mIntent;
+ private String mProvider;
+ private Set<String> mFolderItems = new HashSet<>();
+
+ /** Comparator according to the reading order */
+ @Override
+ public int compareTo(DbEntry another) {
+ if (screenId != another.screenId) {
+ return Integer.compare(screenId, another.screenId);
+ }
+ if (cellY != another.cellY) {
+ return -Integer.compare(cellY, another.cellY);
+ }
+ return Integer.compare(cellX, another.cellX);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ DbEntry entry = (DbEntry) o;
+ return Objects.equals(mIntent, entry.mIntent);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(mIntent);
+ }
+
+ public void updateContentValues(ContentValues values) {
+ values.put(LauncherSettings.Favorites.SCREEN, screenId);
+ values.put(LauncherSettings.Favorites.CELLX, cellX);
+ values.put(LauncherSettings.Favorites.CELLY, cellY);
+ values.put(LauncherSettings.Favorites.SPANX, spanX);
+ values.put(LauncherSettings.Favorites.SPANY, spanY);
+ }
+
+ public String getIntentStr() {
+ return mIntent;
+ }
+ }
}
diff --git a/src/com/android/launcher3/model/LoaderCursor.java b/src/com/android/launcher3/model/LoaderCursor.java
index 4961432..244de96 100644
--- a/src/com/android/launcher3/model/LoaderCursor.java
+++ b/src/com/android/launcher3/model/LoaderCursor.java
@@ -28,25 +28,28 @@
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.CursorWrapper;
+import android.net.Uri;
import android.os.UserHandle;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.util.Log;
import android.util.LongSparseArray;
-import com.android.launcher3.AppInfo;
+import androidx.annotation.VisibleForTesting;
+
import com.android.launcher3.InvariantDeviceProfile;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.Utilities;
import com.android.launcher3.Workspace;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.icons.BitmapInfo;
import com.android.launcher3.icons.IconCache;
import com.android.launcher3.icons.LauncherIcons;
import com.android.launcher3.logging.FileLog;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.util.ContentWriter;
import com.android.launcher3.util.GridOccupancy;
import com.android.launcher3.util.IntArray;
@@ -64,6 +67,7 @@
public final LongSparseArray<UserHandle> allUsers = new LongSparseArray<>();
+ private final Uri mContentUri;
private final Context mContext;
private final PackageManager mPM;
private final IconCache mIconCache;
@@ -96,8 +100,10 @@
public int itemType;
public int restoreFlag;
- public LoaderCursor(Cursor c, LauncherAppState app) {
- super(c);
+ public LoaderCursor(Cursor cursor, Uri contentUri, LauncherAppState app) {
+ super(cursor);
+
+ mContentUri = contentUri;
mContext = app.getContext();
mIconCache = app.getIconCache();
mIDP = app.getInvariantDeviceProfile();
@@ -146,8 +152,10 @@
}
}
+ @VisibleForTesting
public WorkspaceItemInfo loadSimpleWorkspaceItem() {
final WorkspaceItemInfo info = new WorkspaceItemInfo();
+ info.intent = new Intent();
// Non-app shortcuts are only supported for current user.
info.user = user;
info.itemType = itemType;
@@ -312,9 +320,8 @@
public boolean commitDeleted() {
if (itemsToRemove.size() > 0) {
// Remove dead items
- mContext.getContentResolver().delete(LauncherSettings.Favorites.CONTENT_URI,
- Utilities.createDbSelectionQuery(
- LauncherSettings.Favorites._ID, itemsToRemove), null);
+ mContext.getContentResolver().delete(mContentUri, Utilities.createDbSelectionQuery(
+ LauncherSettings.Favorites._ID, itemsToRemove), null);
return true;
}
return false;
@@ -339,7 +346,7 @@
// Update restored items that no longer require special handling
ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.RESTORED, 0);
- mContext.getContentResolver().update(LauncherSettings.Favorites.CONTENT_URI, values,
+ mContext.getContentResolver().update(mContentUri, values,
Utilities.createDbSelectionQuery(
LauncherSettings.Favorites._ID, restoredRows), null);
}
diff --git a/src/com/android/launcher3/model/LoaderTask.java b/src/com/android/launcher3/model/LoaderTask.java
index 8dc7a3a..4c02837 100644
--- a/src/com/android/launcher3/model/LoaderTask.java
+++ b/src/com/android/launcher3/model/LoaderTask.java
@@ -16,11 +16,11 @@
package com.android.launcher3.model;
-import static com.android.launcher3.ItemInfoWithIcon.FLAG_DISABLED_LOCKED_USER;
-import static com.android.launcher3.ItemInfoWithIcon.FLAG_DISABLED_SAFEMODE;
-import static com.android.launcher3.ItemInfoWithIcon.FLAG_DISABLED_SUSPENDED;
import static com.android.launcher3.config.FeatureFlags.MULTI_DB_GRID_MIRATION_ALGO;
import static com.android.launcher3.model.ModelUtils.filterCurrentWorkspaceItems;
+import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_DISABLED_LOCKED_USER;
+import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_DISABLED_SAFEMODE;
+import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_DISABLED_SUSPENDED;
import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
import static com.android.launcher3.util.PackageManagerHelper.hasShortcutsPermission;
import static com.android.launcher3.util.PackageManagerHelper.isSystemApp;
@@ -36,6 +36,7 @@
import android.content.pm.PackageInstaller;
import android.content.pm.PackageInstaller.SessionInfo;
import android.content.pm.ShortcutInfo;
+import android.net.Uri;
import android.os.UserHandle;
import android.os.UserManager;
import android.text.TextUtils;
@@ -44,21 +45,15 @@
import android.util.MutableInt;
import android.util.TimingLogger;
-import androidx.annotation.VisibleForTesting;
-
-import com.android.launcher3.AppInfo;
-import com.android.launcher3.FolderInfo;
import com.android.launcher3.InstallShortcutReceiver;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppState;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherModel;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.Utilities;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.folder.Folder;
import com.android.launcher3.folder.FolderGridOrganizer;
+import com.android.launcher3.folder.FolderNameInfo;
import com.android.launcher3.folder.FolderNameProvider;
import com.android.launcher3.icons.ComponentWithLabelAndIcon;
import com.android.launcher3.icons.ComponentWithLabelAndIcon.ComponentWithIconCachingLogic;
@@ -67,6 +62,12 @@
import com.android.launcher3.icons.ShortcutCachingLogic;
import com.android.launcher3.icons.cache.IconCacheUpdateHandler;
import com.android.launcher3.logging.FileLog;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.FolderInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
+import com.android.launcher3.model.data.PackageItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.pm.InstallSessionHelper;
import com.android.launcher3.pm.PackageInstallInfo;
import com.android.launcher3.pm.UserCache;
@@ -75,7 +76,6 @@
import com.android.launcher3.shortcuts.ShortcutKey;
import com.android.launcher3.shortcuts.ShortcutRequest;
import com.android.launcher3.shortcuts.ShortcutRequest.QueryResult;
-import com.android.launcher3.testing.TestProtocol;
import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.IOUtils;
import com.android.launcher3.util.LooperIdleLock;
@@ -103,9 +103,9 @@
public class LoaderTask implements Runnable {
private static final String TAG = "LoaderTask";
- private final LauncherAppState mApp;
+ protected final LauncherAppState mApp;
private final AllAppsList mBgAllAppsList;
- private final BgDataModel mBgDataModel;
+ protected final BgDataModel mBgDataModel;
private FirstScreenBroadcast mFirstScreenBroadcast;
@@ -167,32 +167,15 @@
}
public void run() {
- if (TestProtocol.sDebugTracing) {
- Log.d(TestProtocol.LAUNCHER_DIDNT_INITIALIZE,
- "LoaderTask1 " + this);
- }
synchronized (this) {
// Skip fast if we are already stopped.
if (mStopped) {
return;
}
}
- if (TestProtocol.sDebugTracing) {
- Log.d(TestProtocol.LAUNCHER_DIDNT_INITIALIZE,
- "LoaderTask2 " + this);
- }
Object traceToken = TraceHelper.INSTANCE.beginSection(TAG);
- TimingLogger logger = TestProtocol.sDebugTracing ?
- new TimingLogger(TAG, "run") {
- @Override
- public void addSplit(String splitLabel) {
- super.addSplit(splitLabel);
- Log.d(TestProtocol.LAUNCHER_DIDNT_INITIALIZE,
- "LoaderTask.addSplit " + splitLabel);
- }
- }
- : new TimingLogger(TAG, "run");
+ TimingLogger logger = new TimingLogger(TAG, "run");
try (LauncherModel.LoaderTransaction transaction = mApp.getModel().beginLoader(this)) {
List<ShortcutInfo> allShortcuts = new ArrayList<>();
loadWorkspace(allShortcuts);
@@ -283,10 +266,6 @@
updateHandler.finish();
logger.addSplit("finish icon update");
- if (TestProtocol.sDebugTracing) {
- Log.d(TestProtocol.LAUNCHER_DIDNT_INITIALIZE,
- "LoaderTask3 " + this);
- }
transaction.commit();
} catch (CancellationException e) {
// Loader stopped, ignore
@@ -302,8 +281,11 @@
this.notify();
}
- @VisibleForTesting
- void loadWorkspace(List<ShortcutInfo> allDeepShortcuts) {
+ private void loadWorkspace(List<ShortcutInfo> allDeepShortcuts) {
+ loadWorkspace(allDeepShortcuts, LauncherSettings.Favorites.CONTENT_URI);
+ }
+
+ protected void loadWorkspace(List<ShortcutInfo> allDeepShortcuts, Uri contentUri) {
final Context context = mApp.getContext();
final ContentResolver contentResolver = context.getContentResolver();
final PackageManagerHelper pmHelper = new PackageManagerHelper(context);
@@ -347,8 +329,8 @@
mFirstScreenBroadcast = new FirstScreenBroadcast(installingPkgs);
Map<ShortcutKey, ShortcutInfo> shortcutKeyToPinnedShortcuts = new HashMap<>();
- final LoaderCursor c = new LoaderCursor(contentResolver.query(
- LauncherSettings.Favorites.CONTENT_URI, null, null, null, null), mApp);
+ final LoaderCursor c = new LoaderCursor(
+ contentResolver.query(contentUri, null, null, null, null), contentUri, mApp);
Map<ComponentKey, AppWidgetProviderInfo> widgetProvidersMap = null;
@@ -553,7 +535,7 @@
pinnedShortcut.getPackage(), info.user)) {
info.runtimeStatusFlags |= FLAG_DISABLED_SUSPENDED;
}
- intent = info.intent;
+ intent = info.getIntent();
allDeepShortcuts.add(pinnedShortcut);
} else {
// Create a shortcut info in disabled mode for now.
@@ -921,15 +903,18 @@
}
private void loadFolderNames() {
- FolderNameProvider provider = FolderNameProvider.newInstance(mApp.getContext());
+ FolderNameProvider provider = FolderNameProvider.newInstance(mApp.getContext(),
+ mBgAllAppsList.data, mBgDataModel.folders);
synchronized (mBgDataModel) {
for (int i = 0; i < mBgDataModel.folders.size(); i++) {
- String[] suggestedOut = new String[FolderNameProvider.SUGGEST_MAX];
+ FolderNameInfo[] suggestionInfos =
+ new FolderNameInfo[FolderNameProvider.SUGGEST_MAX];
FolderInfo info = mBgDataModel.folders.valueAt(i);
if (info.suggestedFolderNames == null) {
- provider.getSuggestedFolderName(mApp.getContext(), info.contents, suggestedOut);
- info.suggestedFolderNames = new Intent().putExtra("suggest", suggestedOut);
+ provider.getSuggestedFolderName(mApp.getContext(), info.contents,
+ suggestionInfos);
+ info.suggestedFolderNames = new Intent().putExtra("suggest", suggestionInfos);
}
}
}
diff --git a/src/com/android/launcher3/model/ModelUtils.java b/src/com/android/launcher3/model/ModelUtils.java
index 628dd95..ef7e828 100644
--- a/src/com/android/launcher3/model/ModelUtils.java
+++ b/src/com/android/launcher3/model/ModelUtils.java
@@ -16,9 +16,9 @@
package com.android.launcher3.model;
import com.android.launcher3.InvariantDeviceProfile;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.config.FeatureFlags;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.util.IntSet;
import java.util.ArrayList;
@@ -97,7 +97,7 @@
return Integer.compare(lhs.screenId, rhs.screenId);
}
default:
- if (FeatureFlags.IS_DOGFOOD_BUILD) {
+ if (FeatureFlags.IS_STUDIO_BUILD) {
throw new RuntimeException(
"Unexpected container type when sorting workspace items.");
}
diff --git a/src/com/android/launcher3/model/ModelWriter.java b/src/com/android/launcher3/model/ModelWriter.java
index ccd1554..2c99df7 100644
--- a/src/com/android/launcher3/model/ModelWriter.java
+++ b/src/com/android/launcher3/model/ModelWriter.java
@@ -27,20 +27,20 @@
import android.os.Looper;
import android.util.Log;
-import com.android.launcher3.FolderInfo;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherAppWidgetHost;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherModel;
import com.android.launcher3.LauncherProvider;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.LauncherSettings.Settings;
import com.android.launcher3.Utilities;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.logging.FileLog;
+import com.android.launcher3.model.data.FolderInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.util.ContentWriter;
import com.android.launcher3.util.ItemInfoMatcher;
@@ -115,8 +115,9 @@
ItemInfo modelItem = mBgDataModel.itemsIdMap.get(itemId);
if (modelItem != null && item != modelItem) {
// check all the data is consistent
- if (!Utilities.IS_DEBUG_DEVICE && !FeatureFlags.IS_DOGFOOD_BUILD &&
- modelItem instanceof WorkspaceItemInfo && item instanceof WorkspaceItemInfo) {
+ if (!Utilities.IS_DEBUG_DEVICE && !FeatureFlags.IS_STUDIO_BUILD
+ && modelItem instanceof WorkspaceItemInfo
+ && item instanceof WorkspaceItemInfo) {
if (modelItem.title.toString().equals(item.title.toString()) &&
modelItem.getIntent().filterEquals(item.getIntent()) &&
modelItem.id == item.id &&
@@ -320,7 +321,7 @@
*/
public void prepareToUndoDelete() {
if (!mPreparingToUndo) {
- if (!mDeleteRunnables.isEmpty() && FeatureFlags.IS_DOGFOOD_BUILD) {
+ if (!mDeleteRunnables.isEmpty() && FeatureFlags.IS_STUDIO_BUILD) {
throw new IllegalStateException("There are still uncommitted delete operations!");
}
mDeleteRunnables.clear();
diff --git a/src/com/android/launcher3/model/PackageInstallStateChangedTask.java b/src/com/android/launcher3/model/PackageInstallStateChangedTask.java
index 2832150..203f1ca 100644
--- a/src/com/android/launcher3/model/PackageInstallStateChangedTask.java
+++ b/src/com/android/launcher3/model/PackageInstallStateChangedTask.java
@@ -19,13 +19,13 @@
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppState;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherModel.CallbackTask;
-import com.android.launcher3.PromiseAppInfo;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.model.BgDataModel.Callbacks;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
+import com.android.launcher3.model.data.PromiseAppInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.pm.PackageInstallInfo;
import com.android.launcher3.util.InstantAppResolver;
diff --git a/src/com/android/launcher3/model/PackageUpdatedTask.java b/src/com/android/launcher3/model/PackageUpdatedTask.java
index 48c56e9..0d97596 100644
--- a/src/com/android/launcher3/model/PackageUpdatedTask.java
+++ b/src/com/android/launcher3/model/PackageUpdatedTask.java
@@ -15,8 +15,8 @@
*/
package com.android.launcher3.model;
-import static com.android.launcher3.WorkspaceItemInfo.FLAG_AUTOINSTALL_ICON;
-import static com.android.launcher3.WorkspaceItemInfo.FLAG_RESTORED_ICON;
+import static com.android.launcher3.model.data.WorkspaceItemInfo.FLAG_AUTOINSTALL_ICON;
+import static com.android.launcher3.model.data.WorkspaceItemInfo.FLAG_RESTORED_ICON;
import android.content.ComponentName;
import android.content.Context;
@@ -29,18 +29,18 @@
import android.util.Log;
import com.android.launcher3.InstallShortcutReceiver;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppState;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.SessionCommitReceiver;
import com.android.launcher3.Utilities;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.icons.BitmapInfo;
import com.android.launcher3.icons.IconCache;
import com.android.launcher3.icons.LauncherIcons;
import com.android.launcher3.logging.FileLog;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.shortcuts.ShortcutRequest;
import com.android.launcher3.testing.TestProtocol;
import com.android.launcher3.util.FlagOp;
@@ -233,7 +233,7 @@
} else if (!isTargetValid) {
removedShortcuts.put(si.id, true);
FileLog.e(TAG, "Restored shortcut no longer valid "
- + si.intent);
+ + si.getIntent());
continue;
} else {
si.status = WorkspaceItemInfo.DEFAULT;
diff --git a/src/com/android/launcher3/model/ShortcutsChangedTask.java b/src/com/android/launcher3/model/ShortcutsChangedTask.java
index 3f79ad0..1cbe5c2 100644
--- a/src/com/android/launcher3/model/ShortcutsChangedTask.java
+++ b/src/com/android/launcher3/model/ShortcutsChangedTask.java
@@ -19,10 +19,10 @@
import android.content.pm.ShortcutInfo;
import android.os.UserHandle;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherSettings;
-import com.android.launcher3.WorkspaceItemInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.shortcuts.ShortcutKey;
import com.android.launcher3.shortcuts.ShortcutRequest;
import com.android.launcher3.util.ItemInfoMatcher;
diff --git a/src/com/android/launcher3/model/UserLockStateChangedTask.java b/src/com/android/launcher3/model/UserLockStateChangedTask.java
index a3adc82..7ec884f 100644
--- a/src/com/android/launcher3/model/UserLockStateChangedTask.java
+++ b/src/com/android/launcher3/model/UserLockStateChangedTask.java
@@ -15,17 +15,16 @@
*/
package com.android.launcher3.model;
-import static com.android.launcher3.ItemInfoWithIcon.FLAG_DISABLED_LOCKED_USER;
+import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_DISABLED_LOCKED_USER;
import android.content.Context;
import android.content.pm.ShortcutInfo;
import android.os.UserHandle;
-import android.os.UserManager;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherSettings;
-import com.android.launcher3.WorkspaceItemInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.shortcuts.ShortcutKey;
import com.android.launcher3.shortcuts.ShortcutRequest;
import com.android.launcher3.shortcuts.ShortcutRequest.QueryResult;
@@ -43,18 +42,19 @@
public class UserLockStateChangedTask extends BaseModelUpdateTask {
private final UserHandle mUser;
+ private boolean mIsUserUnlocked;
- public UserLockStateChangedTask(UserHandle user) {
+ public UserLockStateChangedTask(UserHandle user, boolean isUserUnlocked) {
mUser = user;
+ mIsUserUnlocked = isUserUnlocked;
}
@Override
public void execute(LauncherAppState app, BgDataModel dataModel, AllAppsList apps) {
Context context = app.getContext();
- boolean isUserUnlocked = context.getSystemService(UserManager.class).isUserUnlocked(mUser);
HashMap<ShortcutKey, ShortcutInfo> pinnedShortcuts = new HashMap<>();
- if (isUserUnlocked) {
+ if (mIsUserUnlocked) {
QueryResult shortcuts = new ShortcutRequest(context, mUser)
.query(ShortcutRequest.PINNED);
if (shortcuts.wasSuccess()) {
@@ -65,7 +65,7 @@
// Shortcut manager can fail due to some race condition when the lock state
// changes too frequently. For the purpose of the update,
// consider it as still locked.
- isUserUnlocked = false;
+ mIsUserUnlocked = false;
}
}
@@ -77,7 +77,7 @@
if (itemInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT
&& mUser.equals(itemInfo.user)) {
WorkspaceItemInfo si = (WorkspaceItemInfo) itemInfo;
- if (isUserUnlocked) {
+ if (mIsUserUnlocked) {
ShortcutKey key = ShortcutKey.fromItemInfo(si);
ShortcutInfo shortcut = pinnedShortcuts.get(key);
// We couldn't verify the shortcut during loader. If its no longer available
@@ -108,7 +108,7 @@
}
}
- if (isUserUnlocked) {
+ if (mIsUserUnlocked) {
dataModel.updateDeepShortcutCounts(
null, mUser,
new ShortcutRequest(context, mUser).query(ShortcutRequest.ALL));
diff --git a/src/com/android/launcher3/AppInfo.java b/src/com/android/launcher3/model/data/AppInfo.java
similarity index 94%
rename from src/com/android/launcher3/AppInfo.java
rename to src/com/android/launcher3/model/data/AppInfo.java
index f76ca50..ae79f0d 100644
--- a/src/com/android/launcher3/AppInfo.java
+++ b/src/com/android/launcher3/model/data/AppInfo.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.android.launcher3;
+package com.android.launcher3.model.data;
import android.content.ComponentName;
import android.content.Context;
@@ -28,6 +28,8 @@
import androidx.annotation.VisibleForTesting;
+import com.android.launcher3.LauncherSettings;
+import com.android.launcher3.Utilities;
import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.PackageManagerHelper;
@@ -121,7 +123,8 @@
return new Intent(Intent.ACTION_MAIN)
.addCategory(Intent.CATEGORY_LAUNCHER)
.setComponent(cn)
- .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
+ .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
+ | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
}
public static void updateRuntimeFlagsForActivityTarget(
diff --git a/src/com/android/launcher3/FolderInfo.java b/src/com/android/launcher3/model/data/FolderInfo.java
similarity index 93%
rename from src/com/android/launcher3/FolderInfo.java
rename to src/com/android/launcher3/model/data/FolderInfo.java
index 787eee1..cfe34c1 100644
--- a/src/com/android/launcher3/FolderInfo.java
+++ b/src/com/android/launcher3/model/data/FolderInfo.java
@@ -14,11 +14,13 @@
* limitations under the License.
*/
-package com.android.launcher3;
+package com.android.launcher3.model.data;
import android.content.Intent;
import android.os.Process;
+import com.android.launcher3.LauncherSettings;
+import com.android.launcher3.Utilities;
import com.android.launcher3.model.ModelWriter;
import com.android.launcher3.util.ContentWriter;
@@ -48,6 +50,8 @@
public static final int FLAG_MANUAL_FOLDER_NAME = 0x00000008;
+ public static final String EXTRA_FOLDER_SUGGESTIONS = "suggest";
+
public int options;
public Intent suggestedFolderNames;
@@ -77,7 +81,7 @@
* Add an app or shortcut for a specified rank.
*/
public void add(WorkspaceItemInfo item, int rank, boolean animate) {
- rank = Utilities.boundToRange(rank, 0, contents.size() + 1);
+ rank = Utilities.boundToRange(rank, 0, contents.size());
contents.add(rank, item);
for (int i = 0; i < mListeners.size(); i++) {
mListeners.get(i).onAdd(item, rank);
diff --git a/src/com/android/launcher3/model/data/ItemInfo.java b/src/com/android/launcher3/model/data/ItemInfo.java
new file mode 100644
index 0000000..bd843e7
--- /dev/null
+++ b/src/com/android/launcher3/model/data/ItemInfo.java
@@ -0,0 +1,303 @@
+/*
+ * Copyright (C) 2008 The Android Open 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.launcher3.model.data;
+
+import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_DESKTOP;
+import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_HOTSEAT;
+import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
+import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET;
+import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT;
+import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
+
+import android.content.ComponentName;
+import android.content.ContentValues;
+import android.content.Intent;
+import android.os.Process;
+import android.os.UserHandle;
+
+import androidx.annotation.Nullable;
+
+import com.android.launcher3.LauncherSettings;
+import com.android.launcher3.LauncherSettings.Favorites;
+import com.android.launcher3.Workspace;
+import com.android.launcher3.logger.LauncherAtom;
+import com.android.launcher3.util.ContentWriter;
+
+/**
+ * Represents an item in the launcher.
+ */
+public class ItemInfo {
+
+ public static final boolean DEBUG = true;
+ public static final int NO_ID = -1;
+
+ /**
+ * The id in the settings database for this item
+ */
+ public int id = NO_ID;
+
+ /**
+ * One of {@link Favorites#ITEM_TYPE_APPLICATION},
+ * {@link Favorites#ITEM_TYPE_SHORTCUT},
+ * {@link Favorites#ITEM_TYPE_DEEP_SHORTCUT}
+ * {@link Favorites#ITEM_TYPE_FOLDER},
+ * {@link Favorites#ITEM_TYPE_APPWIDGET} or
+ * {@link Favorites#ITEM_TYPE_CUSTOM_APPWIDGET}.
+ */
+ public int itemType;
+
+ /**
+ * The id of the container that holds this item. For the desktop, this will be
+ * {@link Favorites#CONTAINER_DESKTOP}. For the all applications folder it
+ * will be {@link #NO_ID} (since it is not stored in the settings DB). For user folders
+ * it will be the id of the folder.
+ */
+ public int container = NO_ID;
+
+ /**
+ * Indicates the screen in which the shortcut appears if the container types is
+ * {@link Favorites#CONTAINER_DESKTOP}. (i.e., ignore if the container type is
+ * {@link Favorites#CONTAINER_HOTSEAT})
+ */
+ public int screenId = -1;
+
+ /**
+ * Indicates the X position of the associated cell.
+ */
+ public int cellX = -1;
+
+ /**
+ * Indicates the Y position of the associated cell.
+ */
+ public int cellY = -1;
+
+ /**
+ * Indicates the X cell span.
+ */
+ public int spanX = 1;
+
+ /**
+ * Indicates the Y cell span.
+ */
+ public int spanY = 1;
+
+ /**
+ * Indicates the minimum X cell span.
+ */
+ public int minSpanX = 1;
+
+ /**
+ * Indicates the minimum Y cell span.
+ */
+ public int minSpanY = 1;
+
+ /**
+ * Indicates the position in an ordered list.
+ */
+ public int rank = 0;
+
+ /**
+ * Title of the item
+ */
+ public CharSequence title;
+
+ /**
+ * Content description of the item.
+ */
+ public CharSequence contentDescription;
+
+ public UserHandle user;
+
+ public ItemInfo() {
+ user = Process.myUserHandle();
+ }
+
+ protected ItemInfo(ItemInfo info) {
+ copyFrom(info);
+ }
+
+ public void copyFrom(ItemInfo info) {
+ id = info.id;
+ cellX = info.cellX;
+ cellY = info.cellY;
+ spanX = info.spanX;
+ spanY = info.spanY;
+ rank = info.rank;
+ screenId = info.screenId;
+ itemType = info.itemType;
+ container = info.container;
+ user = info.user;
+ contentDescription = info.contentDescription;
+ }
+
+ public Intent getIntent() {
+ return null;
+ }
+
+ @Nullable
+ public ComponentName getTargetComponent() {
+ Intent intent = getIntent();
+ if (intent != null) {
+ return intent.getComponent();
+ } else {
+ return null;
+ }
+ }
+
+ public void writeToValues(ContentWriter writer) {
+ writer.put(LauncherSettings.Favorites.ITEM_TYPE, itemType)
+ .put(LauncherSettings.Favorites.CONTAINER, container)
+ .put(LauncherSettings.Favorites.SCREEN, screenId)
+ .put(LauncherSettings.Favorites.CELLX, cellX)
+ .put(LauncherSettings.Favorites.CELLY, cellY)
+ .put(LauncherSettings.Favorites.SPANX, spanX)
+ .put(LauncherSettings.Favorites.SPANY, spanY)
+ .put(LauncherSettings.Favorites.RANK, rank);
+ }
+
+ public void readFromValues(ContentValues values) {
+ itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
+ container = values.getAsInteger(LauncherSettings.Favorites.CONTAINER);
+ screenId = values.getAsInteger(LauncherSettings.Favorites.SCREEN);
+ cellX = values.getAsInteger(LauncherSettings.Favorites.CELLX);
+ cellY = values.getAsInteger(LauncherSettings.Favorites.CELLY);
+ spanX = values.getAsInteger(LauncherSettings.Favorites.SPANX);
+ spanY = values.getAsInteger(LauncherSettings.Favorites.SPANY);
+ rank = values.getAsInteger(LauncherSettings.Favorites.RANK);
+ }
+
+ /**
+ * Write the fields of this item to the DB
+ */
+ public void onAddToDatabase(ContentWriter writer) {
+ if (screenId == Workspace.EXTRA_EMPTY_SCREEN_ID) {
+ // We should never persist an item on the extra empty screen.
+ throw new RuntimeException("Screen id should not be EXTRA_EMPTY_SCREEN_ID");
+ }
+
+ writeToValues(writer);
+ writer.put(LauncherSettings.Favorites.PROFILE_ID, user);
+ }
+
+ @Override
+ public final String toString() {
+ return getClass().getSimpleName() + "(" + dumpProperties() + ")";
+ }
+
+ protected String dumpProperties() {
+ return "id=" + id
+ + " type=" + LauncherSettings.Favorites.itemTypeToString(itemType)
+ + " container=" + LauncherSettings.Favorites.containerToString(container)
+ + " targetComponent=" + getTargetComponent()
+ + " screen=" + screenId
+ + " cell(" + cellX + "," + cellY + ")"
+ + " span(" + spanX + "," + spanY + ")"
+ + " minSpan(" + minSpanX + "," + minSpanY + ")"
+ + " rank=" + rank
+ + " user=" + user
+ + " title=" + title;
+ }
+
+ /**
+ * Whether this item is disabled.
+ */
+ public boolean isDisabled() {
+ return false;
+ }
+
+ public int getViewId() {
+ // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
+ // This cast is safe as long as the id < 0x00FFFFFF
+ // Since we jail all the dynamically generated views, there should be no clashes
+ // with any other views.
+ return id;
+ }
+
+ /**
+ * Returns if an Item is a predicted item
+ */
+ public boolean isPredictedItem() {
+ return container == LauncherSettings.Favorites.CONTAINER_HOTSEAT_PREDICTION
+ || container == LauncherSettings.Favorites.CONTAINER_PREDICTION;
+ }
+
+ /**
+ * Can be overridden by inherited classes to fill in {@link LauncherAtom.ItemInfo}
+ */
+ public void setItemBuilder(LauncherAtom.ItemInfo.Builder builder) {
+ }
+
+ /**
+ * Creates {@link LauncherAtom.ItemInfo} with important fields and parent container info.
+ */
+ public LauncherAtom.ItemInfo buildProto(Intent intent, FolderInfo fInfo) {
+
+ LauncherAtom.ItemInfo.Builder itemBuilder = LauncherAtom.ItemInfo.newBuilder();
+ itemBuilder.setIsWork(user != Process.myUserHandle());
+ ComponentName cn = getTargetComponent();
+ switch (itemType) {
+ case ITEM_TYPE_APPLICATION:
+ itemBuilder.setApplication(LauncherAtom.Application.newBuilder()
+ .setComponentName(cn.flattenToShortString())
+ .setPackageName(cn.getPackageName()));
+ break;
+ case ITEM_TYPE_DEEP_SHORTCUT:
+ case ITEM_TYPE_SHORTCUT:
+ itemBuilder.setShortcut(LauncherAtom.Shortcut.newBuilder()
+ .setShortcutName(cn.flattenToShortString()));
+ break;
+ case ITEM_TYPE_APPWIDGET:
+ setItemBuilder(itemBuilder);
+ break;
+ default:
+ break;
+
+ }
+ if (fInfo != null) {
+ LauncherAtom.FolderContainer.Builder folderBuilder =
+ LauncherAtom.FolderContainer.newBuilder();
+ folderBuilder.setGridX(cellX).setGridY(cellY).setPageIndex(screenId);
+
+ switch (fInfo.container) {
+ case CONTAINER_HOTSEAT:
+ folderBuilder.setHotseat(LauncherAtom.HotseatContainer.newBuilder()
+ .setIndex(fInfo.screenId));
+ break;
+ case CONTAINER_DESKTOP:
+ folderBuilder.setWorkspace(LauncherAtom.WorkspaceContainer.newBuilder()
+ .setPageIndex(fInfo.screenId)
+ .setGridX(fInfo.cellX).setGridY(fInfo.cellY));
+ break;
+ }
+ itemBuilder.setFolder(folderBuilder);
+ } else {
+ switch (container) {
+ case CONTAINER_HOTSEAT:
+ itemBuilder.setHotseat(LauncherAtom.HotseatContainer.newBuilder()
+ .setIndex(screenId));
+ break;
+ case CONTAINER_DESKTOP:
+ itemBuilder.setWorkspace(LauncherAtom.WorkspaceContainer.newBuilder()
+ .setGridX(cellX)
+ .setGridY(cellY)
+ .setPageIndex(screenId));
+ break;
+ }
+ }
+ return itemBuilder.build();
+ }
+}
diff --git a/src/com/android/launcher3/ItemInfoWithIcon.java b/src/com/android/launcher3/model/data/ItemInfoWithIcon.java
similarity index 93%
rename from src/com/android/launcher3/ItemInfoWithIcon.java
rename to src/com/android/launcher3/model/data/ItemInfoWithIcon.java
index 1941455..d95f94f 100644
--- a/src/com/android/launcher3/ItemInfoWithIcon.java
+++ b/src/com/android/launcher3/model/data/ItemInfoWithIcon.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.android.launcher3;
+package com.android.launcher3.model.data;
import com.android.launcher3.icons.BitmapInfo;
@@ -60,9 +60,9 @@
*/
public static final int FLAG_DISABLED_LOCKED_USER = 1 << 5;
- public static final int FLAG_DISABLED_MASK = FLAG_DISABLED_SAFEMODE |
- FLAG_DISABLED_NOT_AVAILABLE | FLAG_DISABLED_SUSPENDED |
- FLAG_DISABLED_QUIET_USER | FLAG_DISABLED_BY_PUBLISHER | FLAG_DISABLED_LOCKED_USER;
+ public static final int FLAG_DISABLED_MASK = FLAG_DISABLED_SAFEMODE
+ | FLAG_DISABLED_NOT_AVAILABLE | FLAG_DISABLED_SUSPENDED
+ | FLAG_DISABLED_QUIET_USER | FLAG_DISABLED_BY_PUBLISHER | FLAG_DISABLED_LOCKED_USER;
/**
* The item points to a system app.
diff --git a/src/com/android/launcher3/LauncherAppWidgetInfo.java b/src/com/android/launcher3/model/data/LauncherAppWidgetInfo.java
similarity index 85%
rename from src/com/android/launcher3/LauncherAppWidgetInfo.java
rename to src/com/android/launcher3/model/data/LauncherAppWidgetInfo.java
index b824301..adb97dc 100644
--- a/src/com/android/launcher3/LauncherAppWidgetInfo.java
+++ b/src/com/android/launcher3/model/data/LauncherAppWidgetInfo.java
@@ -14,14 +14,17 @@
* limitations under the License.
*/
-package com.android.launcher3;
+package com.android.launcher3.model.data;
import android.appwidget.AppWidgetHostView;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Process;
-import com.android.launcher3.model.PackageItemInfo;
+import com.android.launcher3.AppWidgetResizeFrame;
+import com.android.launcher3.Launcher;
+import com.android.launcher3.LauncherSettings;
+import com.android.launcher3.logger.LauncherAtom;
import com.android.launcher3.util.ContentWriter;
/**
@@ -153,7 +156,7 @@
* When we bind the widget, we should notify the widget that the size has changed if we have not
* done so already (only really for default workspace widgets).
*/
- void onBindAppWidget(Launcher launcher, AppWidgetHostView hostView) {
+ public void onBindAppWidget(Launcher launcher, AppWidgetHostView hostView) {
if (!mHasNotifiedInitialWidgetSizeChanged) {
AppWidgetResizeFrame.updateWidgetSizeRanges(hostView, launcher, spanX, spanY);
mHasNotifiedInitialWidgetSizeChanged = true;
@@ -162,12 +165,14 @@
@Override
protected String dumpProperties() {
- return super.dumpProperties() + " appWidgetId=" + appWidgetId;
+ return super.dumpProperties()
+ + " providerName=" + providerName
+ + " appWidgetId=" + appWidgetId;
}
public final boolean isWidgetIdAllocated() {
- return (restoreStatus & FLAG_ID_NOT_VALID) == 0 ||
- (restoreStatus & FLAG_ID_ALLOCATED) == FLAG_ID_ALLOCATED;
+ return (restoreStatus & FLAG_ID_NOT_VALID) == 0
+ || (restoreStatus & FLAG_ID_ALLOCATED) == FLAG_ID_ALLOCATED;
}
public final boolean hasRestoreFlag(int flag) {
@@ -182,4 +187,13 @@
public final boolean hasOptionFlag(int option) {
return (options & option) != 0;
}
+
+ @Override
+ public void setItemBuilder(LauncherAtom.ItemInfo.Builder builder) {
+ builder.setWidget(LauncherAtom.Widget.newBuilder()
+ .setSpanX(spanX)
+ .setSpanY(spanY)
+ .setComponentName(providerName.toString())
+ .setPackageName(providerName.getPackageName()));
+ }
}
diff --git a/src/com/android/launcher3/model/PackageItemInfo.java b/src/com/android/launcher3/model/data/PackageItemInfo.java
similarity index 77%
rename from src/com/android/launcher3/model/PackageItemInfo.java
rename to src/com/android/launcher3/model/data/PackageItemInfo.java
index 3ef48cd..b70d0d4 100644
--- a/src/com/android/launcher3/model/PackageItemInfo.java
+++ b/src/com/android/launcher3/model/data/PackageItemInfo.java
@@ -14,11 +14,12 @@
* limitations under the License.
*/
-package com.android.launcher3.model;
+package com.android.launcher3.model.data;
-import com.android.launcher3.ItemInfoWithIcon;
import com.android.launcher3.LauncherSettings;
+import java.util.Objects;
+
/**
* Represents a {@link Package} in the widget tray section.
*/
@@ -48,4 +49,17 @@
public PackageItemInfo clone() {
return new PackageItemInfo(this);
}
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ PackageItemInfo that = (PackageItemInfo) o;
+ return Objects.equals(packageName, that.packageName);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(packageName);
+ }
}
diff --git a/src/com/android/launcher3/PromiseAppInfo.java b/src/com/android/launcher3/model/data/PromiseAppInfo.java
similarity index 97%
rename from src/com/android/launcher3/PromiseAppInfo.java
rename to src/com/android/launcher3/model/data/PromiseAppInfo.java
index e55e4bd..b6231ed 100644
--- a/src/com/android/launcher3/PromiseAppInfo.java
+++ b/src/com/android/launcher3/model/data/PromiseAppInfo.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.android.launcher3;
+package com.android.launcher3.model.data;
import android.content.Context;
import android.content.Intent;
diff --git a/src/com/android/launcher3/WorkspaceItemInfo.java b/src/com/android/launcher3/model/data/WorkspaceItemInfo.java
similarity index 94%
rename from src/com/android/launcher3/WorkspaceItemInfo.java
rename to src/com/android/launcher3/model/data/WorkspaceItemInfo.java
index be907e5..a7bf1f3 100644
--- a/src/com/android/launcher3/WorkspaceItemInfo.java
+++ b/src/com/android/launcher3/model/data/WorkspaceItemInfo.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.android.launcher3;
+package com.android.launcher3.model.data;
import android.app.Person;
import android.content.ComponentName;
@@ -25,7 +25,9 @@
import androidx.annotation.NonNull;
+import com.android.launcher3.LauncherSettings;
import com.android.launcher3.LauncherSettings.Favorites;
+import com.android.launcher3.Utilities;
import com.android.launcher3.icons.IconCache;
import com.android.launcher3.shortcuts.ShortcutKey;
import com.android.launcher3.uioverrides.ApiWrapper;
@@ -120,7 +122,7 @@
public WorkspaceItemInfo(AppInfo info) {
super(info);
title = Utilities.trim(info.title);
- intent = new Intent(info.intent);
+ intent = new Intent(info.getIntent());
}
/**
@@ -199,8 +201,8 @@
/** Returns the WorkspaceItemInfo id associated with the deep shortcut. */
public String getDeepShortcutId() {
- return itemType == Favorites.ITEM_TYPE_DEEP_SHORTCUT ?
- getIntent().getStringExtra(ShortcutKey.EXTRA_SHORTCUT_ID) : null;
+ return itemType == Favorites.ITEM_TYPE_DEEP_SHORTCUT
+ ? getIntent().getStringExtra(ShortcutKey.EXTRA_SHORTCUT_ID) : null;
}
@NonNull
@@ -211,8 +213,8 @@
@Override
public ComponentName getTargetComponent() {
ComponentName cn = super.getTargetComponent();
- if (cn == null && (itemType == Favorites.ITEM_TYPE_SHORTCUT
- || hasStatusFlag(FLAG_SUPPORTS_WEB_UI|FLAG_AUTOINSTALL_ICON|FLAG_RESTORED_ICON))) {
+ if (cn == null && (itemType == Favorites.ITEM_TYPE_SHORTCUT || hasStatusFlag(
+ FLAG_SUPPORTS_WEB_UI | FLAG_AUTOINSTALL_ICON | FLAG_RESTORED_ICON))) {
// Legacy shortcuts and promise icons with web UI may not have a componentName but just
// a packageName. In that case create a dummy componentName instead of adding additional
// check everywhere.
diff --git a/src/com/android/launcher3/notification/NotificationMainView.java b/src/com/android/launcher3/notification/NotificationMainView.java
index 812268a..b03aa9c 100644
--- a/src/com/android/launcher3/notification/NotificationMainView.java
+++ b/src/com/android/launcher3/notification/NotificationMainView.java
@@ -34,10 +34,10 @@
import android.widget.FrameLayout;
import android.widget.TextView;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.Launcher;
import com.android.launcher3.R;
import com.android.launcher3.anim.AnimationSuccessListener;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.touch.BaseSwipeDetector;
import com.android.launcher3.touch.OverScroll;
import com.android.launcher3.touch.SingleAxisSwipeDetector;
@@ -176,7 +176,7 @@
// SingleAxisSwipeDetector.Listener's
@Override
- public void onDragStart(boolean start) { }
+ public void onDragStart(boolean start, float startDisplacement) { }
@Override
diff --git a/src/com/android/launcher3/pageindicators/WorkspacePageIndicator.java b/src/com/android/launcher3/pageindicators/WorkspacePageIndicator.java
index 0f2ca72..408796f 100644
--- a/src/com/android/launcher3/pageindicators/WorkspacePageIndicator.java
+++ b/src/com/android/launcher3/pageindicators/WorkspacePageIndicator.java
@@ -121,7 +121,7 @@
mLinePaint.setAlpha(0);
mLauncher = Launcher.getLauncher(context);
- mLineHeight = res.getDimensionPixelSize(R.dimen.dynamic_grid_page_indicator_line_height);
+ mLineHeight = res.getDimensionPixelSize(R.dimen.workspace_page_indicator_line_height);
boolean darkText = WallpaperColorInfo.INSTANCE.get(context).supportsDarkText();
mActiveAlpha = darkText ? BLACK_ALPHA : WHITE_ALPHA;
diff --git a/src/com/android/launcher3/pm/PinRequestHelper.java b/src/com/android/launcher3/pm/PinRequestHelper.java
index 74a5a31..179061f 100644
--- a/src/com/android/launcher3/pm/PinRequestHelper.java
+++ b/src/com/android/launcher3/pm/PinRequestHelper.java
@@ -30,8 +30,8 @@
import androidx.annotation.Nullable;
import com.android.launcher3.LauncherAppState;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.icons.ShortcutCachingLogic;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
public class PinRequestHelper {
diff --git a/src/com/android/launcher3/pm/ShortcutConfigActivityInfo.java b/src/com/android/launcher3/pm/ShortcutConfigActivityInfo.java
index ac0e065..40d7031 100644
--- a/src/com/android/launcher3/pm/ShortcutConfigActivityInfo.java
+++ b/src/com/android/launcher3/pm/ShortcutConfigActivityInfo.java
@@ -40,9 +40,9 @@
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.icons.ComponentWithLabelAndIcon;
import com.android.launcher3.icons.IconCache;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.util.PackageUserKey;
import java.util.ArrayList;
diff --git a/src/com/android/launcher3/pm/UserCache.java b/src/com/android/launcher3/pm/UserCache.java
index 678b647..f723256 100644
--- a/src/com/android/launcher3/pm/UserCache.java
+++ b/src/com/android/launcher3/pm/UserCache.java
@@ -95,7 +95,7 @@
private void removeUserChangeListener(Runnable command) {
synchronized (this) {
- mUserChangeListeners.add(command);
+ mUserChangeListeners.remove(command);
if (mUserChangeListeners.isEmpty()) {
// Disable cache and stop listening
mContext.unregisterReceiver(mUserChangeReceiver);
diff --git a/src/com/android/launcher3/popup/ArrowPopup.java b/src/com/android/launcher3/popup/ArrowPopup.java
index d9bd714..18bc55a 100644
--- a/src/com/android/launcher3/popup/ArrowPopup.java
+++ b/src/com/android/launcher3/popup/ArrowPopup.java
@@ -32,6 +32,7 @@
import android.graphics.Rect;
import android.graphics.drawable.ShapeDrawable;
import android.util.AttributeSet;
+import android.util.Pair;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
@@ -239,6 +240,17 @@
* and align above if there is enough vertical space.
*/
protected void orientAboutObject() {
+ orientAboutObject(true /* allowAlignLeft */, true /* allowAlignRight */);
+ }
+
+ /**
+ * @see #orientAboutObject()
+ *
+ * @param allowAlignLeft Set to false if we already tried aligning left and didn't have room.
+ * @param allowAlignRight Set to false if we already tried aligning right and didn't have room.
+ * TODO: Can we test this with all permutations of widths/heights and icon locations + RTL?
+ */
+ private void orientAboutObject(boolean allowAlignLeft, boolean allowAlignRight) {
measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int width = getMeasuredWidth();
int extraVerticalSpace = mArrow.getLayoutParams().height + mArrowOffset
@@ -252,14 +264,8 @@
// Align left (right in RTL) if there is room.
int leftAlignedX = mTempRect.left;
int rightAlignedX = mTempRect.right - width;
- int x = leftAlignedX;
- boolean canBeLeftAligned = leftAlignedX + width + insets.left
- < dragLayer.getRight() - insets.right;
- boolean canBeRightAligned = rightAlignedX > dragLayer.getLeft() + insets.left;
- if (!canBeLeftAligned || (mIsRtl && canBeRightAligned)) {
- x = rightAlignedX;
- }
- mIsLeftAligned = x == leftAlignedX;
+ mIsLeftAligned = !mIsRtl ? allowAlignLeft : !allowAlignRight;
+ int x = mIsLeftAligned ? leftAlignedX : rightAlignedX;
// Offset x so that the arrow and shortcut icons are center-aligned with the original icon.
int iconWidth = mTempRect.width();
@@ -281,6 +287,24 @@
}
x += mIsLeftAligned ? xOffset : -xOffset;
+ // Check whether we can still align as we originally wanted, now that we've calculated x.
+ if (!allowAlignLeft && !allowAlignRight) {
+ // We've already tried both ways and couldn't make it fit. onLayout() will set the
+ // gravity to CENTER_HORIZONTAL, but continue below to update y.
+ } else {
+ boolean canBeLeftAligned = x + width + insets.left
+ < dragLayer.getRight() - insets.right;
+ boolean canBeRightAligned = x > dragLayer.getLeft() + insets.left;
+ boolean alignmentStillValid = mIsLeftAligned && canBeLeftAligned
+ || !mIsLeftAligned && canBeRightAligned;
+ if (!alignmentStillValid) {
+ // Try again, but don't allow this alignment we already know won't work.
+ orientAboutObject(allowAlignLeft && !mIsLeftAligned /* allowAlignLeft */,
+ allowAlignRight && mIsLeftAligned /* allowAlignRight */);
+ return;
+ }
+ }
+
// Open above icon if there is room.
int iconHeight = mTempRect.height();
int y = mTempRect.top - height;
@@ -358,6 +382,11 @@
}
}
+ @Override
+ protected Pair<View, String> getAccessibilityTarget() {
+ return Pair.create(this, "");
+ }
+
private void animateOpen() {
setVisibility(View.VISIBLE);
@@ -413,6 +442,8 @@
}
if (getOutlineProvider() instanceof RevealOutlineAnimation) {
((RevealOutlineAnimation) getOutlineProvider()).getOutline(mEndRect);
+ } else {
+ mEndRect.set(0, 0, getMeasuredWidth(), getMeasuredHeight());
}
if (mOpenCloseAnimator != null) {
mOpenCloseAnimator.cancel();
diff --git a/src/com/android/launcher3/popup/PopupContainerWithArrow.java b/src/com/android/launcher3/popup/PopupContainerWithArrow.java
index 05ea694..331298f 100644
--- a/src/com/android/launcher3/popup/PopupContainerWithArrow.java
+++ b/src/com/android/launcher3/popup/PopupContainerWithArrow.java
@@ -18,6 +18,7 @@
import static com.android.launcher3.Utilities.squaredHypot;
import static com.android.launcher3.Utilities.squaredTouchSlop;
+import static com.android.launcher3.logging.LoggerUtils.newContainerTarget;
import static com.android.launcher3.notification.NotificationMainView.NOTIFICATION_ITEM_INFO;
import static com.android.launcher3.popup.PopupPopulator.MAX_SHORTCUTS;
import static com.android.launcher3.popup.PopupPopulator.MAX_SHORTCUTS_IF_NOTIFICATIONS;
@@ -37,7 +38,6 @@
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
-import android.util.Pair;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
@@ -49,17 +49,18 @@
import com.android.launcher3.DragSource;
import com.android.launcher3.DropTarget;
import com.android.launcher3.DropTarget.DragObject;
-import com.android.launcher3.ItemInfo;
-import com.android.launcher3.ItemInfoWithIcon;
import com.android.launcher3.Launcher;
import com.android.launcher3.R;
+import com.android.launcher3.Utilities;
import com.android.launcher3.accessibility.LauncherAccessibilityDelegate;
import com.android.launcher3.accessibility.ShortcutMenuAccessibilityDelegate;
import com.android.launcher3.dot.DotInfo;
import com.android.launcher3.dragndrop.DragController;
import com.android.launcher3.dragndrop.DragOptions;
import com.android.launcher3.dragndrop.DragView;
-import com.android.launcher3.logging.LoggerUtils;
+import com.android.launcher3.dragndrop.DraggableView;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.ItemInfoWithIcon;
import com.android.launcher3.notification.NotificationInfo;
import com.android.launcher3.notification.NotificationItemView;
import com.android.launcher3.notification.NotificationKeyData;
@@ -173,7 +174,7 @@
BaseDragLayer dl = getPopupContainer();
if (!dl.isEventOverView(this, ev)) {
mLauncher.getUserEventDispatcher().logActionTapOutside(
- LoggerUtils.newContainerTarget(ContainerType.DEEPSHORTCUTS));
+ newContainerTarget(ContainerType.DEEPSHORTCUTS));
close(true);
// We let touches on the original icon go through so that users can launch
@@ -185,6 +186,13 @@
}
/**
+ * Returns true if we can show the container.
+ */
+ public static boolean canShow(View icon, ItemInfo item) {
+ return icon instanceof BubbleTextView && ShortcutUtil.supportsShortcuts(item);
+ }
+
+ /**
* Shows the notifications and deep shortcuts associated with {@param icon}.
* @return the container if shown or null.
*/
@@ -196,7 +204,7 @@
return null;
}
ItemInfo item = (ItemInfo) icon.getTag();
- if (!ShortcutUtil.supportsShortcuts(item)) {
+ if (!canShow(icon, item)) {
return null;
}
@@ -330,11 +338,6 @@
}
@Override
- protected Pair<View, String> getAccessibilityTarget() {
- return Pair.create(this, "");
- }
-
- @Override
protected void getTargetObjectLocation(Rect outPos) {
getPopupContainer().getDescendantRectRelativeToSelf(mOriginalIcon, outPos);
outPos.top += mOriginalIcon.getPaddingTop();
@@ -395,6 +398,9 @@
} else if (view instanceof ImageView) {
// Only the system shortcut icon shows on a gray background header.
info.setIconAndContentDescriptionFor((ImageView) view);
+ if (Utilities.ATLEAST_OREO) {
+ view.setTooltipText(view.getContentDescription());
+ }
}
view.setTag(info);
view.setOnClickListener(info);
@@ -491,14 +497,15 @@
}
@Override
- public void fillInLogContainerData(View v, ItemInfo info, Target target, Target targetParent) {
- if (info == NOTIFICATION_ITEM_INFO) {
- target.itemType = ItemType.NOTIFICATION;
+ public void fillInLogContainerData(ItemInfo childInfo, Target child,
+ ArrayList<Target> parents) {
+ if (childInfo == NOTIFICATION_ITEM_INFO) {
+ child.itemType = ItemType.NOTIFICATION;
} else {
- target.itemType = ItemType.DEEPSHORTCUT;
- target.rank = info.rank;
+ child.itemType = ItemType.DEEPSHORTCUT;
+ child.rank = childInfo.rank;
}
- targetParent.containerType = ContainerType.DEEPSHORTCUTS;
+ parents.add(newContainerTarget(ContainerType.DEEPSHORTCUTS));
}
@Override
@@ -667,7 +674,8 @@
iconShift.x = mIconLastTouchPos.x - sv.getIconCenter().x;
iconShift.y = mIconLastTouchPos.y - mLauncher.getDeviceProfile().iconSizePx;
- DragView dv = mLauncher.getWorkspace().beginDragShared(sv.getIconView(),
+ DraggableView draggableView = DraggableView.ofType(DraggableView.DRAGGABLE_ICON);
+ DragView dv = mLauncher.getWorkspace().beginDragShared(sv.getIconView(), draggableView,
mContainer, sv.getFinalInfo(),
new ShortcutDragPreviewProvider(sv.getIconView(), iconShift),
new DragOptions());
diff --git a/src/com/android/launcher3/popup/PopupDataProvider.java b/src/com/android/launcher3/popup/PopupDataProvider.java
index 1092c7b..5a5f668 100644
--- a/src/com/android/launcher3/popup/PopupDataProvider.java
+++ b/src/com/android/launcher3/popup/PopupDataProvider.java
@@ -23,9 +23,9 @@
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.dot.DotInfo;
import com.android.launcher3.model.WidgetItem;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.notification.NotificationKeyData;
import com.android.launcher3.notification.NotificationListener;
import com.android.launcher3.util.ComponentKey;
@@ -33,6 +33,7 @@
import com.android.launcher3.util.ShortcutUtil;
import com.android.launcher3.widget.WidgetListRowEntry;
+import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -238,6 +239,11 @@
}).collect(Collectors.toList());
}
+ public void dump(String prefix, PrintWriter writer) {
+ writer.println(prefix + "PopupDataProvider:");
+ writer.println(prefix + "\tmPackageUserToDotInfos:" + mPackageUserToDotInfos);
+ }
+
public interface PopupDataChangeListener {
PopupDataChangeListener INSTANCE = new PopupDataChangeListener() { };
diff --git a/src/com/android/launcher3/popup/PopupPopulator.java b/src/com/android/launcher3/popup/PopupPopulator.java
index fdcf04f..7da86cc 100644
--- a/src/com/android/launcher3/popup/PopupPopulator.java
+++ b/src/com/android/launcher3/popup/PopupPopulator.java
@@ -25,10 +25,10 @@
import androidx.annotation.VisibleForTesting;
import com.android.launcher3.BaseDraggingActivity;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppState;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.icons.IconCache;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.notification.NotificationInfo;
import com.android.launcher3.notification.NotificationKeyData;
import com.android.launcher3.notification.NotificationListener;
diff --git a/src/com/android/launcher3/popup/RemoteActionShortcut.java b/src/com/android/launcher3/popup/RemoteActionShortcut.java
index 8751202..3875d2e 100644
--- a/src/com/android/launcher3/popup/RemoteActionShortcut.java
+++ b/src/com/android/launcher3/popup/RemoteActionShortcut.java
@@ -33,9 +33,9 @@
import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.BaseDraggingActivity;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.userevent.nano.LauncherLogProto;
@TargetApi(Build.VERSION_CODES.Q)
diff --git a/src/com/android/launcher3/popup/SystemShortcut.java b/src/com/android/launcher3/popup/SystemShortcut.java
index 21c5ac5..ae35d4c 100644
--- a/src/com/android/launcher3/popup/SystemShortcut.java
+++ b/src/com/android/launcher3/popup/SystemShortcut.java
@@ -14,11 +14,11 @@
import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.BaseDraggingActivity;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.Launcher;
import com.android.launcher3.R;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.model.WidgetItem;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action;
import com.android.launcher3.userevent.nano.LauncherLogProto.ControlType;
import com.android.launcher3.util.InstantAppResolver;
@@ -145,8 +145,9 @@
&& ((WorkspaceItemInfo) itemInfo).hasStatusFlag(
WorkspaceItemInfo.FLAG_SUPPORTS_WEB_UI);
boolean isInstantApp = false;
- if (itemInfo instanceof com.android.launcher3.AppInfo) {
- com.android.launcher3.AppInfo appInfo = (com.android.launcher3.AppInfo) itemInfo;
+ if (itemInfo instanceof com.android.launcher3.model.data.AppInfo) {
+ com.android.launcher3.model.data.AppInfo
+ appInfo = (com.android.launcher3.model.data.AppInfo) itemInfo;
isInstantApp = InstantAppResolver.newInstance(activity).isInstantApp(appInfo);
}
boolean enabled = supportsWebUI || isInstantApp;
diff --git a/src/com/android/launcher3/provider/ImportDataTask.java b/src/com/android/launcher3/provider/ImportDataTask.java
index 732fb0b..a5462a6 100644
--- a/src/com/android/launcher3/provider/ImportDataTask.java
+++ b/src/com/android/launcher3/provider/ImportDataTask.java
@@ -37,7 +37,6 @@
import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
import com.android.launcher3.DefaultLayoutParser;
import com.android.launcher3.LauncherAppState;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherProvider;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.LauncherSettings.Favorites;
@@ -46,6 +45,7 @@
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.logging.FileLog;
import com.android.launcher3.model.GridSizeMigrationTask;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
import com.android.launcher3.pm.UserCache;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.IntSparseArrayMap;
diff --git a/src/com/android/launcher3/provider/LauncherDbUtils.java b/src/com/android/launcher3/provider/LauncherDbUtils.java
index 2c843f9..7e05a5a 100644
--- a/src/com/android/launcher3/provider/LauncherDbUtils.java
+++ b/src/com/android/launcher3/provider/LauncherDbUtils.java
@@ -22,10 +22,12 @@
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.os.Binder;
+import android.os.Process;
import android.util.Log;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherSettings.Favorites;
+import com.android.launcher3.pm.UserCache;
import com.android.launcher3.util.IntArray;
import java.util.Locale;
@@ -116,6 +118,23 @@
db.execSQL("DROP TABLE IF EXISTS " + tableName);
}
+ /** Copy fromTable in fromDb to toTable in toDb. */
+ public static void copyTable(SQLiteDatabase fromDb, String fromTable, SQLiteDatabase toDb,
+ String toTable, Context context) {
+ long userSerial = UserCache.INSTANCE.get(context).getSerialNumberForUser(
+ Process.myUserHandle());
+ dropTable(toDb, toTable);
+ Favorites.addTableToDb(toDb, userSerial, false, toTable);
+ if (fromDb != toDb) {
+ toDb.execSQL("ATTACH DATABASE '" + fromDb.getPath() + "' AS from_db");
+ toDb.execSQL(
+ "INSERT INTO " + toTable + " SELECT * FROM from_db." + fromTable);
+ toDb.execSQL("DETACH DATABASE 'from_db'");
+ } else {
+ toDb.execSQL("INSERT INTO " + toTable + " SELECT * FROM " + fromTable);
+ }
+ }
+
/**
* Utility class to simplify managing sqlite transactions
*/
diff --git a/src/com/android/launcher3/provider/LossyScreenMigrationTask.java b/src/com/android/launcher3/provider/LossyScreenMigrationTask.java
index 6d839f3..c0111b9 100644
--- a/src/com/android/launcher3/provider/LossyScreenMigrationTask.java
+++ b/src/com/android/launcher3/provider/LossyScreenMigrationTask.java
@@ -18,7 +18,6 @@
import android.content.ContentValues;
import android.content.Context;
-import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Point;
@@ -43,7 +42,7 @@
protected LossyScreenMigrationTask(
Context context, InvariantDeviceProfile idp, SQLiteDatabase db) {
// Decrease the rows count by 1
- super(context, db, getValidPackages(context),
+ super(context, db, getValidPackages(context), false /* usePreviewTable */,
new Point(idp.numColumns, idp.numRows + 1),
new Point(idp.numColumns, idp.numRows));
diff --git a/src/com/android/launcher3/provider/RestoreDbTask.java b/src/com/android/launcher3/provider/RestoreDbTask.java
index 842be40..33eff57 100644
--- a/src/com/android/launcher3/provider/RestoreDbTask.java
+++ b/src/com/android/launcher3/provider/RestoreDbTask.java
@@ -35,13 +35,13 @@
import com.android.launcher3.AppWidgetsRestoredReceiver;
import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.LauncherAppState;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherProvider.DatabaseHelper;
import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.Utilities;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.logging.FileLog;
import com.android.launcher3.model.GridBackupTable;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.LogConfig;
@@ -108,7 +108,7 @@
private void backupWorkspace(Context context, SQLiteDatabase db) throws Exception {
InvariantDeviceProfile idp = LauncherAppState.getIDP(context);
// TODO(pinyaoting): Support backing up workspace with multiple grid options.
- new GridBackupTable(context, db, db, idp.numHotseatIcons, idp.numColumns, idp.numRows)
+ new GridBackupTable(context, db, idp.numHotseatIcons, idp.numColumns, idp.numRows)
.doBackup(getDefaultProfileId(db), GridBackupTable.OPTION_REQUIRES_SANITIZATION);
}
@@ -117,8 +117,8 @@
throws Exception {
// TODO(pinyaoting): Support restoring workspace with multiple grid options.
final InvariantDeviceProfile idp = LauncherAppState.getIDP(context);
- GridBackupTable backupTable = new GridBackupTable(context, db, db,
- idp.numHotseatIcons, idp.numColumns, idp.numRows);
+ GridBackupTable backupTable = new GridBackupTable(context, db, idp.numHotseatIcons,
+ idp.numColumns, idp.numRows);
if (backupTable.restoreFromRawBackupIfAvailable(getDefaultProfileId(db))) {
sanitizeDB(helper, db, backupManager);
LauncherAppState.getInstance(context).getModel().forceReload();
diff --git a/src/com/android/launcher3/secondarydisplay/PinnedAppsAdapter.java b/src/com/android/launcher3/secondarydisplay/PinnedAppsAdapter.java
index 54b7fb9..e9058c3 100644
--- a/src/com/android/launcher3/secondarydisplay/PinnedAppsAdapter.java
+++ b/src/com/android/launcher3/secondarydisplay/PinnedAppsAdapter.java
@@ -30,12 +30,12 @@
import android.widget.BaseAdapter;
import com.android.launcher3.AbstractFloatingView;
-import com.android.launcher3.AppInfo;
import com.android.launcher3.BubbleTextView;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.R;
import com.android.launcher3.allapps.AllAppsStore;
import com.android.launcher3.allapps.AppInfoComparator;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.pm.UserCache;
import com.android.launcher3.popup.SystemShortcut;
import com.android.launcher3.util.ComponentKey;
diff --git a/src/com/android/launcher3/secondarydisplay/SecondaryDisplayLauncher.java b/src/com/android/launcher3/secondarydisplay/SecondaryDisplayLauncher.java
index 1cc01f4..f1f271f 100644
--- a/src/com/android/launcher3/secondarydisplay/SecondaryDisplayLauncher.java
+++ b/src/com/android/launcher3/secondarydisplay/SecondaryDisplayLauncher.java
@@ -28,18 +28,18 @@
import android.view.inputmethod.InputMethodManager;
import com.android.launcher3.AbstractFloatingView;
-import com.android.launcher3.AppInfo;
import com.android.launcher3.BaseDraggingActivity;
import com.android.launcher3.InvariantDeviceProfile;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppState;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherModel;
-import com.android.launcher3.PromiseAppInfo;
import com.android.launcher3.R;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.allapps.AllAppsContainerView;
import com.android.launcher3.model.BgDataModel;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
+import com.android.launcher3.model.data.PromiseAppInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.popup.PopupDataProvider;
import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.IntArray;
diff --git a/src/com/android/launcher3/secondarydisplay/SecondaryDragLayer.java b/src/com/android/launcher3/secondarydisplay/SecondaryDragLayer.java
index 8fffee8..e35e884 100644
--- a/src/com/android/launcher3/secondarydisplay/SecondaryDragLayer.java
+++ b/src/com/android/launcher3/secondarydisplay/SecondaryDragLayer.java
@@ -30,9 +30,9 @@
import com.android.launcher3.BubbleTextView;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.InvariantDeviceProfile;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.R;
import com.android.launcher3.allapps.AllAppsContainerView;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.popup.PopupContainerWithArrow;
import com.android.launcher3.util.ShortcutUtil;
import com.android.launcher3.util.TouchController;
@@ -54,6 +54,11 @@
public SecondaryDragLayer(Context context, AttributeSet attrs) {
super(context, attrs, 1 /* alphaChannelCount */);
+ recreateControllers();
+ }
+
+ @Override
+ public void recreateControllers() {
mControllers = new TouchController[] {new CloseAllAppsTouchController()};
}
diff --git a/src/com/android/launcher3/settings/DeveloperOptionsFragment.java b/src/com/android/launcher3/settings/DeveloperOptionsFragment.java
index 049fda9..8dc2e61 100644
--- a/src/com/android/launcher3/settings/DeveloperOptionsFragment.java
+++ b/src/com/android/launcher3/settings/DeveloperOptionsFragment.java
@@ -96,6 +96,7 @@
initFlags();
loadPluginPrefs();
+ maybeAddSandboxCategory();
}
@Override
@@ -203,6 +204,31 @@
});
}
+ private void maybeAddSandboxCategory() {
+ Context context = getContext();
+ if (context == null) {
+ return;
+ }
+ Intent launchSandboxIntent =
+ new Intent("com.android.quickstep.action.GESTURE_SANDBOX")
+ .setPackage(context.getPackageName())
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ if (launchSandboxIntent.resolveActivity(context.getPackageManager()) == null) {
+ return;
+ }
+ PreferenceCategory sandboxCategory = newCategory("Sandbox");
+ Preference launchSandboxPreference = new Preference(context);
+ launchSandboxPreference.setKey("launchSandbox");
+ launchSandboxPreference.setTitle("Launch Gesture Navigation Sandbox");
+ launchSandboxPreference.setSummary(
+ "This provides tutorials and a place to practice navigation gestures.");
+ launchSandboxPreference.setOnPreferenceClickListener(preference -> {
+ startActivity(launchSandboxIntent);
+ return true;
+ });
+ sandboxCategory.addPreference(launchSandboxPreference);
+ }
+
private String toName(String action) {
String str = action.replace("com.android.systemui.action.PLUGIN_", "")
.replace("com.android.launcher3.action.PLUGIN_", "");
diff --git a/src/com/android/launcher3/shortcuts/DeepShortcutView.java b/src/com/android/launcher3/shortcuts/DeepShortcutView.java
index 9cc7d8f..e9b92e2 100644
--- a/src/com/android/launcher3/shortcuts/DeepShortcutView.java
+++ b/src/com/android/launcher3/shortcuts/DeepShortcutView.java
@@ -28,7 +28,7 @@
import com.android.launcher3.Launcher;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
-import com.android.launcher3.WorkspaceItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.popup.PopupContainerWithArrow;
/**
diff --git a/src/com/android/launcher3/shortcuts/ShortcutKey.java b/src/com/android/launcher3/shortcuts/ShortcutKey.java
index fa1a85f..3ca9490 100644
--- a/src/com/android/launcher3/shortcuts/ShortcutKey.java
+++ b/src/com/android/launcher3/shortcuts/ShortcutKey.java
@@ -6,7 +6,7 @@
import android.content.pm.ShortcutInfo;
import android.os.UserHandle;
-import com.android.launcher3.ItemInfo;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.util.ComponentKey;
/**
diff --git a/src/com/android/launcher3/states/HintState.java b/src/com/android/launcher3/states/HintState.java
index 290dbb6..43f30f1 100644
--- a/src/com/android/launcher3/states/HintState.java
+++ b/src/com/android/launcher3/states/HintState.java
@@ -17,6 +17,7 @@
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherState;
+import com.android.launcher3.LauncherStateManager;
import com.android.launcher3.Workspace;
import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
@@ -50,8 +51,13 @@
@Override
public void onStateTransitionEnd(Launcher launcher) {
- launcher.getStateManager().goToState(NORMAL);
+ LauncherStateManager stateManager = launcher.getStateManager();
Workspace workspace = launcher.getWorkspace();
- workspace.post(workspace::moveToDefaultScreen);
+ boolean willMoveScreens = workspace.getNextPage() != Workspace.DEFAULT_PAGE;
+ stateManager.goToState(NORMAL, true, willMoveScreens ? null
+ : launcher.getScrimView()::startDragHandleEducationAnim);
+ if (willMoveScreens) {
+ workspace.post(workspace::moveToDefaultScreen);
+ }
}
}
diff --git a/src/com/android/launcher3/states/RotationHelper.java b/src/com/android/launcher3/states/RotationHelper.java
index 852928b..2e0521f 100644
--- a/src/com/android/launcher3/states/RotationHelper.java
+++ b/src/com/android/launcher3/states/RotationHelper.java
@@ -15,22 +15,31 @@
*/
package com.android.launcher3.states;
+import static android.Manifest.permission.WRITE_SECURE_SETTINGS;
import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LOCKED;
import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
+import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
+import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static android.util.DisplayMetrics.DENSITY_DEVICE_STABLE;
+import static com.android.launcher3.config.FeatureFlags.FLAG_ENABLE_FIXED_ROTATION_TRANSFORM;
+import static com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR;
+
+import android.app.Activity;
+import android.content.ContentResolver;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Resources;
-import android.view.WindowManager;
+import android.provider.Settings;
-import com.android.launcher3.Launcher;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
-import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.util.UiThreadHelper;
+import java.util.ArrayList;
+import java.util.List;
+
/**
* Utility class to manage launcher rotation
*/
@@ -38,9 +47,19 @@
public static final String ALLOW_ROTATION_PREFERENCE_KEY = "pref_allowRotation";
+ public static final String FIXED_ROTATION_TRANSFORM_SETTING_NAME = "fixed_rotation_transform";
+ private final ContentResolver mContentResolver;
+
+ /**
+ * Listener to receive changes when {@link #FIXED_ROTATION_TRANSFORM_SETTING_NAME} flag changes.
+ */
+ public interface ForcedRotationChangedListener {
+ void onForcedRotationChanged(boolean isForcedRotation);
+ }
+
public static boolean getAllowRotationDefaultValue() {
- // If the device was scaled, used the original dimensions to determine if rotation
- // is allowed of not.
+ // If the device's pixel density was scaled (usually via settings for A11y), use the
+ // original dimensions to determine if rotation is allowed of not.
Resources res = Resources.getSystem();
int originalSmallestWidth = res.getConfiguration().smallestScreenWidthDp
* res.getDisplayMetrics().densityDpi / DENSITY_DEVICE_STABLE;
@@ -51,11 +70,14 @@
public static final int REQUEST_ROTATE = 1;
public static final int REQUEST_LOCK = 2;
- private final Launcher mLauncher;
- private final SharedPreferences mPrefs;
+ private final Activity mActivity;
+ private final SharedPreferences mSharedPrefs;
+ private final SharedPreferences mFeatureFlagsPrefs;
private boolean mIgnoreAutoRotateSettings;
private boolean mAutoRotateEnabled;
+ private boolean mForcedRotation;
+ private List<ForcedRotationChangedListener> mForcedRotationChangedListeners = new ArrayList<>();
/**
* Rotation request made by
@@ -75,65 +97,84 @@
// This is used to defer setting rotation flags until the activity is being created
private boolean mInitialized;
private boolean mDestroyed;
- private boolean mRotationHasDifferentUI;
private int mLastActivityFlags = -1;
- public RotationHelper(Launcher launcher) {
- mLauncher = launcher;
+ public RotationHelper(Activity activity) {
+ mActivity = activity;
// On large devices we do not handle auto-rotate differently.
- mIgnoreAutoRotateSettings = mLauncher.getResources().getBoolean(R.bool.allow_rotation);
+ mIgnoreAutoRotateSettings = mActivity.getResources().getBoolean(R.bool.allow_rotation);
if (!mIgnoreAutoRotateSettings) {
- mPrefs = Utilities.getPrefs(mLauncher);
- mPrefs.registerOnSharedPreferenceChangeListener(this);
- mAutoRotateEnabled = mPrefs.getBoolean(ALLOW_ROTATION_PREFERENCE_KEY,
+ mSharedPrefs = Utilities.getPrefs(mActivity);
+ mSharedPrefs.registerOnSharedPreferenceChangeListener(this);
+ mAutoRotateEnabled = mSharedPrefs.getBoolean(ALLOW_ROTATION_PREFERENCE_KEY,
getAllowRotationDefaultValue());
} else {
- mPrefs = null;
+ mSharedPrefs = null;
}
+
+ mContentResolver = activity.getContentResolver();
+ mFeatureFlagsPrefs = Utilities.getFeatureFlagsPrefs(mActivity);
+ mFeatureFlagsPrefs.registerOnSharedPreferenceChangeListener(this);
+ updateForcedRotation(true);
}
- public void setRotationHadDifferentUI(boolean rotationHasDifferentUI) {
- mRotationHasDifferentUI = rotationHasDifferentUI;
- }
-
- public boolean homeScreenCanRotate() {
- return mRotationHasDifferentUI || mIgnoreAutoRotateSettings || mAutoRotateEnabled
- || mStateHandlerRequest != REQUEST_NONE
- || mLauncher.getDeviceProfile().isMultiWindowMode;
- }
-
- public void updateRotationAnimation() {
- if (FeatureFlags.FAKE_LANDSCAPE_UI.get()) {
- WindowManager.LayoutParams lp = mLauncher.getWindow().getAttributes();
- int oldAnim = lp.rotationAnimation;
- lp.rotationAnimation = homeScreenCanRotate()
- ? WindowManager.LayoutParams.ROTATION_ANIMATION_ROTATE
- : WindowManager.LayoutParams.ROTATION_ANIMATION_SEAMLESS;
- if (oldAnim != lp.rotationAnimation) {
- mLauncher.getWindow().setAttributes(lp);
+ /**
+ * @param setValueFromPrefs If true, then {@link #mForcedRotation} will get set to the value
+ * from the home developer settings. Otherwise it will not.
+ * This is primarily to allow tests to set their own conditions.
+ */
+ private void updateForcedRotation(boolean setValueFromPrefs) {
+ boolean isForcedRotation = mFeatureFlagsPrefs
+ .getBoolean(FLAG_ENABLE_FIXED_ROTATION_TRANSFORM, true)
+ && !getAllowRotationDefaultValue();
+ if (mForcedRotation == isForcedRotation) {
+ return;
+ }
+ if (setValueFromPrefs) {
+ mForcedRotation = isForcedRotation;
+ }
+ UI_HELPER_EXECUTOR.execute(() -> {
+ if (mActivity.checkSelfPermission(WRITE_SECURE_SETTINGS) == PERMISSION_GRANTED) {
+ Settings.Global.putInt(mContentResolver, FIXED_ROTATION_TRANSFORM_SETTING_NAME,
+ mForcedRotation ? 1 : 0);
}
+ });
+ for (ForcedRotationChangedListener listener : mForcedRotationChangedListeners) {
+ listener.onForcedRotationChanged(mForcedRotation);
}
}
+ /**
+ * will not be called when first registering the listener.
+ */
+ public void addForcedRotationCallback(ForcedRotationChangedListener listener) {
+ mForcedRotationChangedListeners.add(listener);
+ }
+
+ public void removeForcedRotationCallback(ForcedRotationChangedListener listener) {
+ mForcedRotationChangedListeners.remove(listener);
+ }
+
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
+ if (FLAG_ENABLE_FIXED_ROTATION_TRANSFORM.equals(s)) {
+ updateForcedRotation(true);
+ return;
+ }
+
boolean wasRotationEnabled = mAutoRotateEnabled;
- mAutoRotateEnabled = mPrefs.getBoolean(ALLOW_ROTATION_PREFERENCE_KEY,
+ mAutoRotateEnabled = mSharedPrefs.getBoolean(ALLOW_ROTATION_PREFERENCE_KEY,
getAllowRotationDefaultValue());
if (mAutoRotateEnabled != wasRotationEnabled) {
-
notifyChange();
- updateRotationAnimation();
- mLauncher.reapplyUi();
}
}
public void setStateHandlerRequest(int request) {
if (mStateHandlerRequest != request) {
mStateHandlerRequest = request;
- updateRotationAnimation();
notifyChange();
}
}
@@ -155,7 +196,11 @@
// Used by tests only.
public void forceAllowRotationForTesting(boolean allowRotation) {
mIgnoreAutoRotateSettings =
- allowRotation || mLauncher.getResources().getBoolean(R.bool.allow_rotation);
+ allowRotation || mActivity.getResources().getBoolean(R.bool.allow_rotation);
+ // TODO(b/150214193) Tests currently expect launcher to be able to be rotated
+ // Modify tests for this new behavior
+ mForcedRotation = !allowRotation;
+ updateForcedRotation(false);
notifyChange();
}
@@ -163,16 +208,17 @@
if (!mInitialized) {
mInitialized = true;
notifyChange();
- updateRotationAnimation();
}
}
public void destroy() {
if (!mDestroyed) {
mDestroyed = true;
- if (mPrefs != null) {
- mPrefs.unregisterOnSharedPreferenceChangeListener(this);
+ if (mSharedPrefs != null) {
+ mSharedPrefs.unregisterOnSharedPreferenceChangeListener(this);
}
+ mForcedRotationChangedListeners.clear();
+ mFeatureFlagsPrefs.unregisterOnSharedPreferenceChangeListener(this);
}
}
@@ -182,7 +228,10 @@
}
final int activityFlags;
- if (mStateHandlerRequest != REQUEST_NONE) {
+ if (mForcedRotation) {
+ // TODO(b/150214193) Properly address this
+ activityFlags = SCREEN_ORIENTATION_PORTRAIT;
+ } else if (mStateHandlerRequest != REQUEST_NONE) {
activityFlags = mStateHandlerRequest == REQUEST_LOCK ?
SCREEN_ORIENTATION_LOCKED : SCREEN_ORIENTATION_UNSPECIFIED;
} else if (mCurrentTransitionRequest != REQUEST_NONE) {
@@ -200,7 +249,7 @@
}
if (activityFlags != mLastActivityFlags) {
mLastActivityFlags = activityFlags;
- UiThreadHelper.setOrientationAsync(mLauncher, activityFlags);
+ UiThreadHelper.setOrientationAsync(mActivity, activityFlags);
}
}
diff --git a/src/com/android/launcher3/states/SpringLoadedState.java b/src/com/android/launcher3/states/SpringLoadedState.java
index 97c67c5..2ba624c 100644
--- a/src/com/android/launcher3/states/SpringLoadedState.java
+++ b/src/com/android/launcher3/states/SpringLoadedState.java
@@ -17,6 +17,7 @@
import static com.android.launcher3.states.RotationHelper.REQUEST_LOCK;
+import android.content.Context;
import android.graphics.Rect;
import com.android.launcher3.DeviceProfile;
@@ -77,6 +78,11 @@
}
@Override
+ public float getDepth(Context context) {
+ return 0.5f;
+ }
+
+ @Override
public ScaleAndTranslation getHotseatScaleAndTranslation(Launcher launcher) {
return new ScaleAndTranslation(1, 0, 0);
}
diff --git a/src/com/android/launcher3/states/StateAnimationConfig.java b/src/com/android/launcher3/states/StateAnimationConfig.java
new file mode 100644
index 0000000..82cde64
--- /dev/null
+++ b/src/com/android/launcher3/states/StateAnimationConfig.java
@@ -0,0 +1,155 @@
+/*
+ * 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.launcher3.states;
+
+import android.view.animation.Interpolator;
+
+import androidx.annotation.IntDef;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * Utility class for building animator set
+ */
+public class StateAnimationConfig {
+
+ // We separate the state animations into "atomic" and "non-atomic" components. The atomic
+ // components may be run atomically - that is, all at once, instead of user-controlled. However,
+ // atomic components are not restricted to this purpose; they can be user-controlled alongside
+ // non atomic components as well. Note that each gesture model has exactly one atomic component,
+ // PLAY_ATOMIC_OVERVIEW_SCALE *or* PLAY_ATOMIC_OVERVIEW_PEEK.
+ @IntDef(flag = true, value = {
+ PLAY_NON_ATOMIC,
+ PLAY_ATOMIC_OVERVIEW_SCALE,
+ PLAY_ATOMIC_OVERVIEW_PEEK,
+ SKIP_OVERVIEW,
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface AnimationFlags {}
+ public static final int PLAY_NON_ATOMIC = 1 << 0;
+ public static final int PLAY_ATOMIC_OVERVIEW_SCALE = 1 << 1;
+ public static final int PLAY_ATOMIC_OVERVIEW_PEEK = 1 << 2;
+ public static final int SKIP_OVERVIEW = 1 << 3;
+
+ public long duration;
+ public boolean userControlled;
+ public @AnimationFlags int animFlags = ANIM_ALL_COMPONENTS;
+
+ public static final int ANIM_ALL_COMPONENTS = PLAY_NON_ATOMIC | PLAY_ATOMIC_OVERVIEW_SCALE
+ | PLAY_ATOMIC_OVERVIEW_PEEK;
+
+ // Various types of animation state transition
+ @IntDef(value = {
+ ANIM_VERTICAL_PROGRESS,
+ ANIM_WORKSPACE_SCALE,
+ ANIM_WORKSPACE_TRANSLATE,
+ ANIM_WORKSPACE_FADE,
+ ANIM_HOTSEAT_SCALE,
+ ANIM_HOTSEAT_TRANSLATE,
+ ANIM_OVERVIEW_SCALE,
+ ANIM_OVERVIEW_TRANSLATE_X,
+ ANIM_OVERVIEW_TRANSLATE_Y,
+ ANIM_OVERVIEW_FADE,
+ ANIM_ALL_APPS_FADE,
+ ANIM_OVERVIEW_SCRIM_FADE,
+ ANIM_ALL_APPS_HEADER_FADE,
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface AnimType {}
+ public static final int ANIM_VERTICAL_PROGRESS = 0;
+ public static final int ANIM_WORKSPACE_SCALE = 1;
+ public static final int ANIM_WORKSPACE_TRANSLATE = 2;
+ public static final int ANIM_WORKSPACE_FADE = 3;
+ public static final int ANIM_HOTSEAT_SCALE = 4;
+ public static final int ANIM_HOTSEAT_TRANSLATE = 5;
+ public static final int ANIM_OVERVIEW_SCALE = 6;
+ public static final int ANIM_OVERVIEW_TRANSLATE_X = 7;
+ public static final int ANIM_OVERVIEW_TRANSLATE_Y = 8;
+ public static final int ANIM_OVERVIEW_FADE = 9;
+ public static final int ANIM_ALL_APPS_FADE = 10;
+ public static final int ANIM_OVERVIEW_SCRIM_FADE = 11;
+ public static final int ANIM_ALL_APPS_HEADER_FADE = 12; // e.g. predictions
+
+ private static final int ANIM_TYPES_COUNT = 13;
+
+ private final Interpolator[] mInterpolators = new Interpolator[ANIM_TYPES_COUNT];
+
+ public StateAnimationConfig() { }
+
+ /**
+ * Copies the config to target
+ */
+ public void copyTo(StateAnimationConfig target) {
+ target.duration = duration;
+ target.animFlags = animFlags;
+ target.userControlled = userControlled;
+ for (int i = 0; i < ANIM_TYPES_COUNT; i++) {
+ target.mInterpolators[i] = mInterpolators[i];
+ }
+ }
+
+ /**
+ * Returns the interpolator set for animId or fallback if nothing is set
+ *
+ * @see #setInterpolator(int, Interpolator)
+ */
+ public Interpolator getInterpolator(@AnimType int animId, Interpolator fallback) {
+ return mInterpolators[animId] == null ? fallback : mInterpolators[animId];
+ }
+
+ /**
+ * Sets an interpolator for a given animation type
+ */
+ public void setInterpolator(@AnimType int animId, Interpolator interpolator) {
+ mInterpolators[animId] = interpolator;
+ }
+
+ /**
+ * @return Whether Overview is scaling as part of this animation. If this is the only
+ * component (i.e. NON_ATOMIC_COMPONENT isn't included), then this scaling is happening
+ * atomically, rather than being part of a normal state animation. StateHandlers can use
+ * this to designate part of their animation that should scale with Overview.
+ */
+ public boolean playAtomicOverviewScaleComponent() {
+ return hasAnimationFlag(StateAnimationConfig.PLAY_ATOMIC_OVERVIEW_SCALE);
+ }
+
+ /**
+ * @return Whether this animation will play atomically at the same time as a different,
+ * user-controlled state transition. StateHandlers, which contribute to both animations, can
+ * use this to avoid animating the same properties in both animations, since they'd conflict
+ * with one another.
+ */
+ public boolean onlyPlayAtomicComponent() {
+ return getAnimComponents() == StateAnimationConfig.PLAY_ATOMIC_OVERVIEW_SCALE
+ || getAnimComponents() == StateAnimationConfig.PLAY_ATOMIC_OVERVIEW_PEEK;
+ }
+
+ /**
+ * Returns true if the config and any of the provided component flags
+ */
+ public boolean hasAnimationFlag(@AnimationFlags int a) {
+ return (animFlags & a) != 0;
+ }
+
+ /**
+ * @return Only the flags that determine which animation components to play.
+ */
+ public @AnimationFlags int getAnimComponents() {
+ return animFlags & StateAnimationConfig.ANIM_ALL_COMPONENTS;
+ }
+}
diff --git a/src/com/android/launcher3/testing/TestInformationHandler.java b/src/com/android/launcher3/testing/TestInformationHandler.java
index 994912b..e786f07 100644
--- a/src/com/android/launcher3/testing/TestInformationHandler.java
+++ b/src/com/android/launcher3/testing/TestInformationHandler.java
@@ -184,16 +184,15 @@
mDeviceProfile.allAppsCellHeightPx);
break;
}
+
+ case TestProtocol.REQUEST_MOCK_SENSOR_ROTATION:
+ TestProtocol.sDisableSensorRotation = true;
+ break;
}
return response;
}
protected boolean isLauncherInitialized() {
- if (TestProtocol.sDebugTracing) {
- Log.d(TestProtocol.LAUNCHER_DIDNT_INITIALIZE,
- "isLauncherInitialized " + Launcher.ACTIVITY_TRACKER.getCreatedActivity() + ", "
- + LauncherAppState.getInstance(mContext).getModel().isModelLoaded());
- }
return Launcher.ACTIVITY_TRACKER.getCreatedActivity() == null
|| LauncherAppState.getInstance(mContext).getModel().isModelLoaded();
}
diff --git a/src/com/android/launcher3/testing/TestLogging.java b/src/com/android/launcher3/testing/TestLogging.java
index fd066c1..d522d81 100644
--- a/src/com/android/launcher3/testing/TestLogging.java
+++ b/src/com/android/launcher3/testing/TestLogging.java
@@ -17,13 +17,30 @@
package com.android.launcher3.testing;
import android.util.Log;
+import android.view.MotionEvent;
import com.android.launcher3.Utilities;
public final class TestLogging {
- public static void recordEvent(String event) {
+ private static void recordEventSlow(String sequence, String event) {
+ Log.d(TestProtocol.TAPL_EVENTS_TAG, sequence + " / " + event);
+ }
+
+ public static void recordEvent(String sequence, String event) {
if (Utilities.IS_RUNNING_IN_TEST_HARNESS) {
- Log.d(TestProtocol.TAPL_EVENTS_TAG, event);
+ recordEventSlow(sequence, event);
+ }
+ }
+
+ public static void recordEvent(String sequence, String message, Object parameter) {
+ if (Utilities.IS_RUNNING_IN_TEST_HARNESS) {
+ recordEventSlow(sequence, message + ": " + parameter);
+ }
+ }
+
+ public static void recordMotionEvent(String sequence, String message, MotionEvent event) {
+ if (Utilities.IS_RUNNING_IN_TEST_HARNESS && event.getAction() != MotionEvent.ACTION_MOVE) {
+ recordEventSlow(sequence, message + ": " + event);
}
}
}
diff --git a/src/com/android/launcher3/testing/TestProtocol.java b/src/com/android/launcher3/testing/TestProtocol.java
index 6e53790..015de59 100644
--- a/src/com/android/launcher3/testing/TestProtocol.java
+++ b/src/com/android/launcher3/testing/TestProtocol.java
@@ -33,6 +33,9 @@
public static final int BACKGROUND_APP_STATE_ORDINAL = 6;
public static final int HINT_STATE_ORDINAL = 7;
public static final String TAPL_EVENTS_TAG = "TaplEvents";
+ public static final String SEQUENCE_MAIN = "Main";
+ public static final String SEQUENCE_TIS = "TIS";
+ public static final String SEQUENCE_PILFER = "Pilfer";
public static String stateOrdinalToString(int ordinal) {
switch (ordinal) {
@@ -87,9 +90,14 @@
public static final String REQUEST_ENABLE_DEBUG_TRACING = "enable-debug-tracing";
public static final String REQUEST_DISABLE_DEBUG_TRACING = "disable-debug-tracing";
+ public static final String REQUEST_OVERVIEW_ACTIONS_ENABLED = "overview-actions-enabled";
+
+ public static boolean sDisableSensorRotation;
+ public static final String REQUEST_MOCK_SENSOR_ROTATION = "mock-sensor-rotation";
+
public static final String PERMANENT_DIAG_TAG = "TaplTarget";
public static final String NO_BACKGROUND_TO_OVERVIEW_TAG = "b/138251824";
public static final String APP_NOT_DISABLED = "b/139891609";
- public static final String LAUNCHER_DIDNT_INITIALIZE = "b/148313079";
+ public static final String NO_SCROLL_END_WIDGETS = "b/152354290";
}
diff --git a/src/com/android/launcher3/touch/AbstractStateChangeTouchController.java b/src/com/android/launcher3/touch/AbstractStateChangeTouchController.java
index 7ae0526..cbc5257 100644
--- a/src/com/android/launcher3/touch/AbstractStateChangeTouchController.java
+++ b/src/com/android/launcher3/touch/AbstractStateChangeTouchController.java
@@ -19,11 +19,11 @@
import static com.android.launcher3.LauncherState.ALL_APPS;
import static com.android.launcher3.LauncherState.NORMAL;
import static com.android.launcher3.LauncherState.OVERVIEW;
-import static com.android.launcher3.LauncherStateManager.ANIM_ALL;
-import static com.android.launcher3.LauncherStateManager.ATOMIC_OVERVIEW_SCALE_COMPONENT;
-import static com.android.launcher3.LauncherStateManager.NON_ATOMIC_COMPONENT;
import static com.android.launcher3.anim.Interpolators.scrollInterpolatorForVelocity;
-import static com.android.launcher3.config.FeatureFlags.QUICKSTEP_SPRINGS;
+import static com.android.launcher3.config.FeatureFlags.UNSTABLE_SPRINGS;
+import static com.android.launcher3.states.StateAnimationConfig.ANIM_ALL_COMPONENTS;
+import static com.android.launcher3.states.StateAnimationConfig.PLAY_ATOMIC_OVERVIEW_SCALE;
+import static com.android.launcher3.states.StateAnimationConfig.PLAY_NON_ATOMIC;
import static com.android.launcher3.util.DefaultDisplay.getSingleFrameMs;
import android.animation.Animator;
@@ -37,16 +37,16 @@
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherAnimUtils;
import com.android.launcher3.LauncherState;
-import com.android.launcher3.LauncherStateManager.AnimationComponents;
import com.android.launcher3.Utilities;
import com.android.launcher3.anim.AnimationSuccessListener;
import com.android.launcher3.anim.AnimatorPlaybackController;
-import com.android.launcher3.anim.AnimatorSetBuilder;
+import com.android.launcher3.anim.PendingAnimation;
+import com.android.launcher3.states.StateAnimationConfig;
+import com.android.launcher3.states.StateAnimationConfig.AnimationFlags;
import com.android.launcher3.userevent.nano.LauncherLogProto;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action.Direction;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action.Touch;
import com.android.launcher3.util.FlingBlockCheck;
-import com.android.launcher3.util.PendingAnimation;
import com.android.launcher3.util.TouchController;
/**
@@ -176,7 +176,7 @@
protected abstract LauncherState getTargetState(LauncherState fromState,
boolean isDragTowardPositive);
- protected abstract float initCurrentAnimation(@AnimationComponents int animComponents);
+ protected abstract float initCurrentAnimation(@AnimationFlags int animComponents);
/**
* Returns the container that the touch started from when leaving NORMAL state.
@@ -201,10 +201,10 @@
mCurrentAnimation.setOnCancelRunnable(null);
}
int animComponents = goingBetweenNormalAndOverview(mFromState, mToState)
- ? NON_ATOMIC_COMPONENT : ANIM_ALL;
+ ? PLAY_NON_ATOMIC : ANIM_ALL_COMPONENTS;
mScheduleResumeAtomicComponent = false;
if (mAtomicAnim != null) {
- animComponents = NON_ATOMIC_COMPONENT;
+ animComponents = PLAY_NON_ATOMIC;
// Control the non-atomic components until the atomic animation finishes, then control
// the atomic components as well.
mScheduleResumeAtomicComponent = true;
@@ -215,7 +215,7 @@
}
if (mAtomicComponentsController != null) {
- animComponents &= ~ATOMIC_OVERVIEW_SCALE_COMPONENT;
+ animComponents &= ~PLAY_ATOMIC_OVERVIEW_SCALE;
}
mProgressMultiplier = initCurrentAnimation(animComponents);
mCurrentAnimation.dispatchOnStart();
@@ -230,7 +230,7 @@
}
@Override
- public void onDragStart(boolean start) {
+ public void onDragStart(boolean start, float startDisplacement) {
mStartState = mLauncher.getStateManager().getState();
mIsLogContainerSet = false;
if (mCurrentAnimation == null) {
@@ -358,14 +358,18 @@
private AnimatorSet createAtomicAnimForState(LauncherState fromState, LauncherState targetState,
long duration) {
- AnimatorSetBuilder builder = getAnimatorSetBuilderForStates(fromState, targetState);
- return mLauncher.getStateManager().createAtomicAnimation(fromState, targetState, builder,
- ATOMIC_OVERVIEW_SCALE_COMPONENT, duration);
+ StateAnimationConfig config = getConfigForStates(fromState, targetState);
+ config.animFlags = PLAY_ATOMIC_OVERVIEW_SCALE;
+ config.duration = duration;
+ return mLauncher.getStateManager().createAtomicAnimation(fromState, targetState, config);
}
- protected AnimatorSetBuilder getAnimatorSetBuilderForStates(LauncherState fromState,
- LauncherState toState) {
- return new AnimatorSetBuilder();
+ /**
+ * Returns animation config for state transition between provided states
+ */
+ protected StateAnimationConfig getConfigForStates(
+ LauncherState fromState, LauncherState toState) {
+ return new StateAnimationConfig();
}
@Override
@@ -434,8 +438,8 @@
maybeUpdateAtomicAnim(mFromState, targetState, targetState == mToState ? 1f : 0f);
updateSwipeCompleteAnimation(anim, Math.max(duration, getRemainingAtomicDuration()),
targetState, velocity, fling);
- mCurrentAnimation.dispatchOnStartWithVelocity(endProgress, progressVelocity);
- if (fling && targetState == LauncherState.ALL_APPS && !QUICKSTEP_SPRINGS.get()) {
+ mCurrentAnimation.dispatchOnStart();
+ if (fling && targetState == LauncherState.ALL_APPS && !UNSTABLE_SPRINGS.get()) {
mLauncher.getAppsView().addSpringFromFlingUpdateListener(anim, velocity);
}
anim.start();
@@ -531,7 +535,7 @@
// case the user started interacting with it before the animation finished.
mLauncher.getStateManager().goToState(targetState, false /* animated */);
}
- mLauncher.getDragLayer().getScrim().animateToSysuiMultiplier(1, 0, 0);
+ mLauncher.getDragLayer().getScrim().createSysuiMultiplierAnim(1f).setDuration(0).start();
}
private void logReachedState(int logAction, LauncherState targetState) {
diff --git a/src/com/android/launcher3/touch/AllAppsSwipeController.java b/src/com/android/launcher3/touch/AllAppsSwipeController.java
index 31a5d79..4a202b6 100644
--- a/src/com/android/launcher3/touch/AllAppsSwipeController.java
+++ b/src/com/android/launcher3/touch/AllAppsSwipeController.java
@@ -23,7 +23,7 @@
import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherState;
-import com.android.launcher3.LauncherStateManager.AnimationComponents;
+import com.android.launcher3.states.StateAnimationConfig.AnimationFlags;
import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
/**
@@ -76,7 +76,7 @@
}
@Override
- protected float initCurrentAnimation(@AnimationComponents int animComponents) {
+ protected float initCurrentAnimation(@AnimationFlags int animComponents) {
float range = getShiftRange();
long maxAccuracy = (long) (2 * range);
mCurrentAnimation = mLauncher.getStateManager()
diff --git a/src/com/android/launcher3/touch/BaseSwipeDetector.java b/src/com/android/launcher3/touch/BaseSwipeDetector.java
index 30283da..1276ece 100644
--- a/src/com/android/launcher3/touch/BaseSwipeDetector.java
+++ b/src/com/android/launcher3/touch/BaseSwipeDetector.java
@@ -236,7 +236,7 @@
} else {
mSubtractDisplacement.x = mDisplacement.x > 0 ? mTouchSlop : -mTouchSlop;
mSubtractDisplacement.y = mDisplacement.y > 0 ? mTouchSlop : -mTouchSlop;
- }
+ }
}
protected abstract boolean shouldScrollStart(PointF displacement);
diff --git a/src/com/android/launcher3/touch/ItemClickHandler.java b/src/com/android/launcher3/touch/ItemClickHandler.java
index f7ce160..f7091fc 100644
--- a/src/com/android/launcher3/touch/ItemClickHandler.java
+++ b/src/com/android/launcher3/touch/ItemClickHandler.java
@@ -15,14 +15,14 @@
*/
package com.android.launcher3.touch;
-import static com.android.launcher3.ItemInfoWithIcon.FLAG_DISABLED_BY_PUBLISHER;
-import static com.android.launcher3.ItemInfoWithIcon.FLAG_DISABLED_LOCKED_USER;
-import static com.android.launcher3.ItemInfoWithIcon.FLAG_DISABLED_QUIET_USER;
-import static com.android.launcher3.ItemInfoWithIcon.FLAG_DISABLED_SAFEMODE;
-import static com.android.launcher3.ItemInfoWithIcon.FLAG_DISABLED_SUSPENDED;
import static com.android.launcher3.Launcher.REQUEST_BIND_PENDING_APPWIDGET;
import static com.android.launcher3.Launcher.REQUEST_RECONFIGURE_APPWIDGET;
import static com.android.launcher3.model.AppLaunchTracker.CONTAINER_ALL_APPS;
+import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_DISABLED_BY_PUBLISHER;
+import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_DISABLED_LOCKED_USER;
+import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_DISABLED_QUIET_USER;
+import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_DISABLED_SAFEMODE;
+import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_DISABLED_SUSPENDED;
import android.app.AlertDialog;
import android.content.Intent;
@@ -38,19 +38,19 @@
import androidx.annotation.Nullable;
-import com.android.launcher3.AppInfo;
import com.android.launcher3.BubbleTextView;
-import com.android.launcher3.FolderInfo;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.Launcher;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherAppWidgetProviderInfo;
-import com.android.launcher3.PromiseAppInfo;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.folder.Folder;
import com.android.launcher3.folder.FolderIcon;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.FolderInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
+import com.android.launcher3.model.data.PromiseAppInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.pm.InstallSessionHelper;
import com.android.launcher3.util.PackageManagerHelper;
import com.android.launcher3.views.FloatingIconView;
@@ -224,8 +224,9 @@
// Check for abandoned promise
if ((v instanceof BubbleTextView) && shortcut.hasPromiseIconUi()) {
- String packageName = shortcut.intent.getComponent() != null ?
- shortcut.intent.getComponent().getPackageName() : shortcut.intent.getPackage();
+ String packageName = shortcut.getIntent().getComponent() != null
+ ? shortcut.getIntent().getComponent().getPackageName()
+ : shortcut.getIntent().getPackage();
if (!TextUtils.isEmpty(packageName)) {
onClickPendingAppItem(v, launcher, packageName,
shortcut.hasStatusFlag(WorkspaceItemInfo.FLAG_INSTALL_SESSION_ACTIVE));
diff --git a/src/com/android/launcher3/touch/ItemLongClickListener.java b/src/com/android/launcher3/touch/ItemLongClickListener.java
index ba1bfa5..7baeab8 100644
--- a/src/com/android/launcher3/touch/ItemLongClickListener.java
+++ b/src/com/android/launcher3/touch/ItemLongClickListener.java
@@ -28,11 +28,13 @@
import com.android.launcher3.CellLayout;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.DropTarget;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.Launcher;
import com.android.launcher3.dragndrop.DragController;
import com.android.launcher3.dragndrop.DragOptions;
import com.android.launcher3.folder.Folder;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.testing.TestLogging;
+import com.android.launcher3.testing.TestProtocol;
/**
* Class to handle long-clicks on workspace items and start drag as a result.
@@ -46,6 +48,7 @@
ItemLongClickListener::onAllAppsItemLongClick;
private static boolean onWorkspaceItemLongClick(View v) {
+ TestLogging.recordEvent(TestProtocol.SEQUENCE_MAIN, "onWorkspaceItemLongClick");
Launcher launcher = Launcher.getLauncher(v.getContext());
if (!canStartDrag(launcher)) return false;
if (!launcher.isInState(NORMAL) && !launcher.isInState(OVERVIEW)) return false;
@@ -75,6 +78,8 @@
}
private static boolean onAllAppsItemLongClick(View v) {
+ TestLogging.recordEvent(TestProtocol.SEQUENCE_MAIN, "onAllAppsItemLongClick");
+ v.cancelLongPress();
Launcher launcher = Launcher.getLauncher(v.getContext());
if (!canStartDrag(launcher)) return false;
// When we have exited all apps or are in transition, disregard long clicks
diff --git a/src/com/android/launcher3/touch/LandscapePagedViewHandler.java b/src/com/android/launcher3/touch/LandscapePagedViewHandler.java
new file mode 100644
index 0000000..bab5747
--- /dev/null
+++ b/src/com/android/launcher3/touch/LandscapePagedViewHandler.java
@@ -0,0 +1,250 @@
+/*
+ * 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.launcher3.touch;
+
+import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_X;
+import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_Y;
+import static com.android.launcher3.touch.SingleAxisSwipeDetector.HORIZONTAL;
+
+import android.content.res.Resources;
+import android.graphics.PointF;
+import android.graphics.Rect;
+import android.graphics.RectF;
+import android.util.FloatProperty;
+import android.view.MotionEvent;
+import android.view.Surface;
+import android.view.VelocityTracker;
+import android.view.View;
+import android.view.accessibility.AccessibilityEvent;
+
+import com.android.launcher3.DeviceProfile;
+import com.android.launcher3.LauncherState.ScaleAndTranslation;
+import com.android.launcher3.PagedView;
+import com.android.launcher3.Utilities;
+import com.android.launcher3.util.OverScroller;
+
+public class LandscapePagedViewHandler implements PagedOrientationHandler {
+
+ @Override
+ public int getPrimaryValue(int x, int y) {
+ return y;
+ }
+
+ @Override
+ public int getSecondaryValue(int x, int y) {
+ return x;
+ }
+
+ @Override
+ public void delegateScrollTo(PagedView pagedView, int secondaryScroll, int minMaxScroll) {
+ pagedView.superScrollTo(secondaryScroll, minMaxScroll);
+ }
+
+ @Override
+ public void delegateScrollBy(PagedView pagedView, int unboundedScroll, int x, int y) {
+ pagedView.scrollTo(pagedView.getScrollX() + x, unboundedScroll + y);
+ }
+
+ @Override
+ public void scrollerStartScroll(OverScroller scroller, int newPosition) {
+ scroller.startScroll(scroller.getCurrPos(), newPosition - scroller.getCurrPos());
+ }
+
+ @Override
+ public void getCurveProperties(PagedView view, Rect insets, CurveProperties out) {
+ out.scroll = view.getScrollY();
+ out.halfPageSize = view.getNormalChildHeight() / 2;
+ out.halfScreenSize = view.getMeasuredHeight() / 2;
+ out.screenCenter = insets.top + view.getPaddingTop() + out.scroll + out.halfPageSize;
+ }
+
+ @Override
+ public boolean isGoingUp(float displacement) {
+ return displacement > 0;
+ }
+
+ @Override
+ public void adjustFloatingIconStartVelocity(PointF velocity) {
+ float oldX = velocity.x;
+ float oldY = velocity.y;
+ velocity.set(-oldY, oldX);
+ }
+
+ @Override
+ public void delegateScrollTo(PagedView pagedView, int primaryScroll) {
+ pagedView.superScrollTo(pagedView.getScrollX(), primaryScroll);
+ }
+
+ @Override
+ public <T> void set(T target, Int2DAction<T> action, int param) {
+ action.call(target, 0, param);
+ }
+
+ @Override
+ public <T> void set(T target, Float2DAction<T> action, float param) {
+ action.call(target, 0, param);
+ }
+
+ @Override
+ public float getPrimaryDirection(MotionEvent event, int pointerIndex) {
+ return event.getY(pointerIndex);
+ }
+
+ @Override
+ public float getPrimaryVelocity(VelocityTracker velocityTracker, int pointerId) {
+ return velocityTracker.getYVelocity(pointerId);
+ }
+
+ @Override
+ public int getMeasuredSize(View view) {
+ return view.getMeasuredHeight();
+ }
+
+ @Override
+ public int getPrimarySize(Rect rect) {
+ return rect.height();
+ }
+
+ @Override
+ public float getPrimarySize(RectF rect) {
+ return rect.height();
+ }
+
+ @Override
+ public int getSecondaryDimension(View view) {
+ return view.getWidth();
+ }
+
+ @Override
+ public ScaleAndTranslation getScaleAndTranslation(DeviceProfile dp, View view) {
+ float offscreenTranslationY = dp.heightPx - view.getPaddingTop();
+ return new ScaleAndTranslation(1f, 0f, offscreenTranslationY);
+ }
+
+ @Override
+ public float getTranslationValue(ScaleAndTranslation scaleAndTranslation) {
+ return scaleAndTranslation.translationY;
+ }
+
+ @Override
+ public FloatProperty<View> getPrimaryViewTranslate() {
+ return VIEW_TRANSLATE_Y;
+ }
+
+ @Override
+ public FloatProperty<View> getSecondaryViewTranslate() {
+ return VIEW_TRANSLATE_X;
+ }
+
+ @Override
+ public void setPrimaryAndResetSecondaryTranslate(View view, float translation) {
+ view.setTranslationX(0);
+ view.setTranslationY(translation);
+ }
+
+ @Override
+ public int getPrimaryScroll(View view) {
+ return view.getScrollY();
+ }
+
+ @Override
+ public float getPrimaryScale(View view) {
+ return view.getScaleY();
+ }
+
+ @Override
+ public void setMaxScroll(AccessibilityEvent event, int maxScroll) {
+ event.setMaxScrollY(maxScroll);
+ }
+
+ @Override
+ public boolean getRecentsRtlSetting(Resources resources) {
+ return !Utilities.isRtl(resources);
+ }
+
+ @Override
+ public float getDegreesRotated() {
+ return 90;
+ }
+
+ @Override
+ public void offsetTaskRect(RectF rect, float value, int displayRotation) {
+ if (displayRotation == Surface.ROTATION_0) {
+ rect.offset(0, value);
+ } else if (displayRotation == Surface.ROTATION_90) {
+ rect.offset(value, 0);
+ } else if (displayRotation == Surface.ROTATION_180) {
+ rect.offset(0, -value);
+ } else {
+ rect.offset(-value, 0);
+ }
+ }
+
+ @Override
+ public int getChildStart(View view) {
+ return view.getTop();
+ }
+
+ @Override
+ public float getChildStartWithTranslation(View view) {
+ return view.getTop() + view.getTranslationY();
+ }
+
+ @Override
+ public int getCenterForPage(View view, Rect insets) {
+ return (view.getPaddingLeft() + view.getMeasuredWidth() + insets.left
+ - insets.right - view.getPaddingRight()) / 2;
+ }
+
+ @Override
+ public int getScrollOffsetStart(View view, Rect insets) {
+ return insets.top + view.getPaddingTop();
+ }
+
+ @Override
+ public int getScrollOffsetEnd(View view, Rect insets) {
+ return view.getHeight() - view.getPaddingBottom() - insets.bottom;
+ }
+
+ @Override
+ public SingleAxisSwipeDetector.Direction getOppositeSwipeDirection() {
+ return HORIZONTAL;
+ }
+
+ @Override
+ public int getShortEdgeLength(DeviceProfile dp) {
+ return dp.heightPx;
+ }
+
+ @Override
+ public int getTaskDismissDirectionFactor() {
+ return 1;
+ }
+
+ @Override
+ public ChildBounds getChildBounds(View child, int childStart, int pageCenter,
+ boolean layoutChild) {
+ final int childHeight = child.getMeasuredHeight();
+ final int childBottom = childStart + childHeight;
+ final int childWidth = child.getMeasuredWidth();
+ final int childLeft = pageCenter - childWidth/ 2;
+ if (layoutChild) {
+ child.layout(childLeft, childStart, childLeft + childWidth, childBottom);
+ }
+ return new ChildBounds(childHeight, childWidth, childBottom, childLeft);
+ }
+}
diff --git a/src/com/android/launcher3/touch/PagedOrientationHandler.java b/src/com/android/launcher3/touch/PagedOrientationHandler.java
new file mode 100644
index 0000000..50606ec
--- /dev/null
+++ b/src/com/android/launcher3/touch/PagedOrientationHandler.java
@@ -0,0 +1,122 @@
+/*
+ * 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.launcher3.touch;
+
+import android.content.res.Resources;
+import android.graphics.Canvas;
+import android.graphics.PointF;
+import android.graphics.Rect;
+import android.graphics.RectF;
+import android.util.FloatProperty;
+import android.view.MotionEvent;
+import android.view.VelocityTracker;
+import android.view.View;
+import android.view.accessibility.AccessibilityEvent;
+
+import com.android.launcher3.DeviceProfile;
+import com.android.launcher3.LauncherState;
+import com.android.launcher3.PagedView;
+import com.android.launcher3.util.OverScroller;
+
+/**
+ * Abstraction layer to separate horizontal and vertical specific implementations
+ * for {@link com.android.launcher3.PagedView}. Majority of these implementations are (should be) as
+ * simple as choosing the correct X and Y analogous methods.
+ */
+public interface PagedOrientationHandler {
+
+ PagedOrientationHandler PORTRAIT = new PortraitPagedViewHandler();
+ PagedOrientationHandler LANDSCAPE = new LandscapePagedViewHandler();
+ PagedOrientationHandler SEASCAPE = new SeascapePagedViewHandler();
+
+ interface Int2DAction<T> {
+ void call(T target, int x, int y);
+ }
+ interface Float2DAction<T> {
+ void call(T target, float x, float y);
+ }
+ Int2DAction<View> VIEW_SCROLL_BY = View::scrollBy;
+ Int2DAction<View> VIEW_SCROLL_TO = View::scrollTo;
+ Float2DAction<Canvas> CANVAS_TRANSLATE = Canvas::translate;
+ <T> void set(T target, Int2DAction<T> action, int param);
+ <T> void set(T target, Float2DAction<T> action, float param);
+ float getPrimaryDirection(MotionEvent event, int pointerIndex);
+ float getPrimaryVelocity(VelocityTracker velocityTracker, int pointerId);
+ int getMeasuredSize(View view);
+ int getPrimarySize(Rect rect);
+ float getPrimarySize(RectF rect);
+ int getSecondaryDimension(View view);
+ LauncherState.ScaleAndTranslation getScaleAndTranslation(DeviceProfile dp, View view);
+ float getTranslationValue(LauncherState.ScaleAndTranslation scaleAndTranslation);
+ FloatProperty<View> getPrimaryViewTranslate();
+ FloatProperty<View> getSecondaryViewTranslate();
+ void setPrimaryAndResetSecondaryTranslate(View view, float translation);
+ int getPrimaryScroll(View view);
+ float getPrimaryScale(View view);
+ int getChildStart(View view);
+ float getChildStartWithTranslation(View view);
+ int getCenterForPage(View view, Rect insets);
+ int getScrollOffsetStart(View view, Rect insets);
+ int getScrollOffsetEnd(View view, Rect insets);
+ SingleAxisSwipeDetector.Direction getOppositeSwipeDirection();
+ int getShortEdgeLength(DeviceProfile dp);
+ int getTaskDismissDirectionFactor();
+ ChildBounds getChildBounds(View child, int childStart, int pageCenter, boolean layoutChild);
+ void setMaxScroll(AccessibilityEvent event, int maxScroll);
+ boolean getRecentsRtlSetting(Resources resources);
+ float getDegreesRotated();
+ void offsetTaskRect(RectF rect, float value, int delta);
+ int getPrimaryValue(int x, int y);
+ int getSecondaryValue(int x, int y);
+ void delegateScrollTo(PagedView pagedView, int secondaryScroll, int primaryScroll);
+ /** Uses {@params pagedView}.getScroll[X|Y]() method for the secondary amount*/
+ void delegateScrollTo(PagedView pagedView, int primaryScroll);
+ void delegateScrollBy(PagedView pagedView, int unboundedScroll, int x, int y);
+ void scrollerStartScroll(OverScroller scroller, int newPosition);
+ void getCurveProperties(PagedView view, Rect insets, CurveProperties out);
+ boolean isGoingUp(float displacement);
+
+ /**
+ * Maps the velocity from the coordinate plane of the foreground app to that
+ * of Launcher's (which now will always be portrait)
+ */
+ void adjustFloatingIconStartVelocity(PointF velocity);
+
+
+ class CurveProperties {
+ public int scroll;
+ public int halfPageSize;
+ public int screenCenter;
+ public int halfScreenSize;
+ }
+
+ class ChildBounds {
+
+ public final int primaryDimension;
+ public final int secondaryDimension;
+ public final int childPrimaryEnd;
+ public final int childSecondaryEnd;
+
+ ChildBounds(int primaryDimension, int secondaryDimension, int childPrimaryEnd,
+ int childSecondaryEnd) {
+ this.primaryDimension = primaryDimension;
+ this.secondaryDimension = secondaryDimension;
+ this.childPrimaryEnd = childPrimaryEnd;
+ this.childSecondaryEnd = childSecondaryEnd;
+ }
+ }
+}
diff --git a/src/com/android/launcher3/touch/PortraitPagedViewHandler.java b/src/com/android/launcher3/touch/PortraitPagedViewHandler.java
new file mode 100644
index 0000000..245138f
--- /dev/null
+++ b/src/com/android/launcher3/touch/PortraitPagedViewHandler.java
@@ -0,0 +1,248 @@
+/*
+ * 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.launcher3.touch;
+
+import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_X;
+import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_Y;
+import static com.android.launcher3.touch.SingleAxisSwipeDetector.VERTICAL;
+
+import android.content.res.Resources;
+import android.graphics.PointF;
+import android.graphics.Rect;
+import android.graphics.RectF;
+import android.util.FloatProperty;
+import android.view.MotionEvent;
+import android.view.Surface;
+import android.view.VelocityTracker;
+import android.view.View;
+import android.view.accessibility.AccessibilityEvent;
+
+import com.android.launcher3.DeviceProfile;
+import com.android.launcher3.LauncherState.ScaleAndTranslation;
+import com.android.launcher3.PagedView;
+import com.android.launcher3.Utilities;
+import com.android.launcher3.util.OverScroller;
+
+public class PortraitPagedViewHandler implements PagedOrientationHandler {
+
+ @Override
+ public int getPrimaryValue(int x, int y) {
+ return x;
+ }
+
+ @Override
+ public int getSecondaryValue(int x, int y) {
+ return y;
+ }
+
+ @Override
+ public void delegateScrollTo(PagedView pagedView, int secondaryScroll, int primaryScroll) {
+ pagedView.superScrollTo(primaryScroll, secondaryScroll);
+ }
+
+ @Override
+ public void delegateScrollBy(PagedView pagedView, int unboundedScroll, int x, int y) {
+ pagedView.scrollTo(unboundedScroll + x, pagedView.getScrollY() + y);
+ }
+
+ @Override
+ public void scrollerStartScroll(OverScroller scroller, int newPosition) {
+ scroller.startScroll(newPosition - scroller.getCurrPos(), scroller.getCurrPos());
+ }
+
+ @Override
+ public void getCurveProperties(PagedView view, Rect insets, CurveProperties out) {
+ out.scroll = view.getScrollX();
+ out.halfPageSize = view.getNormalChildWidth() / 2;
+ out.halfScreenSize = view.getMeasuredWidth() / 2;
+ out.screenCenter = insets.left + view.getPaddingLeft() + out.scroll + out.halfPageSize;
+ }
+
+ @Override
+ public boolean isGoingUp(float displacement) {
+ return displacement < 0;
+ }
+
+ @Override
+ public void adjustFloatingIconStartVelocity(PointF velocity) {
+ //no-op
+ }
+
+ @Override
+ public void delegateScrollTo(PagedView pagedView, int primaryScroll) {
+ pagedView.superScrollTo(primaryScroll, pagedView.getScrollY());
+ }
+
+ @Override
+ public <T> void set(T target, Int2DAction<T> action, int param) {
+ action.call(target, param, 0);
+ }
+
+ @Override
+ public <T> void set(T target, Float2DAction<T> action, float param) {
+ action.call(target, param, 0);
+ }
+
+ @Override
+ public float getPrimaryDirection(MotionEvent event, int pointerIndex) {
+ return event.getX(pointerIndex);
+ }
+
+ @Override
+ public float getPrimaryVelocity(VelocityTracker velocityTracker, int pointerId) {
+ return velocityTracker.getXVelocity(pointerId);
+ }
+
+ @Override
+ public int getMeasuredSize(View view) {
+ return view.getMeasuredWidth();
+ }
+
+ @Override
+ public int getPrimarySize(Rect rect) {
+ return rect.width();
+ }
+
+ @Override
+ public float getPrimarySize(RectF rect) {
+ return rect.width();
+ }
+
+ @Override
+ public int getSecondaryDimension(View view) {
+ return view.getHeight();
+ }
+
+ @Override
+ public ScaleAndTranslation getScaleAndTranslation(DeviceProfile dp, View view) {
+ float offscreenTranslationX = dp.widthPx - view.getPaddingStart();
+ return new ScaleAndTranslation(1f, offscreenTranslationX, 0f);
+ }
+
+ @Override
+ public float getTranslationValue(ScaleAndTranslation scaleAndTranslation) {
+ return scaleAndTranslation.translationX;
+ }
+
+ @Override
+ public FloatProperty<View> getPrimaryViewTranslate() {
+ return VIEW_TRANSLATE_X;
+ }
+
+ @Override
+ public FloatProperty<View> getSecondaryViewTranslate() {
+ return VIEW_TRANSLATE_Y;
+ }
+
+ @Override
+ public void setPrimaryAndResetSecondaryTranslate(View view, float translation) {
+ view.setTranslationX(translation);
+ view.setTranslationY(0);
+ }
+
+ @Override
+ public int getPrimaryScroll(View view) {
+ return view.getScrollX();
+ }
+
+ @Override
+ public float getPrimaryScale(View view) {
+ return view.getScaleX();
+ }
+
+ @Override
+ public void setMaxScroll(AccessibilityEvent event, int maxScroll) {
+ event.setMaxScrollX(maxScroll);
+ }
+
+ @Override
+ public boolean getRecentsRtlSetting(Resources resources) {
+ return !Utilities.isRtl(resources);
+ }
+
+ @Override
+ public float getDegreesRotated() {
+ return 0;
+ }
+
+ @Override
+ public void offsetTaskRect(RectF rect, float value, int displayRotation) {
+ if (displayRotation == Surface.ROTATION_0) {
+ rect.offset(value, 0);
+ } else if (displayRotation == Surface.ROTATION_90) {
+ rect.offset(0, -value);
+ } else if (displayRotation == Surface.ROTATION_180) {
+ rect.offset(-value, 0);
+ } else {
+ rect.offset(0, value);
+ }
+ }
+
+ @Override
+ public int getChildStart(View view) {
+ return view.getLeft();
+ }
+
+ @Override
+ public float getChildStartWithTranslation(View view) {
+ return view.getLeft() + view.getTranslationX();
+ }
+
+ @Override
+ public int getCenterForPage(View view, Rect insets) {
+ return (view.getPaddingTop() + view.getMeasuredHeight() + insets.top
+ - insets.bottom - view.getPaddingBottom()) / 2;
+ }
+
+ @Override
+ public int getScrollOffsetStart(View view, Rect insets) {
+ return insets.left + view.getPaddingLeft();
+ }
+
+ @Override
+ public int getScrollOffsetEnd(View view, Rect insets) {
+ return view.getWidth() - view.getPaddingRight() - insets.right;
+ }
+
+ @Override
+ public SingleAxisSwipeDetector.Direction getOppositeSwipeDirection() {
+ return VERTICAL;
+ }
+
+ @Override
+ public int getShortEdgeLength(DeviceProfile dp) {
+ return dp.widthPx;
+ }
+
+ @Override
+ public int getTaskDismissDirectionFactor() {
+ return -1;
+ }
+
+ @Override
+ public ChildBounds getChildBounds(View child, int childStart, int pageCenter,
+ boolean layoutChild) {
+ final int childWidth = child.getMeasuredWidth();
+ final int childRight = childStart + childWidth;
+ final int childHeight = child.getMeasuredHeight();
+ final int childTop = pageCenter - childHeight / 2;
+ if (layoutChild) {
+ child.layout(childStart, childTop, childRight, childTop + childHeight);
+ }
+ return new ChildBounds(childWidth, childHeight, childRight, childTop);
+ }
+}
diff --git a/src/com/android/launcher3/touch/SeascapePagedViewHandler.java b/src/com/android/launcher3/touch/SeascapePagedViewHandler.java
new file mode 100644
index 0000000..eebd87f
--- /dev/null
+++ b/src/com/android/launcher3/touch/SeascapePagedViewHandler.java
@@ -0,0 +1,67 @@
+/*
+ * 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.launcher3.touch;
+
+import android.content.res.Resources;
+import android.graphics.PointF;
+import android.graphics.RectF;
+import android.view.Surface;
+
+import com.android.launcher3.Utilities;
+
+public class SeascapePagedViewHandler extends LandscapePagedViewHandler {
+
+ @Override
+ public int getTaskDismissDirectionFactor() {
+ return -1;
+ }
+
+ @Override
+ public boolean getRecentsRtlSetting(Resources resources) {
+ return Utilities.isRtl(resources);
+ }
+
+ @Override
+ public void offsetTaskRect(RectF rect, float value, int displayRotation) {
+ if (displayRotation == Surface.ROTATION_0) {
+ rect.offset(0, value);
+ } else if (displayRotation == Surface.ROTATION_90) {
+ rect.offset(value, 0);
+ } else if (displayRotation == Surface.ROTATION_180) {
+ rect.offset(0, -value);
+ } else {
+ rect.offset(-value, 0);
+ }
+ }
+
+ @Override
+ public float getDegreesRotated() {
+ return 270;
+ }
+
+ @Override
+ public boolean isGoingUp(float displacement) {
+ return displacement < 0;
+ }
+
+ @Override
+ public void adjustFloatingIconStartVelocity(PointF velocity) {
+ float oldX = velocity.x;
+ float oldY = velocity.y;
+ velocity.set(oldY, -oldX);
+ }
+}
diff --git a/src/com/android/launcher3/touch/SingleAxisSwipeDetector.java b/src/com/android/launcher3/touch/SingleAxisSwipeDetector.java
index 9d406f3..d725486 100644
--- a/src/com/android/launcher3/touch/SingleAxisSwipeDetector.java
+++ b/src/com/android/launcher3/touch/SingleAxisSwipeDetector.java
@@ -148,7 +148,8 @@
@Override
protected void reportDragStartInternal(boolean recatch) {
- mListener.onDragStart(!recatch);
+ float startDisplacement = mDir.extractDirection(mSubtractDisplacement);
+ mListener.onDragStart(!recatch, startDisplacement);
}
@Override
@@ -165,8 +166,13 @@
/** Listener to receive updates on the swipe. */
public interface Listener {
- /** @param start whether this was the original drag start, as opposed to a recatch. */
- void onDragStart(boolean start);
+ /**
+ * TODO(b/150256055) consolidate all the different onDrag() methods into one
+ * @param start whether this was the original drag start, as opposed to a recatch.
+ * @param startDisplacement the initial touch displacement for the primary direction as
+ * given by by {@link Direction#extractDirection(PointF)}
+ */
+ void onDragStart(boolean start, float startDisplacement);
boolean onDrag(float displacement);
diff --git a/src/com/android/launcher3/touch/WorkspaceTouchListener.java b/src/com/android/launcher3/touch/WorkspaceTouchListener.java
index 310d598..da631bd 100644
--- a/src/com/android/launcher3/touch/WorkspaceTouchListener.java
+++ b/src/com/android/launcher3/touch/WorkspaceTouchListener.java
@@ -38,6 +38,8 @@
import com.android.launcher3.Launcher;
import com.android.launcher3.Workspace;
import com.android.launcher3.dragndrop.DragLayer;
+import com.android.launcher3.testing.TestLogging;
+import com.android.launcher3.testing.TestProtocol;
import com.android.launcher3.views.OptionsPopupView;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action;
import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
@@ -165,6 +167,7 @@
@Override
public void onLongPress(MotionEvent event) {
+ TestLogging.recordEvent(TestProtocol.SEQUENCE_MAIN, "Workspace.longPress");
if (mLongPressState == STATE_REQUESTED) {
if (canHandleLongPress()) {
mLongPressState = STATE_PENDING_PARENT_INFORM;
diff --git a/src/com/android/launcher3/util/ActivityTracker.java b/src/com/android/launcher3/util/ActivityTracker.java
index b83c8fc..499f655 100644
--- a/src/com/android/launcher3/util/ActivityTracker.java
+++ b/src/com/android/launcher3/util/ActivityTracker.java
@@ -45,13 +45,7 @@
}
public void onActivityDestroyed(T activity) {
- if (TestProtocol.sDebugTracing) {
- Log.d(TestProtocol.LAUNCHER_DIDNT_INITIALIZE, "onActivityDestroyed");
- }
if (mCurrentActivity.get() == activity) {
- if (TestProtocol.sDebugTracing) {
- Log.d(TestProtocol.LAUNCHER_DIDNT_INITIALIZE, "onActivityDestroyed: clear");
- }
mCurrentActivity.clear();
}
}
@@ -116,10 +110,6 @@
}
public boolean handleCreate(T activity) {
- if (TestProtocol.sDebugTracing) {
- Log.d(TestProtocol.LAUNCHER_DIDNT_INITIALIZE,
- "ActivityTracker.handleCreate " + mCurrentActivity.get() + " => " + activity);
- }
mCurrentActivity = new WeakReference<>(activity);
return handleIntent(activity, activity.getIntent(), false, false);
}
diff --git a/src/com/android/launcher3/util/DefaultDisplay.java b/src/com/android/launcher3/util/DefaultDisplay.java
index d3dac04..f18e411 100644
--- a/src/com/android/launcher3/util/DefaultDisplay.java
+++ b/src/com/android/launcher3/util/DefaultDisplay.java
@@ -28,6 +28,8 @@
import android.view.Display;
import android.view.WindowManager;
+import androidx.annotation.VisibleForTesting;
+
import java.util.ArrayList;
/**
@@ -127,6 +129,18 @@
public final DisplayMetrics metrics;
+ @VisibleForTesting
+ public Info(int id, int rotation, int singleFrameMs, Point realSize, Point smallestSize,
+ Point largestSize, DisplayMetrics metrics) {
+ this.id = id;
+ this.rotation = rotation;
+ this.singleFrameMs = singleFrameMs;
+ this.realSize = realSize;
+ this.smallestSize = smallestSize;
+ this.largestSize = largestSize;
+ this.metrics = metrics;
+ }
+
private Info(Context context) {
this(context.getSystemService(WindowManager.class).getDefaultDisplay());
}
diff --git a/src/com/android/launcher3/util/DynamicResource.java b/src/com/android/launcher3/util/DynamicResource.java
index 8a75767..e6ee186 100644
--- a/src/com/android/launcher3/util/DynamicResource.java
+++ b/src/com/android/launcher3/util/DynamicResource.java
@@ -69,6 +69,11 @@
}
@Override
+ public float getFloat(@DimenRes int resId) {
+ return mContext.getResources().getFloat(resId);
+ }
+
+ @Override
public void onPluginConnected(ResourceProvider plugin, Context context) {
mPlugin = plugin;
}
diff --git a/src/com/android/launcher3/util/GridOccupancy.java b/src/com/android/launcher3/util/GridOccupancy.java
index 6a10b0a..9c752a7 100644
--- a/src/com/android/launcher3/util/GridOccupancy.java
+++ b/src/com/android/launcher3/util/GridOccupancy.java
@@ -2,7 +2,7 @@
import android.graphics.Rect;
-import com.android.launcher3.ItemInfo;
+import com.android.launcher3.model.data.ItemInfo;
/**
* Utility object to manage the occupancy in a grid.
diff --git a/src/com/android/launcher3/util/IOUtils.java b/src/com/android/launcher3/util/IOUtils.java
index 4a4a5ca..fcb96d7 100644
--- a/src/com/android/launcher3/util/IOUtils.java
+++ b/src/com/android/launcher3/util/IOUtils.java
@@ -19,7 +19,6 @@
import android.content.Context;
import android.util.Log;
-import com.android.launcher3.Utilities;
import com.android.launcher3.config.FeatureFlags;
import java.io.ByteArrayOutputStream;
@@ -67,7 +66,7 @@
* Utility method to debug binary data
*/
public static String createTempFile(Context context, byte[] data) {
- if (!FeatureFlags.IS_DOGFOOD_BUILD) {
+ if (!FeatureFlags.IS_STUDIO_BUILD) {
throw new IllegalStateException("Method only allowed in development mode");
}
@@ -87,7 +86,7 @@
try {
c.close();
} catch (IOException e) {
- if (FeatureFlags.IS_DOGFOOD_BUILD) {
+ if (FeatureFlags.IS_STUDIO_BUILD) {
Log.d(TAG, "Error closing", e);
}
}
diff --git a/src/com/android/launcher3/util/InstantAppResolver.java b/src/com/android/launcher3/util/InstantAppResolver.java
index 031a40d..6f706d2 100644
--- a/src/com/android/launcher3/util/InstantAppResolver.java
+++ b/src/com/android/launcher3/util/InstantAppResolver.java
@@ -21,8 +21,8 @@
import android.content.pm.PackageManager;
import android.util.Log;
-import com.android.launcher3.AppInfo;
import com.android.launcher3.R;
+import com.android.launcher3.model.data.AppInfo;
/**
* A wrapper class to access instant app related APIs.
diff --git a/src/com/android/launcher3/util/ItemInfoMatcher.java b/src/com/android/launcher3/util/ItemInfoMatcher.java
index 59a5ed6..4d5405d 100644
--- a/src/com/android/launcher3/util/ItemInfoMatcher.java
+++ b/src/com/android/launcher3/util/ItemInfoMatcher.java
@@ -19,11 +19,11 @@
import android.content.ComponentName;
import android.os.UserHandle;
-import com.android.launcher3.FolderInfo;
-import com.android.launcher3.ItemInfo;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherSettings.Favorites;
-import com.android.launcher3.WorkspaceItemInfo;
+import com.android.launcher3.model.data.FolderInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.shortcuts.ShortcutKey;
import java.util.HashSet;
diff --git a/src/com/android/launcher3/util/MainThreadInitializedObject.java b/src/com/android/launcher3/util/MainThreadInitializedObject.java
index 520a9ed..fc9f8f7 100644
--- a/src/com/android/launcher3/util/MainThreadInitializedObject.java
+++ b/src/com/android/launcher3/util/MainThreadInitializedObject.java
@@ -22,6 +22,7 @@
import androidx.annotation.VisibleForTesting;
+import com.android.launcher3.graphics.LauncherPreviewRenderer.PreviewContext;
import com.android.launcher3.util.ResourceBasedOverride.Overrides;
import java.util.concurrent.ExecutionException;
@@ -39,6 +40,10 @@
}
public T get(Context context) {
+ if (context instanceof PreviewContext) {
+ return ((PreviewContext) context).getObject(this, mProvider);
+ }
+
if (mValue == null) {
if (Looper.myLooper() == Looper.getMainLooper()) {
mValue = TraceHelper.whitelistIpcs("main.thread.object",
diff --git a/src/com/android/launcher3/util/OnboardingPrefs.java b/src/com/android/launcher3/util/OnboardingPrefs.java
new file mode 100644
index 0000000..baa1eee
--- /dev/null
+++ b/src/com/android/launcher3/util/OnboardingPrefs.java
@@ -0,0 +1,115 @@
+/*
+ * 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.launcher3.util;
+
+import android.content.SharedPreferences;
+import android.util.ArrayMap;
+
+import androidx.annotation.StringDef;
+
+import com.android.launcher3.Launcher;
+import com.android.launcher3.LauncherStateManager;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.util.Collections;
+import java.util.Map;
+
+/**
+ * Stores and retrieves onboarding-related data via SharedPreferences.
+ */
+public class OnboardingPrefs<T extends Launcher> {
+
+ public static final String HOME_BOUNCE_SEEN = "launcher.apps_view_shown";
+ public static final String SHELF_BOUNCE_SEEN = "launcher.shelf_bounce_seen";
+ public static final String HOME_BOUNCE_COUNT = "launcher.home_bounce_count";
+ public static final String SHELF_BOUNCE_COUNT = "launcher.shelf_bounce_count";
+ public static final String ALL_APPS_COUNT = "launcher.all_apps_count";
+
+ /**
+ * Events that either have happened or have not (booleans).
+ */
+ @StringDef(value = {
+ HOME_BOUNCE_SEEN,
+ SHELF_BOUNCE_SEEN,
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface EventBoolKey {}
+
+ /**
+ * Events that occur multiple times, which we count up to a max defined in {@link #MAX_COUNTS}.
+ */
+ @StringDef(value = {
+ HOME_BOUNCE_COUNT,
+ SHELF_BOUNCE_COUNT,
+ ALL_APPS_COUNT,
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface EventCountKey {}
+
+ private static final Map<String, Integer> MAX_COUNTS;
+ static {
+ Map<String, Integer> maxCounts = new ArrayMap<>(3);
+ maxCounts.put(HOME_BOUNCE_COUNT, 3);
+ maxCounts.put(SHELF_BOUNCE_COUNT, 3);
+ maxCounts.put(ALL_APPS_COUNT, 5);
+ MAX_COUNTS = Collections.unmodifiableMap(maxCounts);
+ }
+
+ protected final T mLauncher;
+ protected final SharedPreferences mSharedPrefs;
+ protected final LauncherStateManager mStateManager;
+
+ public OnboardingPrefs(T launcher, SharedPreferences sharedPrefs,
+ LauncherStateManager stateManager) {
+ mLauncher = launcher;
+ mSharedPrefs = sharedPrefs;
+ mStateManager = stateManager;
+ }
+
+ /** @return The number of times we have seen the given event. */
+ public int getCount(@EventCountKey String key) {
+ return mSharedPrefs.getInt(key, 0);
+ }
+
+ /** @return Whether we have seen this event enough times, as defined by {@link #MAX_COUNTS}. */
+ public boolean hasReachedMaxCount(@EventCountKey String eventKey) {
+ return hasReachedMaxCount(getCount(eventKey), eventKey);
+ }
+
+ private boolean hasReachedMaxCount(int count, @EventCountKey String eventKey) {
+ return count >= MAX_COUNTS.get(eventKey);
+ }
+
+ /** @return Whether we have seen the given event. */
+ public boolean getBoolean(@EventBoolKey String key) {
+ return mSharedPrefs.getBoolean(key, false);
+ }
+
+ /**
+ * Add 1 to the given event count, if we haven't already reached the max count.
+ * @return Whether we have now reached the max count.
+ */
+ public boolean incrementEventCount(@EventCountKey String eventKey) {
+ int count = getCount(eventKey);
+ if (hasReachedMaxCount(count, eventKey)) {
+ return true;
+ }
+ count++;
+ mSharedPrefs.edit().putInt(eventKey, count).apply();
+ return hasReachedMaxCount(count, eventKey);
+ }
+}
diff --git a/src/com/android/launcher3/util/OverScroller.java b/src/com/android/launcher3/util/OverScroller.java
index fc8a138..87e6986 100644
--- a/src/com/android/launcher3/util/OverScroller.java
+++ b/src/com/android/launcher3/util/OverScroller.java
@@ -26,11 +26,13 @@
import android.view.animation.AnimationUtils;
import android.view.animation.Interpolator;
-import androidx.dynamicanimation.animation.DynamicAnimation;
import androidx.dynamicanimation.animation.FloatPropertyCompat;
import androidx.dynamicanimation.animation.SpringAnimation;
import androidx.dynamicanimation.animation.SpringForce;
+import com.android.launcher3.R;
+import com.android.systemui.plugins.ResourceProvider;
+
/**
* Based on {@link android.widget.OverScroller} supporting only 1-d scrolling and with more
* customization options.
@@ -163,6 +165,9 @@
/**
* Returns how long the scroll event will take, in milliseconds.
*
+ * Note that if mScroller.mState == SPRING, this duration is ignored, so can only
+ * serve as an estimate for how long the spring-controlled scroll will take.
+ *
* @return The duration of the scroll in milliseconds.
*/
public final int getDuration() {
@@ -425,6 +430,7 @@
// Current state of the animation.
private int mState = SPLINE;
+ private Context mContext;
private SpringAnimation mSpring;
// Constant gravity value, used in the deceleration phase.
@@ -500,6 +506,7 @@
}
SplineOverScroller(Context context) {
+ mContext = context;
mFinished = true;
final float ppi = context.getResources().getDisplayMetrics().density * 160.0f;
mPhysicalCoeff = SensorManager.GRAVITY_EARTH // g (m/s^2)
@@ -554,21 +561,25 @@
mStartTime = AnimationUtils.currentAnimationTimeMillis();
mDuration = duration;
+ if (mSpring != null) {
+ mSpring.cancel();
+ }
+
if (mState == SPRING) {
- if (mSpring != null) {
- mSpring.cancel();
- }
mSpring = new SpringAnimation(this, SPRING_PROPERTY);
+ ResourceProvider rp = DynamicResource.provider(mContext);
+ float stiffness = rp.getFloat(R.dimen.horizontal_spring_stiffness);
+ float damping = rp.getFloat(R.dimen.horizontal_spring_damping_ratio);
mSpring.setSpring(new SpringForce(mFinal)
- .setStiffness(SpringForce.STIFFNESS_LOW)
- .setDampingRatio(SpringForce.DAMPING_RATIO_LOW_BOUNCY));
+ .setStiffness(stiffness)
+ .setDampingRatio(damping));
mSpring.setStartVelocity(velocity);
mSpring.animateToFinalPosition(mFinal);
mSpring.addEndListener((animation, canceled, value, velocity1) -> {
+ mSpring = null;
finish();
mState = SPLINE;
- mSpring = null;
});
}
// Unused
diff --git a/src/com/android/launcher3/util/PackageManagerHelper.java b/src/com/android/launcher3/util/PackageManagerHelper.java
index 6c18747..ddde6d3 100644
--- a/src/com/android/launcher3/util/PackageManagerHelper.java
+++ b/src/com/android/launcher3/util/PackageManagerHelper.java
@@ -47,14 +47,14 @@
import androidx.annotation.NonNull;
-import com.android.launcher3.AppInfo;
-import com.android.launcher3.ItemInfo;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.PendingAddItemInfo;
-import com.android.launcher3.PromiseAppInfo;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
-import com.android.launcher3.WorkspaceItemInfo;
+import com.android.launcher3.model.data.AppInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
+import com.android.launcher3.model.data.PromiseAppInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import java.net.URISyntaxException;
import java.util.List;
diff --git a/src/com/android/launcher3/util/PackageUserKey.java b/src/com/android/launcher3/util/PackageUserKey.java
index f243ca6..3a3b5a2 100644
--- a/src/com/android/launcher3/util/PackageUserKey.java
+++ b/src/com/android/launcher3/util/PackageUserKey.java
@@ -3,9 +3,10 @@
import android.os.UserHandle;
import android.service.notification.StatusBarNotification;
+import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
-import com.android.launcher3.ItemInfo;
+import com.android.launcher3.model.data.ItemInfo;
import java.util.Arrays;
@@ -60,4 +61,10 @@
PackageUserKey otherKey = (PackageUserKey) obj;
return mPackageName.equals(otherKey.mPackageName) && mUser.equals(otherKey.mUser);
}
+
+ @NonNull
+ @Override
+ public String toString() {
+ return mPackageName + "#" + mUser;
+ }
}
diff --git a/src/com/android/launcher3/util/PendingAnimation.java b/src/com/android/launcher3/util/PendingAnimation.java
deleted file mode 100644
index 617a38b..0000000
--- a/src/com/android/launcher3/util/PendingAnimation.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * 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.launcher3.util;
-
-import android.animation.AnimatorSet;
-import android.annotation.TargetApi;
-import android.os.Build;
-
-import java.util.ArrayList;
-import java.util.function.Consumer;
-
-/**
- * Utility class to keep track of a running animation.
- *
- * This class allows attaching end callbacks to an animation is intended to be used with
- * {@link com.android.launcher3.anim.AnimatorPlaybackController}, since in that case
- * AnimationListeners are not properly dispatched.
- */
-@TargetApi(Build.VERSION_CODES.O)
-public class PendingAnimation {
-
- private final ArrayList<Consumer<OnEndListener>> mEndListeners = new ArrayList<>();
-
- public final AnimatorSet anim;
-
- public PendingAnimation(AnimatorSet anim) {
- this.anim = anim;
- }
-
- public void finish(boolean isSuccess, int logAction) {
- for (Consumer<OnEndListener> listeners : mEndListeners) {
- listeners.accept(new OnEndListener(isSuccess, logAction));
- }
- mEndListeners.clear();
- }
-
- public void addEndListener(Consumer<OnEndListener> listener) {
- mEndListeners.add(listener);
- }
-
- public static class OnEndListener {
- public boolean isSuccess;
- public int logAction;
-
- public OnEndListener(boolean isSuccess, int logAction) {
- this.isSuccess = isSuccess;
- this.logAction = logAction;
- }
- }
-}
diff --git a/src/com/android/launcher3/util/PendingRequestArgs.java b/src/com/android/launcher3/util/PendingRequestArgs.java
index b8bcfed..9b8c6a6 100644
--- a/src/com/android/launcher3/util/PendingRequestArgs.java
+++ b/src/com/android/launcher3/util/PendingRequestArgs.java
@@ -20,7 +20,7 @@
import android.os.Parcel;
import android.os.Parcelable;
-import com.android.launcher3.ItemInfo;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.widget.WidgetAddFlowHandler;
/**
diff --git a/src/com/android/launcher3/util/Preconditions.java b/src/com/android/launcher3/util/Preconditions.java
index ed66422..63d56e4 100644
--- a/src/com/android/launcher3/util/Preconditions.java
+++ b/src/com/android/launcher3/util/Preconditions.java
@@ -28,25 +28,25 @@
public class Preconditions {
public static void assertNotNull(Object o) {
- if (FeatureFlags.IS_DOGFOOD_BUILD && o == null) {
+ if (FeatureFlags.IS_STUDIO_BUILD && o == null) {
throw new IllegalStateException();
}
}
public static void assertWorkerThread() {
- if (FeatureFlags.IS_DOGFOOD_BUILD && !isSameLooper(MODEL_EXECUTOR.getLooper())) {
+ if (FeatureFlags.IS_STUDIO_BUILD && !isSameLooper(MODEL_EXECUTOR.getLooper())) {
throw new IllegalStateException();
}
}
public static void assertUIThread() {
- if (FeatureFlags.IS_DOGFOOD_BUILD && !isSameLooper(Looper.getMainLooper())) {
+ if (FeatureFlags.IS_STUDIO_BUILD && !isSameLooper(Looper.getMainLooper())) {
throw new IllegalStateException();
}
}
public static void assertNonUiThread() {
- if (FeatureFlags.IS_DOGFOOD_BUILD && isSameLooper(Looper.getMainLooper())) {
+ if (FeatureFlags.IS_STUDIO_BUILD && isSameLooper(Looper.getMainLooper())) {
throw new IllegalStateException();
}
}
diff --git a/src/com/android/launcher3/util/ShortcutUtil.java b/src/com/android/launcher3/util/ShortcutUtil.java
index 49c97da..1ec0690 100644
--- a/src/com/android/launcher3/util/ShortcutUtil.java
+++ b/src/com/android/launcher3/util/ShortcutUtil.java
@@ -15,11 +15,11 @@
*/
package com.android.launcher3.util;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.Utilities;
-import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.model.WidgetsModel;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.shortcuts.ShortcutKey;
public class ShortcutUtil {
diff --git a/src/com/android/launcher3/util/VibratorWrapper.java b/src/com/android/launcher3/util/VibratorWrapper.java
index 04741a1..b0defd4 100644
--- a/src/com/android/launcher3/util/VibratorWrapper.java
+++ b/src/com/android/launcher3/util/VibratorWrapper.java
@@ -39,7 +39,7 @@
public static final MainThreadInitializedObject<VibratorWrapper> INSTANCE =
new MainThreadInitializedObject<>(VibratorWrapper::new);
- private static final VibrationEffect EFFECT_CLICK =
+ public static final VibrationEffect EFFECT_CLICK =
createPredefined(VibrationEffect.EFFECT_CLICK);
/**
diff --git a/src/com/android/launcher3/views/AbstractSlideInView.java b/src/com/android/launcher3/views/AbstractSlideInView.java
index 9334c46..11c1029 100644
--- a/src/com/android/launcher3/views/AbstractSlideInView.java
+++ b/src/com/android/launcher3/views/AbstractSlideInView.java
@@ -15,6 +15,8 @@
*/
package com.android.launcher3.views;
+import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
+
import static com.android.launcher3.anim.Interpolators.scrollInterpolatorForVelocity;
import android.animation.Animator;
@@ -62,6 +64,7 @@
protected final ObjectAnimator mOpenCloseAnimator;
protected View mContent;
+ private final View mColorScrim;
protected Interpolator mScrollInterpolator;
// range [0, 1], 0=> completely open, 1=> completely closed
@@ -85,11 +88,30 @@
announceAccessibilityChanges();
}
});
+ int scrimColor = getScrimColor(mLauncher);
+ mColorScrim = scrimColor != -1 ? createColorScrim(mLauncher, scrimColor) : null;
+ }
+
+ protected void attachToContainer() {
+ if (mColorScrim != null) {
+ getPopupContainer().addView(mColorScrim);
+ }
+ getPopupContainer().addView(this);
+ }
+
+ /**
+ * Returns a scrim color for a sliding view. if returned value is -1, no scrim is added.
+ */
+ protected int getScrimColor(Context context) {
+ return -1;
}
protected void setTranslationShift(float translationShift) {
mTranslationShift = translationShift;
mContent.setTranslationY(mTranslationShift * mContent.getHeight());
+ if (mColorScrim != null) {
+ mColorScrim.setAlpha(1 - mTranslationShift);
+ }
}
@Override
@@ -127,7 +149,7 @@
/* SingleAxisSwipeDetector.Listener */
@Override
- public void onDragStart(boolean start) { }
+ public void onDragStart(boolean start, float startDisplacement) { }
@Override
public boolean onDrag(float displacement) {
@@ -185,9 +207,25 @@
protected void onCloseComplete() {
mIsOpen = false;
getPopupContainer().removeView(this);
+ if (mColorScrim != null) {
+ getPopupContainer().removeView(mColorScrim);
+ }
}
protected BaseDragLayer getPopupContainer() {
return mLauncher.getDragLayer();
}
+
+
+ protected static View createColorScrim(Context context, int bgColor) {
+ View view = new View(context);
+ view.forceHasOverlappingRendering(false);
+ view.setBackgroundColor(bgColor);
+
+ BaseDragLayer.LayoutParams lp = new BaseDragLayer.LayoutParams(MATCH_PARENT, MATCH_PARENT);
+ lp.ignoreInsets = true;
+ view.setLayoutParams(lp);
+
+ return view;
+ }
}
diff --git a/src/com/android/launcher3/views/ActivityContext.java b/src/com/android/launcher3/views/ActivityContext.java
index 0331a86..ae459e1 100644
--- a/src/com/android/launcher3/views/ActivityContext.java
+++ b/src/com/android/launcher3/views/ActivityContext.java
@@ -21,9 +21,8 @@
import android.view.View.AccessibilityDelegate;
import com.android.launcher3.DeviceProfile;
-import com.android.launcher3.ItemInfo;
-import com.android.launcher3.graphics.RotationMode;
import com.android.launcher3.dot.DotInfo;
+import com.android.launcher3.model.data.ItemInfo;
/**
* An interface to be used along with a context for various activities in Launcher. This allows a
@@ -57,19 +56,6 @@
DeviceProfile getDeviceProfile();
- /**
- * Device profile to be used by UI elements which are shown directly on top of the wallpaper
- * and whose presentation is tied to the wallpaper (and physical device) and not the activity
- * configuration.
- */
- default DeviceProfile getWallpaperDeviceProfile() {
- return getDeviceProfile();
- }
-
- default RotationMode getRotationMode() {
- return RotationMode.NORMAL;
- }
-
static ActivityContext lookupContext(Context context) {
if (context instanceof ActivityContext) {
return (ActivityContext) context;
diff --git a/src/com/android/launcher3/views/ArrowTipView.java b/src/com/android/launcher3/views/ArrowTipView.java
new file mode 100644
index 0000000..60470dc
--- /dev/null
+++ b/src/com/android/launcher3/views/ArrowTipView.java
@@ -0,0 +1,154 @@
+/*
+ * Copyright (C) 2008 The Android Open 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.launcher3.views;
+
+import android.content.Context;
+import android.graphics.CornerPathEffect;
+import android.graphics.Paint;
+import android.graphics.drawable.ShapeDrawable;
+import android.os.Handler;
+import android.util.TypedValue;
+import android.view.Gravity;
+import android.view.MotionEvent;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+import androidx.core.content.ContextCompat;
+
+import com.android.launcher3.AbstractFloatingView;
+import com.android.launcher3.Launcher;
+import com.android.launcher3.R;
+import com.android.launcher3.anim.Interpolators;
+import com.android.launcher3.dragndrop.DragLayer;
+import com.android.launcher3.graphics.TriangleShape;
+
+/**
+ * A base class for arrow tip view in launcher
+ */
+public class ArrowTipView extends AbstractFloatingView {
+
+ private static final long AUTO_CLOSE_TIMEOUT_MILLIS = 10 * 1000;
+ private static final long SHOW_DELAY_MS = 200;
+ private static final long SHOW_DURATION_MS = 300;
+ private static final long HIDE_DURATION_MS = 100;
+
+ protected final Launcher mLauncher;
+ private final Handler mHandler = new Handler();
+ private Runnable mOnClosed;
+
+ public ArrowTipView(Context context) {
+ super(context, null, 0);
+ mLauncher = Launcher.getLauncher(context);
+ init(context);
+ }
+
+ @Override
+ public boolean onControllerInterceptTouchEvent(MotionEvent ev) {
+ if (ev.getAction() == MotionEvent.ACTION_DOWN) {
+ close(true);
+ }
+ return false;
+ }
+
+ @Override
+ protected void handleClose(boolean animate) {
+ if (mIsOpen) {
+ if (animate) {
+ animate().alpha(0f)
+ .withLayer()
+ .setStartDelay(0)
+ .setDuration(HIDE_DURATION_MS)
+ .setInterpolator(Interpolators.ACCEL)
+ .withEndAction(() -> mLauncher.getDragLayer().removeView(this))
+ .start();
+ } else {
+ animate().cancel();
+ mLauncher.getDragLayer().removeView(this);
+ }
+ if (mOnClosed != null) mOnClosed.run();
+ mIsOpen = false;
+ }
+ }
+
+ @Override
+ public void logActionCommand(int command) {
+ }
+
+ @Override
+ protected boolean isOfType(int type) {
+ return (type & TYPE_ON_BOARD_POPUP) != 0;
+ }
+
+ private void init(Context context) {
+ inflate(context, R.layout.arrow_toast, this);
+ setOrientation(LinearLayout.VERTICAL);
+ View dismissButton = findViewById(R.id.dismiss);
+ dismissButton.setOnClickListener(view -> {
+ handleClose(true);
+ });
+
+ View arrowView = findViewById(R.id.arrow);
+ ViewGroup.LayoutParams arrowLp = arrowView.getLayoutParams();
+ ShapeDrawable arrowDrawable = new ShapeDrawable(TriangleShape.create(
+ arrowLp.width, arrowLp.height, false));
+ Paint arrowPaint = arrowDrawable.getPaint();
+ TypedValue typedValue = new TypedValue();
+ context.getTheme().resolveAttribute(android.R.attr.colorAccent, typedValue, true);
+ arrowPaint.setColor(ContextCompat.getColor(getContext(), typedValue.resourceId));
+ // The corner path effect won't be reflected in the shadow, but shouldn't be noticeable.
+ arrowPaint.setPathEffect(new CornerPathEffect(
+ context.getResources().getDimension(R.dimen.arrow_toast_corner_radius)));
+ arrowView.setBackground(arrowDrawable);
+
+ mIsOpen = true;
+
+ mHandler.postDelayed(() -> handleClose(true), AUTO_CLOSE_TIMEOUT_MILLIS);
+ }
+
+ /**
+ * Show Tip with specified string and Y location
+ */
+ public ArrowTipView show(String text, int top) {
+ ((TextView) findViewById(R.id.text)).setText(text);
+ mLauncher.getDragLayer().addView(this);
+
+ DragLayer.LayoutParams params = (DragLayer.LayoutParams) getLayoutParams();
+ params.gravity = Gravity.CENTER_HORIZONTAL;
+ params.leftMargin = mLauncher.getDeviceProfile().workspacePadding.left;
+ params.rightMargin = mLauncher.getDeviceProfile().workspacePadding.right;
+ post(() -> setY(top - getHeight()));
+ setAlpha(0);
+ animate()
+ .alpha(1f)
+ .withLayer()
+ .setStartDelay(SHOW_DELAY_MS)
+ .setDuration(SHOW_DURATION_MS)
+ .setInterpolator(Interpolators.DEACCEL)
+ .start();
+ return this;
+ }
+
+ /**
+ * Register a callback fired when toast is hidden
+ */
+ public ArrowTipView setOnClosedCallback(Runnable runnable) {
+ mOnClosed = runnable;
+ return this;
+ }
+}
diff --git a/src/com/android/launcher3/views/BaseDragLayer.java b/src/com/android/launcher3/views/BaseDragLayer.java
index cae2c3a..2fc3eaf 100644
--- a/src/com/android/launcher3/views/BaseDragLayer.java
+++ b/src/com/android/launcher3/views/BaseDragLayer.java
@@ -23,7 +23,11 @@
import static com.android.launcher3.util.DefaultDisplay.getSingleFrameMs;
import android.annotation.TargetApi;
+import android.app.WallpaperInfo;
+import android.app.WallpaperManager;
+import android.content.ComponentName;
import android.content.Context;
+import android.content.Intent;
import android.graphics.Insets;
import android.graphics.Rect;
import android.graphics.RectF;
@@ -39,12 +43,16 @@
import android.view.accessibility.AccessibilityEvent;
import android.widget.FrameLayout;
+import androidx.annotation.Nullable;
+
import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.InsettableFrameLayout;
+import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.testing.TestProtocol;
import com.android.launcher3.util.MultiValueAlpha;
import com.android.launcher3.util.MultiValueAlpha.AlphaProperty;
+import com.android.launcher3.util.SimpleBroadcastReceiver;
import com.android.launcher3.util.TouchController;
import java.io.PrintWriter;
@@ -100,6 +108,10 @@
protected final T mActivity;
private final MultiValueAlpha mMultiValueAlpha;
+ private final WallpaperManager mWallpaperManager;
+ private final SimpleBroadcastReceiver mWallpaperChangeReceiver =
+ new SimpleBroadcastReceiver(this::onWallpaperChanged);
+ private final String[] mWallpapersWithoutSysuiScrims;
// All the touch controllers for the view
protected TouchController[] mControllers;
@@ -110,13 +122,23 @@
private TouchCompleteListener mTouchCompleteListener;
+ protected boolean mAllowSysuiScrims = true;
+
public BaseDragLayer(Context context, AttributeSet attrs, int alphaChannelCount) {
super(context, attrs);
mActivity = (T) ActivityContext.lookupContext(context);
mMultiValueAlpha = new MultiValueAlpha(this, alphaChannelCount);
+ mWallpaperManager = context.getSystemService(WallpaperManager.class);
+ mWallpapersWithoutSysuiScrims = getResources().getStringArray(
+ R.array.live_wallpapers_remove_sysui_scrims);
}
/**
+ * Called to reinitialize touch controllers.
+ */
+ public abstract void recreateControllers();
+
+ /**
* Same as {@link #isEventOverView(View, MotionEvent, View)} where evView == this drag layer.
*/
public boolean isEventOverView(View view, MotionEvent ev) {
@@ -150,10 +172,20 @@
return findActiveController(ev);
}
+ private boolean isEventInLauncher(MotionEvent ev) {
+ final float x = ev.getX();
+ final float y = ev.getY();
+
+ return x >= mSystemGestureRegion.left && x < getWidth() - mSystemGestureRegion.right
+ && y >= mSystemGestureRegion.top && y < getHeight() - mSystemGestureRegion.bottom;
+ }
+
private TouchController findControllerToHandleTouch(MotionEvent ev) {
- AbstractFloatingView topView = AbstractFloatingView.getTopOpenView(mActivity);
- if (topView != null && topView.onControllerInterceptTouchEvent(ev)) {
- return topView;
+ if (isEventInLauncher(ev)) {
+ AbstractFloatingView topView = AbstractFloatingView.getTopOpenView(mActivity);
+ if (topView != null && topView.onControllerInterceptTouchEvent(ev)) {
+ return topView;
+ }
}
for (TouchController controller : mControllers) {
@@ -243,19 +275,17 @@
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
+ if (Utilities.IS_RUNNING_IN_TEST_HARNESS) {
+ Log.d(TestProtocol.NO_SCROLL_END_WIDGETS, "BaseDragLayer: " + ev);
+ }
switch (ev.getAction()) {
case ACTION_DOWN: {
- float x = ev.getX();
- float y = ev.getY();
mTouchDispatchState |= TOUCH_DISPATCHING_VIEW;
- if ((y < mSystemGestureRegion.top
- || x < mSystemGestureRegion.left
- || x > (getWidth() - mSystemGestureRegion.right)
- || y > (getHeight() - mSystemGestureRegion.bottom))) {
- mTouchDispatchState |= TOUCH_DISPATCHING_GESTURE;
- } else {
+ if (isEventInLauncher(ev)) {
mTouchDispatchState &= ~TOUCH_DISPATCHING_GESTURE;
+ } else {
+ mTouchDispatchState |= TOUCH_DISPATCHING_GESTURE;
}
break;
}
@@ -509,4 +539,46 @@
}
return super.dispatchApplyWindowInsets(insets);
}
+
+ @Override
+ protected void onAttachedToWindow() {
+ super.onAttachedToWindow();
+ mWallpaperChangeReceiver.register(mActivity, Intent.ACTION_WALLPAPER_CHANGED);
+ onWallpaperChanged(null);
+ }
+
+ @Override
+ protected void onDetachedFromWindow() {
+ super.onDetachedFromWindow();
+ mActivity.unregisterReceiver(mWallpaperChangeReceiver);
+ }
+
+ private void onWallpaperChanged(Intent unusedBroadcastIntent) {
+ WallpaperInfo newWallpaperInfo = mWallpaperManager.getWallpaperInfo();
+ boolean oldAllowSysuiScrims = mAllowSysuiScrims;
+ mAllowSysuiScrims = computeAllowSysuiScrims(newWallpaperInfo);
+ if (mAllowSysuiScrims != oldAllowSysuiScrims) {
+ // Reapply insets so scrim can be removed or re-added if necessary.
+ setInsets(mInsets);
+ }
+ }
+
+ /**
+ * Determines whether we can scrim the status bar and nav bar for the given wallpaper by
+ * checking against a list of live wallpapers that we don't show the scrims on.
+ */
+ private boolean computeAllowSysuiScrims(@Nullable WallpaperInfo newWallpaperInfo) {
+ if (newWallpaperInfo == null) {
+ // New wallpaper is static, not live. Thus, blacklist isn't applicable.
+ return true;
+ }
+ ComponentName newWallpaper = newWallpaperInfo.getComponent();
+ for (String wallpaperWithoutScrim : mWallpapersWithoutSysuiScrims) {
+ if (newWallpaper.equals(ComponentName.unflattenFromString(wallpaperWithoutScrim))) {
+ // New wallpaper is blacklisted from showing a scrim.
+ return false;
+ }
+ }
+ return true;
+ }
}
diff --git a/src/com/android/launcher3/views/ClipIconView.java b/src/com/android/launcher3/views/ClipIconView.java
new file mode 100644
index 0000000..478141a
--- /dev/null
+++ b/src/com/android/launcher3/views/ClipIconView.java
@@ -0,0 +1,349 @@
+/*
+ * 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.launcher3.views;
+
+import static com.android.launcher3.Utilities.mapToRange;
+import static com.android.launcher3.anim.Interpolators.LINEAR;
+import static com.android.launcher3.views.FloatingIconView.SHAPE_PROGRESS_DURATION;
+
+import android.animation.Animator;
+import android.animation.AnimatorListenerAdapter;
+import android.animation.ValueAnimator;
+import android.annotation.TargetApi;
+import android.content.Context;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.Outline;
+import android.graphics.Path;
+import android.graphics.Rect;
+import android.graphics.RectF;
+import android.graphics.drawable.AdaptiveIconDrawable;
+import android.graphics.drawable.ColorDrawable;
+import android.graphics.drawable.Drawable;
+import android.os.Build;
+import android.util.AttributeSet;
+import android.view.View;
+import android.view.ViewOutlineProvider;
+
+import androidx.annotation.Nullable;
+import androidx.dynamicanimation.animation.FloatPropertyCompat;
+import androidx.dynamicanimation.animation.SpringAnimation;
+import androidx.dynamicanimation.animation.SpringForce;
+
+import com.android.launcher3.DeviceProfile;
+import com.android.launcher3.InsettableFrameLayout.LayoutParams;
+import com.android.launcher3.Launcher;
+import com.android.launcher3.R;
+import com.android.launcher3.Utilities;
+import com.android.launcher3.dragndrop.FolderAdaptiveIcon;
+import com.android.launcher3.graphics.IconShape;
+
+/**
+ * A view used to draw both layers of an {@link AdaptiveIconDrawable}.
+ * Supports springing just the foreground layer.
+ * Supports clipping the icon to/from its icon shape.
+ */
+@TargetApi(Build.VERSION_CODES.Q)
+public class ClipIconView extends View implements ClipPathView {
+
+ private static final Rect sTmpRect = new Rect();
+
+ // We spring the foreground drawable relative to the icon's movement in the DragLayer.
+ // We then use these two factor values to scale the movement of the fg within this view.
+ private static final int FG_TRANS_X_FACTOR = 60;
+ private static final int FG_TRANS_Y_FACTOR = 75;
+
+ private static final FloatPropertyCompat<ClipIconView> mFgTransYProperty =
+ new FloatPropertyCompat<ClipIconView>("ClipIconViewFgTransY") {
+ @Override
+ public float getValue(ClipIconView view) {
+ return view.mFgTransY;
+ }
+
+ @Override
+ public void setValue(ClipIconView view, float transY) {
+ view.mFgTransY = transY;
+ view.invalidate();
+ }
+ };
+
+ private static final FloatPropertyCompat<ClipIconView> mFgTransXProperty =
+ new FloatPropertyCompat<ClipIconView>("ClipIconViewFgTransX") {
+ @Override
+ public float getValue(ClipIconView view) {
+ return view.mFgTransX;
+ }
+
+ @Override
+ public void setValue(ClipIconView view, float transX) {
+ view.mFgTransX = transX;
+ view.invalidate();
+ }
+ };
+
+ private final Launcher mLauncher;
+ private final int mBlurSizeOutline;
+ private final boolean mIsRtl;
+
+ private @Nullable Drawable mForeground;
+ private @Nullable Drawable mBackground;
+
+ private boolean mIsVerticalBarLayout = false;
+ private boolean mIsAdaptiveIcon = false;
+
+ private ValueAnimator mRevealAnimator;
+
+ private final Rect mStartRevealRect = new Rect();
+ private final Rect mEndRevealRect = new Rect();
+ private Path mClipPath;
+ private float mTaskCornerRadius;
+
+ private final Rect mOutline = new Rect();
+ private final Rect mFinalDrawableBounds = new Rect();
+
+ private final SpringAnimation mFgSpringY;
+ private float mFgTransY;
+ private final SpringAnimation mFgSpringX;
+ private float mFgTransX;
+
+ public ClipIconView(Context context) {
+ this(context, null);
+ }
+
+ public ClipIconView(Context context, AttributeSet attrs) {
+ this(context, attrs, 0);
+ }
+
+ public ClipIconView(Context context, AttributeSet attrs, int defStyleAttr) {
+ super(context, attrs, defStyleAttr);
+ mLauncher = Launcher.getLauncher(context);
+ mBlurSizeOutline = getResources().getDimensionPixelSize(
+ R.dimen.blur_size_medium_outline);
+ mIsRtl = Utilities.isRtl(getResources());
+
+ mFgSpringX = new SpringAnimation(this, mFgTransXProperty)
+ .setSpring(new SpringForce()
+ .setDampingRatio(SpringForce.DAMPING_RATIO_LOW_BOUNCY)
+ .setStiffness(SpringForce.STIFFNESS_LOW));
+ mFgSpringY = new SpringAnimation(this, mFgTransYProperty)
+ .setSpring(new SpringForce()
+ .setDampingRatio(SpringForce.DAMPING_RATIO_LOW_BOUNCY)
+ .setStiffness(SpringForce.STIFFNESS_LOW));
+ }
+
+ void update(RectF rect, float progress, float shapeProgressStart, float cornerRadius,
+ boolean isOpening, float scale, float minSize, LayoutParams parentLp) {
+ DeviceProfile dp = mLauncher.getDeviceProfile();
+ float dX = mIsRtl
+ ? rect.left - (dp.widthPx - parentLp.getMarginStart() - parentLp.width)
+ : rect.left - parentLp.getMarginStart();
+ float dY = rect.top - parentLp.topMargin;
+
+ // shapeRevealProgress = 1 when progress = shapeProgressStart + SHAPE_PROGRESS_DURATION
+ float toMax = isOpening ? 1 / SHAPE_PROGRESS_DURATION : 1f;
+ float shapeRevealProgress = Utilities.boundToRange(mapToRange(
+ Math.max(shapeProgressStart, progress), shapeProgressStart, 1f, 0, toMax,
+ LINEAR), 0, 1);
+
+ if (mIsVerticalBarLayout) {
+ mOutline.right = (int) (rect.width() / scale);
+ } else {
+ mOutline.bottom = (int) (rect.height() / scale);
+ }
+
+ mTaskCornerRadius = cornerRadius / scale;
+ if (mIsAdaptiveIcon) {
+ if (!isOpening && progress >= shapeProgressStart) {
+ if (mRevealAnimator == null) {
+ mRevealAnimator = (ValueAnimator) IconShape.getShape().createRevealAnimator(
+ this, mStartRevealRect, mOutline, mTaskCornerRadius, !isOpening);
+ mRevealAnimator.addListener(new AnimatorListenerAdapter() {
+ @Override
+ public void onAnimationEnd(Animator animation) {
+ mRevealAnimator = null;
+ }
+ });
+ mRevealAnimator.start();
+ // We pause here so we can set the current fraction ourselves.
+ mRevealAnimator.pause();
+ }
+ mRevealAnimator.setCurrentFraction(shapeRevealProgress);
+ }
+
+ float drawableScale = (mIsVerticalBarLayout ? mOutline.width() : mOutline.height())
+ / minSize;
+ setBackgroundDrawableBounds(drawableScale);
+ if (isOpening) {
+ // Center align foreground
+ int height = mFinalDrawableBounds.height();
+ int width = mFinalDrawableBounds.width();
+ int diffY = mIsVerticalBarLayout ? 0
+ : (int) (((height * drawableScale) - height) / 2);
+ int diffX = mIsVerticalBarLayout ? (int) (((width * drawableScale) - width) / 2)
+ : 0;
+ sTmpRect.set(mFinalDrawableBounds);
+ sTmpRect.offset(diffX, diffY);
+ mForeground.setBounds(sTmpRect);
+ } else {
+ // Spring the foreground relative to the icon's movement within the DragLayer.
+ int diffX = (int) (dX / dp.availableWidthPx * FG_TRANS_X_FACTOR);
+ int diffY = (int) (dY / dp.availableHeightPx * FG_TRANS_Y_FACTOR);
+
+ mFgSpringX.animateToFinalPosition(diffX);
+ mFgSpringY.animateToFinalPosition(diffY);
+ }
+ }
+ invalidate();
+ invalidateOutline();
+ }
+
+ private void setBackgroundDrawableBounds(float scale) {
+ sTmpRect.set(mFinalDrawableBounds);
+ Utilities.scaleRectAboutCenter(sTmpRect, scale);
+ // Since the drawable is at the top of the view, we need to offset to keep it centered.
+ if (mIsVerticalBarLayout) {
+ sTmpRect.offsetTo((int) (mFinalDrawableBounds.left * scale), sTmpRect.top);
+ } else {
+ sTmpRect.offsetTo(sTmpRect.left, (int) (mFinalDrawableBounds.top * scale));
+ }
+ mBackground.setBounds(sTmpRect);
+ }
+
+ protected void endReveal() {
+ if (mRevealAnimator != null) {
+ mRevealAnimator.end();
+ }
+ }
+
+ void setIcon(@Nullable Drawable drawable, int iconOffset, LayoutParams lp, boolean isOpening) {
+ mIsAdaptiveIcon = drawable instanceof AdaptiveIconDrawable;
+ if (mIsAdaptiveIcon) {
+ boolean isFolderIcon = drawable instanceof FolderAdaptiveIcon;
+
+ AdaptiveIconDrawable adaptiveIcon = (AdaptiveIconDrawable) drawable;
+ Drawable background = adaptiveIcon.getBackground();
+ if (background == null) {
+ background = new ColorDrawable(Color.TRANSPARENT);
+ }
+ mBackground = background;
+ Drawable foreground = adaptiveIcon.getForeground();
+ if (foreground == null) {
+ foreground = new ColorDrawable(Color.TRANSPARENT);
+ }
+ mForeground = foreground;
+
+ final int originalHeight = lp.height;
+ final int originalWidth = lp.width;
+
+ int blurMargin = mBlurSizeOutline / 2;
+ mFinalDrawableBounds.set(0, 0, originalWidth, originalHeight);
+
+ if (!isFolderIcon) {
+ mFinalDrawableBounds.inset(iconOffset - blurMargin, iconOffset - blurMargin);
+ }
+ mForeground.setBounds(mFinalDrawableBounds);
+ mBackground.setBounds(mFinalDrawableBounds);
+
+ mStartRevealRect.set(0, 0, originalWidth, originalHeight);
+
+ if (!isFolderIcon) {
+ Utilities.scaleRectAboutCenter(mStartRevealRect, IconShape.getNormalizationScale());
+ }
+
+ float aspectRatio = mLauncher.getDeviceProfile().aspectRatio;
+ if (mIsVerticalBarLayout) {
+ lp.width = (int) Math.max(lp.width, lp.height * aspectRatio);
+ } else {
+ lp.height = (int) Math.max(lp.height, lp.width * aspectRatio);
+ }
+
+ int left = mIsRtl
+ ? mLauncher.getDeviceProfile().widthPx - lp.getMarginStart() - lp.width
+ : lp.leftMargin;
+ layout(left, lp.topMargin, left + lp.width, lp.topMargin + lp.height);
+
+ float scale = Math.max((float) lp.height / originalHeight,
+ (float) lp.width / originalWidth);
+ float bgDrawableStartScale;
+ if (isOpening) {
+ bgDrawableStartScale = 1f;
+ mOutline.set(0, 0, originalWidth, originalHeight);
+ } else {
+ bgDrawableStartScale = scale;
+ mOutline.set(0, 0, lp.width, lp.height);
+ }
+ setBackgroundDrawableBounds(bgDrawableStartScale);
+ mEndRevealRect.set(0, 0, lp.width, lp.height);
+ setOutlineProvider(new ViewOutlineProvider() {
+ @Override
+ public void getOutline(View view, Outline outline) {
+ outline.setRoundRect(mOutline, mTaskCornerRadius);
+ }
+ });
+ setClipToOutline(true);
+ } else {
+ setBackground(drawable);
+ setClipToOutline(false);
+ }
+
+ invalidate();
+ invalidateOutline();
+ }
+
+ @Override
+ public void setClipPath(Path clipPath) {
+ mClipPath = clipPath;
+ invalidate();
+ }
+
+ @Override
+ public void draw(Canvas canvas) {
+ int count = canvas.save();
+ if (mClipPath != null) {
+ canvas.clipPath(mClipPath);
+ }
+ super.draw(canvas);
+ if (mBackground != null) {
+ mBackground.draw(canvas);
+ }
+ if (mForeground != null) {
+ int count2 = canvas.save();
+ canvas.translate(mFgTransX, mFgTransY);
+ mForeground.draw(canvas);
+ canvas.restoreToCount(count2);
+ }
+ canvas.restoreToCount(count);
+ }
+
+ void recycle() {
+ setBackground(null);
+ mIsAdaptiveIcon = false;
+ mForeground = null;
+ mBackground = null;
+ mClipPath = null;
+ mFinalDrawableBounds.setEmpty();
+ if (mRevealAnimator != null) {
+ mRevealAnimator.cancel();
+ }
+ mRevealAnimator = null;
+ mTaskCornerRadius = 0;
+ mOutline.setEmpty();
+ mFgTransY = 0;
+ mFgSpringX.cancel();
+ mFgTransX = 0;
+ mFgSpringY.cancel();
+ }
+}
diff --git a/src/com/android/launcher3/views/FloatingIconView.java b/src/com/android/launcher3/views/FloatingIconView.java
index fa625ed..e114cf8 100644
--- a/src/com/android/launcher3/views/FloatingIconView.java
+++ b/src/com/android/launcher3/views/FloatingIconView.java
@@ -18,8 +18,6 @@
import static com.android.launcher3.LauncherAnimUtils.DRAWABLE_ALPHA;
import static com.android.launcher3.Utilities.getBadge;
import static com.android.launcher3.Utilities.getFullDrawable;
-import static com.android.launcher3.Utilities.mapToRange;
-import static com.android.launcher3.anim.Interpolators.LINEAR;
import static com.android.launcher3.config.FeatureFlags.ADAPTIVE_ICON_WINDOW_ANIM;
import static com.android.launcher3.states.RotationHelper.REQUEST_LOCK;
import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
@@ -28,17 +26,12 @@
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
-import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.Outline;
-import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.AdaptiveIconDrawable;
-import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.CancellationSignal;
@@ -46,29 +39,25 @@
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
-import android.view.ViewOutlineProvider;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
+import android.widget.FrameLayout;
import android.widget.ImageView;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import androidx.annotation.WorkerThread;
-import androidx.dynamicanimation.animation.FloatPropertyCompat;
-import androidx.dynamicanimation.animation.SpringAnimation;
-import androidx.dynamicanimation.animation.SpringForce;
import com.android.launcher3.BubbleTextView;
-import com.android.launcher3.InsettableFrameLayout.LayoutParams;
-import com.android.launcher3.ItemInfo;
+import com.android.launcher3.DeviceProfile;
+import com.android.launcher3.InsettableFrameLayout;
import com.android.launcher3.Launcher;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.dragndrop.DragLayer;
import com.android.launcher3.dragndrop.FolderAdaptiveIcon;
import com.android.launcher3.folder.FolderIcon;
-import com.android.launcher3.graphics.IconShape;
-import com.android.launcher3.graphics.ShiftedBitmapDrawable;
import com.android.launcher3.icons.LauncherIcons;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.popup.SystemShortcut;
import com.android.launcher3.shortcuts.DeepShortcutView;
@@ -76,8 +65,8 @@
* A view that is created to look like another view with the purpose of creating fluid animations.
*/
@TargetApi(Build.VERSION_CODES.Q)
-public class FloatingIconView extends View implements
- Animator.AnimatorListener, ClipPathView, OnGlobalLayoutListener {
+public class FloatingIconView extends FrameLayout implements
+ Animator.AnimatorListener, OnGlobalLayoutListener {
private static final String TAG = FloatingIconView.class.getSimpleName();
@@ -86,81 +75,32 @@
public static final float SHAPE_PROGRESS_DURATION = 0.10f;
private static final int FADE_DURATION_MS = 200;
- private static final Rect sTmpRect = new Rect();
private static final RectF sTmpRectF = new RectF();
private static final Object[] sTmpObjArray = new Object[1];
- // We spring the foreground drawable relative to the icon's movement in the DragLayer.
- // We then use these two factor values to scale the movement of the fg within this view.
- private static final int FG_TRANS_X_FACTOR = 60;
- private static final int FG_TRANS_Y_FACTOR = 75;
-
- private static final FloatPropertyCompat<FloatingIconView> mFgTransYProperty
- = new FloatPropertyCompat<FloatingIconView>("FloatingViewFgTransY") {
- @Override
- public float getValue(FloatingIconView view) {
- return view.mFgTransY;
- }
-
- @Override
- public void setValue(FloatingIconView view, float transY) {
- view.mFgTransY = transY;
- view.invalidate();
- }
- };
-
- private static final FloatPropertyCompat<FloatingIconView> mFgTransXProperty
- = new FloatPropertyCompat<FloatingIconView>("FloatingViewFgTransX") {
- @Override
- public float getValue(FloatingIconView view) {
- return view.mFgTransX;
- }
-
- @Override
- public void setValue(FloatingIconView view, float transX) {
- view.mFgTransX = transX;
- view.invalidate();
- }
- };
-
private Runnable mEndRunnable;
private CancellationSignal mLoadIconSignal;
private final Launcher mLauncher;
- private final int mBlurSizeOutline;
private final boolean mIsRtl;
private boolean mIsVerticalBarLayout = false;
- private boolean mIsAdaptiveIcon = false;
private boolean mIsOpening;
private IconLoadResult mIconLoadResult;
+ private ClipIconView mClipIconView;
private @Nullable Drawable mBadge;
- private @Nullable Drawable mForeground;
- private @Nullable Drawable mBackground;
- private float mRotation;
- private ValueAnimator mRevealAnimator;
- private final Rect mStartRevealRect = new Rect();
- private final Rect mEndRevealRect = new Rect();
- private Path mClipPath;
- private float mTaskCornerRadius;
private View mOriginalIcon;
private RectF mPositionOut;
private Runnable mOnTargetChangeRunnable;
- private final Rect mOutline = new Rect();
private final Rect mFinalDrawableBounds = new Rect();
private AnimatorSet mFadeAnimatorSet;
private ListenerView mListenerView;
- private final SpringAnimation mFgSpringY;
- private float mFgTransY;
- private final SpringAnimation mFgSpringX;
- private float mFgTransX;
-
public FloatingIconView(Context context) {
this(context, null);
}
@@ -172,19 +112,11 @@
public FloatingIconView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mLauncher = Launcher.getLauncher(context);
- mBlurSizeOutline = getResources().getDimensionPixelSize(
- R.dimen.blur_size_medium_outline);
mIsRtl = Utilities.isRtl(getResources());
mListenerView = new ListenerView(context, attrs);
-
- mFgSpringX = new SpringAnimation(this, mFgTransXProperty)
- .setSpring(new SpringForce()
- .setDampingRatio(SpringForce.DAMPING_RATIO_LOW_BOUNCY)
- .setStiffness(SpringForce.STIFFNESS_LOW));
- mFgSpringY = new SpringAnimation(this, mFgTransYProperty)
- .setSpring(new SpringForce()
- .setDampingRatio(SpringForce.DAMPING_RATIO_LOW_BOUNCY)
- .setStiffness(SpringForce.STIFFNESS_LOW));
+ mClipIconView = new ClipIconView(context, attrs);
+ addView(mClipIconView);
+ setWillNotDraw(false);
}
@Override
@@ -213,10 +145,12 @@
float cornerRadius, boolean isOpening) {
setAlpha(alpha);
- LayoutParams lp = (LayoutParams) getLayoutParams();
+ InsettableFrameLayout.LayoutParams lp =
+ (InsettableFrameLayout.LayoutParams) getLayoutParams();
+
+ DeviceProfile dp = mLauncher.getDeviceProfile();
float dX = mIsRtl
- ? rect.left
- - (mLauncher.getDeviceProfile().widthPx - lp.getMarginStart() - lp.width)
+ ? rect.left - (dp.widthPx - lp.getMarginStart() - lp.width)
: rect.left - lp.getMarginStart();
float dY = rect.top - lp.topMargin;
setTranslationX(dX);
@@ -227,69 +161,15 @@
float scaleY = rect.height() / minSize;
float scale = Math.max(1f, Math.min(scaleX, scaleY));
+ mClipIconView.update(rect, progress, shapeProgressStart, cornerRadius, isOpening, scale,
+ minSize, lp);
+
setPivotX(0);
setPivotY(0);
setScaleX(scale);
setScaleY(scale);
- // shapeRevealProgress = 1 when progress = shapeProgressStart + SHAPE_PROGRESS_DURATION
- float toMax = isOpening ? 1 / SHAPE_PROGRESS_DURATION : 1f;
- float shapeRevealProgress = Utilities.boundToRange(mapToRange(
- Math.max(shapeProgressStart, progress), shapeProgressStart, 1f, 0, toMax,
- LINEAR), 0, 1);
-
- if (mIsVerticalBarLayout) {
- mOutline.right = (int) (rect.width() / scale);
- } else {
- mOutline.bottom = (int) (rect.height() / scale);
- }
-
- mTaskCornerRadius = cornerRadius / scale;
- if (mIsAdaptiveIcon) {
- if (!isOpening && progress >= shapeProgressStart) {
- if (mRevealAnimator == null) {
- mRevealAnimator = (ValueAnimator) IconShape.getShape().createRevealAnimator(
- this, mStartRevealRect, mOutline, mTaskCornerRadius, !isOpening);
- mRevealAnimator.addListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationEnd(Animator animation) {
- mRevealAnimator = null;
- }
- });
- mRevealAnimator.start();
- // We pause here so we can set the current fraction ourselves.
- mRevealAnimator.pause();
- }
- mRevealAnimator.setCurrentFraction(shapeRevealProgress);
- }
-
- float drawableScale = (mIsVerticalBarLayout ? mOutline.width() : mOutline.height())
- / minSize;
- setBackgroundDrawableBounds(drawableScale);
- if (isOpening) {
- // Center align foreground
- int height = mFinalDrawableBounds.height();
- int width = mFinalDrawableBounds.width();
- int diffY = mIsVerticalBarLayout ? 0
- : (int) (((height * drawableScale) - height) / 2);
- int diffX = mIsVerticalBarLayout ? (int) (((width * drawableScale) - width) / 2)
- : 0;
- sTmpRect.set(mFinalDrawableBounds);
- sTmpRect.offset(diffX, diffY);
- mForeground.setBounds(sTmpRect);
- } else {
- // Spring the foreground relative to the icon's movement within the DragLayer.
- int diffX = (int) (dX / mLauncher.getDeviceProfile().availableWidthPx
- * FG_TRANS_X_FACTOR);
- int diffY = (int) (dY / mLauncher.getDeviceProfile().availableHeightPx
- * FG_TRANS_Y_FACTOR);
-
- mFgSpringX.animateToFinalPosition(diffX);
- mFgSpringY.animateToFinalPosition(diffY);
- }
- }
invalidate();
- invalidateOutline();
}
@Override
@@ -301,9 +181,7 @@
mEndRunnable.run();
} else {
// End runnable also ends the reveal animator, so we manually handle it here.
- if (mRevealAnimator != null) {
- mRevealAnimator.end();
- }
+ mClipIconView.endReveal();
}
}
@@ -314,24 +192,25 @@
* @param positionOut Rect that will hold the size and position of v.
*/
private void matchPositionOf(Launcher launcher, View v, boolean isOpening, RectF positionOut) {
- float rotation = getLocationBoundsForView(launcher, v, isOpening, positionOut);
- final LayoutParams lp = new LayoutParams(
+ getLocationBoundsForView(launcher, v, isOpening, positionOut);
+ final InsettableFrameLayout.LayoutParams lp = new InsettableFrameLayout.LayoutParams(
Math.round(positionOut.width()),
Math.round(positionOut.height()));
- updatePosition(rotation, positionOut, lp);
+ updatePosition(positionOut, lp);
setLayoutParams(lp);
+
+ mClipIconView.setLayoutParams(new FrameLayout.LayoutParams(lp.width, lp.height));
}
- private void updatePosition(float rotation, RectF position, LayoutParams lp) {
- mRotation = rotation;
- mPositionOut.set(position);
+ private void updatePosition(RectF pos, InsettableFrameLayout.LayoutParams lp) {
+ mPositionOut.set(pos);
lp.ignoreInsets = true;
// Position the floating view exactly on top of the original
- lp.topMargin = Math.round(position.top);
+ lp.topMargin = Math.round(pos.top);
if (mIsRtl) {
- lp.setMarginStart(Math.round(mLauncher.getDeviceProfile().widthPx - position.right));
+ lp.setMarginStart(Math.round(mLauncher.getDeviceProfile().widthPx - pos.right));
} else {
- lp.setMarginStart(Math.round(position.left));
+ lp.setMarginStart(Math.round(pos.left));
}
// Set the properties here already to make sure they are available when running the first
// animation frame.
@@ -346,7 +225,7 @@
* - For DeepShortcutView, we return the bounds of the icon view.
* - For BubbleTextView, we return the icon bounds.
*/
- private static float getLocationBoundsForView(Launcher launcher, View v, boolean isOpening,
+ private static void getLocationBoundsForView(Launcher launcher, View v, boolean isOpening,
RectF outRect) {
boolean ignoreTransform = !isOpening;
if (v instanceof DeepShortcutView) {
@@ -357,7 +236,7 @@
ignoreTransform = false;
}
if (v == null) {
- return 0;
+ return;
}
Rect iconBounds = new Rect();
@@ -371,15 +250,13 @@
float[] points = new float[] {iconBounds.left, iconBounds.top, iconBounds.right,
iconBounds.bottom};
- float[] rotation = new float[] {0};
Utilities.getDescendantCoordRelativeToAncestor(v, launcher.getDragLayer(), points,
- false, ignoreTransform, rotation);
+ false, ignoreTransform);
outRect.set(
Math.min(points[0], points[2]),
Math.min(points[1], points[3]),
Math.max(points[0], points[2]),
Math.max(points[1], points[3]));
- return rotation[0];
}
/**
@@ -412,9 +289,8 @@
drawable = originalView.getBackground();
}
} else {
- boolean isFolderIcon = originalView instanceof FolderIcon;
- int width = isFolderIcon ? originalView.getWidth() : (int) pos.width();
- int height = isFolderIcon ? originalView.getHeight() : (int) pos.height();
+ int width = (int) pos.width();
+ int height = (int) pos.height();
if (supportsAdaptiveIcons) {
drawable = getFullDrawable(l, info, width, height, sTmpObjArray);
if (drawable instanceof AdaptiveIconDrawable) {
@@ -451,110 +327,42 @@
/**
* Sets the drawables of the {@param originalView} onto this view.
*
- * @param originalView The View that the FloatingIconView will replace.
* @param drawable The drawable of the original view.
* @param badge The badge of the original view.
* @param iconOffset The amount of offset needed to match this view with the original view.
*/
@UiThread
- private void setIcon(View originalView, @Nullable Drawable drawable, @Nullable Drawable badge,
- int iconOffset) {
+ private void setIcon(@Nullable Drawable drawable, @Nullable Drawable badge, int iconOffset) {
+ final InsettableFrameLayout.LayoutParams lp =
+ (InsettableFrameLayout.LayoutParams) getLayoutParams();
mBadge = badge;
-
- mIsAdaptiveIcon = drawable instanceof AdaptiveIconDrawable;
- if (mIsAdaptiveIcon) {
- boolean isFolderIcon = drawable instanceof FolderAdaptiveIcon;
-
- AdaptiveIconDrawable adaptiveIcon = (AdaptiveIconDrawable) drawable;
- Drawable background = adaptiveIcon.getBackground();
- if (background == null) {
- background = new ColorDrawable(Color.TRANSPARENT);
- }
- mBackground = background;
- Drawable foreground = adaptiveIcon.getForeground();
- if (foreground == null) {
- foreground = new ColorDrawable(Color.TRANSPARENT);
- }
- mForeground = foreground;
-
- final LayoutParams lp = (LayoutParams) getLayoutParams();
+ mClipIconView.setIcon(drawable, iconOffset, lp, mIsOpening);
+ if (drawable instanceof AdaptiveIconDrawable) {
final int originalHeight = lp.height;
final int originalWidth = lp.width;
- int blurMargin = mBlurSizeOutline / 2;
mFinalDrawableBounds.set(0, 0, originalWidth, originalHeight);
- if (!isFolderIcon) {
- mFinalDrawableBounds.inset(iconOffset - blurMargin, iconOffset - blurMargin);
- }
- mForeground.setBounds(mFinalDrawableBounds);
- mBackground.setBounds(mFinalDrawableBounds);
-
- mStartRevealRect.set(0, 0, originalWidth, originalHeight);
-
- if (mBadge != null) {
- mBadge.setBounds(mStartRevealRect);
- if (!mIsOpening && !isFolderIcon) {
- DRAWABLE_ALPHA.set(mBadge, 0);
- }
- }
-
- if (isFolderIcon) {
- ((FolderIcon) originalView).getPreviewBounds(sTmpRect);
- float bgStroke = ((FolderIcon) originalView).getBackgroundStrokeWidth();
- if (mForeground instanceof ShiftedBitmapDrawable) {
- ShiftedBitmapDrawable sbd = (ShiftedBitmapDrawable) mForeground;
- sbd.setShiftX(sbd.getShiftX() - sTmpRect.left - bgStroke);
- sbd.setShiftY(sbd.getShiftY() - sTmpRect.top - bgStroke);
- }
- if (mBadge instanceof ShiftedBitmapDrawable) {
- ShiftedBitmapDrawable sbd = (ShiftedBitmapDrawable) mBadge;
- sbd.setShiftX(sbd.getShiftX() - sTmpRect.left - bgStroke);
- sbd.setShiftY(sbd.getShiftY() - sTmpRect.top - bgStroke);
- }
- } else {
- Utilities.scaleRectAboutCenter(mStartRevealRect,
- IconShape.getNormalizationScale());
- }
-
float aspectRatio = mLauncher.getDeviceProfile().aspectRatio;
if (mIsVerticalBarLayout) {
lp.width = (int) Math.max(lp.width, lp.height * aspectRatio);
} else {
lp.height = (int) Math.max(lp.height, lp.width * aspectRatio);
}
+ setLayoutParams(lp);
- int left = mIsRtl
- ? mLauncher.getDeviceProfile().widthPx - lp.getMarginStart() - lp.width
- : lp.leftMargin;
- layout(left, lp.topMargin, left + lp.width, lp.topMargin + lp.height);
+ final LayoutParams clipViewLp = (LayoutParams) mClipIconView.getLayoutParams();
+ final int clipViewOgHeight = clipViewLp.height;
+ final int clipViewOgWidth = clipViewLp.width;
+ clipViewLp.width = lp.width;
+ clipViewLp.height = lp.height;
+ mClipIconView.setLayoutParams(clipViewLp);
- float scale = Math.max((float) lp.height / originalHeight,
- (float) lp.width / originalWidth);
- float bgDrawableStartScale;
- if (mIsOpening) {
- bgDrawableStartScale = 1f;
- mOutline.set(0, 0, originalWidth, originalHeight);
- } else {
- bgDrawableStartScale = scale;
- mOutline.set(0, 0, lp.width, lp.height);
+ if (mBadge != null) {
+ mBadge.setBounds(0, 0, clipViewOgWidth, clipViewOgHeight);
}
- setBackgroundDrawableBounds(bgDrawableStartScale);
- mEndRevealRect.set(0, 0, lp.width, lp.height);
- setOutlineProvider(new ViewOutlineProvider() {
- @Override
- public void getOutline(View view, Outline outline) {
- outline.setRoundRect(mOutline, mTaskCornerRadius);
- }
- });
- setClipToOutline(true);
- } else {
- setBackground(drawable);
- setClipToOutline(false);
}
-
invalidate();
- invalidateOutline();
}
/**
@@ -571,7 +379,7 @@
synchronized (mIconLoadResult) {
if (mIconLoadResult.isIconLoaded) {
- setIcon(originalView, mIconLoadResult.drawable, mIconLoadResult.badge,
+ setIcon(mIconLoadResult.drawable, mIconLoadResult.badge,
mIconLoadResult.iconOffset);
hideOriginalView(originalView);
} else {
@@ -580,7 +388,7 @@
return;
}
- setIcon(originalView, mIconLoadResult.drawable, mIconLoadResult.badge,
+ setIcon(mIconLoadResult.drawable, mIconLoadResult.badge,
mIconLoadResult.iconOffset);
setVisibility(VISIBLE);
@@ -600,23 +408,12 @@
}
}
- private void setBackgroundDrawableBounds(float scale) {
- sTmpRect.set(mFinalDrawableBounds);
- Utilities.scaleRectAboutCenter(sTmpRect, scale);
- // Since the drawable is at the top of the view, we need to offset to keep it centered.
- if (mIsVerticalBarLayout) {
- sTmpRect.offsetTo((int) (mFinalDrawableBounds.left * scale), sTmpRect.top);
- } else {
- sTmpRect.offsetTo(sTmpRect.left, (int) (mFinalDrawableBounds.top * scale));
- }
- mBackground.setBounds(sTmpRect);
- }
-
@WorkerThread
@SuppressWarnings("WrongThread")
private static int getOffsetForIconBounds(Launcher l, Drawable drawable, RectF position) {
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O ||
- !(drawable instanceof AdaptiveIconDrawable)) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O
+ || !(drawable instanceof AdaptiveIconDrawable)
+ || (drawable instanceof FolderAdaptiveIcon)) {
return 0;
}
int blurSizeOutline =
@@ -640,33 +437,11 @@
}
@Override
- public void setClipPath(Path clipPath) {
- mClipPath = clipPath;
- invalidate();
- }
-
- @Override
- public void draw(Canvas canvas) {
- int count = canvas.save();
- canvas.rotate(mRotation,
- mFinalDrawableBounds.exactCenterX(), mFinalDrawableBounds.exactCenterY());
- if (mClipPath != null) {
- canvas.clipPath(mClipPath);
- }
- super.draw(canvas);
- if (mBackground != null) {
- mBackground.draw(canvas);
- }
- if (mForeground != null) {
- int count2 = canvas.save();
- canvas.translate(mFgTransX, mFgTransY);
- mForeground.draw(canvas);
- canvas.restoreToCount(count2);
- }
+ protected void dispatchDraw(Canvas canvas) {
+ super.dispatchDraw(canvas);
if (mBadge != null) {
mBadge.draw(canvas);
}
- canvas.restoreToCount(count);
}
public void fastFinish() {
@@ -703,10 +478,10 @@
@Override
public void onGlobalLayout() {
if (mOriginalIcon.isAttachedToWindow() && mPositionOut != null) {
- float rotation = getLocationBoundsForView(mLauncher, mOriginalIcon, mIsOpening,
+ getLocationBoundsForView(mLauncher, mOriginalIcon, mIsOpening,
sTmpRectF);
- if (rotation != mRotation || !sTmpRectF.equals(mPositionOut)) {
- updatePosition(rotation, sTmpRectF, (LayoutParams) getLayoutParams());
+ if (!sTmpRectF.equals(mPositionOut)) {
+ updatePosition(sTmpRectF, (InsettableFrameLayout.LayoutParams) getLayoutParams());
if (mOnTargetChangeRunnable != null) {
mOnTargetChangeRunnable.run();
}
@@ -822,12 +597,6 @@
}
});
- if (mBadge != null) {
- ObjectAnimator badgeFade = ObjectAnimator.ofInt(mBadge, DRAWABLE_ALPHA, 255);
- badgeFade.addUpdateListener(valueAnimator -> invalidate());
- fade.play(badgeFade);
- }
-
if (originalView instanceof IconLabelDotView) {
IconLabelDotView view = (IconLabelDotView) originalView;
fade.addListener(new AnimatorListenerAdapter() {
@@ -869,21 +638,12 @@
setScaleX(1);
setScaleY(1);
setAlpha(1);
- setBackground(null);
if (mLoadIconSignal != null) {
mLoadIconSignal.cancel();
}
mLoadIconSignal = null;
mEndRunnable = null;
- mIsAdaptiveIcon = false;
- mForeground = null;
- mBackground = null;
- mClipPath = null;
mFinalDrawableBounds.setEmpty();
- if (mRevealAnimator != null) {
- mRevealAnimator.cancel();
- }
- mRevealAnimator = null;
if (mFadeAnimatorSet != null) {
mFadeAnimatorSet.cancel();
}
@@ -892,15 +652,10 @@
mListenerView.setListener(null);
mOriginalIcon = null;
mOnTargetChangeRunnable = null;
- mTaskCornerRadius = 0;
- mOutline.setEmpty();
- mFgTransY = 0;
- mFgSpringX.cancel();
- mFgTransX = 0;
- mFgSpringY.cancel();
mBadge = null;
sTmpObjArray[0] = null;
mIconLoadResult = null;
+ mClipIconView.recycle();
}
private static class IconLoadResult {
@@ -911,7 +666,7 @@
Runnable onIconLoaded;
boolean isIconLoaded;
- public IconLoadResult(ItemInfo itemInfo) {
+ IconLoadResult(ItemInfo itemInfo) {
this.itemInfo = itemInfo;
}
}
diff --git a/src/com/android/launcher3/views/ScrimView.java b/src/com/android/launcher3/views/ScrimView.java
index 8ce98f2..442c5fd 100644
--- a/src/com/android/launcher3/views/ScrimView.java
+++ b/src/com/android/launcher3/views/ScrimView.java
@@ -22,8 +22,10 @@
import static com.android.launcher3.LauncherState.ALL_APPS;
import static com.android.launcher3.LauncherState.NORMAL;
-import static com.android.launcher3.anim.Interpolators.ACCEL;
+import static com.android.launcher3.anim.Interpolators.ACCEL_DEACCEL;
import static com.android.launcher3.anim.Interpolators.DEACCEL;
+import static com.android.launcher3.anim.Interpolators.LINEAR;
+import static com.android.launcher3.anim.Interpolators.clampToProgress;
import static com.android.launcher3.icons.GraphicsUtils.setColorAlphaBound;
import android.animation.Animator;
@@ -33,14 +35,16 @@
import android.animation.PropertyValuesHolder;
import android.animation.RectEvaluator;
import android.content.Context;
+import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
+import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.AttributeSet;
-import android.util.Property;
+import android.util.IntProperty;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
@@ -78,10 +82,10 @@
* Simple scrim which draws a flat color
*/
public class ScrimView<T extends Launcher> extends View implements Insettable, OnChangeListener,
- AccessibilityStateChangeListener, StateListener {
+ AccessibilityStateChangeListener {
- public static final Property<ScrimView, Integer> DRAG_HANDLE_ALPHA =
- new Property<ScrimView, Integer>(Integer.TYPE, "dragHandleAlpha") {
+ public static final IntProperty<ScrimView> DRAG_HANDLE_ALPHA =
+ new IntProperty<ScrimView>("dragHandleAlpha") {
@Override
public Integer get(ScrimView scrimView) {
@@ -89,7 +93,7 @@
}
@Override
- public void set(ScrimView scrimView, Integer value) {
+ public void setValue(ScrimView scrimView, int value) {
scrimView.setDragHandleAlpha(value);
}
};
@@ -98,6 +102,12 @@
private static final int SETTINGS = R.string.settings_button_text;
private static final int ALPHA_CHANNEL_COUNT = 1;
+ private static final long DRAG_HANDLE_BOUNCE_DURATION_MS = 300;
+ // How much to delay before repeating the bounce.
+ private static final long DRAG_HANDLE_BOUNCE_DELAY_MS = 200;
+ // Repeat this many times (i.e. total number of bounces is 1 + this).
+ private static final int DRAG_HANDLE_BOUNCE_REPEAT_COUNT = 2;
+
private final Rect mTempRect = new Rect();
private final int[] mTempPos = new int[2];
@@ -106,6 +116,18 @@
private final AccessibilityManager mAM;
protected final int mEndScrim;
+ private final StateListener mAccessibilityLauncherStateListener = new StateListener() {
+ @Override
+ public void onStateTransitionStart(LauncherState toState) {}
+
+ @Override
+ public void onStateTransitionComplete(LauncherState finalState) {
+ setImportantForAccessibility(finalState == ALL_APPS
+ ? IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
+ : IMPORTANT_FOR_ACCESSIBILITY_AUTO);
+ }
+ };
+
protected float mMaxScrimAlpha;
protected float mProgress = 1;
@@ -115,10 +137,13 @@
protected int mEndFlatColor;
protected int mEndFlatColorAlpha;
- protected final int mDragHandleSize;
+ protected final Point mDragHandleSize;
+ private final int mDragHandleTouchSize;
+ private final int mDragHandlePaddingInVerticalBarLayout;
protected float mDragHandleOffset;
private final Rect mDragHandleBounds;
private final RectF mHitRect = new RectF();
+ private ObjectAnimator mDragHandleAnim;
private final MultiValueAlpha mMultiValueAlpha;
@@ -136,9 +161,13 @@
mMaxScrimAlpha = 0.7f;
- mDragHandleSize = context.getResources()
- .getDimensionPixelSize(R.dimen.vertical_drag_handle_size);
- mDragHandleBounds = new Rect(0, 0, mDragHandleSize, mDragHandleSize);
+ Resources res = context.getResources();
+ mDragHandleSize = new Point(res.getDimensionPixelSize(R.dimen.vertical_drag_handle_width),
+ res.getDimensionPixelSize(R.dimen.vertical_drag_handle_height));
+ mDragHandleBounds = new Rect(0, 0, mDragHandleSize.x, mDragHandleSize.y);
+ mDragHandleTouchSize = res.getDimensionPixelSize(R.dimen.vertical_drag_handle_touch_size);
+ mDragHandlePaddingInVerticalBarLayout = context.getResources()
+ .getDimensionPixelSize(R.dimen.vertical_drag_handle_padding_in_vertical_bar_layout);
mAccessibilityHelper = createAccessibilityHelper();
ViewCompat.setAccessibilityDelegate(this, mAccessibilityHelper);
@@ -160,7 +189,7 @@
@Override
public void setInsets(Rect insets) {
updateDragHandleBounds();
- updateDragHandleVisibility(null);
+ updateDragHandleVisibility();
}
@Override
@@ -204,6 +233,7 @@
public void setProgress(float progress) {
if (mProgress != progress) {
mProgress = progress;
+ stopDragHandleEducationAnim();
updateColors();
updateDragHandleAlpha();
invalidate();
@@ -251,70 +281,103 @@
@Override
public boolean onTouchEvent(MotionEvent event) {
- boolean value = super.onTouchEvent(event);
- if (!value && mDragHandle != null && event.getAction() == ACTION_DOWN
- && mDragHandle.getAlpha() == 255
- && mHitRect.contains(event.getX(), event.getY())) {
-
- final Drawable drawable = mDragHandle;
- mDragHandle = null;
-
- Rect bounds = new Rect(mDragHandleBounds);
- bounds.offset(0, -(int) mDragHandleOffset);
- drawable.setBounds(bounds);
-
- Rect topBounds = new Rect(bounds);
- topBounds.offset(0, -bounds.height() / 2);
-
- Rect invalidateRegion = new Rect(bounds);
- invalidateRegion.top = topBounds.top;
-
- Keyframe frameTop = Keyframe.ofObject(0.6f, topBounds);
- frameTop.setInterpolator(DEACCEL);
- Keyframe frameBot = Keyframe.ofObject(1, bounds);
- frameBot.setInterpolator(ACCEL);
- PropertyValuesHolder holder = PropertyValuesHolder .ofKeyframe("bounds",
- Keyframe.ofObject(0, bounds), frameTop, frameBot);
- holder.setEvaluator(new RectEvaluator());
-
- ObjectAnimator anim = ObjectAnimator.ofPropertyValuesHolder(drawable, holder);
- anim.addListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationEnd(Animator animation) {
- getOverlay().remove(drawable);
- updateDragHandleVisibility(drawable);
+ boolean superHandledTouch = super.onTouchEvent(event);
+ if (event.getAction() == ACTION_DOWN) {
+ if (!superHandledTouch && mHitRect.contains(event.getX(), event.getY())) {
+ if (startDragHandleEducationAnim()) {
+ return true;
}
- });
- anim.addUpdateListener((v) -> invalidate(invalidateRegion));
- getOverlay().add(drawable);
- anim.start();
- return true;
+ }
+ stopDragHandleEducationAnim();
}
- return value;
+ return superHandledTouch;
+ }
+
+ /**
+ * Animates the drag handle to demonstrate how to get to all apps.
+ * @return Whether the animation was started (false if drag handle is invisible).
+ */
+ public boolean startDragHandleEducationAnim() {
+ stopDragHandleEducationAnim();
+
+ if (mDragHandle == null || mDragHandle.getAlpha() != 255) {
+ return false;
+ }
+
+ final Drawable drawable = mDragHandle;
+ mDragHandle = null;
+
+ Rect bounds = new Rect(mDragHandleBounds);
+ bounds.offset(0, -(int) mDragHandleOffset);
+ drawable.setBounds(bounds);
+
+ Rect topBounds = new Rect(bounds);
+ topBounds.offset(0, -bounds.height());
+
+ Rect invalidateRegion = new Rect(bounds);
+ invalidateRegion.top = topBounds.top;
+
+ final float progressToReachTop = 0.6f;
+ Keyframe frameTop = Keyframe.ofObject(progressToReachTop, topBounds);
+ frameTop.setInterpolator(DEACCEL);
+ Keyframe frameBot = Keyframe.ofObject(1, bounds);
+ frameBot.setInterpolator(ACCEL_DEACCEL);
+ PropertyValuesHolder holder = PropertyValuesHolder.ofKeyframe("bounds",
+ Keyframe.ofObject(0, bounds), frameTop, frameBot);
+ holder.setEvaluator(new RectEvaluator());
+
+ mDragHandleAnim = ObjectAnimator.ofPropertyValuesHolder(drawable, holder);
+ long totalBounceDuration = DRAG_HANDLE_BOUNCE_DURATION_MS + DRAG_HANDLE_BOUNCE_DELAY_MS;
+ // The bounce finishes by this progress, the rest of the duration just delays next bounce.
+ float delayStartProgress = 1f - (float) DRAG_HANDLE_BOUNCE_DELAY_MS / totalBounceDuration;
+ mDragHandleAnim.addUpdateListener((v) -> invalidate(invalidateRegion));
+ mDragHandleAnim.setDuration(totalBounceDuration);
+ mDragHandleAnim.setInterpolator(clampToProgress(LINEAR, 0, delayStartProgress));
+ mDragHandleAnim.setRepeatCount(DRAG_HANDLE_BOUNCE_REPEAT_COUNT);
+ getOverlay().add(drawable);
+
+ mDragHandleAnim.addListener(new AnimatorListenerAdapter() {
+ @Override
+ public void onAnimationEnd(Animator animation) {
+ mDragHandleAnim = null;
+ getOverlay().remove(drawable);
+ updateDragHandleVisibility(drawable);
+ }
+ });
+ mDragHandleAnim.start();
+ return true;
+ }
+
+ private void stopDragHandleEducationAnim() {
+ if (mDragHandleAnim != null) {
+ mDragHandleAnim.end();
+ }
}
protected void updateDragHandleBounds() {
DeviceProfile grid = mLauncher.getDeviceProfile();
final int left;
final int width = getMeasuredWidth();
- final int top = getMeasuredHeight() - mDragHandleSize - grid.getInsets().bottom;
+ final int top = getMeasuredHeight() - mDragHandleSize.y - grid.getInsets().bottom;
final int topMargin;
if (grid.isVerticalBarLayout()) {
- topMargin = grid.workspacePadding.bottom;
+ topMargin = grid.workspacePadding.bottom + mDragHandlePaddingInVerticalBarLayout;
if (grid.isSeascape()) {
- left = width - grid.getInsets().right - mDragHandleSize;
+ left = width - grid.getInsets().right - mDragHandleSize.x
+ - mDragHandlePaddingInVerticalBarLayout;
} else {
- left = mDragHandleSize + grid.getInsets().left;
+ left = grid.getInsets().left + mDragHandlePaddingInVerticalBarLayout;
}
} else {
- left = (width - mDragHandleSize) / 2;
+ left = Math.round((width - mDragHandleSize.x) / 2f);
topMargin = grid.hotseatBarSizePx;
}
mDragHandleBounds.offsetTo(left, top - topMargin);
mHitRect.set(mDragHandleBounds);
- float inset = -mDragHandleSize / 2;
- mHitRect.inset(inset, inset);
+ // Inset outwards to increase touch size.
+ mHitRect.inset((mDragHandleSize.x - mDragHandleTouchSize) / 2f,
+ (mDragHandleSize.y - mDragHandleTouchSize) / 2f);
if (mDragHandle != null) {
mDragHandle.setBounds(mDragHandleBounds);
@@ -324,24 +387,28 @@
@Override
public void onAccessibilityStateChanged(boolean enabled) {
LauncherStateManager stateManager = mLauncher.getStateManager();
- stateManager.removeStateListener(this);
+ stateManager.removeStateListener(mAccessibilityLauncherStateListener);
if (enabled) {
- stateManager.addStateListener(this);
- handleStateChangedComplete(stateManager.getState());
+ stateManager.addStateListener(mAccessibilityLauncherStateListener);
+ mAccessibilityLauncherStateListener.onStateTransitionComplete(stateManager.getState());
} else {
setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
}
+ updateDragHandleVisibility();
+ }
+
+ public void updateDragHandleVisibility() {
updateDragHandleVisibility(null);
}
- private void updateDragHandleVisibility(Drawable recycle) {
- boolean visible = mLauncher.getDeviceProfile().isVerticalBarLayout() || mAM.isEnabled();
+ private void updateDragHandleVisibility(@Nullable Drawable recycle) {
+ boolean visible = shouldDragHandleBeVisible();
boolean wasVisible = mDragHandle != null;
if (visible != wasVisible) {
if (visible) {
mDragHandle = recycle != null ? recycle :
- mLauncher.getDrawable(R.drawable.drag_handle_indicator);
+ mLauncher.getDrawable(R.drawable.drag_handle_indicator_shadow);
mDragHandle.setBounds(mDragHandleBounds);
updateDragHandleAlpha();
@@ -352,6 +419,10 @@
}
}
+ protected boolean shouldDragHandleBeVisible() {
+ return mLauncher.getDeviceProfile().isVerticalBarLayout() || mAM.isEnabled();
+ }
+
@Override
public boolean dispatchHoverEvent(MotionEvent event) {
return mAccessibilityHelper.dispatchHoverEvent(event) || super.dispatchHoverEvent(event);
@@ -369,20 +440,6 @@
mAccessibilityHelper.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
}
- @Override
- public void onStateTransitionStart(LauncherState toState) {}
-
- @Override
- public void onStateTransitionComplete(LauncherState finalState) {
- handleStateChangedComplete(finalState);
- }
-
- private void handleStateChangedComplete(LauncherState finalState) {
- setImportantForAccessibility(finalState == ALL_APPS
- ? IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
- : IMPORTANT_FOR_ACCESSIBILITY_AUTO);
- }
-
protected class AccessibilityHelper extends ExploreByTouchHelper {
private static final int DRAG_HANDLE_ID = 1;
@@ -393,7 +450,7 @@
@Override
protected int getVirtualViewAt(float x, float y) {
- return mDragHandleBounds.contains((int) x, (int) y)
+ return mHitRect.contains((int) x, (int) y)
? DRAG_HANDLE_ID : INVALID_ID;
}
@@ -466,7 +523,10 @@
}
}
- public int getDragHandleSize() {
- return mDragHandleSize;
+ /**
+ * @return The top of this scrim view, or {@link Float#MAX_VALUE} if there's no distinct top.
+ */
+ public float getVisualTop() {
+ return Float.MAX_VALUE;
}
}
diff --git a/src/com/android/launcher3/views/WorkEduView.java b/src/com/android/launcher3/views/WorkEduView.java
index b6c81ae..d849138 100644
--- a/src/com/android/launcher3/views/WorkEduView.java
+++ b/src/com/android/launcher3/views/WorkEduView.java
@@ -46,17 +46,22 @@
public class WorkEduView extends AbstractSlideInView implements Insettable {
private static final int DEFAULT_CLOSE_DURATION = 200;
- private static final String KEY_WORK_EDU_STEP = "showed_work_profile_edu";
+ public static final String KEY_WORK_EDU_STEP = "showed_work_profile_edu";
+ public static final String KEY_LEGACY_WORK_EDU_SEEN = "showed_bottom_user_education";
private static final int WORK_EDU_NOT_STARTED = 0;
private static final int WORK_EDU_PERSONAL_APPS = 1;
private static final int WORK_EDU_WORK_APPS = 2;
+ protected static final int FINAL_SCRIM_BG_COLOR = 0x88000000;
+
+
private Rect mInsets = new Rect();
private View mViewWrapper;
private Button mProceedButton;
private TextView mContentText;
private AllAppsPagedView mAllAppsPagedView;
+
private int mNextWorkEduStep = WORK_EDU_PERSONAL_APPS;
@@ -98,6 +103,8 @@
mProceedButton = findViewById(R.id.proceed);
mContentText = findViewById(R.id.content_text);
+ // make sure layout does not shrink when we change the text
+ mContentText.post(() -> mContentText.setMinLines(mContentText.getLineCount()));
if (mLauncher.getAppsView().getContentView() instanceof AllAppsPagedView) {
mAllAppsPagedView = (AllAppsPagedView) mLauncher.getAppsView().getContentView();
}
@@ -141,10 +148,15 @@
}
private void show() {
- mLauncher.getDragLayer().addView(this);
+ attachToContainer();
animateOpen();
}
+ @Override
+ protected int getScrimColor(Context context) {
+ return FINAL_SCRIM_BG_COLOR;
+ }
+
private void goToFirstPage() {
if (mAllAppsPagedView != null) {
mAllAppsPagedView.snapToPageImmediately(AllAppsContainerView.AdapterHolder.MAIN);
@@ -170,8 +182,8 @@
if (oldListener != null) {
launcher.getStateManager().removeStateListener(oldListener);
}
- if (launcher.getSharedPrefs().getInt(KEY_WORK_EDU_STEP, WORK_EDU_NOT_STARTED)
- != WORK_EDU_NOT_STARTED) {
+ if (hasSeenLegacyEdu(launcher) || launcher.getSharedPrefs().getInt(KEY_WORK_EDU_STEP,
+ WORK_EDU_NOT_STARTED) != WORK_EDU_NOT_STARTED) {
return null;
}
@@ -201,8 +213,8 @@
* Shows work apps edu if user had dismissed full edu flow
*/
public static void showWorkEduIfNeeded(Launcher launcher) {
- if (launcher.getSharedPrefs().getInt(KEY_WORK_EDU_STEP, WORK_EDU_NOT_STARTED)
- != WORK_EDU_PERSONAL_APPS) {
+ if (hasSeenLegacyEdu(launcher) || launcher.getSharedPrefs().getInt(KEY_WORK_EDU_STEP,
+ WORK_EDU_NOT_STARTED) != WORK_EDU_PERSONAL_APPS) {
return;
}
LayoutInflater layoutInflater = LayoutInflater.from(launcher);
@@ -211,4 +223,8 @@
v.show();
v.goToWorkTab(false);
}
+
+ private static boolean hasSeenLegacyEdu(Launcher launcher) {
+ return launcher.getSharedPrefs().getBoolean(KEY_LEGACY_WORK_EDU_SEEN, false);
+ }
}
diff --git a/src/com/android/launcher3/views/WorkFooterContainer.java b/src/com/android/launcher3/views/WorkFooterContainer.java
deleted file mode 100644
index f8add9a..0000000
--- a/src/com/android/launcher3/views/WorkFooterContainer.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * 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.launcher3.views;
-
-import static com.android.launcher3.util.PackageManagerHelper.hasShortcutsPermission;
-
-import android.animation.ObjectAnimator;
-import android.animation.PropertyValuesHolder;
-import android.content.Context;
-import android.content.pm.PackageManager;
-import android.graphics.Rect;
-import android.util.AttributeSet;
-import android.view.View;
-import android.widget.LinearLayout;
-import android.widget.TextView;
-
-import com.android.launcher3.Insettable;
-import com.android.launcher3.Launcher;
-import com.android.launcher3.R;
-import com.android.launcher3.Utilities;
-import com.android.launcher3.allapps.WorkModeSwitch;
-import com.android.launcher3.pm.UserCache;
-
-/**
- * Container to show work footer in all-apps.
- */
-public class WorkFooterContainer extends LinearLayout implements Insettable {
- private Rect mInsets = new Rect();
-
- private WorkModeSwitch mWorkModeSwitch;
- private TextView mWorkModeLabel;
-
- protected final ObjectAnimator mOpenCloseAnimator;
-
- public WorkFooterContainer(Context context) {
- this(context, null, 0);
- }
-
- public WorkFooterContainer(Context context, AttributeSet attrs) {
- this(context, attrs, 0);
- }
-
- public WorkFooterContainer(Context context, AttributeSet attrs, int defStyleAttr) {
- super(context, attrs, defStyleAttr);
- mOpenCloseAnimator = ObjectAnimator.ofPropertyValuesHolder(this);
- }
-
- @Override
- protected void onLayout(boolean changed, int l, int t, int r, int b) {
- super.onLayout(changed, l, t, r, b);
- updateTranslation();
- this.setVisibility(shouldShowWorkFooter() ? VISIBLE : GONE);
- }
-
- @Override
- protected void onFinishInflate() {
- super.onFinishInflate();
- mWorkModeSwitch = findViewById(R.id.work_mode_toggle);
- mWorkModeLabel = findViewById(R.id.work_mode_label);
- }
-
- @Override
- public void offsetTopAndBottom(int offset) {
- super.offsetTopAndBottom(offset);
- updateTranslation();
- }
-
- private void updateTranslation() {
- if (getParent() instanceof View) {
- View parent = (View) getParent();
- int availableBot = parent.getHeight() - parent.getPaddingBottom();
- setTranslationY(Math.max(0, availableBot - getBottom()));
- }
- }
-
- @Override
- public void setInsets(Rect insets) {
- int bottomInset = insets.bottom - mInsets.bottom;
- mInsets.set(insets);
- setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(),
- getPaddingBottom() + bottomInset);
- }
-
- /**
- * Animates in/out work profile toggle panel based on the tab user is on
- */
- public void setWorkTabVisible(boolean workTabVisible) {
- if (!shouldShowWorkFooter()) return;
-
- mOpenCloseAnimator.setValues(PropertyValuesHolder.ofFloat(ALPHA, workTabVisible ? 1 : 0));
- mOpenCloseAnimator.start();
- }
-
- /**
- * Refreshes views based on current work profile enabled status
- */
- public void refresh() {
- if (!shouldShowWorkFooter()) return;
- boolean anyProfileQuietModeEnabled = UserCache.INSTANCE.get(
- getContext()).isAnyProfileQuietModeEnabled();
-
- mWorkModeLabel.setText(anyProfileQuietModeEnabled
- ? R.string.work_mode_off_label : R.string.work_mode_on_label);
- mWorkModeLabel.setCompoundDrawablesWithIntrinsicBounds(
- anyProfileQuietModeEnabled ? R.drawable.ic_corp_off : R.drawable.ic_corp, 0, 0, 0);
- mWorkModeSwitch.refresh();
- }
-
- private boolean shouldShowWorkFooter() {
- Launcher launcher = Launcher.getLauncher(getContext());
- return Utilities.ATLEAST_P && (hasShortcutsPermission(launcher)
- || launcher.checkSelfPermission("android.permission.MODIFY_QUIET_MODE")
- == PackageManager.PERMISSION_GRANTED);
- }
-}
diff --git a/src/com/android/launcher3/widget/BaseWidgetSheet.java b/src/com/android/launcher3/widget/BaseWidgetSheet.java
index 6cae43d..3e5113a 100644
--- a/src/com/android/launcher3/widget/BaseWidgetSheet.java
+++ b/src/com/android/launcher3/widget/BaseWidgetSheet.java
@@ -15,8 +15,6 @@
*/
package com.android.launcher3.widget;
-import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
-
import static com.android.launcher3.icons.GraphicsUtils.setColorAlphaBound;
import static com.android.launcher3.logging.LoggerUtils.newContainerTarget;
@@ -30,11 +28,13 @@
import com.android.launcher3.DragSource;
import com.android.launcher3.DropTarget.DragObject;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.dragndrop.DragOptions;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.popup.PopupDataProvider;
+import com.android.launcher3.testing.TestLogging;
+import com.android.launcher3.testing.TestProtocol;
import com.android.launcher3.touch.ItemLongClickListener;
import com.android.launcher3.uioverrides.WallpaperColorInfo;
import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
@@ -42,7 +42,8 @@
import com.android.launcher3.util.SystemUiController;
import com.android.launcher3.util.Themes;
import com.android.launcher3.views.AbstractSlideInView;
-import com.android.launcher3.views.BaseDragLayer;
+
+import java.util.ArrayList;
/**
* Base class for various widgets popup
@@ -55,11 +56,14 @@
/* Touch handling related member variables. */
private Toast mWidgetInstructionToast;
- protected final View mColorScrim;
-
public BaseWidgetSheet(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
- mColorScrim = createColorScrim(context);
+ }
+
+ protected int getScrimColor(Context context) {
+ WallpaperColorInfo colors = WallpaperColorInfo.INSTANCE.get(context);
+ int alpha = context.getResources().getInteger(R.integer.extracted_color_gradient_alpha);
+ return setColorAlphaBound(colors.getSecondaryColor(), alpha);
}
@Override
@@ -90,6 +94,8 @@
@Override
public boolean onLongClick(View v) {
+ TestLogging.recordEvent(TestProtocol.SEQUENCE_MAIN, "Widgets.onLongClick");
+ v.cancelLongPress();
if (!ItemLongClickListener.canStartDrag(mLauncher)) return false;
if (v instanceof WidgetCell) {
@@ -98,16 +104,6 @@
return true;
}
- protected void attachToContainer() {
- getPopupContainer().addView(mColorScrim);
- getPopupContainer().addView(this);
- }
-
- protected void setTranslationShift(float translationShift) {
- super.setTranslationShift(translationShift);
- mColorScrim.setAlpha(1 - mTranslationShift);
- }
-
private boolean beginDraggingWidget(WidgetCell v) {
// Get the widget preview as the drag representation
WidgetImageView image = v.getWidgetView();
@@ -138,7 +134,6 @@
protected void onCloseComplete() {
super.onCloseComplete();
- getPopupContainer().removeView(mColorScrim);
clearNavBarColor();
}
@@ -155,9 +150,11 @@
}
@Override
- public void fillInLogContainerData(View v, ItemInfo info, Target target, Target targetParent) {
- targetParent.containerType = ContainerType.WIDGETS;
- targetParent.cardinality = getElementsRowCount();
+ public void fillInLogContainerData(ItemInfo childInfo, Target child,
+ ArrayList<Target> parents) {
+ Target target = newContainerTarget(ContainerType.WIDGETS);
+ target.cardinality = getElementsRowCount();
+ parents.add(target);
}
@Override
@@ -177,19 +174,4 @@
protected SystemUiController getSystemUiController() {
return mLauncher.getSystemUiController();
}
-
- private static View createColorScrim(Context context) {
- View view = new View(context);
- view.forceHasOverlappingRendering(false);
-
- WallpaperColorInfo colors = WallpaperColorInfo.INSTANCE.get(context);
- int alpha = context.getResources().getInteger(R.integer.extracted_color_gradient_alpha);
- view.setBackgroundColor(setColorAlphaBound(colors.getSecondaryColor(), alpha));
-
- BaseDragLayer.LayoutParams lp = new BaseDragLayer.LayoutParams(MATCH_PARENT, MATCH_PARENT);
- lp.ignoreInsets = true;
- view.setLayoutParams(lp);
-
- return view;
- }
}
diff --git a/src/com/android/launcher3/widget/LauncherAppWidgetHostView.java b/src/com/android/launcher3/widget/LauncherAppWidgetHostView.java
index f3fd7ca..5d33f13 100644
--- a/src/com/android/launcher3/widget/LauncherAppWidgetHostView.java
+++ b/src/com/android/launcher3/widget/LauncherAppWidgetHostView.java
@@ -20,13 +20,13 @@
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.PointF;
+import android.graphics.Rect;
import android.os.Handler;
import android.os.SystemClock;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
-import android.view.ViewConfiguration;
import android.view.ViewDebug;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityNodeInfo;
@@ -35,15 +35,14 @@
import android.widget.RemoteViews;
import com.android.launcher3.CheckLongPressHelper;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.Launcher;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherAppWidgetProviderInfo;
import com.android.launcher3.R;
-import com.android.launcher3.SimpleOnStylusPressListener;
-import com.android.launcher3.StylusEventHelper;
import com.android.launcher3.Utilities;
import com.android.launcher3.dragndrop.DragLayer;
+import com.android.launcher3.dragndrop.DraggableView;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
import com.android.launcher3.util.Executors;
import com.android.launcher3.util.Themes;
import com.android.launcher3.views.BaseDragLayer.TouchCompleteListener;
@@ -52,7 +51,7 @@
* {@inheritDoc}
*/
public class LauncherAppWidgetHostView extends NavigableAppWidgetHostView
- implements TouchCompleteListener, View.OnLongClickListener {
+ implements TouchCompleteListener, View.OnLongClickListener, DraggableView {
// Related to the auto-advancing of widgets
private static final long ADVANCE_INTERVAL = 20000;
@@ -64,14 +63,11 @@
protected final LayoutInflater mInflater;
private final CheckLongPressHelper mLongPressHelper;
- private final StylusEventHelper mStylusEventHelper;
protected final Launcher mLauncher;
@ViewDebug.ExportedProperty(category = "launcher")
private boolean mReinflateOnConfigChange;
- private float mSlop;
-
private boolean mIsScrollable;
private boolean mIsAttachedToWindow;
private boolean mIsAutoAdvanceRegistered;
@@ -91,7 +87,6 @@
super(context);
mLauncher = Launcher.getLauncher(context);
mLongPressHelper = new CheckLongPressHelper(this, this);
- mStylusEventHelper = new StylusEventHelper(new SimpleOnStylusPressListener(this), this);
mInflater = LayoutInflater.from(context);
setAccessibilityDelegate(mLauncher.getAccessibilityDelegate());
setBackgroundResource(R.drawable.widget_internal_focus_bg);
@@ -155,68 +150,19 @@
}
public boolean onInterceptTouchEvent(MotionEvent ev) {
- // Just in case the previous long press hasn't been cleared, we make sure to start fresh
- // on touch down.
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
- mLongPressHelper.cancelLongPress();
- }
-
- // Consume any touch events for ourselves after longpress is triggered
- if (mLongPressHelper.hasPerformedLongPress()) {
- mLongPressHelper.cancelLongPress();
- return true;
- }
-
- // Watch for longpress or stylus button press events at this level to
- // make sure users can always pick up this widget
- if (mStylusEventHelper.onMotionEvent(ev)) {
- mLongPressHelper.cancelLongPress();
- return true;
- }
-
- switch (ev.getAction()) {
- case MotionEvent.ACTION_DOWN: {
- DragLayer dragLayer = Launcher.getLauncher(getContext()).getDragLayer();
-
- if (mIsScrollable) {
- dragLayer.requestDisallowInterceptTouchEvent(true);
- }
- if (!mStylusEventHelper.inStylusButtonPressed()) {
- mLongPressHelper.postCheckForLongPress();
- }
- dragLayer.setTouchCompleteListener(this);
- break;
+ DragLayer dragLayer = Launcher.getLauncher(getContext()).getDragLayer();
+ if (mIsScrollable) {
+ dragLayer.requestDisallowInterceptTouchEvent(true);
}
-
- case MotionEvent.ACTION_UP:
- case MotionEvent.ACTION_CANCEL:
- mLongPressHelper.cancelLongPress();
- break;
- case MotionEvent.ACTION_MOVE:
- if (!Utilities.pointInView(this, ev.getX(), ev.getY(), mSlop)) {
- mLongPressHelper.cancelLongPress();
- }
- break;
+ dragLayer.setTouchCompleteListener(this);
}
-
- // Otherwise continue letting touch events fall through to children
- return false;
+ mLongPressHelper.onTouchEvent(ev);
+ return mLongPressHelper.hasPerformedLongPress();
}
public boolean onTouchEvent(MotionEvent ev) {
- // If the widget does not handle touch, then cancel
- // long press when we release the touch
- switch (ev.getAction()) {
- case MotionEvent.ACTION_UP:
- case MotionEvent.ACTION_CANCEL:
- mLongPressHelper.cancelLongPress();
- break;
- case MotionEvent.ACTION_MOVE:
- if (!Utilities.pointInView(this, ev.getX(), ev.getY(), mSlop)) {
- mLongPressHelper.cancelLongPress();
- }
- break;
- }
+ mLongPressHelper.onTouchEvent(ev);
// We want to keep receiving though events to be able to cancel long press on ACTION_UP
return true;
}
@@ -224,7 +170,6 @@
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
- mSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
mIsAttachedToWindow = true;
checkIfAutoAdvance();
@@ -412,4 +357,17 @@
}
return false;
}
+
+ @Override
+ public int getViewType() {
+ return DRAGGABLE_WIDGET;
+ }
+
+ @Override
+ public void getVisualDragBounds(Rect bounds) {
+ int width = (int) (getMeasuredWidth() * mScaleToFit);
+ int height = (int) (getMeasuredHeight() * mScaleToFit);
+
+ bounds.set(0, 0 , width, height);
+ }
}
diff --git a/src/com/android/launcher3/widget/NavigableAppWidgetHostView.java b/src/com/android/launcher3/widget/NavigableAppWidgetHostView.java
index 68b1595..104ad77 100644
--- a/src/com/android/launcher3/widget/NavigableAppWidgetHostView.java
+++ b/src/com/android/launcher3/widget/NavigableAppWidgetHostView.java
@@ -24,12 +24,15 @@
import android.view.ViewDebug;
import android.view.ViewGroup;
+import com.android.launcher3.dragndrop.DraggableView;
+
import java.util.ArrayList;
/**
* Extension of AppWidgetHostView with support for controlled keyboard navigation.
*/
-public abstract class NavigableAppWidgetHostView extends AppWidgetHostView {
+public abstract class NavigableAppWidgetHostView extends AppWidgetHostView
+ implements DraggableView {
@ViewDebug.ExportedProperty(category = "launcher")
private boolean mChildrenFocused;
@@ -133,4 +136,14 @@
// The host view's background changes when selected, to indicate the focus is inside.
setSelected(childIsFocused);
}
+
+ @Override
+ public int getViewType() {
+ return DRAGGABLE_WIDGET;
+ }
+
+ @Override
+ public void getVisualDragBounds(Rect bounds) {
+ bounds.set(0, 0 , getMeasuredWidth(), getMeasuredHeight());
+ }
}
diff --git a/src/com/android/launcher3/widget/PendingAppWidgetHostView.java b/src/com/android/launcher3/widget/PendingAppWidgetHostView.java
index 6038873..9021d9e 100644
--- a/src/com/android/launcher3/widget/PendingAppWidgetHostView.java
+++ b/src/com/android/launcher3/widget/PendingAppWidgetHostView.java
@@ -33,15 +33,16 @@
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.View.OnClickListener;
+import android.widget.RemoteViews;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.FastBitmapDrawable;
-import com.android.launcher3.ItemInfoWithIcon;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.R;
import com.android.launcher3.icons.IconCache;
import com.android.launcher3.icons.IconCache.ItemInfoUpdateReceiver;
-import com.android.launcher3.model.PackageItemInfo;
+import com.android.launcher3.model.data.ItemInfoWithIcon;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
+import com.android.launcher3.model.data.PackageItemInfo;
import com.android.launcher3.touch.ItemClickHandler;
import com.android.launcher3.util.Themes;
@@ -94,6 +95,15 @@
}
@Override
+ public void updateAppWidget(RemoteViews remoteViews) {
+ super.updateAppWidget(remoteViews);
+ WidgetManagerHelper widgetManagerHelper = new WidgetManagerHelper(getContext());
+ if (widgetManagerHelper.isAppWidgetRestored(mInfo.appWidgetId)) {
+ reInflate();
+ }
+ }
+
+ @Override
public void updateAppWidgetSize(Bundle newOptions, int minWidth, int minHeight, int maxWidth,
int maxHeight) {
// No-op
diff --git a/src/com/android/launcher3/widget/PendingItemDragHelper.java b/src/com/android/launcher3/widget/PendingItemDragHelper.java
index 662e627..3c11274 100644
--- a/src/com/android/launcher3/widget/PendingItemDragHelper.java
+++ b/src/com/android/launcher3/widget/PendingItemDragHelper.java
@@ -32,6 +32,7 @@
import com.android.launcher3.PendingAddItemInfo;
import com.android.launcher3.R;
import com.android.launcher3.dragndrop.DragOptions;
+import com.android.launcher3.dragndrop.DraggableView;
import com.android.launcher3.dragndrop.LivePreviewWidgetCell;
import com.android.launcher3.graphics.DragPreviewProvider;
import com.android.launcher3.icons.LauncherIcons;
@@ -79,6 +80,8 @@
mEstimatedCellSize = launcher.getWorkspace().estimateItemSize(mAddInfo);
+ DraggableView draggableView;
+
if (mAddInfo instanceof PendingAddWidgetInfo) {
PendingAddWidgetInfo createWidgetInfo = (PendingAddWidgetInfo) mAddInfo;
@@ -110,6 +113,7 @@
dragOffset = null;
dragRegion = null;
+ draggableView = DraggableView.ofType(DraggableView.DRAGGABLE_WIDGET);
} else {
PendingAddShortcutInfo createShortcutInfo = (PendingAddShortcutInfo) mAddInfo;
Drawable icon = createShortcutInfo.activityInfo.getFullResIcon(app.getIconCache());
@@ -136,6 +140,7 @@
dragRegion.top = (mEstimatedCellSize[1]
- iconSize - dp.iconTextSizePx - dp.iconDrawablePaddingPx) / 2;
dragRegion.bottom = dragRegion.top + iconSize;
+ draggableView = DraggableView.ofType(DraggableView.DRAGGABLE_ICON);
}
// Since we are not going through the workspace for starting the drag, set drag related
@@ -148,8 +153,8 @@
+ (int) ((scale * preview.getHeight() - preview.getHeight()) / 2);
// Start the drag
- launcher.getDragController().startDrag(preview, dragLayerX, dragLayerY, source, mAddInfo,
- dragOffset, dragRegion, scale, scale, options);
+ launcher.getDragController().startDrag(preview, draggableView, dragLayerX, dragLayerY,
+ source, mAddInfo, dragOffset, dragRegion, scale, scale, options);
}
@Override
diff --git a/src/com/android/launcher3/widget/WidgetAddFlowHandler.java b/src/com/android/launcher3/widget/WidgetAddFlowHandler.java
index 5387be8..ebc2a25 100644
--- a/src/com/android/launcher3/widget/WidgetAddFlowHandler.java
+++ b/src/com/android/launcher3/widget/WidgetAddFlowHandler.java
@@ -20,10 +20,10 @@
import android.os.Parcel;
import android.os.Parcelable;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.Launcher;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherAppWidgetProviderInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
import com.android.launcher3.util.PendingRequestArgs;
/**
diff --git a/src/com/android/launcher3/widget/WidgetCell.java b/src/com/android/launcher3/widget/WidgetCell.java
index f055adf..4a0b4ef 100644
--- a/src/com/android/launcher3/widget/WidgetCell.java
+++ b/src/com/android/launcher3/widget/WidgetCell.java
@@ -31,10 +31,9 @@
import android.widget.TextView;
import com.android.launcher3.BaseActivity;
+import com.android.launcher3.CheckLongPressHelper;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.R;
-import com.android.launcher3.SimpleOnStylusPressListener;
-import com.android.launcher3.StylusEventHelper;
import com.android.launcher3.WidgetPreviewLoader;
import com.android.launcher3.icons.BaseIconFactory;
import com.android.launcher3.model.WidgetItem;
@@ -71,7 +70,6 @@
protected WidgetItem mItem;
private WidgetPreviewLoader mWidgetPreviewLoader;
- private StylusEventHelper mStylusEventHelper;
protected CancellationSignal mActiveRequest;
private boolean mAnimatePreview = true;
@@ -80,7 +78,8 @@
private Bitmap mDeferredBitmap;
protected final BaseActivity mActivity;
- protected DeviceProfile mDeviceProfile;
+ protected final DeviceProfile mDeviceProfile;
+ private final CheckLongPressHelper mLongPressHelper;
public WidgetCell(Context context) {
this(context, null);
@@ -95,8 +94,9 @@
mActivity = BaseActivity.fromContext(context);
mDeviceProfile = mActivity.getDeviceProfile();
- mStylusEventHelper = new StylusEventHelper(new SimpleOnStylusPressListener(this), this);
+ mLongPressHelper = new CheckLongPressHelper(this);
+ mLongPressHelper.setLongPressTimeoutFactor(1);
setContainerWidth();
setWillNotDraw(false);
setClipToPadding(false);
@@ -210,11 +210,15 @@
@Override
public boolean onTouchEvent(MotionEvent ev) {
- boolean handled = super.onTouchEvent(ev);
- if (mStylusEventHelper.onMotionEvent(ev)) {
- return true;
- }
- return handled;
+ super.onTouchEvent(ev);
+ mLongPressHelper.onTouchEvent(ev);
+ return true;
+ }
+
+ @Override
+ public void cancelLongPress() {
+ super.cancelLongPress();
+ mLongPressHelper.cancelLongPress();
}
/**
diff --git a/src/com/android/launcher3/widget/WidgetListRowEntry.java b/src/com/android/launcher3/widget/WidgetListRowEntry.java
index 335b8c7..17e4673 100644
--- a/src/com/android/launcher3/widget/WidgetListRowEntry.java
+++ b/src/com/android/launcher3/widget/WidgetListRowEntry.java
@@ -15,9 +15,9 @@
*/
package com.android.launcher3.widget;
-import com.android.launcher3.ItemInfo;
-import com.android.launcher3.model.PackageItemInfo;
import com.android.launcher3.model.WidgetItem;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.PackageItemInfo;
import java.util.ArrayList;
diff --git a/src/com/android/launcher3/widget/WidgetManagerHelper.java b/src/com/android/launcher3/widget/WidgetManagerHelper.java
index 8b08d77..4b6c569 100644
--- a/src/com/android/launcher3/widget/WidgetManagerHelper.java
+++ b/src/com/android/launcher3/widget/WidgetManagerHelper.java
@@ -28,10 +28,10 @@
import androidx.annotation.Nullable;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherAppWidgetProviderInfo;
import com.android.launcher3.Utilities;
import com.android.launcher3.model.WidgetsModel;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
import com.android.launcher3.pm.UserCache;
import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.PackageUserKey;
@@ -49,6 +49,9 @@
*/
public class WidgetManagerHelper {
+ //TODO: replace this with OPTION_APPWIDGET_RESTORE_COMPLETED b/63667276
+ public static final String WIDGET_OPTION_RESTORE_COMPLETED = "appWidgetRestoreCompleted";
+
final AppWidgetManager mAppWidgetManager;
final Context mContext;
@@ -127,6 +130,14 @@
return null;
}
+ /**
+ * Returns if a AppWidgetProvider has marked a widget restored
+ */
+ public boolean isAppWidgetRestored(int appWidgetId) {
+ return !WidgetsModel.GO_DISABLE_WIDGETS && mAppWidgetManager.getAppWidgetOptions(
+ appWidgetId).getBoolean(WIDGET_OPTION_RESTORE_COMPLETED);
+ }
+
public static Map<ComponentKey, AppWidgetProviderInfo> getAllProvidersMap(Context context) {
if (WidgetsModel.GO_DISABLE_WIDGETS) {
return Collections.emptyMap();
diff --git a/src/com/android/launcher3/widget/WidgetsBottomSheet.java b/src/com/android/launcher3/widget/WidgetsBottomSheet.java
index a7078a2..30be7a6 100644
--- a/src/com/android/launcher3/widget/WidgetsBottomSheet.java
+++ b/src/com/android/launcher3/widget/WidgetsBottomSheet.java
@@ -16,8 +16,8 @@
package com.android.launcher3.widget;
-import android.animation.Animator;
-import android.animation.ObjectAnimator;
+import static com.android.launcher3.anim.Interpolators.FAST_OUT_SLOW_IN;
+
import android.animation.PropertyValuesHolder;
import android.content.Context;
import android.graphics.Rect;
@@ -28,17 +28,16 @@
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
+import android.view.animation.Interpolator;
import android.widget.TextView;
-import androidx.annotation.Nullable;
-
import com.android.launcher3.Insettable;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.R;
import com.android.launcher3.ResourceUtils;
-import com.android.launcher3.anim.Interpolators;
+import com.android.launcher3.anim.PendingAnimation;
import com.android.launcher3.model.WidgetItem;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.util.PackageUserKey;
import java.util.List;
@@ -156,7 +155,7 @@
setupNavBarColor();
mOpenCloseAnimator.setValues(
PropertyValuesHolder.ofFloat(TRANSLATION_SHIFT, TRANSLATION_SHIFT_OPENED));
- mOpenCloseAnimator.setInterpolator(Interpolators.FAST_OUT_SLOW_IN);
+ mOpenCloseAnimator.setInterpolator(FAST_OUT_SLOW_IN);
mOpenCloseAnimator.start();
}
@@ -191,9 +190,9 @@
mIsOpen ? R.string.widgets_list : R.string.widgets_list_closed));
}
- @Nullable
@Override
- public Animator createHintCloseAnim(float distanceToMove) {
- return ObjectAnimator.ofInt(this, PADDING_BOTTOM, (int) (distanceToMove + mInsets.bottom));
+ public void addHintCloseAnim(
+ float distanceToMove, Interpolator interpolator, PendingAnimation target) {
+ target.setInt(this, PADDING_BOTTOM, (int) (distanceToMove + mInsets.bottom), interpolator);
}
}
diff --git a/src/com/android/launcher3/widget/WidgetsDiffReporter.java b/src/com/android/launcher3/widget/WidgetsDiffReporter.java
index f3b325d..df6e2c3 100644
--- a/src/com/android/launcher3/widget/WidgetsDiffReporter.java
+++ b/src/com/android/launcher3/widget/WidgetsDiffReporter.java
@@ -21,7 +21,7 @@
import androidx.recyclerview.widget.RecyclerView;
import com.android.launcher3.icons.IconCache;
-import com.android.launcher3.model.PackageItemInfo;
+import com.android.launcher3.model.data.PackageItemInfo;
import com.android.launcher3.widget.WidgetsListAdapter.WidgetListRowEntryComparator;
import java.util.ArrayList;
diff --git a/src/com/android/launcher3/widget/WidgetsFullSheet.java b/src/com/android/launcher3/widget/WidgetsFullSheet.java
index 2a102d2..37a30af 100644
--- a/src/com/android/launcher3/widget/WidgetsFullSheet.java
+++ b/src/com/android/launcher3/widget/WidgetsFullSheet.java
@@ -15,23 +15,23 @@
*/
package com.android.launcher3.widget;
+import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_Y;
import static com.android.launcher3.testing.TestProtocol.NORMAL_STATE_ORDINAL;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
-import android.animation.AnimatorSet;
-import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
+import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
+import android.view.animation.Interpolator;
-import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import com.android.launcher3.Insettable;
@@ -39,7 +39,10 @@
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherAppWidgetHost.ProviderChangedListener;
import com.android.launcher3.R;
+import com.android.launcher3.Utilities;
+import com.android.launcher3.anim.PendingAnimation;
import com.android.launcher3.compat.AccessibilityManagerCompat;
+import com.android.launcher3.testing.TestProtocol;
import com.android.launcher3.views.RecyclerViewFastScroller;
import com.android.launcher3.views.TopRoundedCornerView;
@@ -68,6 +71,14 @@
}
+ @Override
+ public boolean dispatchTouchEvent(MotionEvent ev) {
+ if (Utilities.IS_RUNNING_IN_TEST_HARNESS) {
+ Log.d(TestProtocol.NO_SCROLL_END_WIDGETS, "WidgetsFullSheet: " + ev);
+ }
+ return super.dispatchTouchEvent(ev);
+ }
+
public WidgetsFullSheet(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
@@ -87,6 +98,11 @@
onWidgetsBound();
}
+ @VisibleForTesting
+ public WidgetsRecyclerView getRecyclerView() {
+ return mRecyclerView;
+ }
+
@Override
protected Pair<View, String> getAccessibilityTarget() {
return Pair.create(mRecyclerView, getContext().getString(
@@ -177,6 +193,7 @@
.setDuration(DEFAULT_OPEN_DURATION)
.setInterpolator(AnimationUtils.loadInterpolator(
getContext(), android.R.interpolator.linear_out_slow_in));
+ mRecyclerView.setLayoutFrozen(true);
mOpenCloseAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
@@ -186,7 +203,6 @@
}
});
post(() -> {
- mRecyclerView.setLayoutFrozen(true);
mOpenCloseAnimator.start();
mContent.animate().alpha(1).setDuration(FADE_IN_DURATION);
});
@@ -242,13 +258,11 @@
return mAdapter.getItemCount();
}
- @Nullable
@Override
- public Animator createHintCloseAnim(float distanceToMove) {
- AnimatorSet anim = new AnimatorSet();
- anim.play(ObjectAnimator.ofFloat(mRecyclerView, TRANSLATION_Y, -distanceToMove));
- anim.play(ObjectAnimator.ofFloat(mRecyclerView, ALPHA, 0.5f));
- return anim;
+ public void addHintCloseAnim(
+ float distanceToMove, Interpolator interpolator, PendingAnimation target) {
+ target.setFloat(mRecyclerView, VIEW_TRANSLATE_Y, -distanceToMove, interpolator);
+ target.setViewAlpha(mRecyclerView, 0.5f, interpolator);
}
@Override
diff --git a/src/com/android/launcher3/widget/WidgetsRecyclerView.java b/src/com/android/launcher3/widget/WidgetsRecyclerView.java
index c15557b..63e063f 100644
--- a/src/com/android/launcher3/widget/WidgetsRecyclerView.java
+++ b/src/com/android/launcher3/widget/WidgetsRecyclerView.java
@@ -19,11 +19,15 @@
import android.content.Context;
import android.graphics.Point;
import android.util.AttributeSet;
+import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
+import android.view.accessibility.AccessibilityNodeInfo;
import com.android.launcher3.BaseRecyclerView;
import com.android.launcher3.R;
+import com.android.launcher3.Utilities;
+import com.android.launcher3.testing.TestProtocol;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
@@ -155,18 +159,75 @@
mScrollbar.isHitInParent(e.getX(), e.getY(), mFastScrollerOffset);
}
if (mTouchDownOnScroller) {
- return mScrollbar.handleTouchEvent(e, mFastScrollerOffset);
+ final boolean result = mScrollbar.handleTouchEvent(e, mFastScrollerOffset);
+ if (Utilities.IS_RUNNING_IN_TEST_HARNESS) {
+ Log.d(TestProtocol.NO_SCROLL_END_WIDGETS, "onInterceptTouchEvent 1 " + result);
+ }
+ return result;
+ }
+ if (Utilities.IS_RUNNING_IN_TEST_HARNESS) {
+ Log.d(TestProtocol.NO_SCROLL_END_WIDGETS, "onInterceptTouchEvent 2 false");
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
+ if (Utilities.IS_RUNNING_IN_TEST_HARNESS) {
+ Log.d(TestProtocol.NO_SCROLL_END_WIDGETS, "WidgetsRecyclerView.onTouchEvent");
+ }
if (mTouchDownOnScroller) {
mScrollbar.handleTouchEvent(e, mFastScrollerOffset);
}
}
@Override
- public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { }
+ public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
+ if (Utilities.IS_RUNNING_IN_TEST_HARNESS) {
+ Log.d(TestProtocol.NO_SCROLL_END_WIDGETS, "onRequestDisallowInterceptTouchEvent "
+ + disallowIntercept);
+ }
+ }
+
+ @Override
+ public boolean dispatchTouchEvent(MotionEvent ev) {
+ final boolean result = super.dispatchTouchEvent(ev);
+ if (Utilities.IS_RUNNING_IN_TEST_HARNESS) {
+ Log.d(TestProtocol.NO_SCROLL_END_WIDGETS, "WidgetsRecyclerView: state: "
+ + getScrollState()
+ + " can scroll: " + getLayoutManager().canScrollVertically()
+ + " result: " + result
+ + " layout suppressed: " + isLayoutSuppressed()
+ + " event: " + ev);
+ }
+ return result;
+ }
+
+ @Override
+ public void stopNestedScroll() {
+ if (Utilities.IS_RUNNING_IN_TEST_HARNESS) {
+ Log.d(TestProtocol.NO_SCROLL_END_WIDGETS, "stopNestedScroll");
+ }
+ super.stopNestedScroll();
+ }
+
+ @Override
+ public void setLayoutFrozen(boolean frozen) {
+ if (frozen != isLayoutSuppressed()) {
+ if (Utilities.IS_RUNNING_IN_TEST_HARNESS) {
+ Log.d(TestProtocol.NO_SCROLL_END_WIDGETS, "setLayoutFrozen " + frozen
+ + " @ " + android.util.Log.getStackTraceString(new Throwable()));
+ }
+ }
+ super.setLayoutFrozen(frozen);
+ }
+
+ @Override
+ public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
+ super.onInitializeAccessibilityNodeInfo(info);
+ if (Utilities.IS_RUNNING_IN_TEST_HARNESS) {
+ Log.d(TestProtocol.NO_SCROLL_END_WIDGETS,
+ "onInitializeAccessibilityNodeInfo, scrollable: " + info.isScrollable());
+ }
+ }
}
\ No newline at end of file
diff --git a/src/com/android/launcher3/widget/custom/CustomWidgetManager.java b/src/com/android/launcher3/widget/custom/CustomWidgetManager.java
index 2aed936..0b66ec0 100644
--- a/src/com/android/launcher3/widget/custom/CustomWidgetManager.java
+++ b/src/com/android/launcher3/widget/custom/CustomWidgetManager.java
@@ -29,8 +29,8 @@
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherAppWidgetProviderInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
import com.android.launcher3.uioverrides.plugins.PluginManagerWrapper;
import com.android.launcher3.util.MainThreadInitializedObject;
import com.android.launcher3.util.PackageUserKey;
@@ -51,6 +51,7 @@
public static final MainThreadInitializedObject<CustomWidgetManager> INSTANCE =
new MainThreadInitializedObject<>(CustomWidgetManager::new);
+ private final Context mContext;
/**
* auto provider Id is an ever-increasing number that serves as the providerId whenever a new
* custom widget has been connected.
@@ -62,6 +63,7 @@
private Consumer<PackageUserKey> mWidgetRefreshCallback;
private CustomWidgetManager(Context context) {
+ mContext = context;
mPlugins = new SparseArray<>();
mCustomWidgets = new ArrayList<>();
mWidgetsIdMap = new SparseArray<>();
@@ -69,6 +71,10 @@
.addPluginListener(this, CustomWidgetPlugin.class, true);
}
+ public void onDestroy() {
+ PluginManagerWrapper.INSTANCE.get(mContext).removePluginListener(this);
+ }
+
@Override
public void onPluginConnected(CustomWidgetPlugin plugin, Context context) {
mPlugins.put(mAutoProviderId, plugin);
diff --git a/src_plugins/com/android/systemui/plugins/ResourceProvider.java b/src_plugins/com/android/systemui/plugins/ResourceProvider.java
index eaed9e7..d1767a0 100644
--- a/src_plugins/com/android/systemui/plugins/ResourceProvider.java
+++ b/src_plugins/com/android/systemui/plugins/ResourceProvider.java
@@ -44,4 +44,9 @@
* @see android.content.res.Resources#getColor(int)
*/
int getColor(int resId);
+
+ /**
+ * @see android.content.res.Resources#getFloat(int)
+ */
+ float getFloat(int resId);
}
diff --git a/src_shortcuts_overrides/com/android/launcher3/model/WidgetsModel.java b/src_shortcuts_overrides/com/android/launcher3/model/WidgetsModel.java
index 5ebf8d3..9d87788 100644
--- a/src_shortcuts_overrides/com/android/launcher3/model/WidgetsModel.java
+++ b/src_shortcuts_overrides/com/android/launcher3/model/WidgetsModel.java
@@ -6,6 +6,7 @@
import static com.android.launcher3.pm.ShortcutConfigActivityInfo.queryList;
import android.appwidget.AppWidgetProviderInfo;
+import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Process;
@@ -23,6 +24,7 @@
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.icons.ComponentWithLabelAndIcon;
import com.android.launcher3.icons.IconCache;
+import com.android.launcher3.model.data.PackageItemInfo;
import com.android.launcher3.pm.ShortcutConfigActivityInfo;
import com.android.launcher3.util.MultiHashMap;
import com.android.launcher3.util.PackageUserKey;
@@ -115,7 +117,7 @@
}
setWidgetsAndShortcuts(widgetsAndShortcuts, app, packageUser);
} catch (Exception e) {
- if (!FeatureFlags.IS_DOGFOOD_BUILD && Utilities.isBinderSizeError(e)) {
+ if (!FeatureFlags.IS_STUDIO_BUILD && Utilities.isBinderSizeError(e)) {
// the returned value may be incomplete and will not be refreshed until the next
// time Launcher starts.
// TODO: after figuring out a repro step, introduce a dirty bit to check when
@@ -243,4 +245,20 @@
}
}
}
+
+ public WidgetItem getWidgetProviderInfoByProviderName(
+ ComponentName providerName) {
+ ArrayList<WidgetItem> widgetsList = mWidgetsList.get(
+ new PackageItemInfo(providerName.getPackageName()));
+ if (widgetsList == null) {
+ return null;
+ }
+
+ for (WidgetItem item : widgetsList) {
+ if (item.componentName.equals(providerName)) {
+ return item;
+ }
+ }
+ return null;
+ }
}
\ No newline at end of file
diff --git a/src_ui_overrides/com/android/launcher3/uioverrides/DisplayRotationListener.java b/src_ui_overrides/com/android/launcher3/uioverrides/DisplayRotationListener.java
deleted file mode 100644
index b1a67e9..0000000
--- a/src_ui_overrides/com/android/launcher3/uioverrides/DisplayRotationListener.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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.launcher3.uioverrides;
-
-import android.content.Context;
-import android.view.OrientationEventListener;
-
-/**
- * Utility class for listening for rotation changes
- */
-public class DisplayRotationListener extends OrientationEventListener {
-
- private final Runnable mCallback;
-
- public DisplayRotationListener(Context context, Runnable callback) {
- super(context);
- mCallback = callback;
- }
-
- @Override
- public void onOrientationChanged(int i) {
- mCallback.run();
- }
-}
diff --git a/src/com/android/launcher3/views/Transposable.java b/src_ui_overrides/com/android/launcher3/uioverrides/PreviewSurfaceRenderer.java
similarity index 60%
copy from src/com/android/launcher3/views/Transposable.java
copy to src_ui_overrides/com/android/launcher3/uioverrides/PreviewSurfaceRenderer.java
index 929c1aa..4913cad 100644
--- a/src/com/android/launcher3/views/Transposable.java
+++ b/src_ui_overrides/com/android/launcher3/uioverrides/PreviewSurfaceRenderer.java
@@ -1,5 +1,5 @@
-/**
- * Copyright (C) 2019 The Android Open Source Project
+/*
+ * 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.
@@ -13,14 +13,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package com.android.launcher3.views;
-import com.android.launcher3.graphics.RotationMode;
+package com.android.launcher3.uioverrides;
-/**
- * Indicates that a view can be transposed.
- */
-public interface Transposable {
+import android.content.Context;
+import android.os.Bundle;
- RotationMode getRotationMode();
+/** Render preview using surface view. */
+public class PreviewSurfaceRenderer {
+
+ /** Handle a received surface view request. */
+ public static void render(Context context, Bundle bundle) { }
}
diff --git a/src_ui_overrides/com/android/launcher3/uioverrides/states/AllAppsState.java b/src_ui_overrides/com/android/launcher3/uioverrides/states/AllAppsState.java
index a56801f..313ea05 100644
--- a/src_ui_overrides/com/android/launcher3/uioverrides/states/AllAppsState.java
+++ b/src_ui_overrides/com/android/launcher3/uioverrides/states/AllAppsState.java
@@ -15,8 +15,8 @@
*/
package com.android.launcher3.uioverrides.states;
-import static com.android.launcher3.allapps.DiscoveryBounce.HOME_BOUNCE_SEEN;
import static com.android.launcher3.anim.Interpolators.DEACCEL_2;
+import static com.android.launcher3.util.OnboardingPrefs.HOME_BOUNCE_SEEN;
import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.Launcher;
diff --git a/tests/Android.mk b/tests/Android.mk
index d1a6c06..a9fff8e 100644
--- a/tests/Android.mk
+++ b/tests/Android.mk
@@ -51,7 +51,7 @@
androidx.test.rules \
androidx.test.uiautomator_uiautomator \
mockito-target-minus-junit4 \
- launcher-log-protos-lite
+ launcher_log_protos_lite
ifneq (,$(wildcard frameworks/base))
LOCAL_PRIVATE_PLATFORM_APIS := true
diff --git a/tests/src/com/android/launcher3/allapps/search/DefaultAppSearchAlgorithmTest.java b/tests/src/com/android/launcher3/allapps/search/DefaultAppSearchAlgorithmTest.java
index 293b04a..bdf01f3 100644
--- a/tests/src/com/android/launcher3/allapps/search/DefaultAppSearchAlgorithmTest.java
+++ b/tests/src/com/android/launcher3/allapps/search/DefaultAppSearchAlgorithmTest.java
@@ -20,14 +20,14 @@
import android.content.ComponentName;
-import com.android.launcher3.AppInfo;
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.launcher3.model.data.AppInfo;
import org.junit.Test;
import org.junit.runner.RunWith;
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
/**
* Unit tests for {@link DefaultAppSearchAlgorithm}
*/
diff --git a/tests/src/com/android/launcher3/touch/SingleAxisSwipeDetectorTest.java b/tests/src/com/android/launcher3/touch/SingleAxisSwipeDetectorTest.java
index b0ece77..472e1a1 100644
--- a/tests/src/com/android/launcher3/touch/SingleAxisSwipeDetectorTest.java
+++ b/tests/src/com/android/launcher3/touch/SingleAxisSwipeDetectorTest.java
@@ -89,7 +89,7 @@
mGenerator.put(0, 100, 100);
mGenerator.move(0, 100, 100 - mTouchSlop);
// TODO: actually calculate the following parameters and do exact value checks.
- verify(mMockListener).onDragStart(anyBoolean());
+ verify(mMockListener).onDragStart(anyBoolean(), anyFloat());
}
@Test
@@ -99,7 +99,7 @@
mGenerator.put(0, 100, 100);
mGenerator.move(0, 100, 100 + mTouchSlop);
// TODO: actually calculate the following parameters and do exact value checks.
- verify(mMockListener).onDragStart(anyBoolean());
+ verify(mMockListener).onDragStart(anyBoolean(), anyFloat());
}
@Test
@@ -107,7 +107,7 @@
mGenerator.put(0, 100, 100);
mGenerator.move(0, 100 + mTouchSlop, 100);
// TODO: actually calculate the following parameters and do exact value checks.
- verify(mMockListener, never()).onDragStart(anyBoolean());
+ verify(mMockListener, never()).onDragStart(anyBoolean(), anyFloat());
}
@Test
@@ -118,7 +118,7 @@
mGenerator.put(0, 100, 100);
mGenerator.move(0, 100 + mTouchSlop, 100);
// TODO: actually calculate the following parameters and do exact value checks.
- verify(mMockListener).onDragStart(anyBoolean());
+ verify(mMockListener).onDragStart(anyBoolean(), anyFloat());
}
@Test
@@ -129,7 +129,7 @@
mGenerator.put(0, 100, 100);
mGenerator.move(0, 100 - mTouchSlop, 100);
// TODO: actually calculate the following parameters and do exact value checks.
- verify(mMockListener).onDragStart(anyBoolean());
+ verify(mMockListener).onDragStart(anyBoolean(), anyFloat());
}
@Test
@@ -140,7 +140,7 @@
mGenerator.put(0, 100, 100);
mGenerator.move(0, 100 - mTouchSlop, 100);
// TODO: actually calculate the following parameters and do exact value checks.
- verify(mMockListener).onDragStart(anyBoolean());
+ verify(mMockListener).onDragStart(anyBoolean(), anyFloat());
}
@Test
@@ -151,7 +151,7 @@
mGenerator.put(0, 100, 100);
mGenerator.move(0, 100 + mTouchSlop, 100);
// TODO: actually calculate the following parameters and do exact value checks.
- verify(mMockListener).onDragStart(anyBoolean());
+ verify(mMockListener).onDragStart(anyBoolean(), anyFloat());
}
@Test
diff --git a/tests/src/com/android/launcher3/ui/AbstractLauncherUiTest.java b/tests/src/com/android/launcher3/ui/AbstractLauncherUiTest.java
index 4ffc251..a7089fe 100644
--- a/tests/src/com/android/launcher3/ui/AbstractLauncherUiTest.java
+++ b/tests/src/com/android/launcher3/ui/AbstractLauncherUiTest.java
@@ -18,14 +18,12 @@
import static androidx.test.InstrumentationRegistry.getInstrumentation;
import static com.android.launcher3.WorkspaceLayoutManager.FIRST_SCREEN_ID;
-import static com.android.launcher3.tapl.LauncherInstrumentation.ContainerType;
import static com.android.launcher3.ui.TaplTestsLauncher3.getAppPackageName;
import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-import static java.lang.System.exit;
-
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
@@ -35,9 +33,12 @@
import android.content.pm.ActivityInfo;
import android.content.pm.LauncherActivityInfo;
import android.content.pm.LauncherApps;
+import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
+import android.os.Debug;
import android.os.Process;
import android.os.RemoteException;
+import android.os.StrictMode;
import android.util.Log;
import androidx.test.InstrumentationRegistry;
@@ -46,7 +47,6 @@
import androidx.test.uiautomator.UiDevice;
import androidx.test.uiautomator.Until;
-import com.android.launcher3.ItemInfo;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherSettings;
@@ -54,7 +54,9 @@
import com.android.launcher3.LauncherStateManager;
import com.android.launcher3.Utilities;
import com.android.launcher3.model.AppLaunchTracker;
+import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.tapl.LauncherInstrumentation;
+import com.android.launcher3.tapl.LauncherInstrumentation.ContainerType;
import com.android.launcher3.tapl.TestHelpers;
import com.android.launcher3.testcomponent.TestCommandReceiver;
import com.android.launcher3.testing.TestProtocol;
@@ -69,6 +71,7 @@
import com.android.launcher3.util.rule.TestStabilityRule;
import org.junit.After;
+import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.RuleChain;
@@ -97,11 +100,47 @@
public static final long DEFAULT_UI_TIMEOUT = 10000;
private static final String TAG = "AbstractLauncherUiTest";
+ private static String sDetectedActivityLeak;
+ private static boolean sActivityLeakReported;
+ private static final String SYSTEMUI_PACKAGE = "com.android.systemui";
+
protected LooperExecutor mMainThreadExecutor = MAIN_EXECUTOR;
protected final UiDevice mDevice = UiDevice.getInstance(getInstrumentation());
protected final LauncherInstrumentation mLauncher = new LauncherInstrumentation();
protected Context mTargetContext;
protected String mTargetPackage;
+ private int mLauncherPid;
+
+ static {
+ if (TestHelpers.isInLauncherProcess()) {
+ StrictMode.VmPolicy.Builder builder =
+ new StrictMode.VmPolicy.Builder()
+ .detectActivityLeaks()
+ .penaltyLog()
+ .penaltyListener(Runnable::run, violation -> {
+ // Runs in the main thread. We can't dumpheap in the main thread,
+ // so let's just mark the fact that the leak has happened.
+ if (sDetectedActivityLeak == null) {
+ sDetectedActivityLeak = violation.toString();
+ try {
+ Debug.dumpHprofData(
+ getInstrumentation().getTargetContext()
+ .getFilesDir().getPath()
+ + "/ActivityLeakHeapDump.hprof");
+ } catch (Throwable e) {
+ Log.e(TAG, "dumpHprofData failed", e);
+ }
+ }
+ });
+ StrictMode.setVmPolicy(builder.build());
+ }
+ }
+
+ public static void checkDetectedLeaks() {
+ if (sDetectedActivityLeak != null && !sActivityLeakReported) {
+ sActivityLeakReported = true;
+ }
+ }
protected AbstractLauncherUiTest() {
mLauncher.enableCheckEventsForSuccessfulGestures();
@@ -121,6 +160,9 @@
checkLauncherIntegrity(launcher, containerType)));
}
mLauncher.enableDebugTracing();
+ // Avoid double-reporting of Launcher crashes.
+ mLauncher.setOnLauncherCrashed(() -> mLauncherPid = 0);
+ mLauncher.disableSensorRotation();
}
protected final LauncherActivityRule mActivityMonitor = new LauncherActivityRule();
@@ -158,7 +200,7 @@
return TestHelpers.isInLauncherProcess()
? RuleChain.outerRule(ShellCommandRule.setDefaultLauncher())
- .around(inner) :
+ .around(inner) :
inner;
}
@@ -173,19 +215,58 @@
return mDevice;
}
+ private boolean hasSystemUiObject(String resId) {
+ return mDevice.hasObject(By.res(SYSTEMUI_PACKAGE, resId));
+ }
+
@Before
public void setUp() throws Exception {
+ Log.d(TAG, "Before disabling battery defender");
+ mDevice.executeShellCommand("setprop vendor.battery.defender.disable 1");
+ Log.d(TAG, "Before enabling stay awake");
+ mDevice.executeShellCommand("settings put global stay_on_while_plugged_in 3");
+ for (int i = 0; i < 10 && hasSystemUiObject("keyguard_status_view"); ++i) {
+ Log.d(TAG, "Before unlocking the phone");
+ mDevice.executeShellCommand("input keyevent 82");
+ mDevice.waitForIdle();
+ }
+ Assert.assertTrue("Keyguard still visible",
+ mDevice.wait(
+ Until.gone(By.res(SYSTEMUI_PACKAGE, "keyguard_status_view")), 60000));
+ Log.d(TAG, "Keyguard is not visible");
+
+ final String launcherPackageName = mDevice.getLauncherPackageName();
+ try {
+ final Context context = InstrumentationRegistry.getContext();
+ final PackageManager pm = context.getPackageManager();
+ final PackageInfo launcherPackage = pm.getPackageInfo(launcherPackageName, 0);
+
+ if (!launcherPackage.versionName.equals("BuildFromAndroidStudio")) {
+ Assert.assertEquals("Launcher version doesn't match tests version",
+ pm.getPackageInfo(context.getPackageName(), 0).getLongVersionCode(),
+ launcherPackage.getLongVersionCode());
+ }
+ } catch (PackageManager.NameNotFoundException e) {
+ throw new RuntimeException(e);
+ }
+
+ mLauncherPid = 0;
// Disable app tracker
AppLaunchTracker.INSTANCE.initializeForTesting(new AppLaunchTracker());
mTargetContext = InstrumentationRegistry.getTargetContext();
mTargetPackage = mTargetContext.getPackageName();
+ mLauncherPid = mLauncher.getPid();
}
@After
public void verifyLauncherState() {
// Limits UI tests affecting tests running after them.
mLauncher.waitForLauncherInitialized();
+ if (mLauncherPid != 0) {
+ assertEquals("Launcher crashed, pid mismatch:", mLauncherPid, mLauncher.getPid());
+ }
+ checkDetectedLeaks();
}
protected void clearLauncherData() throws IOException, InterruptedException {
@@ -196,6 +277,8 @@
} else {
clearPackageData(mDevice.getLauncherPackageName());
mLauncher.enableDebugTracing();
+ mLauncherPid = mLauncher.getPid();
+ mLauncher.disableSensorRotation();
}
}
@@ -213,7 +296,8 @@
protected void resetLoaderState() {
try {
mMainThreadExecutor.execute(
- () -> LauncherAppState.getInstance(mTargetContext).getModel().forceReload());
+ () -> LauncherAppState.getInstance(
+ mTargetContext).getModel().forceReload());
} catch (Throwable t) {
throw new IllegalArgumentException(t);
}
@@ -227,7 +311,8 @@
ContentResolver resolver = mTargetContext.getContentResolver();
int screenId = FIRST_SCREEN_ID;
// Update the screen id counter for the provider.
- LauncherSettings.Settings.call(resolver, LauncherSettings.Settings.METHOD_NEW_SCREEN_ID);
+ LauncherSettings.Settings.call(resolver,
+ LauncherSettings.Settings.METHOD_NEW_SCREEN_ID);
if (screenId > FIRST_SCREEN_ID) {
screenId = FIRST_SCREEN_ID;
@@ -241,7 +326,8 @@
item.screenId = screenId;
item.onAddToDatabase(writer);
writer.put(LauncherSettings.Favorites._ID, item.id);
- resolver.insert(LauncherSettings.Favorites.CONTENT_URI, writer.getValues(mTargetContext));
+ resolver.insert(LauncherSettings.Favorites.CONTENT_URI,
+ writer.getValues(mTargetContext));
resetLoaderState();
// Launch the home activity
@@ -272,7 +358,8 @@
});
}
- // Cannot be used in TaplTests between a Tapl call injecting a gesture and a tapl call expecting
+ // Cannot be used in TaplTests between a Tapl call injecting a gesture and a tapl call
+ // expecting
// the results of that gesture because the wait can hide flakeness.
protected void waitForState(String message, Supplier<LauncherState> state) {
waitForLauncherCondition(message,
@@ -285,7 +372,8 @@
// Cannot be used in TaplTests after injecting any gesture using Tapl because this can hide
// flakiness.
- protected void waitForLauncherCondition(String message, Function<Launcher, Boolean> condition) {
+ protected void waitForLauncherCondition(String
+ message, Function<Launcher, Boolean> condition) {
waitForLauncherCondition(message, condition, DEFAULT_ACTIVITY_TIMEOUT);
}
@@ -361,7 +449,8 @@
public Intent blockingGetExtraIntent() throws InterruptedException {
Intent intent = blockingGetIntent();
- return intent == null ? null : (Intent) intent.getParcelableExtra(Intent.EXTRA_INTENT);
+ return intent == null ? null : (Intent) intent.getParcelableExtra(
+ Intent.EXTRA_INTENT);
}
}
@@ -388,7 +477,8 @@
if (newTask) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
} else {
- intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK | Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
+ intent.addFlags(
+ Intent.FLAG_ACTIVITY_MULTIPLE_TASK | Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
}
getInstrumentation().getTargetContext().startActivity(intent);
assertTrue("App didn't start: " + selector,
@@ -425,7 +515,8 @@
protected boolean isInState(Supplier<LauncherState> state) {
if (!TestHelpers.isInLauncherProcess()) return true;
- return getFromLauncher(launcher -> launcher.getStateManager().getState() == state.get());
+ return getFromLauncher(
+ launcher -> launcher.getStateManager().getState() == state.get());
}
protected int getAllAppsScroll(Launcher launcher) {
diff --git a/tests/src/com/android/launcher3/ui/PortraitLandscapeRunner.java b/tests/src/com/android/launcher3/ui/PortraitLandscapeRunner.java
index 1a68122..38f50c1 100644
--- a/tests/src/com/android/launcher3/ui/PortraitLandscapeRunner.java
+++ b/tests/src/com/android/launcher3/ui/PortraitLandscapeRunner.java
@@ -56,6 +56,7 @@
private void evaluateInPortrait() throws Throwable {
mTest.mDevice.setOrientationNatural();
mTest.mLauncher.setExpectedRotation(Surface.ROTATION_0);
+ AbstractLauncherUiTest.checkDetectedLeaks();
base.evaluate();
mTest.getDevice().pressHome();
}
@@ -63,6 +64,7 @@
private void evaluateInLandscape() throws Throwable {
mTest.mDevice.setOrientationLeft();
mTest.mLauncher.setExpectedRotation(Surface.ROTATION_90);
+ AbstractLauncherUiTest.checkDetectedLeaks();
base.evaluate();
mTest.getDevice().pressHome();
}
diff --git a/tests/src/com/android/launcher3/ui/TaplTestsLauncher3.java b/tests/src/com/android/launcher3/ui/TaplTestsLauncher3.java
index 54caf1e..de1ada4 100644
--- a/tests/src/com/android/launcher3/ui/TaplTestsLauncher3.java
+++ b/tests/src/com/android/launcher3/ui/TaplTestsLauncher3.java
@@ -40,9 +40,7 @@
import com.android.launcher3.widget.WidgetsFullSheet;
import com.android.launcher3.widget.WidgetsRecyclerView;
-import org.junit.After;
import org.junit.Before;
-import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -51,21 +49,10 @@
public class TaplTestsLauncher3 extends AbstractLauncherUiTest {
private static final String APP_NAME = "LauncherTestApp";
- private int mLauncherPid;
-
@Before
public void setUp() throws Exception {
- mLauncherPid = 0;
super.setUp();
initialize(this);
- mLauncherPid = mLauncher.getPid();
- }
-
- @After
- public void teardown() {
- if (mLauncherPid != 0) {
- assertEquals("Launcher crashed, pid mismatch:", mLauncherPid, mLauncher.getPid());
- }
}
public static void initialize(AbstractLauncherUiTest test) throws Exception {
@@ -77,6 +64,7 @@
test.waitForResumed("Launcher internal state is still Background");
// Check that we switched to home.
test.mLauncher.getWorkspace();
+ AbstractLauncherUiTest.checkDetectedLeaks();
}
// Please don't add negative test cases for methods that fail only after a long wait.
@@ -122,7 +110,6 @@
}
@Test
- @Ignore
public void testPressHomeOnAllAppsContextMenu() throws Exception {
final AllApps allApps = mLauncher.getWorkspace().switchToAllApps();
allApps.freeze();
@@ -327,7 +314,7 @@
switchToAllApps();
allApps.freeze();
try {
- allApps.getAppIcon(APP_NAME).dragToWorkspace();
+ allApps.getAppIcon(APP_NAME).dragToWorkspace(false);
mLauncher.getWorkspace().getWorkspaceAppIcon(APP_NAME).launch(getAppPackageName());
} finally {
allApps.unfreeze();
@@ -355,7 +342,7 @@
getMenuItem(0);
final String shortcutName = menuItem.getText();
- menuItem.dragToWorkspace();
+ menuItem.dragToWorkspace(false);
mLauncher.getWorkspace().getWorkspaceAppIcon(shortcutName).launch(getAppPackageName());
} finally {
allApps.unfreeze();
diff --git a/tests/src/com/android/launcher3/ui/WorkTabTest.java b/tests/src/com/android/launcher3/ui/WorkTabTest.java
index d9edc35..8d571ff 100644
--- a/tests/src/com/android/launcher3/ui/WorkTabTest.java
+++ b/tests/src/com/android/launcher3/ui/WorkTabTest.java
@@ -16,23 +16,42 @@
package com.android.launcher3.ui;
import static com.android.launcher3.LauncherState.ALL_APPS;
+import static com.android.launcher3.LauncherState.NORMAL;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
+import android.os.Process;
+import android.os.UserHandle;
+import android.os.UserManager;
+import android.widget.TextView;
+
import androidx.test.filters.LargeTest;
import androidx.test.runner.AndroidJUnit4;
+import com.android.launcher3.R;
+import com.android.launcher3.allapps.AllAppsContainerView;
+import com.android.launcher3.allapps.AllAppsPagedView;
+import com.android.launcher3.allapps.WorkModeSwitch;
+import com.android.launcher3.dragndrop.DragLayer;
+import com.android.launcher3.views.WorkEduView;
+
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import java.util.List;
+import java.util.Objects;
+
@LargeTest
@RunWith(AndroidJUnit4.class)
public class WorkTabTest extends AbstractLauncherUiTest {
private int mProfileUserId;
+ private static final int WORK_PAGE = AllAppsContainerView.AdapterHolder.WORK;
+
@Before
public void createWorkProfile() throws Exception {
String output =
@@ -54,14 +73,119 @@
@Test
public void workTabExists() {
mDevice.pressHome();
- waitForLauncherCondition("Launcher didn't start", launcher -> launcher != null);
+ waitForLauncherCondition("Launcher didn't start", Objects::nonNull);
+ executeOnLauncher(launcher -> launcher.getStateManager().goToState(ALL_APPS));
+ waitForLauncherCondition("Personal tab is missing",
+ launcher -> launcher.getAppsView().isPersonalTabVisible(), 60000);
+ waitForLauncherCondition("Work tab is missing",
+ launcher -> launcher.getAppsView().isWorkTabVisible(), 60000);
+ }
+
+ @Test
+ public void toggleWorks() {
+ mDevice.pressHome();
+ waitForLauncherCondition("Launcher didn't start", Objects::nonNull);
+ executeOnLauncher(launcher -> launcher.getStateManager().goToState(ALL_APPS));
+ waitForState("Launcher internal state didn't switch to All Apps", () -> ALL_APPS);
+ getOnceNotNull("Apps view did not bind",
+ launcher -> launcher.getAppsView().getWorkModeSwitch(), 60000);
+
+ UserManager userManager = getFromLauncher(l -> l.getSystemService(UserManager.class));
+ assertEquals(2, userManager.getUserProfiles().size());
+ UserHandle workProfile = getFromLauncher(l -> {
+ UserHandle myHandle = Process.myUserHandle();
+ List<UserHandle> userProfiles = userManager.getUserProfiles();
+ return userProfiles.get(0) == myHandle ? userProfiles.get(1) : userProfiles.get(0);
+ });
+
+ waitForLauncherCondition("work profile can't be turned off",
+ l -> userManager.requestQuietModeEnabled(true, workProfile));
+
+ assertTrue(userManager.isQuietModeEnabled(workProfile));
+ executeOnLauncher(launcher -> {
+ WorkModeSwitch wf = launcher.getAppsView().getWorkModeSwitch();
+ ((AllAppsPagedView) launcher.getAppsView().getContentView()).snapToPageImmediately(
+ AllAppsContainerView.AdapterHolder.WORK);
+ wf.toggle();
+ });
+ waitForLauncherCondition("Work toggle did not work",
+ l -> l.getSystemService(UserManager.class).isQuietModeEnabled(workProfile));
+ }
+
+ @Test
+ public void testWorkEduFlow() {
+ mDevice.pressHome();
+ waitForLauncherCondition("Launcher didn't start", Objects::nonNull);
+ executeOnLauncher(launcher -> launcher.getSharedPrefs().edit().remove(
+ WorkEduView.KEY_WORK_EDU_STEP).remove(
+ WorkEduView.KEY_LEGACY_WORK_EDU_SEEN).commit());
+
+ waitForLauncherCondition("Work tab not setup",
+ launcher -> launcher.getAppsView().getContentView() instanceof AllAppsPagedView,
+ 60000);
+
+ executeOnLauncher(launcher -> launcher.getStateManager().goToState(ALL_APPS));
+ WorkEduView workEduView = getEduView();
+ // verify personal app edu is seen first and click "next"
+ executeOnLauncher(l -> {
+ assertEquals(((TextView) workEduView.findViewById(R.id.content_text)).getText(),
+ l.getResources().getString(R.string.work_profile_edu_personal_apps));
+ workEduView.findViewById(R.id.proceed).callOnClick();
+ });
+ // verify work edu is seen next
+ waitForLauncherCondition("Launcher did not show the next edu screen", l ->
+ ((AllAppsPagedView) l.getAppsView().getContentView()).getCurrentPage() == WORK_PAGE
+ && ((TextView) workEduView.findViewById(
+ R.id.content_text)).getText().equals(
+ l.getResources().getString(R.string.work_profile_edu_work_apps)));
+ }
+
+ @Test
+ public void testWorkEduIntermittent() {
+ mDevice.pressHome();
+ waitForLauncherCondition("Launcher didn't start", Objects::nonNull);
+ executeOnLauncher(launcher -> launcher.getSharedPrefs().edit().remove(
+ WorkEduView.KEY_WORK_EDU_STEP).remove(
+ WorkEduView.KEY_LEGACY_WORK_EDU_SEEN).commit());
+
+
+ waitForLauncherCondition("Work tab not setup",
+ launcher -> launcher.getAppsView().getContentView() instanceof AllAppsPagedView,
+ 60000);
executeOnLauncher(launcher -> launcher.getStateManager().goToState(ALL_APPS));
- /*
- assertTrue("Personal tab is missing", waitForLauncherCondition(
- launcher -> launcher.getAppsView().isPersonalTabVisible()));
- assertTrue("Work tab is missing", waitForLauncherCondition(
- launcher -> launcher.getAppsView().isWorkTabVisible()));
- */
+ // verify personal app edu is seen
+ getEduView();
+
+ // dismiss personal edu
+ mDevice.pressHome();
+ waitForState("Launcher did not go home", () -> NORMAL);
+
+ // open work tab
+ executeOnLauncher(launcher -> launcher.getStateManager().goToState(ALL_APPS));
+ waitForState("Launcher did not switch to all apps", () -> ALL_APPS);
+ executeOnLauncher(launcher -> {
+ AllAppsPagedView pagedView = (AllAppsPagedView) launcher.getAppsView().getContentView();
+ pagedView.setCurrentPage(WORK_PAGE);
+ });
+
+ WorkEduView workEduView = getEduView();
+
+ // verify work tab edu is shown
+ waitForLauncherCondition("Launcher did not show the next edu screen",
+ l -> ((TextView) workEduView.findViewById(R.id.content_text)).getText().equals(
+ l.getResources().getString(R.string.work_profile_edu_work_apps)));
}
+
+
+ private WorkEduView getEduView() {
+ waitForLauncherCondition("Edu did not show", l -> {
+ DragLayer dragLayer = l.getDragLayer();
+ return dragLayer.getChildCount() > 0 && dragLayer.getChildAt(
+ dragLayer.getChildCount() - 1) instanceof WorkEduView;
+ });
+ return getFromLauncher(launcher -> (WorkEduView) launcher.getDragLayer().getChildAt(
+ launcher.getDragLayer().getChildCount() - 1));
+ }
+
}
\ No newline at end of file
diff --git a/tests/src/com/android/launcher3/ui/widget/AddConfigWidgetTest.java b/tests/src/com/android/launcher3/ui/widget/AddConfigWidgetTest.java
index 4b1a067..0a6579a 100644
--- a/tests/src/com/android/launcher3/ui/widget/AddConfigWidgetTest.java
+++ b/tests/src/com/android/launcher3/ui/widget/AddConfigWidgetTest.java
@@ -28,10 +28,10 @@
import androidx.test.filters.LargeTest;
import androidx.test.runner.AndroidJUnit4;
-import com.android.launcher3.ItemInfo;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherAppWidgetProviderInfo;
import com.android.launcher3.Workspace;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
import com.android.launcher3.tapl.Widgets;
import com.android.launcher3.testcomponent.WidgetConfigActivity;
import com.android.launcher3.ui.AbstractLauncherUiTest;
@@ -41,7 +41,6 @@
import com.android.launcher3.util.rule.ShellCommandRule;
import org.junit.Before;
-import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -71,14 +70,12 @@
@Test
@PortraitLandscape
- @Ignore // b/148867106
public void testWidgetConfig() throws Throwable {
runTest(true);
}
@Test
@PortraitLandscape
- @Ignore // b/148867106
public void testConfigCancelled() throws Throwable {
runTest(false);
}
@@ -97,7 +94,7 @@
WidgetConfigStartupMonitor monitor = new WidgetConfigStartupMonitor();
widgets.
getWidget(mWidgetInfo.getLabel(mTargetContext.getPackageManager())).
- dragToWorkspace();
+ dragToWorkspace(true);
// Widget id for which the config activity was opened
mWidgetId = monitor.getWidgetId();
diff --git a/tests/src/com/android/launcher3/ui/widget/AddWidgetTest.java b/tests/src/com/android/launcher3/ui/widget/AddWidgetTest.java
index f9d1d93..5e26aa6 100644
--- a/tests/src/com/android/launcher3/ui/widget/AddWidgetTest.java
+++ b/tests/src/com/android/launcher3/ui/widget/AddWidgetTest.java
@@ -23,8 +23,8 @@
import androidx.test.filters.LargeTest;
import androidx.test.runner.AndroidJUnit4;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherAppWidgetProviderInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
import com.android.launcher3.tapl.Widget;
import com.android.launcher3.ui.AbstractLauncherUiTest;
import com.android.launcher3.ui.TestViewHelpers;
@@ -57,7 +57,7 @@
getWorkspace().
openAllWidgets().
getWidget(widgetInfo.getLabel(mTargetContext.getPackageManager())).
- dragToWorkspace();
+ dragToWorkspace(false);
assertTrue(mActivityMonitor.itemExists(
(info, view) -> info instanceof LauncherAppWidgetInfo &&
@@ -83,7 +83,7 @@
mDevice.pressHome();
mLauncher.getWorkspace().openAllWidgets()
.getWidget("com.android.launcher3.testcomponent.CustomShortcutConfigActivity")
- .dragToWorkspace();
+ .dragToWorkspace(false);
mLauncher.getWorkspace().getWorkspaceAppIcon("Shortcut")
.launch(getAppPackageName());
}
diff --git a/tests/src/com/android/launcher3/ui/widget/BindWidgetTest.java b/tests/src/com/android/launcher3/ui/widget/BindWidgetTest.java
index 21a654f..62ce085 100644
--- a/tests/src/com/android/launcher3/ui/widget/BindWidgetTest.java
+++ b/tests/src/com/android/launcher3/ui/widget/BindWidgetTest.java
@@ -21,6 +21,7 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import android.appwidget.AppWidgetHost;
@@ -33,15 +34,18 @@
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
+import android.widget.RemoteViews;
import androidx.test.filters.LargeTest;
import androidx.test.runner.AndroidJUnit4;
import com.android.launcher3.LauncherAppWidgetHost;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherAppWidgetProviderInfo;
import com.android.launcher3.LauncherSettings;
+import com.android.launcher3.R;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
import com.android.launcher3.pm.InstallSessionHelper;
+import com.android.launcher3.tapl.Widget;
import com.android.launcher3.tapl.Workspace;
import com.android.launcher3.ui.AbstractLauncherUiTest;
import com.android.launcher3.ui.TestViewHelpers;
@@ -86,7 +90,8 @@
// Clear all existing data
LauncherSettings.Settings.call(mResolver, LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB);
- LauncherSettings.Settings.call(mResolver, LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG);
+ LauncherSettings.Settings.call(mResolver,
+ LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG);
}
@After
@@ -172,6 +177,26 @@
assertNotNull(AppWidgetManager.getInstance(mTargetContext)
.getAppWidgetInfo(mCursor.getInt(mCursor.getColumnIndex(
LauncherSettings.Favorites.APPWIDGET_ID))));
+
+ // send OPTION_APPWIDGET_RESTORE_COMPLETED
+ int appWidgetId = mCursor.getInt(
+ mCursor.getColumnIndex(LauncherSettings.Favorites.APPWIDGET_ID));
+ AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mTargetContext);
+
+ Bundle b = new Bundle();
+ b.putBoolean(WidgetManagerHelper.WIDGET_OPTION_RESTORE_COMPLETED, true);
+ RemoteViews remoteViews = new RemoteViews(mTargetPackage, R.layout.appwidget_not_ready);
+ appWidgetManager.updateAppWidgetOptions(appWidgetId, b);
+ appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
+
+
+ // verify changes are reflected
+ waitForLauncherCondition("App widget options did not update",
+ l -> appWidgetManager.getAppWidgetOptions(appWidgetId).getBoolean(
+ WidgetManagerHelper.WIDGET_OPTION_RESTORE_COMPLETED));
+ executeOnLauncher(l -> l.getAppWidgetHost().startListening());
+ verifyWidgetPresent(info);
+ assertNull(mLauncher.getWorkspace().tryGetPendingWidget(DEFAULT_UI_TIMEOUT));
}
@Test
@@ -243,17 +268,22 @@
}
private void verifyWidgetPresent(LauncherAppWidgetProviderInfo info) {
+ final Widget widget = mLauncher.getWorkspace().tryGetWidget(info.label, DEFAULT_UI_TIMEOUT);
+ if (widget == null) mLauncher.dumpViewHierarchy(); // b/152645831
assertTrue("Widget is not present",
- mLauncher.getWorkspace().tryGetWidget(info.label, DEFAULT_UI_TIMEOUT) != null);
+ widget != null);
}
private void verifyPendingWidgetPresent() {
+ final Widget widget = mLauncher.getWorkspace().tryGetPendingWidget(DEFAULT_UI_TIMEOUT);
+ if (widget == null) mLauncher.dumpViewHierarchy(); // b/152645831
assertTrue("Pending widget is not present",
- mLauncher.getWorkspace().tryGetPendingWidget(DEFAULT_UI_TIMEOUT) != null);
+ widget != null);
}
/**
* Creates a LauncherAppWidgetInfo corresponding to {@param info}
+ *
* @param bindWidget if true the info is bound and a valid widgetId is assigned to
* the LauncherAppWidgetInfo
*/
@@ -306,7 +336,7 @@
.keySet().forEach(packageUserKey -> packages.add(packageUserKey.mPackageName));
return packages;
});
- while(true) {
+ while (true) {
try {
mTargetContext.getPackageManager().getPackageInfo(
pkg, PackageManager.GET_UNINSTALLED_PACKAGES);
@@ -316,7 +346,7 @@
}
}
pkg = invalidPackage + count;
- count ++;
+ count++;
}
LauncherAppWidgetInfo item = new LauncherAppWidgetInfo(10,
new ComponentName(pkg, "com.test.widgetprovider"));
diff --git a/tests/src/com/android/launcher3/ui/widget/RequestPinItemTest.java b/tests/src/com/android/launcher3/ui/widget/RequestPinItemTest.java
index 0246f95..0e43d81 100644
--- a/tests/src/com/android/launcher3/ui/widget/RequestPinItemTest.java
+++ b/tests/src/com/android/launcher3/ui/widget/RequestPinItemTest.java
@@ -29,12 +29,12 @@
import androidx.test.filters.LargeTest;
import androidx.test.runner.AndroidJUnit4;
-import com.android.launcher3.ItemInfo;
-import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.Utilities;
import com.android.launcher3.Workspace.ItemOperator;
-import com.android.launcher3.WorkspaceItemInfo;
+import com.android.launcher3.model.data.ItemInfo;
+import com.android.launcher3.model.data.LauncherAppWidgetInfo;
+import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.shortcuts.ShortcutKey;
import com.android.launcher3.tapl.AddToHomeScreenPrompt;
import com.android.launcher3.testcomponent.AppWidgetNoConfig;
diff --git a/tests/src/com/android/launcher3/util/rule/FailureInvestigator.java b/tests/src/com/android/launcher3/util/rule/FailureInvestigator.java
index 5880eb6..e4f520f 100644
--- a/tests/src/com/android/launcher3/util/rule/FailureInvestigator.java
+++ b/tests/src/com/android/launcher3/util/rule/FailureInvestigator.java
@@ -102,10 +102,15 @@
logSinceBoot =
UiDevice.getInstance(getInstrumentation())
.executeShellCommand("logcat -d -t " + systemBootTime.replace(" ", ""));
- } catch (IOException e) {
+ } catch (IOException | OutOfMemoryError e) {
return 0;
}
+ if (matches("android\\:\\:uirenderer\\:\\:renderthread\\:\\:EglManager\\:\\:swapBuffers",
+ logSinceBoot)) {
+ return 148529608;
+ }
+
for (ExceptionMatch exceptionMatch : EXCEPTION_MATCHES) {
if (matches(exceptionMatch.exceptionPattern, exception)) {
for (LogcatMatch logcatMatch : exceptionMatch.logcatMatches) {
diff --git a/tests/src/com/android/launcher3/util/rule/FailureWatcher.java b/tests/src/com/android/launcher3/util/rule/FailureWatcher.java
index 02d07bb..cdda0f0 100644
--- a/tests/src/com/android/launcher3/util/rule/FailureWatcher.java
+++ b/tests/src/com/android/launcher3/util/rule/FailureWatcher.java
@@ -8,7 +8,6 @@
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
-import org.junit.runners.model.Statement;
import java.io.ByteArrayOutputStream;
import java.io.File;
@@ -16,7 +15,6 @@
public class FailureWatcher extends TestWatcher {
private static final String TAG = "FailureWatcher";
- private static boolean sHadFailedTestDeinitialization;
final private UiDevice mDevice;
public FailureWatcher(UiDevice device) {
@@ -62,35 +60,4 @@
device.takeScreenshot(new File(pathname));
}
-
- @Override
- public Statement apply(Statement base, Description description) {
- return new Statement() {
-
- @Override
- public void evaluate() throws Throwable {
- if (sHadFailedTestDeinitialization) {
- Log.d(TAG, "Skipping due to a recent test deinitialization failure: " +
- description.getDisplayName());
- return;
- }
-
- try {
- base.evaluate();
- } catch (Throwable e) {
- final String stackTrace = Log.getStackTraceString(e);
- if (!stackTrace.contains(
- "androidx.test.internal.runner.junit4.statement.RunBefores.evaluate")) {
- // Test failed to deinitialize. Since the global state is probably
- // corrupted, won't execute other tests.
- Log.d(TAG,
- "Detected an exception from test finalizer, will skip further "
- + "tests: " + stackTrace);
- sHadFailedTestDeinitialization = true;
- }
- throw e;
- }
- }
- };
- }
}
diff --git a/tests/src/com/android/launcher3/util/rule/SimpleActivityRule.java b/tests/src/com/android/launcher3/util/rule/SimpleActivityRule.java
index 33a6cf9..1dbba6a 100644
--- a/tests/src/com/android/launcher3/util/rule/SimpleActivityRule.java
+++ b/tests/src/com/android/launcher3/util/rule/SimpleActivityRule.java
@@ -64,6 +64,7 @@
mBase.evaluate();
} finally {
app.unregisterActivityLifecycleCallbacks(this);
+ mActivity = null;
}
}
diff --git a/tests/tapl/com/android/launcher3/tapl/AddToHomeScreenPrompt.java b/tests/tapl/com/android/launcher3/tapl/AddToHomeScreenPrompt.java
index afb50e0..5daac39 100644
--- a/tests/tapl/com/android/launcher3/tapl/AddToHomeScreenPrompt.java
+++ b/tests/tapl/com/android/launcher3/tapl/AddToHomeScreenPrompt.java
@@ -21,6 +21,8 @@
import androidx.test.uiautomator.By;
import androidx.test.uiautomator.UiObject2;
+import com.android.launcher3.testing.TestProtocol;
+
import java.util.regex.Pattern;
public class AddToHomeScreenPrompt {
@@ -38,6 +40,16 @@
public void addAutomatically() {
try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck()) {
+ if (mLauncher.getNavigationModel()
+ != LauncherInstrumentation.NavigationModel.THREE_BUTTON) {
+ if (!mLauncher.isLauncher3()) {
+ mLauncher.expectEvent(
+ TestProtocol.SEQUENCE_TIS,
+ LauncherInstrumentation.EVENT_TOUCH_DOWN_TIS);
+ mLauncher.expectEvent(
+ TestProtocol.SEQUENCE_TIS, LauncherInstrumentation.EVENT_TOUCH_UP_TIS);
+ }
+ }
mLauncher.waitForObjectInContainer(
mWidgetCell.getParent().getParent().getParent().getParent(),
By.text(ADD_AUTOMATICALLY)).click();
diff --git a/tests/tapl/com/android/launcher3/tapl/AllApps.java b/tests/tapl/com/android/launcher3/tapl/AllApps.java
index 4a2d699..808be66 100644
--- a/tests/tapl/com/android/launcher3/tapl/AllApps.java
+++ b/tests/tapl/com/android/launcher3/tapl/AllApps.java
@@ -43,7 +43,7 @@
AllApps(LauncherInstrumentation launcher) {
super(launcher);
final UiObject2 allAppsContainer = verifyActiveContainer();
- mHeight = allAppsContainer.getVisibleBounds().height();
+ mHeight = mLauncher.getVisibleBounds(allAppsContainer).height();
final UiObject2 appListRecycler = mLauncher.waitForObjectInContainer(allAppsContainer,
"apps_list_view");
// Wait for the recycler to populate.
@@ -66,7 +66,7 @@
LauncherInstrumentation.log("hasClickableIcon: icon not visible");
return false;
}
- final Rect iconBounds = icon.getVisibleBounds();
+ final Rect iconBounds = mLauncher.getVisibleBounds(icon);
LauncherInstrumentation.log("hasClickableIcon: icon bounds: " + iconBounds);
if (iconBounds.height() < mIconHeight / 2) {
LauncherInstrumentation.log("hasClickableIcon: icon has insufficient height");
@@ -86,7 +86,7 @@
private boolean iconCenterInSearchBox(UiObject2 allAppsContainer, UiObject2 icon) {
final Point iconCenter = icon.getVisibleCenter();
- return getSearchBox(allAppsContainer).getVisibleBounds().contains(
+ return mLauncher.getVisibleBounds(getSearchBox(allAppsContainer)).contains(
iconCenter.x, iconCenter.y);
}
@@ -125,11 +125,11 @@
mLauncher.getObjectsInContainer(allAppsContainer, "icon")
.stream()
.filter(icon ->
- icon.getVisibleBounds().bottom
+ mLauncher.getVisibleBounds(icon).bottom
<= displayBottom)
.collect(Collectors.toList()),
- searchBox.getVisibleBounds().bottom
- - allAppsContainer.getVisibleBounds().top);
+ mLauncher.getVisibleBounds(searchBox).bottom
+ - mLauncher.getVisibleBounds(allAppsContainer).top);
final int newScroll = getAllAppsScroll();
mLauncher.assertTrue(
"Scrolled in a wrong direction in AllApps: from " + scroll + " to "
@@ -166,7 +166,8 @@
final UiObject2 searchBox = getSearchBox(allAppsContainer);
int attempts = 0;
- final Rect margins = new Rect(0, searchBox.getVisibleBounds().bottom + 1, 0, 5);
+ final Rect margins =
+ new Rect(0, mLauncher.getVisibleBounds(searchBox).bottom + 1, 0, 5);
for (int scroll = getAllAppsScroll();
scroll != 0;
diff --git a/tests/tapl/com/android/launcher3/tapl/AppIcon.java b/tests/tapl/com/android/launcher3/tapl/AppIcon.java
index 3f814fd..bdfd563 100644
--- a/tests/tapl/com/android/launcher3/tapl/AppIcon.java
+++ b/tests/tapl/com/android/launcher3/tapl/AppIcon.java
@@ -22,6 +22,8 @@
import androidx.test.uiautomator.BySelector;
import androidx.test.uiautomator.UiObject2;
+import com.android.launcher3.testing.TestProtocol;
+
import java.util.regex.Pattern;
/**
@@ -30,6 +32,7 @@
public final class AppIcon extends Launchable {
private static final Pattern START_EVENT = Pattern.compile("start:");
+ private static final Pattern LONG_CLICK_EVENT = Pattern.compile("onAllAppsItemLongClick");
AppIcon(LauncherInstrumentation launcher, UiObject2 icon) {
super(launcher, icon);
@@ -45,17 +48,22 @@
public AppIconMenu openMenu() {
try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck()) {
return new AppIconMenu(mLauncher, mLauncher.clickAndGet(
- mObject, "deep_shortcuts_container"));
+ mObject, "deep_shortcuts_container", LONG_CLICK_EVENT));
}
}
@Override
+ protected void addExpectedEventsForLongClick() {
+ mLauncher.expectEvent(TestProtocol.SEQUENCE_MAIN, LONG_CLICK_EVENT);
+ }
+
+ @Override
protected String getLongPressIndicator() {
return "deep_shortcuts_container";
}
@Override
protected void expectActivityStartEvents() {
- mLauncher.expectEvent(START_EVENT);
+ mLauncher.expectEvent(TestProtocol.SEQUENCE_MAIN, START_EVENT);
}
}
diff --git a/tests/tapl/com/android/launcher3/tapl/AppIconMenuItem.java b/tests/tapl/com/android/launcher3/tapl/AppIconMenuItem.java
index fadfd9f..37a7b91 100644
--- a/tests/tapl/com/android/launcher3/tapl/AppIconMenuItem.java
+++ b/tests/tapl/com/android/launcher3/tapl/AppIconMenuItem.java
@@ -18,6 +18,8 @@
import androidx.test.uiautomator.UiObject2;
+import com.android.launcher3.testing.TestProtocol;
+
import java.util.regex.Pattern;
/**
@@ -39,12 +41,16 @@
}
@Override
+ protected void addExpectedEventsForLongClick() {
+ }
+
+ @Override
protected String getLongPressIndicator() {
return "drop_target_bar";
}
@Override
protected void expectActivityStartEvents() {
- mLauncher.expectEvent(START_SHORTCUT_EVENT);
+ mLauncher.expectEvent(TestProtocol.SEQUENCE_MAIN, START_SHORTCUT_EVENT);
}
}
diff --git a/tests/tapl/com/android/launcher3/tapl/Background.java b/tests/tapl/com/android/launcher3/tapl/Background.java
index 9f29a1a..80b8e89 100644
--- a/tests/tapl/com/android/launcher3/tapl/Background.java
+++ b/tests/tapl/com/android/launcher3/tapl/Background.java
@@ -25,7 +25,6 @@
import android.view.MotionEvent;
import androidx.annotation.NonNull;
-import androidx.test.uiautomator.By;
import androidx.test.uiautomator.UiObject2;
import com.android.launcher3.testing.TestProtocol;
@@ -72,6 +71,7 @@
}
protected void goToOverviewUnchecked() {
+ final boolean launcherWasVisible = mLauncher.isLauncherVisible();
switch (mLauncher.getNavigationModel()) {
case ZERO_BUTTON: {
final int centerX = mLauncher.getDevice().getDisplayWidth() / 2;
@@ -131,12 +131,21 @@
}
case THREE_BUTTON:
- mLauncher.expectEvent(SQUARE_BUTTON_EVENT);
+ mLauncher.expectEvent(TestProtocol.SEQUENCE_MAIN, SQUARE_BUTTON_EVENT);
mLauncher.runToState(
() -> mLauncher.waitForSystemUiObject("recent_apps").click(),
OVERVIEW_STATE_ORDINAL);
break;
}
+ expectSwitchToOverviewEvents();
+
+ if (!launcherWasVisible) {
+ mLauncher.expectEvent(
+ TestProtocol.SEQUENCE_MAIN, LauncherInstrumentation.EVENT_START_ACTIVITY);
+ }
+ }
+
+ private void expectSwitchToOverviewEvents() {
}
/**
@@ -157,6 +166,7 @@
}
protected void quickSwitchToPreviousApp(int expectedState) {
+ final boolean launcherWasVisible = mLauncher.isLauncherVisible();
boolean transposeInLandscape = false;
switch (mLauncher.getNavigationModel()) {
case TWO_BUTTON:
@@ -180,29 +190,38 @@
endX = startX;
endY = 0;
}
- final boolean launcherIsVisible =
- mLauncher.hasLauncherObject(By.textStartsWith(""));
final boolean isZeroButton = mLauncher.getNavigationModel()
== LauncherInstrumentation.NavigationModel.ZERO_BUTTON;
+ if (!launcherWasVisible) {
+ mLauncher.expectEvent(
+ TestProtocol.SEQUENCE_MAIN,
+ LauncherInstrumentation.EVENT_START_ACTIVITY);
+ }
mLauncher.swipeToState(startX, startY, endX, endY, 20, expectedState,
- launcherIsVisible && isZeroButton
+ launcherWasVisible && isZeroButton
? LauncherInstrumentation.GestureScope.INSIDE_TO_OUTSIDE
- : LauncherInstrumentation.GestureScope.OUTSIDE
- );
+ : LauncherInstrumentation.GestureScope.OUTSIDE);
break;
}
case THREE_BUTTON:
// Double press the recents button.
UiObject2 recentsButton = mLauncher.waitForSystemUiObject("recent_apps");
- mLauncher.expectEvent(SQUARE_BUTTON_EVENT);
+ mLauncher.expectEvent(TestProtocol.SEQUENCE_MAIN, SQUARE_BUTTON_EVENT);
+ if (!launcherWasVisible) {
+ mLauncher.expectEvent(
+ TestProtocol.SEQUENCE_MAIN,
+ LauncherInstrumentation.EVENT_START_ACTIVITY);
+ }
mLauncher.runToState(() -> recentsButton.click(), OVERVIEW_STATE_ORDINAL);
mLauncher.getOverview();
- mLauncher.expectEvent(SQUARE_BUTTON_EVENT);
+ mLauncher.expectEvent(TestProtocol.SEQUENCE_MAIN, SQUARE_BUTTON_EVENT);
recentsButton.click();
break;
}
- mLauncher.expectEvent(TASK_START_EVENT);
+ mLauncher.expectEvent(TestProtocol.SEQUENCE_MAIN, TASK_START_EVENT);
+ mLauncher.expectEvent(
+ TestProtocol.SEQUENCE_MAIN, LauncherInstrumentation.EVENT_STOP_ACTIVITY);
}
protected String getSwipeHeightRequestName() {
diff --git a/tests/tapl/com/android/launcher3/tapl/BaseOverview.java b/tests/tapl/com/android/launcher3/tapl/BaseOverview.java
index a769acf..69afcc4 100644
--- a/tests/tapl/com/android/launcher3/tapl/BaseOverview.java
+++ b/tests/tapl/com/android/launcher3/tapl/BaseOverview.java
@@ -117,8 +117,8 @@
// part) one in the center, and parts of its right and left siblings. Find the
// main task view by its width.
final UiObject2 widestTask = Collections.max(taskViews,
- (t1, t2) -> Integer.compare(t1.getVisibleBounds().width(),
- t2.getVisibleBounds().width()));
+ (t1, t2) -> Integer.compare(mLauncher.getVisibleBounds(t1).width(),
+ mLauncher.getVisibleBounds(t2).width()));
return new OverviewTask(mLauncher, widestTask, this);
}
diff --git a/tests/tapl/com/android/launcher3/tapl/Launchable.java b/tests/tapl/com/android/launcher3/tapl/Launchable.java
index b20384e..2922acf 100644
--- a/tests/tapl/com/android/launcher3/tapl/Launchable.java
+++ b/tests/tapl/com/android/launcher3/tapl/Launchable.java
@@ -25,6 +25,8 @@
import androidx.test.uiautomator.UiObject2;
import androidx.test.uiautomator.Until;
+import com.android.launcher3.testing.TestProtocol;
+
/**
* Ancestor for AppIcon and AppMenuItem.
*/
@@ -55,13 +57,15 @@
private Background launch(BySelector selector) {
LauncherInstrumentation.log("Launchable.launch before click " +
- mObject.getVisibleCenter() + " in " + mObject.getVisibleBounds());
+ mObject.getVisibleCenter() + " in " + mLauncher.getVisibleBounds(mObject));
mLauncher.executeAndWaitForEvent(
() -> mLauncher.clickLauncherObject(mObject),
event -> event.getEventType() == TYPE_WINDOW_STATE_CHANGED,
() -> "Launching an app didn't open a new window: " + mObject.getText());
expectActivityStartEvents();
+ mLauncher.expectEvent(
+ TestProtocol.SEQUENCE_MAIN, LauncherInstrumentation.EVENT_STOP_ACTIVITY);
mLauncher.assertTrue(
"App didn't start: " + selector,
@@ -72,8 +76,9 @@
/**
* Drags an object to the center of homescreen.
+ * @param startsActivity whether it's expected to start an activity.
*/
- public void dragToWorkspace() {
+ public void dragToWorkspace(boolean startsActivity) {
try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck()) {
final Point launchableCenter = getObject().getVisibleCenter();
final Point displaySize = mLauncher.getRealDisplaySize();
@@ -86,9 +91,13 @@
? launchableCenter.x - width / 2
: launchableCenter.x + width / 2,
displaySize.y / 2),
- getLongPressIndicator());
+ getLongPressIndicator(),
+ startsActivity,
+ () -> addExpectedEventsForLongClick());
}
}
+ protected abstract void addExpectedEventsForLongClick();
+
protected abstract String getLongPressIndicator();
}
diff --git a/tests/tapl/com/android/launcher3/tapl/LauncherInstrumentation.java b/tests/tapl/com/android/launcher3/tapl/LauncherInstrumentation.java
index f7b4f2b..84eae2d 100644
--- a/tests/tapl/com/android/launcher3/tapl/LauncherInstrumentation.java
+++ b/tests/tapl/com/android/launcher3/tapl/LauncherInstrumentation.java
@@ -69,12 +69,9 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
-import java.util.Date;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
@@ -82,7 +79,6 @@
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
-import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@@ -95,19 +91,17 @@
private static final String TAG = "Tapl";
private static final int ZERO_BUTTON_STEPS_FROM_BACKGROUND_TO_HOME = 20;
private static final int GESTURE_STEP_MS = 16;
- private static final SimpleDateFormat DATE_TIME_FORMAT =
- new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
private static long START_TIME = System.currentTimeMillis();
- static final Pattern EVENT_LOG_ENTRY = Pattern.compile(
- "(?<time>[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] "
- + "[0-9][0-9]:[0-9][0-9]:[0-9][0-9]\\.[0-9][0-9][0-9])"
- + ".*" + TestProtocol.TAPL_EVENTS_TAG + ": (?<event>.*)");
-
private static final Pattern EVENT_TOUCH_DOWN = getTouchEventPattern("ACTION_DOWN");
private static final Pattern EVENT_TOUCH_UP = getTouchEventPattern("ACTION_UP");
private static final Pattern EVENT_TOUCH_CANCEL = getTouchEventPattern("ACTION_CANCEL");
private static final Pattern EVENT_PILFER_POINTERS = Pattern.compile("pilferPointers");
+ static final Pattern EVENT_START_ACTIVITY = Pattern.compile("Activity\\.onStart");
+ static final Pattern EVENT_STOP_ACTIVITY = Pattern.compile("Activity\\.onStop");
+
+ static final Pattern EVENT_TOUCH_DOWN_TIS = getTouchEventPatternTIS("ACTION_DOWN");
+ static final Pattern EVENT_TOUCH_UP_TIS = getTouchEventPatternTIS("ACTION_UP");
// Types for launcher containers that the user is interacting with. "Background" is a
// pseudo-container corresponding to inactive launcher covered by another app.
@@ -170,19 +164,28 @@
private Consumer<ContainerType> mOnSettledStateAction;
- // Not null when we are collecting expected events to compare with actual ones.
- private List<Pattern> mExpectedEvents;
+ private static LogEventChecker sEventChecker;
+ // True if there is an gesture in progress that needs event verification.
+ private static boolean sCheckingEvents;
- private Date mStartRecordingTime;
private boolean mCheckEventsForSuccessfulGestures = false;
+ private int mExpectedPid;
+ private Runnable mOnLauncherCrashed;
- private static Pattern getTouchEventPattern(String action) {
+ private static Pattern getTouchEventPattern(String prefix, String action) {
// The pattern includes sanity checks that we don't get a multi-touch events or other
// surprises.
return Pattern.compile(
- "Touch event: MotionEvent.*?action=" + action + ".*?id\\[0\\]=0"
- +
- ".*?toolType\\[0\\]=TOOL_TYPE_FINGER.*?buttonState=0.*?pointerCount=1");
+ prefix + ": MotionEvent.*?action=" + action + ".*?id\\[0\\]=0"
+ + ".*?toolType\\[0\\]=TOOL_TYPE_FINGER.*?buttonState=0.*?pointerCount=1");
+ }
+
+ private static Pattern getTouchEventPattern(String action) {
+ return getTouchEventPattern("Touch event", action);
+ }
+
+ private static Pattern getTouchEventPatternTIS(String action) {
+ return getTouchEventPattern("TouchInteractionService.onInputEvent", action);
}
/**
@@ -244,12 +247,18 @@
}
}
}
+
+ disableSensorRotation();
}
public void enableCheckEventsForSuccessfulGestures() {
mCheckEventsForSuccessfulGestures = true;
}
+ public void setOnLauncherCrashed(Runnable onLauncherCrashed) {
+ mOnLauncherCrashed = onLauncherCrashed;
+ }
+
Context getContext() {
return mInstrumentation.getContext();
}
@@ -311,7 +320,7 @@
};
}
- private void dumpViewHierarchy() {
+ public void dumpViewHierarchy() {
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
mDevice.dumpWindowHierarchy(stream);
@@ -325,34 +334,62 @@
}
}
+ private String getSystemAnomalyMessage() {
+ try {
+ final StringBuilder sb = new StringBuilder();
+
+ UiObject2 object = mDevice.findObject(By.res("android", "alertTitle"));
+ if (object != null) {
+ sb.append("TITLE: ").append(object.getText());
+ }
+
+ object = mDevice.findObject(By.res("android", "message"));
+ if (object != null) {
+ sb.append(" PACKAGE: ").append(object.getApplicationPackage())
+ .append(" MESSAGE: ").append(object.getText());
+ }
+
+ if (sb.length() != 0) {
+ return "System alert popup is visible: " + sb;
+ }
+
+ if (hasSystemUiObject("keyguard_status_view")) return "Phone is locked";
+
+ if (!mDevice.hasObject(By.textStartsWith(""))) return "Screen is empty";
+ } catch (Throwable e) {
+ Log.w(TAG, "getSystemAnomalyMessage failed", e);
+ }
+
+ return null;
+ }
+
private String getAnomalyMessage() {
- UiObject2 object = mDevice.findObject(By.res("android", "alertTitle"));
- if (object != null) {
- return "System alert popup is visible: " + object.getText();
+ if (mExpectedPid != 0 && mExpectedPid != getPid()) {
+ mExpectedPid = 0;
+ if (mOnLauncherCrashed != null) mOnLauncherCrashed.run();
+ return "Launcher crashed";
}
- object = mDevice.findObject(By.res("android", "message"));
- if (object != null) {
- return "Message popup by " + object.getApplicationPackage() + " is visible: "
- + object.getText();
+ final String systemAnomalyMessage = getSystemAnomalyMessage();
+ if (systemAnomalyMessage != null) {
+ return "http://go/tapl : Tests are broken by a non-Launcher system error: "
+ + systemAnomalyMessage;
}
- if (hasSystemUiObject("keyguard_status_view")) return "Phone is locked";
-
- if (!mDevice.hasObject(By.textStartsWith(""))) return "Screen is empty";
-
return null;
}
public void checkForAnomaly() {
final String anomalyMessage = getAnomalyMessage();
if (anomalyMessage != null) {
- String message = "http://go/tapl : Tests are broken by a non-Launcher system error: "
- + anomalyMessage;
- log("Hierarchy dump for: " + message);
+ if (sCheckingEvents) {
+ sCheckingEvents = false;
+ sEventChecker.finishNoWait();
+ }
+ log("Hierarchy dump for: " + anomalyMessage);
dumpViewHierarchy();
- Assert.fail(formatSystemHealthMessage(message));
+ Assert.fail(formatSystemHealthMessage(anomalyMessage));
}
}
@@ -420,10 +457,12 @@
log("Hierarchy dump for: " + message);
dumpViewHierarchy();
- final String eventMismatch = getEventMismatchMessage(false);
-
- if (eventMismatch != null) {
- message = message + ", having produced " + eventMismatch;
+ if (sCheckingEvents) {
+ sCheckingEvents = false;
+ final String eventMismatch = sEventChecker.verify(0);
+ if (eventMismatch != null) {
+ message = message + ", having produced " + eventMismatch;
+ }
}
Assert.fail(formatSystemHealthMessage(message));
@@ -540,7 +579,7 @@
return waitForLauncherObject(APPS_RES_ID);
}
case OVERVIEW: {
- if (mDevice.isNaturalOrientation()) {
+ if (hasAllAppsInOverview()) {
waitForLauncherObject(APPS_RES_ID);
} else {
waitUntilGone(APPS_RES_ID);
@@ -608,6 +647,7 @@
// otherwise waitForIdle may return immediately in case when there was a big enough
// pause in accessibility events prior to pressing Home.
final String action;
+ final boolean launcherWasVisible = isLauncherVisible();
if (getNavigationModel() == NavigationModel.ZERO_BUTTON) {
checkForAnomaly();
@@ -636,24 +676,27 @@
displaySize.x / 2, displaySize.y - 1,
displaySize.x / 2, 0,
ZERO_BUTTON_STEPS_FROM_BACKGROUND_TO_HOME, NORMAL_STATE_ORDINAL,
- hasLauncherObject(By.textStartsWith(""))
+ launcherWasVisible
? GestureScope.INSIDE_TO_OUTSIDE
: GestureScope.OUTSIDE);
}
+ if (!launcherWasVisible) {
+ expectEvent(TestProtocol.SEQUENCE_MAIN, EVENT_START_ACTIVITY);
+ }
}
} else {
+ if (!launcherWasVisible) {
+ expectEvent(TestProtocol.SEQUENCE_MAIN, EVENT_START_ACTIVITY);
+ }
log("Hierarchy before clicking home:");
dumpViewHierarchy();
log(action = "clicking home button from " + getVisibleStateMessage());
try (LauncherInstrumentation.Closable c = addContextLayer(action)) {
mDevice.waitForIdle();
- if (getNavigationModel() == NavigationModel.TWO_BUTTON) {
- if (hasLauncherObject(CONTEXT_MENU_RES_ID) ||
- hasLauncherObject(WIDGETS_RES_ID)
- && !mDevice.isNaturalOrientation()) {
- expectEvent(EVENT_PILFER_POINTERS);
- }
+ if (!isLauncher3() && getNavigationModel() == NavigationModel.TWO_BUTTON) {
+ expectEvent(TestProtocol.SEQUENCE_TIS, EVENT_TOUCH_DOWN_TIS);
+ expectEvent(TestProtocol.SEQUENCE_TIS, EVENT_TOUCH_UP_TIS);
}
runToState(
@@ -672,6 +715,11 @@
}
}
+ boolean isLauncherVisible() {
+ mDevice.waitForIdle();
+ return hasLauncherObject(By.textStartsWith(""));
+ }
+
/**
* Gets the Workspace object if the current state is "active home", i.e. workspace. Fails if the
* launcher is not in that state.
@@ -931,12 +979,16 @@
int getBottomGestureMarginInContainer(UiObject2 container) {
final int bottomGestureStartOnScreen = getRealDisplaySize().y - getBottomGestureSize();
- return container.getVisibleBounds().bottom - bottomGestureStartOnScreen;
+ return getVisibleBounds(container).bottom - bottomGestureStartOnScreen;
}
void clickLauncherObject(UiObject2 object) {
- expectEvent(LauncherInstrumentation.EVENT_TOUCH_DOWN);
- expectEvent(LauncherInstrumentation.EVENT_TOUCH_UP);
+ expectEvent(TestProtocol.SEQUENCE_MAIN, LauncherInstrumentation.EVENT_TOUCH_DOWN);
+ expectEvent(TestProtocol.SEQUENCE_MAIN, LauncherInstrumentation.EVENT_TOUCH_UP);
+ if (!isLauncher3() && getNavigationModel() != NavigationModel.THREE_BUTTON) {
+ expectEvent(TestProtocol.SEQUENCE_TIS, LauncherInstrumentation.EVENT_TOUCH_DOWN_TIS);
+ expectEvent(TestProtocol.SEQUENCE_TIS, LauncherInstrumentation.EVENT_TOUCH_UP_TIS);
+ }
object.click();
}
@@ -945,10 +997,10 @@
Collection<UiObject2> items,
int topPaddingInContainer) {
final UiObject2 lowestItem = Collections.max(items, (i1, i2) ->
- Integer.compare(i1.getVisibleBounds().top, i2.getVisibleBounds().top));
+ Integer.compare(getVisibleBounds(i1).top, getVisibleBounds(i2).top));
- final int itemRowCurrentTopOnScreen = lowestItem.getVisibleBounds().top;
- final Rect containerRect = container.getVisibleBounds();
+ final int itemRowCurrentTopOnScreen = getVisibleBounds(lowestItem).top;
+ final Rect containerRect = getVisibleBounds(container);
final int itemRowNewTopOnScreen = containerRect.top + topPaddingInContainer;
final int distance = itemRowCurrentTopOnScreen - itemRowNewTopOnScreen + getTouchSlop();
@@ -967,7 +1019,7 @@
void scroll(
UiObject2 container, Direction direction, Rect margins, int steps, boolean slowDown) {
- final Rect rect = container.getVisibleBounds();
+ final Rect rect = getVisibleBounds(container);
if (margins != null) {
rect.left += margins.left;
rect.top += margins.top;
@@ -1075,20 +1127,27 @@
public void sendPointer(long downTime, long currentTime, int action, Point point,
GestureScope gestureScope) {
+ final boolean notLauncher3 = !isLauncher3();
switch (action) {
case MotionEvent.ACTION_DOWN:
if (gestureScope != GestureScope.OUTSIDE) {
- expectEvent(EVENT_TOUCH_DOWN);
+ expectEvent(TestProtocol.SEQUENCE_MAIN, EVENT_TOUCH_DOWN);
+ }
+ if (notLauncher3 && getNavigationModel() != NavigationModel.THREE_BUTTON) {
+ expectEvent(TestProtocol.SEQUENCE_TIS, EVENT_TOUCH_DOWN_TIS);
}
break;
case MotionEvent.ACTION_UP:
- if (gestureScope != GestureScope.INSIDE) {
- expectEvent(EVENT_PILFER_POINTERS);
+ if (notLauncher3 && gestureScope != GestureScope.INSIDE) {
+ expectEvent(TestProtocol.SEQUENCE_PILFER, EVENT_PILFER_POINTERS);
}
if (gestureScope != GestureScope.OUTSIDE) {
- expectEvent(gestureScope == GestureScope.INSIDE
+ expectEvent(TestProtocol.SEQUENCE_MAIN, gestureScope == GestureScope.INSIDE
? EVENT_TOUCH_UP : EVENT_TOUCH_CANCEL);
}
+ if (notLauncher3 && getNavigationModel() != NavigationModel.THREE_BUTTON) {
+ expectEvent(TestProtocol.SEQUENCE_TIS, EVENT_TOUCH_UP_TIS);
+ }
break;
}
@@ -1122,10 +1181,12 @@
}
@NonNull
- UiObject2 clickAndGet(@NonNull final UiObject2 target, @NonNull String resName) {
+ UiObject2 clickAndGet(
+ @NonNull final UiObject2 target, @NonNull String resName, Pattern longClickEvent) {
final Point targetCenter = target.getVisibleCenter();
final long downTime = SystemClock.uptimeMillis();
sendPointer(downTime, downTime, MotionEvent.ACTION_DOWN, targetCenter, GestureScope.INSIDE);
+ expectEvent(TestProtocol.SEQUENCE_MAIN, longClickEvent);
final UiObject2 result = waitForLauncherObject(resName);
sendPointer(downTime, SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, targetCenter,
GestureScope.INSIDE);
@@ -1182,6 +1243,32 @@
getTestInfo(TestProtocol.REQUEST_ENABLE_DEBUG_TRACING);
}
+ public boolean hasAllAppsInOverview() {
+ // Vertical bar layouts don't contain all apps
+ if (!mDevice.isNaturalOrientation()) {
+ return false;
+ }
+ // Portrait two button (quickstep) always has all apps.
+ if (getNavigationModel() == NavigationModel.TWO_BUTTON) {
+ return true;
+ }
+ // Overview actions hide all apps
+ if (overviewActionsEnabled()) {
+ return false;
+ }
+ // ...otherwise there should be all apps
+ return true;
+ }
+
+ private boolean overviewActionsEnabled() {
+ return getTestInfo(TestProtocol.REQUEST_OVERVIEW_ACTIONS_ENABLED).getBoolean(
+ TestProtocol.TEST_INFO_RESPONSE_FIELD);
+ }
+
+ public void disableSensorRotation() {
+ getTestInfo(TestProtocol.REQUEST_MOCK_SENSOR_ROTATION);
+ }
+
public void disableDebugTracing() {
getTestInfo(TestProtocol.REQUEST_DISABLE_DEBUG_TRACING);
}
@@ -1217,129 +1304,45 @@
return tasks;
}
- private List<String> getEvents() {
- final ArrayList<String> events = new ArrayList<>();
- try {
- // Logcat may skip events after the specified time. Querying for events starting 1 sec
- // earlier.
- final Date startTime = new Date(mStartRecordingTime.getTime() - 1000);
- final String logcatEvents = mDevice.executeShellCommand(
- "logcat -d -v year --pid=" + getPid() + " -t "
- + DATE_TIME_FORMAT.format(startTime).replaceAll(" ", "")
- + " -s " + TestProtocol.TAPL_EVENTS_TAG);
- final Matcher matcher = EVENT_LOG_ENTRY.matcher(logcatEvents);
- while (matcher.find()) {
- // Skip events before recording start time.
- if (DATE_TIME_FORMAT.parse(matcher.group("time"))
- .compareTo(mStartRecordingTime) < 0) {
- continue;
- }
-
- events.add(matcher.group("event"));
- }
- return events;
- } catch (IOException e) {
- throw new RuntimeException(e);
- } catch (ParseException e) {
- throw new AssertionError(e);
- }
- }
-
- private void startRecordingEvents() {
- Assert.assertTrue("Already recording events", mExpectedEvents == null);
- mExpectedEvents = new ArrayList<>();
- mStartRecordingTime = new Date();
- log("startRecordingEvents: " + DATE_TIME_FORMAT.format(mStartRecordingTime));
- }
-
- private void stopRecordingEvents() {
- mExpectedEvents = null;
- mStartRecordingTime = null;
- }
-
public Closable eventsCheck() {
- if ("com.android.launcher3".equals(getLauncherPackageName())) {
- // Not checking specific Launcher3 event sequences.
- return () -> {
- };
- }
-
- // Entering events check block.
- startRecordingEvents();
+ Assert.assertTrue("Nested event checking", !sCheckingEvents);
+ sCheckingEvents = true;
+ mExpectedPid = getPid();
+ if (sEventChecker == null) sEventChecker = new LogEventChecker();
+ sEventChecker.start();
return () -> {
- // Leaving events check block.
- if (mExpectedEvents == null) {
- return; // There was a failure. Noo need to report another one.
- }
+ checkForAnomaly();
- if (!mCheckEventsForSuccessfulGestures) {
- stopRecordingEvents();
- return;
- }
-
- final String message = getEventMismatchMessage(true);
- if (message != null) {
- Assert.fail(formatSystemHealthMessage(
- "http://go/tapl : unexpected event sequence: " + message));
+ if (sCheckingEvents) {
+ sCheckingEvents = false;
+ if (mCheckEventsForSuccessfulGestures) {
+ final String message = sEventChecker.verify(WAIT_TIME_MS);
+ if (message != null) {
+ Assert.fail(formatSystemHealthMessage(
+ "http://go/tapl : successful gesture produced " + message));
+ }
+ } else {
+ sEventChecker.finishNoWait();
+ }
}
};
}
- void expectEvent(Pattern expected) {
- if (mExpectedEvents != null) mExpectedEvents.add(expected);
+ boolean isLauncher3() {
+ return "com.android.launcher3".equals(getLauncherPackageName());
}
- private String getEventMismatchMessage(boolean waitForExpectedCount) {
- if (mExpectedEvents == null) return null;
+ void expectEvent(String sequence, Pattern expected) {
+ if (sCheckingEvents) sEventChecker.expectPattern(sequence, expected);
+ }
+ Rect getVisibleBounds(UiObject2 object) {
try {
- List<String> actual = getEvents();
-
- if (waitForExpectedCount) {
- // Wait until Launcher generates the expected number of events.
- final long endTime = SystemClock.uptimeMillis() + WAIT_TIME_MS;
- while (SystemClock.uptimeMillis() < endTime
- && actual.size() < mExpectedEvents.size()) {
- SystemClock.sleep(100);
- actual = getEvents();
- }
- }
-
- for (int i = 0; i < mExpectedEvents.size(); ++i) {
- if (i >= actual.size()) {
- return formatEventMismatchMessage("too few actual events", actual, i);
- }
- if (!mExpectedEvents.get(i).matcher(actual.get(i)).find()) {
- return formatEventMismatchMessage("a mismatched event", actual, i);
- }
- }
-
- if (actual.size() > mExpectedEvents.size()) {
- return formatEventMismatchMessage(
- "too many actual events", actual, mExpectedEvents.size());
- }
- } finally {
- stopRecordingEvents();
+ return object.getVisibleBounds();
+ } catch (Throwable t) {
+ fail(t.toString());
+ return null;
}
-
- return null;
- }
-
- private String formatEventList(List events, int position) {
- final StringBuilder sb = new StringBuilder();
- for (int i = 0; i < events.size(); ++i) {
- sb.append("\n| ");
- sb.append(i == position ? "---> " : " ");
- sb.append(events.get(i).toString());
- }
- if (position == events.size()) sb.append("\n| ---> (end)");
- return sb.toString();
- }
-
- private String formatEventMismatchMessage(String message, List<String> actual, int position) {
- return message + ":"
- + "\nExpected:" + formatEventList(mExpectedEvents, position)
- + "\nActual:" + formatEventList(actual, position);
}
}
\ No newline at end of file
diff --git a/tests/tapl/com/android/launcher3/tapl/LogEventChecker.java b/tests/tapl/com/android/launcher3/tapl/LogEventChecker.java
new file mode 100644
index 0000000..78dfc36
--- /dev/null
+++ b/tests/tapl/com/android/launcher3/tapl/LogEventChecker.java
@@ -0,0 +1,241 @@
+/*
+ * 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.launcher3.tapl;
+
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+
+import android.util.Log;
+
+import com.android.launcher3.testing.TestProtocol;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Semaphore;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Utility class to read log on a background thread.
+ */
+public class LogEventChecker {
+
+ private static final Pattern EVENT_LOG_ENTRY = Pattern.compile(
+ ".*" + TestProtocol.TAPL_EVENTS_TAG + ": (?<sequence>[a-zA-Z]+) / (?<event>.*)");
+
+ private static final String START_PREFIX = "START_READER ";
+ private static final String FINISH_PREFIX = "FINISH_READER ";
+ private static final String SKIP_EVENTS_TAG = "b/153670015";
+
+ private volatile CountDownLatch mFinished;
+
+ // Map from an event sequence name to an ordered list of expected events in that sequence.
+ private final ListMap<Pattern> mExpectedEvents = new ListMap<>();
+
+ private final ListMap<String> mEvents = new ListMap<>();
+ private final Semaphore mEventsCounter = new Semaphore(0);
+
+ private volatile String mStartCommand;
+ private volatile String mFinishCommand;
+
+ LogEventChecker() {
+ final Thread thread = new Thread(this::onRun, "log-reader-thread");
+ thread.setPriority(Thread.NORM_PRIORITY);
+ thread.start();
+ }
+
+ void start() {
+ if (mFinished != null) {
+ try {
+ mFinished.await();
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ mFinished = null;
+ }
+ mEvents.clear();
+ Log.d(SKIP_EVENTS_TAG, "Cleared events");
+ mExpectedEvents.clear();
+ mEventsCounter.drainPermits();
+ final String id = UUID.randomUUID().toString();
+ mStartCommand = START_PREFIX + id;
+ mFinishCommand = FINISH_PREFIX + id;
+ Log.d(TestProtocol.TAPL_EVENTS_TAG, mStartCommand);
+ }
+
+ private void onRun() {
+ try {
+ // Note that we use Runtime.exec to start the log reading process instead of running
+ // it via UIAutomation, so that we can directly access the "Process" object and
+ // ensure that the instrumentation is not stuck forever.
+ final String cmd = "logcat -s " + TestProtocol.TAPL_EVENTS_TAG;
+
+ try (BufferedReader reader = new BufferedReader(new InputStreamReader(
+ Runtime.getRuntime().exec(cmd).getInputStream()))) {
+ for (; ; ) {
+ // Skip everything before the next start command.
+ for (; ; ) {
+ final String event = reader.readLine();
+ if (event.contains(TestProtocol.TAPL_EVENTS_TAG)
+ && event.contains(mStartCommand)) {
+ Log.d(SKIP_EVENTS_TAG, "Read start: " + event);
+ break;
+ }
+ }
+
+ // Store all actual events until the finish command.
+ for (; ; ) {
+ final String event = reader.readLine();
+ if (event.contains(TestProtocol.TAPL_EVENTS_TAG)) {
+ if (event.contains(mFinishCommand)) {
+ mFinished.countDown();
+ Log.d(SKIP_EVENTS_TAG, "Read finish: " + event);
+ break;
+ } else {
+ final Matcher matcher = EVENT_LOG_ENTRY.matcher(event);
+ if (matcher.find()) {
+ mEvents.add(matcher.group("sequence"), matcher.group("event"));
+ Log.d(SKIP_EVENTS_TAG, "Read event: " + event);
+ mEventsCounter.release();
+ }
+ }
+ }
+ }
+ }
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ void expectPattern(String sequence, Pattern pattern) {
+ mExpectedEvents.add(sequence, pattern);
+ }
+
+ private void finishSync(long waitForExpectedCountMs) {
+ try {
+ // Wait until Launcher generates the expected number of events.
+ int expectedCount = mExpectedEvents.entrySet()
+ .stream().mapToInt(e -> e.getValue().size()).sum();
+ mEventsCounter.tryAcquire(expectedCount, waitForExpectedCountMs, MILLISECONDS);
+ finishNoWait();
+ mFinished.await();
+ mFinished = null;
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ void finishNoWait() {
+ mFinished = new CountDownLatch(1);
+ Log.d(TestProtocol.TAPL_EVENTS_TAG, mFinishCommand);
+ }
+
+ String verify(long waitForExpectedCountMs) {
+ finishSync(waitForExpectedCountMs);
+
+ final StringBuilder sb = new StringBuilder();
+ boolean hasMismatches = false;
+ for (Map.Entry<String, List<Pattern>> expectedEvents : mExpectedEvents.entrySet()) {
+ String sequence = expectedEvents.getKey();
+
+ List<String> actual = new ArrayList<>(mEvents.getNonNull(sequence));
+ Log.d(SKIP_EVENTS_TAG, "Verifying events");
+ final int mismatchPosition = getMismatchPosition(expectedEvents.getValue(), actual);
+ hasMismatches = hasMismatches || mismatchPosition != -1;
+ formatSequenceWithMismatch(
+ sb,
+ sequence,
+ expectedEvents.getValue(),
+ actual,
+ mismatchPosition);
+ }
+ // Check for unexpected event sequences in the actual data.
+ for (String actualNamedSequence : mEvents.keySet()) {
+ if (!mExpectedEvents.containsKey(actualNamedSequence)) {
+ hasMismatches = true;
+ formatSequenceWithMismatch(
+ sb,
+ actualNamedSequence,
+ new ArrayList<>(),
+ mEvents.get(actualNamedSequence),
+ 0);
+ }
+ }
+
+ return hasMismatches ? "mismatching events: " + sb.toString() : null;
+ }
+
+ // If the list of actual events matches the list of expected events, returns -1, otherwise
+ // the position of the mismatch.
+ private static int getMismatchPosition(List<Pattern> expected, List<String> actual) {
+ for (int i = 0; i < expected.size(); ++i) {
+ if (i >= actual.size()
+ || !expected.get(i).matcher(actual.get(i)).find()) {
+ return i;
+ }
+ }
+
+ if (actual.size() > expected.size()) return expected.size();
+
+ return -1;
+ }
+
+ private static void formatSequenceWithMismatch(
+ StringBuilder sb,
+ String sequenceName,
+ List<Pattern> expected,
+ List<String> actualEvents,
+ int mismatchPosition) {
+ sb.append("\n>> SEQUENCE " + sequenceName + " - "
+ + (mismatchPosition == -1 ? "MATCH" : "MISMATCH"));
+ sb.append("\n EXPECTED:");
+ formatEventListWithMismatch(sb, expected, mismatchPosition);
+ sb.append("\n ACTUAL:");
+ formatEventListWithMismatch(sb, actualEvents, mismatchPosition);
+ }
+
+ private static void formatEventListWithMismatch(StringBuilder sb, List events, int position) {
+ for (int i = 0; i < events.size(); ++i) {
+ sb.append("\n | ");
+ sb.append(i == position ? "---> " : " ");
+ sb.append(events.get(i).toString());
+ }
+ if (position == events.size()) sb.append("\n | ---> (end)");
+ }
+
+ private static class ListMap<T> extends HashMap<String, List<T>> {
+
+ void add(String key, T value) {
+ getNonNull(key).add(value);
+ }
+
+ List<T> getNonNull(String key) {
+ List<T> list = get(key);
+ if (list == null) {
+ list = new ArrayList<>();
+ put(key, list);
+ }
+ return list;
+ }
+ }
+}
diff --git a/tests/tapl/com/android/launcher3/tapl/OptionsPopupMenuItem.java b/tests/tapl/com/android/launcher3/tapl/OptionsPopupMenuItem.java
index c2f701b..63a97f4 100644
--- a/tests/tapl/com/android/launcher3/tapl/OptionsPopupMenuItem.java
+++ b/tests/tapl/com/android/launcher3/tapl/OptionsPopupMenuItem.java
@@ -15,11 +15,15 @@
*/
package com.android.launcher3.tapl;
+import android.os.Build;
+
import androidx.annotation.NonNull;
import androidx.test.uiautomator.By;
import androidx.test.uiautomator.UiObject2;
import androidx.test.uiautomator.Until;
+import com.android.launcher3.testing.TestProtocol;
+
public class OptionsPopupMenuItem {
private final LauncherInstrumentation mLauncher;
@@ -37,8 +41,14 @@
public void launch(@NonNull String expectedPackageName) {
try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck()) {
LauncherInstrumentation.log("OptionsPopupMenuItem before click "
- + mObject.getVisibleCenter() + " in " + mObject.getVisibleBounds());
+ + mObject.getVisibleCenter() + " in " + mLauncher.getVisibleBounds(mObject));
mLauncher.clickLauncherObject(mObject);
+ if (!Build.MODEL.contains("Cuttlefish") ||
+ Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q &&
+ !"R".equals(Build.VERSION.CODENAME)) {
+ mLauncher.expectEvent(
+ TestProtocol.SEQUENCE_MAIN, LauncherInstrumentation.EVENT_STOP_ACTIVITY);
+ }
mLauncher.assertTrue(
"App didn't start: " + By.pkg(expectedPackageName),
mLauncher.getDevice().wait(Until.hasObject(By.pkg(expectedPackageName)),
diff --git a/tests/tapl/com/android/launcher3/tapl/OverviewTask.java b/tests/tapl/com/android/launcher3/tapl/OverviewTask.java
index 410e5a1..fae5f19 100644
--- a/tests/tapl/com/android/launcher3/tapl/OverviewTask.java
+++ b/tests/tapl/com/android/launcher3/tapl/OverviewTask.java
@@ -22,6 +22,8 @@
import androidx.test.uiautomator.UiObject2;
+import com.android.launcher3.testing.TestProtocol;
+
import java.util.regex.Pattern;
/**
@@ -54,7 +56,7 @@
"want to dismiss a task")) {
verifyActiveContainer();
// Dismiss the task via flinging it up.
- final Rect taskBounds = mTask.getVisibleBounds();
+ final Rect taskBounds = mLauncher.getVisibleBounds(mTask);
final int centerX = taskBounds.centerX();
final int centerY = taskBounds.centerY();
mLauncher.linearGesture(centerX, centerY, centerX, 0, 10, false,
@@ -76,7 +78,9 @@
event -> event.getEventType() == TYPE_WINDOW_STATE_CHANGED,
() -> "Launching task didn't open a new window: "
+ mTask.getParent().getContentDescription());
- mLauncher.expectEvent(TASK_START_EVENT);
+ mLauncher.expectEvent(TestProtocol.SEQUENCE_MAIN, TASK_START_EVENT);
+ mLauncher.expectEvent(
+ TestProtocol.SEQUENCE_MAIN, LauncherInstrumentation.EVENT_STOP_ACTIVITY);
}
return new Background(mLauncher);
}
diff --git a/tests/tapl/com/android/launcher3/tapl/Widget.java b/tests/tapl/com/android/launcher3/tapl/Widget.java
index a658f16..53ef796 100644
--- a/tests/tapl/com/android/launcher3/tapl/Widget.java
+++ b/tests/tapl/com/android/launcher3/tapl/Widget.java
@@ -18,11 +18,17 @@
import androidx.test.uiautomator.UiObject2;
+import com.android.launcher3.testing.TestProtocol;
+
+import java.util.regex.Pattern;
+
/**
* Widget in workspace or a widget list.
*/
public final class Widget extends Launchable {
+ private static final Pattern LONG_CLICK_EVENT = Pattern.compile("Widgets.onLongClick");
+
Widget(LauncherInstrumentation launcher, UiObject2 icon) {
super(launcher, icon);
}
@@ -35,4 +41,9 @@
@Override
protected void expectActivityStartEvents() {
}
+
+ @Override
+ protected void addExpectedEventsForLongClick() {
+ mLauncher.expectEvent(TestProtocol.SEQUENCE_MAIN, LONG_CLICK_EVENT);
+ }
}
diff --git a/tests/tapl/com/android/launcher3/tapl/Widgets.java b/tests/tapl/com/android/launcher3/tapl/Widgets.java
index 8659aa7..39ac645 100644
--- a/tests/tapl/com/android/launcher3/tapl/Widgets.java
+++ b/tests/tapl/com/android/launcher3/tapl/Widgets.java
@@ -16,6 +16,8 @@
package com.android.launcher3.tapl;
+import static com.android.launcher3.tapl.LauncherInstrumentation.WAIT_TIME_MS;
+
import android.graphics.Point;
import android.graphics.Rect;
@@ -23,6 +25,7 @@
import androidx.test.uiautomator.BySelector;
import androidx.test.uiautomator.Direction;
import androidx.test.uiautomator.UiObject2;
+import androidx.test.uiautomator.Until;
import com.android.launcher3.tapl.LauncherInstrumentation.GestureScope;
@@ -73,7 +76,7 @@
mLauncher.scroll(
widgetsContainer,
Direction.UP,
- new Rect(0, 0, widgetsContainer.getVisibleBounds().width(), 0),
+ new Rect(0, 0, mLauncher.getVisibleBounds(widgetsContainer).width(), 0),
FLING_STEPS, false);
try (LauncherInstrumentation.Closable c1 = mLauncher.addContextLayer("flung back")) {
verifyActiveContainer();
@@ -88,46 +91,53 @@
}
public Widget getWidget(String labelText) {
- final UiObject2 widgetsContainer = verifyActiveContainer();
- final Point displaySize = mLauncher.getRealDisplaySize();
- final BySelector labelSelector = By.clazz("android.widget.TextView").text(labelText);
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck();
+ LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
+ "getting widget " + labelText + " in widgets list")) {
+ final UiObject2 widgetsContainer = verifyActiveContainer();
+ mLauncher.assertTrue("Widgets container didn't become scrollable",
+ widgetsContainer.wait(Until.scrollable(true), WAIT_TIME_MS));
+ final Point displaySize = mLauncher.getRealDisplaySize();
+ final BySelector labelSelector = By.clazz("android.widget.TextView").text(labelText);
- int i = 0;
- for (; ; ) {
- final Collection<UiObject2> cells = mLauncher.getObjectsInContainer(
- widgetsContainer, "widgets_scroll_container");
- mLauncher.assertTrue("Widgets doesn't have 2 rows", cells.size() >= 2);
- for (UiObject2 cell : cells) {
- final UiObject2 label = cell.findObject(labelSelector);
- if (label == null) continue;
+ int i = 0;
+ for (; ; ) {
+ final Collection<UiObject2> cells = mLauncher.getObjectsInContainer(
+ widgetsContainer, "widgets_scroll_container");
+ mLauncher.assertTrue("Widgets doesn't have 2 rows", cells.size() >= 2);
+ for (UiObject2 cell : cells) {
+ final UiObject2 label = cell.findObject(labelSelector);
+ if (label == null) continue;
- final UiObject2 widget = label.getParent().getParent();
- mLauncher.assertEquals(
- "View is not WidgetCell",
- "com.android.launcher3.widget.WidgetCell",
- widget.getClassName());
+ final UiObject2 widget = label.getParent().getParent();
+ mLauncher.assertEquals(
+ "View is not WidgetCell",
+ "com.android.launcher3.widget.WidgetCell",
+ widget.getClassName());
- int maxWidth = 0;
- for (UiObject2 sibling : widget.getParent().getChildren()) {
- maxWidth = Math.max(sibling.getVisibleBounds().width(), maxWidth);
+ int maxWidth = 0;
+ for (UiObject2 sibling : widget.getParent().getChildren()) {
+ maxWidth = Math.max(mLauncher.getVisibleBounds(sibling).width(), maxWidth);
+ }
+
+ if (mLauncher.getVisibleBounds(widget).bottom
+ <= displaySize.y - mLauncher.getBottomGestureSize()) {
+ int visibleDelta = maxWidth - mLauncher.getVisibleBounds(widget).width();
+ if (visibleDelta > 0) {
+ Rect parentBounds = mLauncher.getVisibleBounds(cell);
+ mLauncher.linearGesture(parentBounds.centerX() + visibleDelta
+ + mLauncher.getTouchSlop(),
+ parentBounds.centerY(), parentBounds.centerX(),
+ parentBounds.centerY(), 10, true, GestureScope.INSIDE);
+ }
+
+ return new Widget(mLauncher, widget);
+ }
}
- int visibleDelta = maxWidth - widget.getVisibleBounds().width();
- if (visibleDelta > 0) {
- Rect parentBounds = cell.getVisibleBounds();
- mLauncher.linearGesture(parentBounds.centerX() + visibleDelta,
- parentBounds.centerY(), parentBounds.centerX(),
- parentBounds.centerY(), 10, true, GestureScope.INSIDE);
- }
-
- if (widget.getVisibleBounds().bottom
- <= displaySize.y - mLauncher.getBottomGestureSize()) {
- return new Widget(mLauncher, widget);
- }
+ mLauncher.assertTrue("Too many attempts", ++i <= 40);
+ mLauncher.scrollToLastVisibleRow(widgetsContainer, cells, 0);
}
-
- mLauncher.assertTrue("Too many attempts", ++i <= 40);
- mLauncher.scrollToLastVisibleRow(widgetsContainer, cells, 0);
}
}
}
diff --git a/tests/tapl/com/android/launcher3/tapl/Workspace.java b/tests/tapl/com/android/launcher3/tapl/Workspace.java
index a0d5443..b3b5e32 100644
--- a/tests/tapl/com/android/launcher3/tapl/Workspace.java
+++ b/tests/tapl/com/android/launcher3/tapl/Workspace.java
@@ -52,6 +52,7 @@
static final Pattern EVENT_CTRL_W_UP = Pattern.compile(
"Key event: KeyEvent.*?action=ACTION_UP.*?keyCode=KEYCODE_W"
+ ".*?metaState=META_CTRL_ON");
+ private static final Pattern LONG_CLICK_EVENT = Pattern.compile("onWorkspaceItemLongClick");
private final UiObject2 mHotseat;
@@ -176,8 +177,11 @@
mLauncher,
getHotseatAppIcon("Chrome"),
new Point(mLauncher.getDevice().getDisplayWidth(),
- workspace.getVisibleBounds().centerY()),
- "deep_shortcuts_container");
+ mLauncher.getVisibleBounds(workspace).centerY()),
+ "deep_shortcuts_container",
+ false,
+ () -> mLauncher.expectEvent(
+ TestProtocol.SEQUENCE_MAIN, LONG_CLICK_EVENT));
verifyActiveContainer();
}
}
@@ -198,7 +202,7 @@
static void dragIconToWorkspace(
LauncherInstrumentation launcher, Launchable launchable, Point dest,
- String longPressIndicator) {
+ String longPressIndicator, boolean startsActivity, Runnable expectLongClickEvents) {
LauncherInstrumentation.log("dragIconToWorkspace: begin");
final Point launchableCenter = launchable.getObject().getVisibleCenter();
final long downTime = SystemClock.uptimeMillis();
@@ -207,6 +211,7 @@
launcher.sendPointer(downTime, downTime, MotionEvent.ACTION_DOWN,
launchableCenter, LauncherInstrumentation.GestureScope.INSIDE);
LauncherInstrumentation.log("dragIconToWorkspace: sent down");
+ expectLongClickEvents.run();
launcher.waitForLauncherObject(longPressIndicator);
LauncherInstrumentation.log("dragIconToWorkspace: indicator");
launcher.movePointer(launchableCenter, dest, 10, downTime, true,
@@ -219,6 +224,10 @@
downTime, SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, dest,
LauncherInstrumentation.GestureScope.INSIDE),
NORMAL_STATE_ORDINAL);
+ if (startsActivity) {
+ launcher.expectEvent(
+ TestProtocol.SEQUENCE_MAIN, LauncherInstrumentation.EVENT_STOP_ACTIVITY);
+ }
LauncherInstrumentation.log("dragIconToWorkspace: end");
launcher.waitUntilGone("drop_target_bar");
}
@@ -260,8 +269,8 @@
public Widgets openAllWidgets() {
try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck()) {
verifyActiveContainer();
- mLauncher.expectEvent(EVENT_CTRL_W_DOWN);
- mLauncher.expectEvent(EVENT_CTRL_W_UP);
+ mLauncher.expectEvent(TestProtocol.SEQUENCE_MAIN, EVENT_CTRL_W_DOWN);
+ mLauncher.expectEvent(TestProtocol.SEQUENCE_MAIN, EVENT_CTRL_W_UP);
mLauncher.getDevice().pressKeyCode(KeyEvent.KEYCODE_W, KeyEvent.META_CTRL_ON);
try (LauncherInstrumentation.Closable c = mLauncher.addContextLayer("pressed Ctrl+W")) {
return new Widgets(mLauncher);
@@ -281,16 +290,22 @@
@Nullable
public Widget tryGetWidget(String label, long timeout) {
- final UiObject2 widget = mLauncher.tryWaitForLauncherObject(
- By.clazz("com.android.launcher3.widget.LauncherAppWidgetHostView").desc(label),
- timeout);
- return widget != null ? new Widget(mLauncher, widget) : null;
+ try (LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
+ "getting widget " + label + " on workspace with timeout " + timeout)) {
+ final UiObject2 widget = mLauncher.tryWaitForLauncherObject(
+ By.clazz("com.android.launcher3.widget.LauncherAppWidgetHostView").desc(label),
+ timeout);
+ return widget != null ? new Widget(mLauncher, widget) : null;
+ }
}
@Nullable
public Widget tryGetPendingWidget(long timeout) {
- final UiObject2 widget = mLauncher.tryWaitForLauncherObject(
- By.clazz("com.android.launcher3.widget.PendingAppWidgetHostView"), timeout);
- return widget != null ? new Widget(mLauncher, widget) : null;
+ try (LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
+ "getting pending widget on workspace with timeout " + timeout)) {
+ final UiObject2 widget = mLauncher.tryWaitForLauncherObject(
+ By.clazz("com.android.launcher3.widget.PendingAppWidgetHostView"), timeout);
+ return widget != null ? new Widget(mLauncher, widget) : null;
+ }
}
}
\ No newline at end of file