Snap for 13476683 from ab84f60449 to 25Q3-release

Change-Id: I7945e6b5a9d14cfd28d56b5249ed05453e9cf5fd
This commit is contained in:
Android Build Coastguard Worker committed 2025-05-10 14:18:44 -07:00
commit e55087cbb7
67 files changed
+2176 -112

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
*.iml
.project
.classpath
.project.properties
gen/
bin/
.idea/
.gradle/
local.properties
gradle/
build/
gradlew*
.DS_Store
+120
View File
@@ -0,0 +1,120 @@
// Copyright (C) 2025 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package {
// See: http://go/android-license-faq
default_applicable_licenses: ["Android-Apache-2.0"],
}
android_library {
name: "widget_picker_dagger_annotations",
sdk_version: "current",
min_sdk_version: min_launcher3_sdk_version,
srcs: [
"src/com/android/launcher3/widgetpicker/WidgetPickerSingleton.kt",
],
static_libs: [
"androidx.annotation_annotation",
"jsr330",
],
}
android_library {
name: "widget_picker_component",
sdk_version: "current",
min_sdk_version: min_launcher3_sdk_version,
srcs: [
"src/com/android/launcher3/widgetpicker/WidgetPickerModule.kt",
"src/com/android/launcher3/widgetpicker/WidgetPickerComponent.kt",
],
static_libs: [
"dagger2",
"widget_picker_dagger_annotations",
],
}
// Data types that are accessible & potentially provided by hosts using the widget picker library
android_library {
name: "widget_picker_shared_data_types",
sdk_version: "current",
min_sdk_version: min_launcher3_sdk_version,
srcs: [
"src/com/android/launcher3/widgetpicker/shared/model/PickableWidget.kt",
"src/com/android/launcher3/widgetpicker/shared/model/WidgetAppIcon.kt",
"src/com/android/launcher3/widgetpicker/shared/model/WidgetAppId.kt",
"src/com/android/launcher3/widgetpicker/shared/model/WidgetId.kt",
"src/com/android/launcher3/widgetpicker/shared/model/WidgetPreview.kt",
"src/com/android/launcher3/widgetpicker/shared/model/WidgetUserProfiles.kt",
],
static_libs: [
"androidx.core_core-ktx",
"androidx.annotation_annotation",
],
}
android_library {
name: "widget_picker_data_repositories",
sdk_version: "current",
min_sdk_version: min_launcher3_sdk_version,
srcs: [
"src/com/android/launcher3/widgetpicker/data/repository/WidgetAppIconsRepository.kt",
"src/com/android/launcher3/widgetpicker/data/repository/WidgetPreviewRepository.kt",
"src/com/android/launcher3/widgetpicker/data/repository/WidgetRecommendationsRepository.kt",
"src/com/android/launcher3/widgetpicker/data/repository/WidgetsRepository.kt",
"src/com/android/launcher3/widgetpicker/data/repository/WidgetUsersRepository.kt",
],
static_libs: [
"widget_picker_shared_data_types",
"kotlinx_coroutines_android",
"kotlinx_coroutines",
],
}
android_library {
name: "widget_picker_ui_components",
sdk_version: "current",
min_sdk_version: min_launcher3_sdk_version,
srcs: [
"src/com/android/launcher3/widgetpicker/ui/components/ScrollableFloatingToolbar.kt",
"src/com/android/launcher3/widgetpicker/ui/components/LeadingIconToolbarTab.kt",
"src/com/android/launcher3/widgetpicker/ui/components/TitledBottomSheet.kt",
],
static_libs: [
"androidx.compose.foundation_foundation",
"androidx.compose.foundation_foundation-layout",
"androidx.compose.runtime_runtime",
"androidx.compose.ui_ui",
"androidx.compose.ui_ui-tooling",
"androidx.compose.material3_material3",
"androidx.compose.material3_material3-window-size-class",
"androidx.compose.material_material-icons-extended",
"androidx.activity_activity-compose",
"widget_picker_window_size_class",
],
}
android_library {
name: "widget_picker_window_size_class",
sdk_version: "current",
min_sdk_version: min_launcher3_sdk_version,
srcs: [
"src/com/android/launcher3/widgetpicker/ui/windowsizeclass/WindowSizeClass.kt",
],
static_libs: [
"androidx.compose.runtime_runtime",
"androidx.compose.material3_material3-window-size-class",
"androidx.window_window",
],
}
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (C) 2025 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT 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.widgetpicker">
</manifest>
+7
View File
@@ -0,0 +1,7 @@
{
"presubmit": [
{
"name": "WidgetPickerScreenshotTests"
}
]
}
+113
View File
@@ -0,0 +1,113 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
plugins {
id(libs.plugins.android.library.get().pluginId)
id(libs.plugins.kotlin.android.get().pluginId)
id(libs.plugins.kotlin.kapt.get().pluginId)
id(libs.plugins.compose.compiler.get().pluginId)
}
// For the screenshot testing lib dependencies
apply<ResourceFixerPlugin>()
val androidTop = extra["ANDROID_TOP"].toString()
val robolibBuildDir = project(":RobolectricLib").layout.buildDirectory.toString()
val widgetPickerDir = "$androidTop/packages/apps/Launcher3/modules/widgetpicker"
android.buildFeatures.compose = true
android {
namespace = "com.android.launcher3.widgetpicker"
testNamespace = "com.android.launcher3.widgetpicker.tests"
defaultConfig {
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
testApplicationId = "com.android.launcher3.widgetpicker.tests"
}
sourceSets {
named("main") {
java.setSrcDirs(listOf("$widgetPickerDir/src"))
manifest.srcFile("$widgetPickerDir/AndroidManifest.xml")
res.setSrcDirs(listOf("$widgetPickerDir/res"))
}
named("androidTest") {
java.setSrcDirs(listOf("$widgetPickerDir/tests/multivalentScreenshotTests/src/"))
manifest.srcFile("$widgetPickerDir/tests/AndroidManifest.xml")
}
}
signingConfigs {
getByName("debug") {
// This is necessary or the private APIs from the studiow-generate SDK won't work.
// Without the platform keystore, it will crash with:
// "java.lang.NoSuchMethodError: No static method asyncTraceForTrackBegin"
storeFile = file("$androidTop/vendor/google/certs/devkeys/platform.keystore")
}
}
testOptions {
unitTests {
isIncludeAndroidResources = true
}
}
// Exclude META-INF for running test with android studio
packagingOptions.resources.excludes.add("META-INF/versions/9/OSGI-INF/MANIFEST.MF")
}
dependencies {
implementation(libs.androidx.core)
implementation(libs.dagger)
kapt(libs.dagger.compiler)
kapt(libs.dagger.android.processor)
// Compose UI dependencies
implementation(libs.compose.ui)
implementation(libs.compose.runtime)
implementation(libs.compose.foundation.layout)
implementation(libs.compose.material3)
implementation(libs.androidx.activity.compose)
// Other UI dependencies
implementation(libs.androidx.material3.window.size.cls)
implementation(libs.androidx.window)
// Compose android studio preview support
implementation(libs.compose.material.icons.extended)
implementation(libs.compose.ui.tooling.preview)
debugImplementation(libs.compose.ui.tooling)
// Testing
// this needs to be modern to support JDK-17 + asm byte code.
testImplementation(libs.mockito.robolectric.bytebuddy.agent)
testImplementation(libs.mockito.robolectric.bytebuddy)
testImplementation(libs.mockito.robolectric)
androidTestImplementation(libs.google.truth)
androidTestImplementation(libs.junit)
androidTestImplementation(libs.mockito.kotlin)
androidTestImplementation(libs.androidx.test.runner)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.test.rules)
// Compose UI Tests
androidTestApi(libs.compose.ui.test.junit4)
debugApi(libs.compose.ui.test.manifest)
// Shared testing libs
testImplementation(project(":RobolectricLib"))
androidTestImplementation(project(":SharedTestLib"))
androidTestImplementation(project(":PlatformParameterizedLib"))
androidTestImplementation(project(":ScreenshotLib"))
androidTestImplementation(project(":ScreenshotComposeLib"))
}
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2025 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT 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>
</resources>
@@ -0,0 +1,63 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.widgetpicker
import dagger.Subcomponent
/**
* A sub-component that apps can include in their dagger module to bootstrap & interact with apis
* provided by widget picker.
*
* Steps:
* 1. Include this component as a sub-component on your app's main dagger module (and remember to
* update Android.bp & gradle files).
* 2. Ensure bindings necessary for repository interfaces used in [WidgetPickerModule] are provided
* in your app.
* 3. Host a singleton class in your app to create an instance of widget picker component on-demand
* e.g. when user wants to open widget picker.
*
* Example for #3.
*
* ```
* @MyAppSingleton
* public class WidgetPickerProvider {
* private final Provider<WidgetPickerComponent.Factory> widgetPickerComponentProvider;
*
* @Inject
* public WidgetPickerProvider(Provider<WidgetPickerComponent.Factory> widgetPickerComponentProvider) {
* this.widgetPickerComponentProvider = widgetPickerComponentProvider;
* }
*
* public boolean show(...) {
* WidgetPickerComponent component = widgetPickerComponentProvider.get().build();
* WidgetPickerUiInteractor interactor = component.getWidgetInteractor();
* return interactor.show(...);
* }
* }
* ```
*/
@WidgetPickerSingleton
@Subcomponent(modules = [WidgetPickerModule::class])
interface WidgetPickerComponent {
@Subcomponent.Factory
interface Factory {
fun build(): WidgetPickerComponent
}
// Interactors / APIs available for clients to interact with widget picker will go here.
// e.g. fun getWidgetPickerUiInteractor(): WidgetPickerUiInteractor
}
@@ -0,0 +1,49 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.widgetpicker
import dagger.Module
/**
* Module that contains the bindings necessary for the widget picker library.
*
* See [WidgetPickerComponent] on how to include this module in your app. Dependencies in this
* module will need to be provided by the host application.
* 1. In following example, we depend on host for providing the `WidgetsRepository`
*
* ```
* @Provides
* @WidgetPickerSingleton
* fun provideWidgetsInteractor(widgetsRepository: WidgetsRepository): WidgetsInteractor
* = WidgetsInteractorImpl(widgetsRepository)
* ```
* 2. Following shows an example of the host module providing concrete implementation for the
* dependency.
*
* ```
* @Module(includes = [WidgetPickerModule::class]
* abstract MyAppSpecificWidgetPickerModule {
* @Binds fun bindWidgetsRepository(impl: MyAppSpecificWidgetsRepositoryImpl): WidgetsRepository
* }
* ```
*/
@Module
interface WidgetPickerModule {
companion object {
// TODO(b/408284734): Add the necessary bindings for widget picker
}
}
@@ -0,0 +1,25 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.widgetpicker
import javax.inject.Scope
/** Scope annotation for singleton items within the widget picker. */
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
@Scope
annotation class WidgetPickerSingleton
@@ -0,0 +1,30 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.widgetpicker.data.repository
import com.android.launcher3.widgetpicker.shared.model.WidgetAppIcon
import com.android.launcher3.widgetpicker.shared.model.WidgetAppId
import kotlinx.coroutines.flow.Flow
/** A repository that provides app icons for the widget picker. */
interface WidgetAppIconsRepository {
/**
* Loads and returns app icon (may initially return a low res icon, followed by a high res once
* available).
*/
fun getAppIcon(widgetAppId: WidgetAppId): Flow<WidgetAppIcon>
}
@@ -0,0 +1,26 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.widgetpicker.data.repository
import com.android.launcher3.widgetpicker.shared.model.WidgetId
import com.android.launcher3.widgetpicker.shared.model.WidgetPreview
/** A repository that provides previews for the widgets to be displayed in the widget picker. */
interface WidgetPreviewRepository {
/** Returns the preview for a widget represented by given [WidgetId]. */
suspend fun getPreview(widgetId: WidgetId): WidgetPreview
}
@@ -0,0 +1,25 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.widgetpicker.data.repository
import com.android.launcher3.widgetpicker.shared.model.WidgetId
/** A repository of widgets that can be recommended to the users in widget picker. */
interface WidgetRecommendationsRepository {
/** Returns a list of widgets that can be recommended to the users in the widget picker. */
suspend fun getRecommendations(): List<WidgetId>
}
@@ -0,0 +1,30 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.widgetpicker.data.repository
import com.android.launcher3.widgetpicker.shared.model.WidgetUserProfileType
import com.android.launcher3.widgetpicker.shared.model.WidgetUserProfiles
import kotlinx.coroutines.flow.Flow
/**
* A repository that provides information about user profiles for which widgets need to be shown in
* the widget picker.
*/
interface WidgetUsersRepository {
/** Get and listen to the changes in available user profiles. */
fun observeUsers(types: List<WidgetUserProfileType>): Flow<WidgetUserProfiles>
}
@@ -0,0 +1,27 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.widgetpicker.data.repository
import com.android.launcher3.widgetpicker.shared.model.PickableWidget
import kotlinx.coroutines.flow.Flow
/** A repository of widgets available on the device from various apps */
interface WidgetsRepository {
/** Observe widgets available on the device. */
fun observeWidgets(): Flow<List<PickableWidget>>
}
@@ -0,0 +1,41 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.widgetpicker.shared.model
import android.appwidget.AppWidgetProviderInfo
/**
* Raw information about a widget that can be considered for display in widget picker list.
*
* Note: It is widget picker's responsibility to run eligibility checks to see if the widget can be
* displayed in picker.
*
* @property id a unique identifier for the widget
* @property appId a unique identifier for the app group that this widget could belong to
* @property label a user friendly label for the widget.
* @property description a user friendly description for the widget
* @property appWidgetProviderInfo widget info associated with the widget as configured by the
* developer; note: this should be a local clone and not the object that was received from
* appwidget manager.
*/
data class PickableWidget(
val id: WidgetId,
val appId: WidgetAppId,
val label: String,
val description: String,
val appWidgetProviderInfo: AppWidgetProviderInfo,
)
@@ -0,0 +1,55 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.widgetpicker.shared.model
import android.graphics.Bitmap
import androidx.annotation.DrawableRes
/**
* Icon to be displayed for an app that hosts widgets.
*
* @property icon an icon representing the app
* @property badge an icon that can be placed over the app [icon] to highlight additional important
* characteristics about the app e.g. if app belongs to a work profile.
*/
data class WidgetAppIcon(val icon: AppIcon, val badge: AppIconBadge)
/** A data type holding information for rendering an icon */
sealed class AppIcon {
/** An icon that can be rendered as a [Bitmap]. */
data class HighResBitmapIcon(val bitmap: Bitmap) : AppIcon()
/**
* A low res icon that should be rendered by filling the icon slot with the provided [color].
*/
data class LowResColorIcon(val color: Int) : AppIcon()
/** Represents a missing app icon. */
data object PlaceHolderAppIcon : AppIcon()
}
sealed class AppIconBadge {
/**
* A badge that should be rendered using the provided drawable [drawableResId] and tinted with
* provided [tintColor].
*/
data class DrawableBadge(@DrawableRes val drawableResId: Int, val tintColor: Int) :
AppIconBadge()
/** Indicates there is no badge available for an app icon. */
data object NoBadge : AppIconBadge()
}
@@ -0,0 +1,31 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.widgetpicker.shared.model
import android.os.UserHandle
/**
* A unique identifier to represent a specific app hosting widgets
*
* @property packageName package of the app hosting widgets; e.g. for widget such as
* "com.example.app/widget.MyWidgetReceiver", the app package should be "com.example.app".
* @property userHandle the user to which this specific app instance belongs to; for example, work
* profile user will have a separate app instance from a personal app instance.
* @property category a unique identifier representing a custom group that is not an app but is
* visually displayed as an app hosting certain types of widgets.
*/
data class WidgetAppId(val packageName: String, val userHandle: UserHandle, val category: Int?)
@@ -0,0 +1,34 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.widgetpicker.shared.model
import android.content.ComponentName
import android.os.UserHandle
/**
* Combination of properties that can be used to uniquely identify a widget in the widget picker.
*
* The information may be also used to combine with other data sources or other purposes such as
* logging.
*
* @property componentName [ComponentName] of the widget's broadcast receiver e.g.
* "com.example.app/widget.MyWidgetReceiver".
* @property userHandle the user to which this specific widget instance belongs to; for example, a
* work profile user will have a separate app instance holding a separate widget from a personal
* app instance.
*/
data class WidgetId(val componentName: ComponentName, val userHandle: UserHandle)
@@ -0,0 +1,52 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.widgetpicker.shared.model
import android.appwidget.AppWidgetProviderInfo
import android.graphics.Bitmap
import android.widget.RemoteViews
/** Represents different types & states of a widget preview. */
sealed class WidgetPreview {
/**
* Holds widget's preview as a [Bitmap].
*
* This is the case when developer only provides image previews via the `android:previewImage`
* configuration on their app widget info xml.
*/
data class BitmapWidgetPreview(val bitmap: Bitmap) : WidgetPreview()
/**
* Holds widget preview as [RemoteViews].
*
* This is the case when developer provides previews using the generated previews api
* (`AppWidgetManager.setWidgetPreview`).
*/
data class RemoteViewsWidgetPreview(val remoteViews: RemoteViews) : WidgetPreview()
/**
* Holds the widget previews as [AppWidgetProviderInfo] containing the layout xml widget
* preview.
*
* @property providerInfo [AppWidgetProviderInfo] where initial layout is set to the widget's
* `android:previewLayout`.
*/
data class ProviderInfoWidgetPreview(val providerInfo: AppWidgetProviderInfo) : WidgetPreview()
/** Represents a state where widget preview is not available. */
data object PlaceholderWidgetPreview : WidgetPreview()
}
@@ -0,0 +1,47 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.widgetpicker.shared.model
/**
* Holds data about all the available user profiles on device that are supported in the widget
* picker.
*/
data class WidgetUserProfiles(val users: List<WidgetUserProfile>)
/**
* Data about a specific user profile that is supported in the widget picker.
*
* @property type profile type of the user e.g. personal / work etc.
* @property label a user friendly string representing the profile e.g. Personal / Work; when a work
* profile is setup, this may be set by the enterprise.
* @property paused indicates if the user profile is currently paused
* @property pausedProfileMessage optional message that can be shown to the user when a profile is
* [paused] (instead of listing widgets for the profile); this may be set by the enterprise; if
* null and the profile is [paused] a default message will be displayed.
*/
data class WidgetUserProfile(
val type: WidgetUserProfileType,
val label: String,
val paused: Boolean,
val pausedProfileMessage: String,
)
/** Represents types of user profiles that are supported in the widget picker. */
enum class WidgetUserProfileType {
PERSONAL,
WORK,
}
@@ -0,0 +1,114 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.widgetpicker.ui.components
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.expandIn
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkOut
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.minimumInteractiveComponentSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
/**
* A tab (suitable for displaying in a horizontal toolbar) that shows a leading icon along with its
* label.
*
* The icon is shown only when tab is selected (it animates per the provided transition spec.)
*/
@Composable
fun LeadingIconToolbarTab(
leadingIcon: ImageVector,
label: String,
selected: Boolean,
onClick: () -> Unit,
selectedBackgroundColor: Color = LeadingIconToolbarTabDefaults.selectedBackgroundColor,
contentColor: Color = LeadingIconToolbarTabDefaults.contentColor,
textStyle: TextStyle = LeadingIconToolbarTabDefaults.textStyle,
iconEnterTransition: EnterTransition = LeadingIconToolbarTabDefaults.iconEnterTransition,
iconExitTransition: ExitTransition = LeadingIconToolbarTabDefaults.iconExitTransition,
) {
val backgroundColor =
if (selected) {
selectedBackgroundColor
} else {
Color.Transparent
}
Row(
modifier =
Modifier.fillMaxWidth()
.clip(CircleShape)
.background(color = backgroundColor)
.minimumInteractiveComponentSize()
.padding(horizontal = LeadingIconToolbarTabDefaults.horizontalPadding)
.clickable { onClick() },
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
) {
this@Row.AnimatedVisibility(
visible = selected,
enter = iconEnterTransition,
exit = iconExitTransition,
) {
Icon(
imageVector = leadingIcon,
contentDescription = null, // decorative
modifier = Modifier.padding(end = LeadingIconToolbarTabDefaults.contentSpacing),
tint = contentColor,
)
}
Text(text = label, style = textStyle, color = contentColor)
}
}
/** Holds default values used by the [LeadingIconToolbarTab]. */
object LeadingIconToolbarTabDefaults {
val selectedBackgroundColor: Color
@Composable get() = MaterialTheme.colorScheme.secondaryContainer
val contentColor: Color
@Composable get() = MaterialTheme.colorScheme.onSecondaryContainer
val textStyle: TextStyle
@Composable get() = MaterialTheme.typography.labelLarge
val horizontalPadding = 16.dp
val contentSpacing = 8.dp
val iconEnterTransition: EnterTransition = fadeIn() + expandIn(expandFrom = Alignment.Center)
val iconExitTransition: ExitTransition = fadeOut() + shrinkOut(shrinkTowards = Alignment.Center)
}
@@ -0,0 +1,242 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.widgetpicker.ui.components
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.Measurable
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.fastFold
import androidx.compose.ui.util.fastForEachIndexed
import androidx.compose.ui.util.fastMap
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
/**
* A horizontal toolbar that displays the provided [tabs] in a scrollable row.
* - When the tab content is longer, the selected tab is auto-scrolled into the visible area.
* - When the tab content is less than the [maxWidth], the toolbar wraps the contents.
*
* This is a mixed variant of the androidx compose material3 library's FloatingToolbar and
* PrimaryScrollableTabRow components. Visually it looks like the FloatingToolbar and in additional
* supports longer tab names by enabling scrolling behavior similar to a PrimaryScrollableTabRow.
* - compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/FloatingToolbar.kt
* - compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/TabRow.kt
*
* This design is suitable for 2-3 tabs.
*
* @property tabs A list of tabs (typically [LeadingIconToolbarTab]) that can be arranged in a
* scrollable row.
* @property selectedTabIndex the tab that is currently selected; this enables bringing the tab into
* the visible area.
* @property modifier additional modifications to be applied to the top level of the toolbar.
* @property shape shape to clip the contents of the toolbar; defaults to fully rounded corners.
* @property edgePadding padding applied horizontally on sides of the toolbar; in case of long
* length tabs, visually the padding will appear only on left (in LTR for instance) and when you
* scroll completely to right, the padding will appear on right; in case tab content is smaller in
* length, the padding appears on both sides.
* @property maxWidth if the toolbar needs to be constraint to a specific width.
* @property minTabWidth minimum width to be guaranteed for individual tabs
* @property containerColor color to be applied to the surface of toolbar
* @property scrollState the [ScrollState] of the toolbar's scrollable tab content
*/
@Composable
fun ScrollableFloatingToolbar(
tabs: List<@Composable () -> Unit>,
selectedTabIndex: Int,
modifier: Modifier = Modifier,
shape: Shape = ScrollableFloatingToolbarDefaults.shape,
edgePadding: Dp = ScrollableFloatingToolbarDefaults.edgePadding,
maxWidth: Dp = ScrollableFloatingToolbarDefaults.maxWidth,
minTabWidth: Dp = ScrollableFloatingToolbarDefaults.minTabWidth,
containerColor: Color = ScrollableFloatingToolbarDefaults.containerColor,
) {
check(tabs.size in 2..3) { "Unexpected number of tabs: ${tabs.size}. Suitable for 2-3 tabs." }
val scrollState = rememberScrollState()
Surface(
color = containerColor,
modifier = modifier.clip(shape).wrapContentSize(align = Alignment.Center),
) {
ScrollableTabsLayout(
tabs = tabs,
scrollState = scrollState,
maxWidth = maxWidth,
edgePadding = edgePadding,
minTabWidth = minTabWidth,
selectedTabIndex = selectedTabIndex,
)
}
}
@Composable
private fun ScrollableTabsLayout(
tabs: List<@Composable () -> Unit>,
scrollState: ScrollState,
maxWidth: Dp,
edgePadding: Dp,
minTabWidth: Dp,
selectedTabIndex: Int,
) {
val coroutineScope = rememberCoroutineScope()
val tabsScrollState =
remember(scrollState, coroutineScope) {
TabsScrollState(scrollState = scrollState, coroutineScope = coroutineScope)
}
val tabsContent: @Composable () -> Unit = { tabs.forEach { it() } }
Layout(
contents = listOf(tabsContent),
modifier =
Modifier.widthIn(max = maxWidth) // constraint the layout itself to specific max.
.wrapContentSize(align = Alignment.Center)
.padding(vertical = ScrollableFloatingToolbarDefaults.verticalPadding)
.horizontalScroll(scrollState)
.selectableGroup()
.clipToBounds(),
) { (tabMeasurables), constraints ->
val edgePaddingPx = edgePadding.roundToPx()
val minTabWidthPx = minTabWidth.roundToPx()
val layoutHeightPx = tabMeasurables.maxIntrinsicHeight()
val tabConstraints =
constraints.copy(
minWidth = minTabWidthPx,
minHeight = layoutHeightPx,
maxHeight = layoutHeightPx,
)
val tabPlaceables = tabMeasurables.fastMap { it.measure(tabConstraints) }
// Start with the left padding and add up the width of each tab.
// Also keep track of the position of each tab.
val (accumulatedWidthPx: Int, tabPositions: List<TabPosition>) =
tabPlaceables.fold(initial = Pair(edgePaddingPx, mutableListOf<TabPosition>())) {
(accumulatedWidthPx, accumulatedPositions),
placeable ->
val tabWidthPx = maxOf(minTabWidthPx, placeable.width)
accumulatedPositions.add(
TabPosition(leftPx = accumulatedWidthPx, widthPx = tabWidthPx)
)
Pair(accumulatedWidthPx + tabWidthPx, accumulatedPositions)
}
// add right padding
val totalLayoutWidthPx = accumulatedWidthPx + edgePaddingPx
layout(totalLayoutWidthPx, layoutHeightPx) {
tabPlaceables.fastForEachIndexed { index, placeable ->
placeable.placeRelative(x = tabPositions[index].leftPx, y = 0)
}
tabsScrollState.scrollToSelectedTab(
tabPositions = tabPositions,
selectedTab = selectedTabIndex,
totalWidthPx = totalLayoutWidthPx,
)
}
}
}
private data class TabPosition(val leftPx: Int, val widthPx: Int)
private class TabsScrollState(
private val scrollState: ScrollState,
private val coroutineScope: CoroutineScope,
) {
private var selectedTab: Int? = null
fun scrollToSelectedTab(tabPositions: List<TabPosition>, selectedTab: Int, totalWidthPx: Int) {
if (this.selectedTab != selectedTab) {
this.selectedTab = selectedTab
tabPositions.getOrNull(selectedTab)?.let { selectedTabPosition ->
val targetScrollOffset =
offsetRequiredToCenterTheTab(
tabPosition = selectedTabPosition,
totalToolbarWidth = totalWidthPx,
visibleRightOffset = scrollState.maxValue,
)
if (scrollState.value != targetScrollOffset) {
coroutineScope.launch { scrollState.animateScrollTo(targetScrollOffset) }
}
}
}
}
/**
* Returns the offset position to scroll to such that the given tab is positioned in center of
* the visible toolbar width.
*/
private fun offsetRequiredToCenterTheTab(
tabPosition: TabPosition,
totalToolbarWidth: Int,
visibleRightOffset: Int,
): Int {
val visibleToolbarWidth = totalToolbarWidth - visibleRightOffset
val currentTabStart = tabPosition.leftPx
val visibleToolbarCenter = visibleToolbarWidth / 2
val tabHalfWidth = tabPosition.widthPx / 2
val centeredTabOffset = currentTabStart - (visibleToolbarCenter - tabHalfWidth)
return centeredTabOffset.coerceIn(0, visibleRightOffset.coerceAtLeast(0))
}
}
/**
* Finds out the smallest height in px beyond which increasing the height never decreases the width
* of measurable(s) in this list.
*/
private fun List<Measurable>.maxIntrinsicHeight() =
fastFold(initial = 0) { curr, measurable ->
maxOf(curr, measurable.maxIntrinsicHeight(Constraints.Infinity))
}
/** Holds default values used by the [ScrollableFloatingToolbar]. */
object ScrollableFloatingToolbarDefaults {
val shape = CircleShape
val verticalPadding = 8.dp
val edgePadding: Dp = 8.dp
val maxWidth: Dp = 348.dp
val minTabWidth: Dp = 90.dp
val containerColor: Color
@Composable get() = MaterialTheme.colorScheme.surfaceBright
}
@@ -0,0 +1,210 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.widgetpicker.ui.components
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.displayCutout
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.union
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.SheetValue
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.times
import com.android.launcher3.widgetpicker.ui.components.DragHandleDimens.dragHandleHeight
import com.android.launcher3.widgetpicker.ui.components.DragHandleDimens.dragHandleWidth
import com.android.launcher3.widgetpicker.ui.components.TitledBottomSheetDimens.headerBottomMargin
import com.android.launcher3.widgetpicker.ui.components.TitledBottomSheetDimens.sheetInnerHorizontalPadding
import com.android.launcher3.widgetpicker.ui.components.TitledBottomSheetDimens.sheetInnerTopPadding
import com.android.launcher3.widgetpicker.ui.windowsizeclass.WindowInfo
import com.android.launcher3.widgetpicker.ui.windowsizeclass.calculateWindowInfo
import com.android.launcher3.widgetpicker.ui.windowsizeclass.isExtraTall
/**
* A bottom sheet with title and description on the top. Intended to serve as a common container
* structure for different types of widget pickers.
*
* @param modifier modifier to be applies to the bottom sheet container.
* @param title A top level title for the bottom sheet.
* @param description an optional short (1-2 line) description that can be shown below the title.
* @param heightStyle indicates how much vertical space should the bottom sheet take; see
* [ModalBottomSheetHeightStyle].
* @param showDragHandle whether to show drag handle; e.g. if the content doesn't need scrolling set
* this to false.
* @param onDismissRequest callback to be invoked when the bottom sheet is closed
* @param content the content to be displayed below the [title] and [description]
*/
@Composable
@OptIn(ExperimentalMaterial3Api::class)
fun TitledBottomSheet(
modifier: Modifier = Modifier,
title: String,
description: String?,
heightStyle: ModalBottomSheetHeightStyle,
showDragHandle: Boolean = true,
onDismissRequest: () -> Unit,
content: @Composable () -> Unit,
) {
val modalBottomSheetState =
rememberModalBottomSheetState(
skipPartiallyExpanded = true,
confirmValueChange = { value -> value != SheetValue.PartiallyExpanded },
)
val windowInfo = LocalConfiguration.current.calculateWindowInfo()
val dragHandle: (@Composable () -> Unit)? =
remember(showDragHandle) {
if (showDragHandle) {
{
DragHandle(
modifier =
Modifier.padding(
top = sheetInnerTopPadding,
bottom = headerBottomMargin,
)
)
}
} else null
}
ModalBottomSheet(
sheetState = modalBottomSheetState,
sheetMaxWidth = Dp.Unspecified,
containerColor = MaterialTheme.colorScheme.surfaceContainer,
onDismissRequest = onDismissRequest,
dragHandle = dragHandle,
modifier =
modifier.windowInsetsPadding(WindowInsets.statusBars.union(WindowInsets.displayCutout)),
) {
Column(
modifier =
Modifier.sheetContentHeight(heightStyle, windowInfo)
.padding(horizontal = sheetInnerHorizontalPadding)
.padding(top = sheetInnerTopPadding.takeIf { !showDragHandle } ?: 0.dp)
) {
Header(title = title, description = description)
content()
}
}
}
@Composable
private fun DragHandle(modifier: Modifier) {
Surface(
modifier = modifier,
color = MaterialTheme.colorScheme.outline,
shape = MaterialTheme.shapes.medium,
) {
Box(Modifier.size(width = dragHandleWidth, height = dragHandleHeight))
}
}
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
@Composable
private fun Header(title: String, description: String?) {
Column(modifier = Modifier.padding(bottom = headerBottomMargin).fillMaxWidth()) {
Text(
modifier = Modifier.wrapContentHeight().fillMaxWidth(),
maxLines = 1,
text = title,
textAlign = TextAlign.Center,
style = MaterialTheme.typography.headlineSmallEmphasized,
color = MaterialTheme.colorScheme.onSurface,
)
description?.let {
Text(
modifier = Modifier.wrapContentHeight().fillMaxWidth(),
maxLines = 2,
text = it,
textAlign = TextAlign.Center,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
private object TitledBottomSheetDimens {
val sheetInnerTopPadding = 16.dp
val sheetInnerHorizontalPadding = 10.dp
val headerBottomMargin = 24.dp
}
private object DragHandleDimens {
val dragHandleHeight = 4.dp
val dragHandleWidth = 32.dp
}
/**
* Describes how should the default height of the bottom sheet look like (excluding the insets such
* as status bar).
*/
enum class ModalBottomSheetHeightStyle {
/**
* Fills the available height; capped to a max for extra tall cases. Useful for cases where
* irrespective of content, we want it to be expanded fully.
*/
FILL_HEIGHT,
/**
* Wraps the content's height; capped to a max for extra tall cases. Set up vertical scrolling
* if the content can be longer than the available height. Useful for cases like single app
* widget picker or pin widget picker that don't need to expand fully.
*/
WRAP_CONTENT,
}
@Composable
private fun Modifier.sheetContentHeight(
style: ModalBottomSheetHeightStyle,
windowInfo: WindowInfo,
): Modifier {
val heightModifier =
when (style) {
ModalBottomSheetHeightStyle.FILL_HEIGHT -> this.fillMaxHeight()
ModalBottomSheetHeightStyle.WRAP_CONTENT -> this.wrapContentHeight()
}
return if (windowInfo.isExtraTall()) {
// Cap the height to max 2/3 of total window height; so the bottom sheet doesn't feel too
// huge.
heightModifier.heightIn(max = 2 * windowInfo.size.height / 3)
} else {
heightModifier
}
}
@@ -0,0 +1,53 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.widgetpicker.ui.windowsizeclass
import android.content.res.Configuration
import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi
import androidx.compose.material3.windowsizeclass.WindowSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.toComposeRect
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.window.layout.WindowMetricsCalculator
/**
* Provides window size for the current configuration.
*
* Unlike "calculateWindowSizeClass" provided by windowSizeClass material library, this works
* independent of whether you are running with activity (real app) or not (android studio preview).
* And the "currentWindowAdaptiveInfo" provided by material adaptive library seems deprecated.
*/
@OptIn(ExperimentalMaterial3WindowSizeClassApi::class)
@Composable
// Suppress: Configuration is used as receiver to indicate recomposition on config changes.
@Suppress("UnusedReceiverParameter")
fun Configuration.calculateWindowInfo(): WindowInfo {
val density = LocalDensity.current
val context = LocalContext.current
val metrics = WindowMetricsCalculator.getOrCreate().computeCurrentWindowMetrics(context)
val size = with(density) { metrics.bounds.toComposeRect().size.toDpSize() }
return WindowInfo(WindowSizeClass.calculateFromSize(size), size)
}
/** Information about the window's size. */
data class WindowInfo(val windowSizeClass: WindowSizeClass, val size: DpSize)
/** Returns true if the window is extra tall e.g. portrait on a tablet. */
fun WindowInfo.isExtraTall() = size.height > 1200.dp
+69
View File
@@ -0,0 +1,69 @@
// Copyright (C) 2025 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package {
// See: http://go/android-license-faq
default_applicable_licenses: ["Android-Apache-2.0"],
default_team: "trendy_team_launcher",
}
android_app {
name: "WidgetPickerTestApp",
defaults: [
"platform_app_defaults",
"SystemUI_optimized_defaults",
],
platform_apis: true,
static_libs: [
"widget_picker_ui_components",
],
}
android_test {
name: "WidgetPickerScreenshotTests",
manifest: "AndroidManifest.xml",
srcs: [
"multivalentScreenshotTests/src/com/android/launcher3/widgetpicker/goldenpathmanager/WidgetPickerGoldenPathManager.kt",
"multivalentScreenshotTests/src/com/android/launcher3/widgetpicker/ui/components/FloatingToolbarScreenshotTest.kt",
],
sdk_version: "current",
static_libs: [
"widget_picker_ui_components",
"collector-device-lib-platform",
"testables",
"androidx.compose.runtime_runtime",
"junit",
"androidx.test.ext.junit",
"androidx.test.rules",
"androidx.test.runner",
"platform-screenshot-diff-core",
"platform-parametric-runner-lib",
"ScreenshotComposeUtilsLib",
"SystemUI-res", // Theme.SystemUI (dragged in by ScreenshotComposeUtilsLib)
],
libs: [
"android.test.base.stubs.system",
"android.test.runner.stubs.system",
],
kotlincflags: ["-Xjvm-default=all"],
// Needed to compile native libs for cuttlefish
compile_multilib: "both",
// Needed to link mokito libraries to run unbundled
use_embedded_native_libs: false,
instrumentation_for: "WidgetPickerTestApp",
test_config: "WidgetPickerScreenshotTests.xml",
test_suites: ["device-tests"],
certificate: "platform",
asset_dirs: ["multivalentScreenshotTests/assets/widgetpicker_screenshots"],
}
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8"?><!--
~ Copyright (C) 2025 The Android Open Source Project
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT 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"
xmlns:tools="http://schemas.android.com/tools"
package="com.android.launcher3.widgetpicker.tests">
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"
tools:ignore="ProtectedPermissions" />
<instrumentation
android:name="androidx.test.runner.AndroidJUnitRunner"
android:label="Tests for the appwidget picker library"
android:targetPackage="com.android.launcher3.widgetpicker.tests">
</instrumentation>
</manifest>
@@ -0,0 +1,36 @@
<!--
Copyright (C) 2025 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<configuration description="Runs screenshot tests for the widget picker library.">
<option name="test-suite-tag" value="apct-instrumentation" />
<option name="test-suite-tag" value="apct" />
<target_preparer class="com.android.tradefed.targetprep.DeviceSetup">
<option name="optimized-property-setting" value="true" />
</target_preparer>
<target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
<option name="cleanup-apks" value="true" />
<option name="test-file-name" value="WidgetPickerScreenshotTests.apk" />
</target_preparer>
<metrics_collector class="com.android.tradefed.device.metric.FilePullerLogCollector">
<option name="directory-keys"
value="/data/user/0/com.android.launcher3.widgetpicker.tests/files/widgetpicker_screenshots" />
<option name="collect-on-run-ended-only" value="true" />
</metrics_collector>
<test class="com.android.tradefed.testtype.AndroidJUnitTest">
<option name="package" value="com.android.launcher3.widgetpicker.tests" />
<option name="runner" value="androidx.test.runner.AndroidJUnitRunner" />
</test>
</configuration>
@@ -0,0 +1,55 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.widgetpicker.goldenpathmanager
import android.os.Build
import androidx.test.platform.app.InstrumentationRegistry
import platform.test.screenshot.GoldenPathManager
import platform.test.screenshot.PathConfig
/** Class to manage location of goldens for the widget picker specific screenshot tests */
class WidgetPickerGoldenPathManager(pathConfig: PathConfig) :
GoldenPathManager(
appContext = InstrumentationRegistry.getInstrumentation().context,
assetsPathRelativeToBuildRoot = assetPath,
deviceLocalPath = deviceLocalPath,
pathConfig = pathConfig,
) {
private companion object {
private const val ASSETS_PATH =
"packages/apps/Launcher3/modules/widgetpicker/tests/multivalentScreenshotTests/assets/widgetpicker_screenshots"
private const val ASSETS_PATH_ROBO =
"packages/apps/Launcher3/modules/widgetpicker/tests/multivalentScreenshotTests/assets/widgetpicker_screenshots_robolectric"
private val assetPath: String
get() = if (Build.FINGERPRINT.contains("robolectric")) ASSETS_PATH_ROBO else ASSETS_PATH
private val deviceLocalPath: String
get() =
InstrumentationRegistry.getInstrumentation()
.targetContext
.filesDir
.absolutePath
.toString() + "/widgetpicker_screenshots"
}
override fun toString(): String {
// This string is appended to all actual/expected screenshots on the device, so make sure
// it is a static value.
return "WidgetPickerGoldenPathManager"
}
}
@@ -0,0 +1,243 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.widgetpicker.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.Work
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.android.launcher3.widgetpicker.goldenpathmanager.WidgetPickerGoldenPathManager
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import platform.test.runner.parameterized.ParameterizedAndroidJunit4
import platform.test.runner.parameterized.Parameters
import platform.test.screenshot.DeviceEmulationSpec
import platform.test.screenshot.Displays
import platform.test.screenshot.getEmulatedDevicePathConfig
import platform.test.screenshot.utils.compose.ComposeScreenshotTestRule
@RunWith(ParameterizedAndroidJunit4::class)
class FloatingToolbarScreenshotTest(emulationSpec: DeviceEmulationSpec) {
@get:Rule(order = 1)
val screenshotRule =
ComposeScreenshotTestRule(
emulationSpec,
WidgetPickerGoldenPathManager(getEmulatedDevicePathConfig(emulationSpec)),
)
@Test
fun scrollableFloatingToolbar_twoTabs() {
screenshotRule.screenshotTest("scrollableFloatingToolbar_twoTabs") { TwoTabsPreview() }
}
@Test
fun scrollableFloatingToolbar_threeTabs() {
screenshotRule.screenshotTest("scrollableFloatingToolbar_threeTabs") { ThreeTabsPreview() }
}
companion object {
@Parameters(name = "{0}")
@JvmStatic
fun getTestSpecs(): List<DeviceEmulationSpec> {
return DeviceEmulationSpec.forDisplays(Displays.Phone, isLandscape = false)
}
}
}
@Preview
@Composable
private fun TwoTabsPreview() {
var selectedIndexOne: Int by remember { mutableStateOf(0) }
var selectedIndexTwo: Int by remember { mutableStateOf(1) }
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier =
Modifier.background(
MaterialTheme.colorScheme.surfaceContainer
) // uses bg color of picker
.padding(8.dp),
) {
TestComposable(
tabs = TWO_TABS,
selectedIndex = selectedIndexOne,
onClick = { selectedIndexOne = it },
)
TestSpacer()
TestComposable(
tabs = TWO_TABS,
selectedIndex = selectedIndexTwo,
onClick = { selectedIndexTwo = it },
)
TestSpacer()
TestComposable(
tabs = TWO_LONG_TABS,
selectedIndex = selectedIndexOne,
onClick = { selectedIndexOne = it },
)
TestSpacer()
TestComposable(
tabs = TWO_LONG_TABS,
selectedIndex = selectedIndexTwo,
onClick = { selectedIndexTwo = it },
)
}
}
@Preview
@Composable
private fun ThreeTabsPreview() {
var selectedIndexOne: Int by remember { mutableStateOf(0) }
var selectedIndexTwo: Int by remember { mutableStateOf(1) }
var selectedIndexThree: Int by remember { mutableStateOf(2) }
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier =
Modifier.background(
MaterialTheme.colorScheme.surfaceContainer
) // uses bg color of picker
.padding(8.dp),
) {
TestComposable(
tabs = THREE_TABS,
selectedIndex = selectedIndexOne,
onClick = { selectedIndexOne = it },
)
TestSpacer()
TestComposable(
tabs = THREE_TABS,
selectedIndex = selectedIndexTwo,
onClick = { selectedIndexTwo = it },
)
TestSpacer()
TestComposable(
tabs = THREE_TABS,
selectedIndex = selectedIndexThree,
onClick = { selectedIndexThree = it },
)
TestSpacer()
TestComposable(
tabs = THREE_LONG_TABS,
selectedIndex = selectedIndexOne,
onClick = { selectedIndexOne = it },
)
TestSpacer()
TestComposable(
tabs = THREE_LONG_TABS,
selectedIndex = selectedIndexTwo,
onClick = { selectedIndexTwo = it },
)
TestSpacer()
TestComposable(
tabs = THREE_LONG_TABS,
selectedIndex = selectedIndexThree,
onClick = { selectedIndexThree = it },
)
}
}
@Composable
private fun TestComposable(
tabs: List<FloatingToolbarTestItems>,
selectedIndex: Int,
onClick: (id: Int) -> Unit = {},
) {
ScrollableFloatingToolbar(
modifier = Modifier.wrapContentSize(align = Alignment.Center),
selectedTabIndex = selectedIndex,
tabs =
tabs.map {
{
LeadingIconToolbarTab(
label = it.label,
leadingIcon = it.leadingIcon,
selected = it.id == selectedIndex,
onClick = { onClick(it.id) },
)
}
},
)
}
@Composable
private fun TestSpacer() {
Spacer(modifier = Modifier.height(8.dp).fillMaxWidth())
}
private data class FloatingToolbarTestItems(
val id: Int,
val label: String,
val leadingIcon: ImageVector,
)
private val THREE_TABS =
listOf(
FloatingToolbarTestItems(id = 0, label = "Featured", leadingIcon = Icons.Filled.Star),
FloatingToolbarTestItems(id = 1, label = "Personal", leadingIcon = Icons.Filled.Person),
FloatingToolbarTestItems(id = 2, label = "Work", leadingIcon = Icons.Filled.Work),
)
private val THREE_LONG_TABS =
listOf(
FloatingToolbarTestItems(id = 0, label = "A long tab A", leadingIcon = Icons.Filled.Star),
FloatingToolbarTestItems(
id = 1,
label = "Super longer tab B",
leadingIcon = Icons.Filled.Person,
),
FloatingToolbarTestItems(
id = 2,
label = "Much much longer tab C",
leadingIcon = Icons.Filled.Work,
),
)
private val TWO_TABS =
listOf(
FloatingToolbarTestItems(id = 0, label = "Featured", leadingIcon = Icons.Filled.Star),
FloatingToolbarTestItems(id = 1, label = "Browse", leadingIcon = Icons.Filled.Person),
)
private val TWO_LONG_TABS =
listOf(
FloatingToolbarTestItems(id = 0, label = "A long tab", leadingIcon = Icons.Filled.Star),
FloatingToolbarTestItems(
id = 1,
label = "Another long tab",
leadingIcon = Icons.Filled.Person,
),
)
+8 -1
View File
@@ -391,7 +391,6 @@
<item name="privateSpaceSettingsColor">@androidprv:color/surface_effect_2</item>
<item name="privateSpaceDividerColor">@androidprv:color/surface_effect_3</item>
<item name="bottomSheetDragHandleColor">@androidprv:color/surface_effect_1</item>
<item name="overviewScrimColor">?attr/overviewScrimColorBlur</item>
</style>
<style name="BlurFallbackStyle">
@@ -405,6 +404,14 @@
<item name="privateSpaceSettingsColor">@color/materialColorSurfaceBright</item>
<item name="privateSpaceDividerColor">@color/materialColorOutlineVariant</item>
<item name="bottomSheetDragHandleColor">@color/materialColorOutlineVariant</item>
</style>
<style name="OverviewBlurStyle">
<item name="overviewScrimColor">?attr/overviewScrimColorBlur</item>
</style>
<style name="OverviewBlurFallbackStyle">
<item name="overviewScrimColor">?attr/overviewScrimColorFallback</item>
</style>
</resources>
@@ -1139,7 +1139,7 @@ public class QuickstepTransitionManager implements OnDeviceProfileChangeListener
private Animator getBackgroundAnimator() {
LauncherState launcherState = mLauncher.getStateManager().getState();
boolean currentlyBlurringAllApps = Flags.allAppsBlur() && launcherState == ALL_APPS
&& mLauncher.isBackgroundBlurEnabled();
&& mLauncher.isAllAppsBackgroundBlurEnabled();
if (currentlyBlurringAllApps) {
// Don't additionally animate/blur the background for this launch (All Apps content
// already scales slightly to simulate depth).
@@ -136,6 +136,7 @@ public class DepthController extends BaseDepthController implements StateHandler
} else {
removeOnDrawListener();
setBaseSurface(null);
setEarlyWakeup(false);
}
}
@@ -88,10 +88,6 @@ public class FallbackTaskbarUIController
@Override
protected void onDestroy() {
super.onDestroy();
RecentsView recentsView = getRecentsView();
if (recentsView != null) {
recentsView.setTaskLaunchListener(null);
}
mRecentsContainer.setTaskbarUIController(null);
mRecentsContainer.getStateManager().removeStateListener(mStateListener);
}
@@ -28,6 +28,7 @@ import com.android.launcher3.model.data.ItemInfo
import com.android.launcher3.model.data.WorkspaceItemInfo
import com.android.launcher3.popup.SystemShortcut
import com.android.launcher3.views.ActivityContext
import com.android.window.flags.Flags.enablePinningAppWithContextMenu
/**
* A single menu item shortcut to allow users to pin an item to the taskbar and unpin an item from
@@ -88,4 +89,10 @@ class PinToTaskbarShortcut<T>(
writer.addItemToDatabase(newInfo, CONTAINER_HOTSEAT, mItemInfo.screenId, cellX, cellY)
}
companion object {
fun isPinningAppWithContextMenuEnabled(context: TaskbarActivityContext): Boolean {
return enablePinningAppWithContextMenu() && context.isTaskbarShowingDesktopTasks
}
}
}
@@ -1108,6 +1108,7 @@ public class TaskbarLauncherStateController {
RecentsView recentsView = mControllers.uiController.getRecentsView();
if (recentsView != null) {
recentsView.setTaskLaunchListener(null);
recentsView.setTaskLaunchCancelledRunnable(null);
}
if (mSkipNextRecentsAnimEnd && !canceled) {
@@ -19,7 +19,6 @@ import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_ALL_APP
import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_HOTSEAT;
import static com.android.launcher3.model.data.AppInfo.COMPONENT_KEY_COMPARATOR;
import static com.android.launcher3.util.SplitConfigurationOptions.getLogEventForPosition;
import static com.android.window.flags.Flags.enablePinningAppWithContextMenu;
import android.content.Intent;
import android.content.pm.LauncherApps;
@@ -149,7 +148,7 @@ public class TaskbarPopupController implements TaskbarControllers.LoggableTaskba
ItemInfo itemInfo = null;
if (icon.getTag() instanceof ItemInfo item && ShortcutUtil.supportsShortcuts(item)) {
itemInfo = item;
} else if (enablePinningAppWithContextMenu()
} else if (PinToTaskbarShortcut.Companion.isPinningAppWithContextMenuEnabled(mContext)
&& icon.getTag() instanceof SingleTask task) {
Task.TaskKey key = task.getTask().getKey();
AppInfo appInfo = getApp(
@@ -174,7 +173,7 @@ public class TaskbarPopupController implements TaskbarControllers.LoggableTaskba
.collect(Collectors.toList());
// TODO(b/375648361): Revisit to see if this can be implemented within getSystemShortcuts().
if (enablePinningAppWithContextMenu()) {
if (PinToTaskbarShortcut.Companion.isPinningAppWithContextMenuEnabled(mContext)) {
SystemShortcut shortcut = createPinShortcut(context, itemInfo, icon);
if (shortcut != null) {
systemShortcuts.add(0, shortcut);
@@ -24,6 +24,7 @@ import com.android.launcher3.Flags.enableRecentsInTaskbar
import com.android.launcher3.model.data.ItemInfo
import com.android.launcher3.model.data.TaskItemInfo
import com.android.launcher3.model.data.WorkspaceItemInfo
import com.android.launcher3.taskbar.PinToTaskbarShortcut.Companion.isPinningAppWithContextMenuEnabled
import com.android.launcher3.taskbar.TaskbarControllers.LoggableTaskbarController
import com.android.launcher3.util.CancellableTask
import com.android.quickstep.RecentsFilterState
@@ -32,7 +33,6 @@ import com.android.quickstep.util.DesktopTask
import com.android.quickstep.util.GroupTask
import com.android.quickstep.util.SingleTask
import com.android.systemui.shared.recents.model.Task
import com.android.window.flags.Flags.enablePinningAppWithContextMenu
import com.android.wm.shell.shared.desktopmode.DesktopModeStatus
import java.io.PrintWriter
@@ -41,8 +41,10 @@ import java.io.PrintWriter
* - When in Fullscreen mode: show the N most recent Tasks
* - When in Desktop Mode: show the currently running (open) Tasks
*/
class TaskbarRecentAppsController(context: Context, private val recentsModel: RecentsModel) :
LoggableTaskbarController {
class TaskbarRecentAppsController(
private val context: Context,
private val recentsModel: RecentsModel,
) : LoggableTaskbarController {
var canShowRunningApps =
DesktopModeStatus.canEnterDesktopMode(context) &&
@@ -332,12 +334,13 @@ class TaskbarRecentAppsController(context: Context, private val recentsModel: Re
if (Flags.enableMultiInstanceMenuTaskbar()) {
val deduplicatedDesktopTasks =
desktopTasks.distinctBy { Pair(it.task.key.packageName, it.task.key.userId) }
val activityContext = controllers.taskbarActivityContext
shownTasks
.filter {
it is SingleTask &&
it.task.key.id in deduplicatedDesktopTasks.map { it.task.key.id } &&
(!enablePinningAppWithContextMenu() ||
(!isPinningAppWithContextMenuEnabled(activityContext) ||
shownHotseatItems.none { hotseatItem ->
it.containsPackage(
hotseatItem.targetPackage,
@@ -72,6 +72,11 @@ public class TaskbarUIController implements BubbleBarController.BubbleBarLocatio
@CallSuper
protected void onDestroy() {
mControllers = null;
RecentsView recentsView = getRecentsView();
if (recentsView != null) {
recentsView.setTaskLaunchListener(null);
recentsView.setTaskLaunchCancelledRunnable(null);
}
}
protected boolean isTaskbarTouchable() {
@@ -114,7 +114,7 @@ public class TaskbarAllAppsSlideInView extends AbstractSlideInView<TaskbarOverla
}
private void showOnFullyAttachedToWindow(boolean animate) {
if (mActivityContext.isBackgroundBlurEnabled()) {
if (mActivityContext.isAllAppsBackgroundBlurEnabled()) {
ViewRootImpl overlayVri = mActivityContext.getRootView().getViewRootImpl();
if (overlayVri == null) {
Log.w(TAG, "overlayVRI is null, cannot notifyRendererOfExpensiveFrame()");
@@ -125,7 +125,7 @@ public class TaskbarOverlayContext extends BaseTaskbarContext {
}
@Override
public boolean isBackgroundBlurEnabled() {
public boolean isAllAppsBackgroundBlurEnabled() {
return Flags.allAppsBlur() && mOverlayController != null
&& mOverlayController.isBackgroundBlurEnabled();
}
@@ -135,7 +135,7 @@ public class TaskbarOverlayContext extends BaseTaskbarContext {
if (!Flags.allAppsBlur()) {
return;
}
getTheme().applyStyle(getBlurStyleResId(), true);
getTheme().applyStyle(getAllAppsBlurStyleResId(), true);
}
@Override
@@ -301,6 +301,7 @@ public class QuickstepLauncher extends Launcher implements RecentsViewContainer,
@Override
protected void setupViews() {
getTheme().applyStyle(getOverviewBlurStyleResId(), true);
getAppWidgetHolder().setOnViewCreationCallback(new QuickstepInteractionHandler(this));
super.setupViews();
@@ -456,9 +457,15 @@ public class QuickstepLauncher extends Launcher implements RecentsViewContainer,
}
@Override
public boolean isBackgroundBlurEnabled() {
return mDepthController != null && mDepthController.areBlursEnabled() && (
Flags.allAppsBlur() || enableOverviewBackgroundWallpaperBlur());
public boolean isAllAppsBackgroundBlurEnabled() {
return mDepthController != null && mDepthController.areBlursEnabled()
&& Flags.allAppsBlur();
}
@Override
public boolean isOverviewBackgroundBlurEnabled() {
return mDepthController != null && mDepthController.areBlursEnabled()
&& enableOverviewBackgroundWallpaperBlur();
}
@Override
@@ -466,17 +473,18 @@ public class QuickstepLauncher extends Launcher implements RecentsViewContainer,
if (!Flags.allAppsBlur() && !enableOverviewBackgroundWallpaperBlur()) {
return;
}
int blurStyleResId = getBlurStyleResId();
getTheme().applyStyle(blurStyleResId, true);
if (Flags.allAppsBlur()) {
int blurStyleResId = getAllAppsBlurStyleResId();
getTheme().applyStyle(blurStyleResId, true);
getAppsView().onThemeChanged(
new ContextThemeWrapper(getApplicationContext(), blurStyleResId));
}
if (enableOverviewBackgroundWallpaperBlur()) {
getTheme().applyStyle(getOverviewBlurStyleResId(), true);
getScrimView().setBackgroundColor(
getStateManager().getState().getWorkspaceScrimColor(this));
RecentsView<?, ?> recentsView = getOverviewPanel();
recentsView.updateBlurStyle(isBackgroundBlurEnabled());
recentsView.updateBlurStyle(isOverviewBackgroundBlurEnabled());
}
}
@@ -1575,4 +1583,10 @@ public class QuickstepLauncher extends Launcher implements RecentsViewContainer,
public void returnToHomescreen() {
getStateManager().goToState(LauncherState.NORMAL);
}
@Override
public int getOverviewBlurStyleResId() {
return isOverviewBackgroundBlurEnabled() ? R.style.OverviewBlurStyle
: R.style.OverviewBlurFallbackStyle;
}
}
@@ -26,14 +26,18 @@ import android.content.pm.ActivityInfo
import android.content.pm.LauncherActivityInfo
import android.content.pm.LauncherApps
import android.content.pm.ShortcutInfo
import android.graphics.Bitmap
import android.graphics.Rect
import android.os.Bundle
import android.os.Flags.allowPrivateProfile
import android.os.IBinder
import android.os.UserHandle
import android.os.UserManager
import android.util.ArrayMap
import android.view.SurfaceControlViewHost
import android.widget.Toast
import android.window.RemoteTransition
import android.window.ScreenCapture
import com.android.launcher3.Flags.enablePrivateSpace
import com.android.launcher3.Flags.privateSpaceSysAppsSeparation
import com.android.launcher3.R
@@ -193,4 +197,15 @@ open class SystemApiWrapper @Inject constructor(@ApplicationContext context: Con
override fun isFileDrawable(shortcutInfo: ShortcutInfo) =
shortcutInfo.hasIconFile() || shortcutInfo.hasIconUri()
override fun captureSnapshot(host: SurfaceControlViewHost, width: Int, height: Int): Bitmap =
ScreenCapture.captureLayers(
ScreenCapture.LayerCaptureArgs.Builder(host.surfacePackage!!.surfaceControl)
.setSourceCrop(Rect(0, 0, width, height))
.setAllowProtected(true)
.setHintForSeamlessTransition(true)
.build()
)
.asBitmap()
.copy(Bitmap.Config.ARGB_8888, true)
}
@@ -15,15 +15,12 @@
*/
package com.android.launcher3.uioverrides.touchcontrollers;
import static android.os.Trace.TRACE_TAG_APP;
import static com.android.launcher3.AbstractFloatingView.TYPE_TOUCH_CONTROLLER_NO_INTERCEPT;
import static com.android.launcher3.AbstractFloatingView.getTopOpenViewWithType;
import static com.android.launcher3.LauncherState.ALL_APPS;
import static com.android.launcher3.LauncherState.NORMAL;
import static com.android.launcher3.LauncherState.OVERVIEW;
import android.os.Trace;
import android.view.MotionEvent;
import com.android.app.animation.Interpolators;
@@ -37,6 +34,7 @@ import com.android.launcher3.states.StateAnimationConfig;
import com.android.launcher3.touch.AbstractStateChangeTouchController;
import com.android.launcher3.touch.AllAppsSwipeController;
import com.android.launcher3.touch.SingleAxisSwipeDetector;
import com.android.launcher3.uioverrides.QuickstepLauncher;
import com.android.launcher3.uioverrides.states.OverviewState;
import com.android.quickstep.SystemUiProxy;
import com.android.quickstep.util.LayoutUtils;
@@ -220,12 +218,10 @@ public class PortraitStatesTouchController extends AbstractStateChangeTouchContr
@Override
protected void onReinitToState(LauncherState newToState) {
super.onReinitToState(newToState);
if (Flags.allAppsBlur() && mLauncher.isBackgroundBlurEnabled() && newToState == ALL_APPS) {
if (Flags.allAppsBlur() && mLauncher.isAllAppsBackgroundBlurEnabled()
&& newToState == ALL_APPS) {
// About to start blurring during swipe to All Apps; prepare the renderer.
Trace.instantForTrack(TRACE_TAG_APP, TAG, "notifyRendererForGpuLoadUp");
mLauncher.getRootView().getViewRootImpl().notifyRendererForGpuLoadUp(
"swiping to All Apps");
mLauncher.getRootView().getViewRootImpl().notifyRendererOfExpensiveFrame();
((QuickstepLauncher) mLauncher).getDepthController().setEarlyWakeup(true);
}
if (newToState != ALL_APPS) {
InteractionJankMonitorWrapper.cancel(Cuj.CUJ_LAUNCHER_OPEN_ALL_APPS);
@@ -134,6 +134,7 @@ public final class RecentsActivity extends StatefulActivity<RecentsState> implem
* Init drag layer and overview panel views.
*/
protected void setupViews() {
getTheme().applyStyle(getOverviewBlurStyleResId(), true);
SystemUiProxy systemUiProxy = SystemUiProxy.INSTANCE.get(this);
// SplitSelectStateController needs to be created before setContentView()
mSplitSelectStateController =
@@ -374,7 +375,6 @@ public final class RecentsActivity extends StatefulActivity<RecentsState> implem
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setWallpaperDependentTheme(this);
getTheme().applyStyle(getBlurStyleResId(), true);
mStateManager = new StateManager<>(this, RecentsState.BG_LAUNCHER);
initDeviceProfile();
@@ -564,7 +564,7 @@ public final class RecentsActivity extends StatefulActivity<RecentsState> implem
}
@Override
public int getBlurStyleResId() {
return R.style.BlurFallbackStyle;
public int getOverviewBlurStyleResId() {
return R.style.OverviewBlurFallbackStyle;
}
}
@@ -251,9 +251,11 @@ constructor(
if (isShowing()) {
return
}
theme.applyStyle(overviewBlurStyleResId, true)
if (windowView == null) {
windowView = layoutInflater.inflate(R.layout.fallback_recents_activity, null)
}
windowManager.addView(windowView, windowLayoutParams)
windowView?.let {
@@ -503,6 +505,10 @@ constructor(
return RecentsAtomicAnimationFactory<RecentsWindowManager, RecentsState>(this)
}
override fun getOverviewBlurStyleResId(): Int {
return R.style.OverviewBlurFallbackStyle
}
@AssistedFactory
interface Factory {
/** Creates a new instance of [RecentsWindowManager] for a given [context]. */
@@ -30,6 +30,7 @@ import android.util.Log;
import android.view.AttachedSurfaceControl;
import android.view.SurfaceControl;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
@@ -258,13 +259,9 @@ public class BaseDepthController {
// SurfaceFlinger will adjust its internal offsets to avoid jank.
boolean wantsEarlyWakeUp = depth > 0 && depth < 1;
if (wantsEarlyWakeUp && !mInEarlyWakeUp) {
Trace.instantForTrack(TRACE_TAG_APP, TAG, "notifyRendererForGpuLoadUp");
mLauncher.getRootView().getViewRootImpl().notifyRendererForGpuLoadUp("applyBlur");
finalTransaction.setEarlyWakeupStart();
mInEarlyWakeUp = true;
setEarlyWakeup(finalTransaction, true);
} else if (!wantsEarlyWakeUp && mInEarlyWakeUp) {
finalTransaction.setEarlyWakeupEnd();
mInEarlyWakeUp = false;
setEarlyWakeup(finalTransaction, false);
}
if (applyImmediately) {
@@ -281,6 +278,41 @@ public class BaseDepthController {
blurWorkspaceDepthTargets();
}
/**
* Sets the early wakeup state.
*
* @param inEarlyWakeUp whether SurfaceFlinger's early wakeup timing should be active.
*/
public void setEarlyWakeup(boolean inEarlyWakeUp) {
if (mInEarlyWakeUp == inEarlyWakeUp) {
return;
}
try (SurfaceControl.Transaction transaction = createTransaction()) {
setEarlyWakeup(transaction, inEarlyWakeUp);
transaction.apply();
}
}
/**
* Sets the early wakeup state.
*
* @param transaction transaction to apply to.
* @param start whether to start or end the early wakeup.
*/
protected void setEarlyWakeup(@NonNull SurfaceControl.Transaction transaction, boolean start) {
if (mInEarlyWakeUp == start) {
return;
}
if (start) {
Trace.instantForTrack(TRACE_TAG_APP, TAG, "notifyRendererForGpuLoadUp");
mLauncher.getRootView().getViewRootImpl().notifyRendererForGpuLoadUp("applyBlur");
transaction.setEarlyWakeupStart();
} else {
transaction.setEarlyWakeupEnd();
}
mInEarlyWakeUp = start;
}
/** @return {@code true} if the workspace should be blurred. */
@VisibleForTesting
public boolean blurWorkspaceDepthTargets() {
@@ -1296,6 +1296,7 @@ public abstract class RecentsView<
if (mDesktopVisibilityController != null) {
mDesktopVisibilityController.unregisterDesktopVisibilityListener(mUtils);
}
mTaskLaunchListener = null;
mOnTaskLaunchCancelledRunnable = null;
reset();
}
@@ -25,6 +25,7 @@ import android.widget.FrameLayout.LayoutParams.MATCH_PARENT
import android.widget.FrameLayout.LayoutParams.WRAP_CONTENT
import androidx.activity.ComponentActivity
import androidx.test.core.app.ApplicationProvider
import androidx.test.filters.FlakyTest
import com.android.launcher3.R
import com.android.launcher3.taskbar.bubbles.testing.FakeBubbleViewFactory
import com.android.wm.shell.shared.bubbles.BubbleBarLocation
@@ -79,6 +80,7 @@ class BubbleBarViewScreenshotTest(emulationSpec: DeviceEmulationSpec) {
}
}
@FlakyTest(bugId = 416207075)
@Test
fun bubbleBarView_collapsed_twoBubbles() {
screenshotRule.screenshotTest("bubbleBarView_collapsed_twoBubbles") { activity ->
@@ -26,6 +26,7 @@ import com.android.launcher3.Flags.FLAG_ENABLE_MULTI_INSTANCE_MENU_TASKBAR
import com.android.launcher3.R
import com.android.launcher3.model.data.AppInfo
import com.android.launcher3.model.data.WorkspaceItemInfo
import com.android.launcher3.statehandlers.DesktopVisibilityController
import com.android.launcher3.taskbar.TaskbarControllerTestUtil.runOnMainSync
import com.android.launcher3.taskbar.TaskbarViewTestUtil.createHotseatWorkspaceItem
import com.android.launcher3.taskbar.TaskbarViewTestUtil.createRecents
@@ -41,6 +42,7 @@ import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.kotlin.whenever
@RunWith(LauncherMultivalentJUnit::class)
@EmulatedDevices(["pixelFoldable2023", "pixelTablet2023"])
@@ -57,6 +59,9 @@ class TaskbarPopupControllerTest {
private val taskbarContext: TaskbarActivityContext
get() = taskbarUnitTestRule.activityContext
private val desktopVisibilityController: DesktopVisibilityController
get() = DesktopVisibilityController.INSTANCE[context]
private lateinit var taskbarView: TaskbarView
private lateinit var hotseatIcon: BubbleTextView
private lateinit var recentTaskIcon: BubbleTextView
@@ -97,6 +102,7 @@ class TaskbarPopupControllerTest {
@Test
@EnableFlags(FLAG_ENABLE_PINNING_APP_WITH_CONTEXT_MENU)
fun showForIcon_recentTask() {
whenever(desktopVisibilityController.isInDesktopMode(context.displayId)).thenReturn(true)
assertThat(hasPopupMenu()).isFalse()
runOnMainSync { popupController.showForIcon(recentTaskIcon) }
assertThat(hasPopupMenu()).isTrue()
+2 -2
View File
@@ -177,8 +177,8 @@
</declare-styleable>
<declare-styleable name="GridSize">
<attr name="minDeviceWidthPx" format="float"/>
<attr name="minDeviceHeightPx" format="float"/>
<attr name="minDeviceWidth" format="dimension"/>
<attr name="minDeviceHeight" format="dimension"/>
<attr name="numGridRows" format="integer"/>
<attr name="numGridColumns" format="integer"/>
<attr name="dbFile" />
+5 -5
View File
@@ -19,15 +19,15 @@
launcher:numGridRows="3"
launcher:dbFile="launcher_7_by_3.db"
launcher:defaultLayoutId="@xml/default_workspace_7x3"
launcher:minDeviceWidthPx="0"
launcher:minDeviceHeightPx="0"
launcher:minDeviceWidth="0px"
launcher:minDeviceHeight="0px"
/>
<GridSize
launcher:numGridColumns="8"
launcher:numGridRows="3"
launcher:dbFile="launcher_8_by_3.db"
launcher:defaultLayoutId="@xml/default_workspace_8x3"
launcher:minDeviceWidthPx="0"
launcher:minDeviceHeightPx="2093"
launcher:minDeviceWidth="0px"
launcher:minDeviceHeight="2093px"
/>
</GridSizeSpecs>
</GridSizeSpecs>
@@ -523,8 +523,9 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
}
private void setNonPendingIcon(ItemInfoWithIcon info) {
boolean isPrivateSpaceIcon = Objects.equals(info.getTargetPackage(), PRIVATE_SPACE_PACKAGE);
// Set nonPendingIcon acts as a restart which should refresh the flag state when applicable.
int flags = Objects.equals(info.getTargetPackage(), PRIVATE_SPACE_PACKAGE)
int flags = isPrivateSpaceIcon
? info.bitmap.creationFlags : shouldUseTheme() ? FLAG_THEMED : 0;
// Remove badge on icons smaller than 48dp.
if (mHideBadge || mDisplay == DISPLAY_SEARCH_RESULT_SMALL) {
@@ -536,6 +537,9 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
FastBitmapDrawable iconDrawable = info.newIcon(getContext(), flags);
mDotParams.appColor = iconDrawable.getIconColor();
mDotParams.dotColor = Themes.getAttrColor(getContext(), R.attr.notificationDotColor);
if (isPrivateSpaceIcon) {
iconDrawable.setAnimationEnabled(false);
}
setIcon(iconDrawable);
}
@@ -1277,8 +1277,8 @@ public class InvariantDeviceProfile {
mNumRows = (int) a.getFloat(R.styleable.GridSize_numGridRows, 0);
mNumColumns = (int) a.getFloat(R.styleable.GridSize_numGridColumns, 0);
mMinDeviceWidthPx = a.getFloat(R.styleable.GridSize_minDeviceWidthPx, 0);
mMinDeviceHeightPx = a.getFloat(R.styleable.GridSize_minDeviceHeightPx, 0);
mMinDeviceWidthPx = a.getDimensionPixelSize(R.styleable.GridSize_minDeviceWidth, 0);
mMinDeviceHeightPx = a.getDimensionPixelSize(R.styleable.GridSize_minDeviceHeight, 0);
mDbFile = a.getString(R.styleable.GridSize_dbFile);
mDefaultLayoutId = a.getResourceId(
R.styleable.GridSize_defaultLayoutId, 0);
+4 -1
View File
@@ -27,6 +27,7 @@ import static com.android.launcher3.AbstractFloatingView.TYPE_FOLDER;
import static com.android.launcher3.AbstractFloatingView.TYPE_ICON_SURFACE;
import static com.android.launcher3.AbstractFloatingView.TYPE_REBIND_SAFE;
import static com.android.launcher3.AbstractFloatingView.getTopOpenViewWithType;
import static com.android.launcher3.Flags.allAppsBlur;
import static com.android.launcher3.Flags.enableAddAppWidgetViaConfigActivityV2;
import static com.android.launcher3.Flags.enableStrictMode;
import static com.android.launcher3.Flags.enableWorkspaceInflation;
@@ -514,7 +515,6 @@ public class Launcher extends StatefulActivity<LauncherState>
super.onCreate(savedInstanceState);
setWallpaperDependentTheme(this);
getTheme().applyStyle(getBlurStyleResId(), true);
LauncherAppState app = LauncherAppState.getInstance(this);
mModel = app.getModel();
@@ -1370,6 +1370,9 @@ public class Launcher extends StatefulActivity<LauncherState>
* Finds all the views we need and configure them properly.
*/
protected void setupViews() {
if (allAppsBlur()) {
getTheme().applyStyle(getAllAppsBlurStyleResId(), true);
}
mStartupLatencyLogger.logStart(LAUNCHER_LATENCY_STARTUP_VIEW_INFLATION);
inflateRootView(R.layout.launcher);
mStartupLatencyLogger.logEnd(LAUNCHER_LATENCY_STARTUP_VIEW_INFLATION);
@@ -42,8 +42,6 @@ public interface WorkspaceLayoutManager {
// The is the first screen. It is always present, even if its empty.
int FIRST_SCREEN_ID = 0;
// This is the second page. On two panel home it is always present, even if its empty.
int SECOND_SCREEN_ID = 1;
/**
* At bind time, we use the rank (screenId) to compute x and y for hotseat items.
@@ -846,7 +846,7 @@ public class ActivityAllAppsContainerView<T extends Context & ActivityContext>
if (!Flags.allAppsBlur()) {
return mBottomSheetBackgroundColorLegacy;
}
if (!mActivityContext.isBackgroundBlurEnabled()) {
if (!mActivityContext.isAllAppsBackgroundBlurEnabled()) {
// Don't apply any alpha if the blur is disabled.
return mBottomSheetBackgroundColorBlurFallback;
}
@@ -854,7 +854,7 @@ public class ActivityAllAppsContainerView<T extends Context & ActivityContext>
}
boolean isBackgroundBlurEnabled() {
return Flags.allAppsBlur() && mActivityContext.isBackgroundBlurEnabled();
return Flags.allAppsBlur() && mActivityContext.isAllAppsBackgroundBlurEnabled();
}
/** Refresh the UI according to the current theme. */
@@ -15,19 +15,25 @@
*/
package com.android.launcher3.graphics;
import static com.android.launcher3.BuildConfig.IS_DEBUG_DEVICE;
import static com.android.launcher3.Flags.enableLauncherIconShapes;
import static com.android.launcher3.graphics.PreviewSurfaceRenderer.KEY_BITMAP_GENERATION_DELAY_MS;
import static com.android.launcher3.graphics.PreviewSurfaceRenderer.KEY_VIEW_HEIGHT;
import static com.android.launcher3.graphics.PreviewSurfaceRenderer.KEY_VIEW_WIDTH;
import static com.android.launcher3.graphics.PreviewSurfaceRenderer.MIN_BITMAP_GENERATION_DELAY_MS;
import static com.android.launcher3.graphics.ThemeManager.PREF_ICON_SHAPE;
import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
import static com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR;
import static java.util.Objects.requireNonNullElse;
import static java.util.concurrent.CompletableFuture.delayedExecutor;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
@@ -50,6 +56,7 @@ import com.android.launcher3.dagger.LauncherAppSingleton;
import com.android.launcher3.model.BgDataModel;
import com.android.launcher3.shapes.IconShapeModel;
import com.android.launcher3.shapes.ShapesProvider;
import com.android.launcher3.util.ApiWrapper;
import com.android.launcher3.util.ContentProviderProxy.ProxyProvider;
import com.android.launcher3.util.DaggerSingletonTracker;
import com.android.launcher3.util.Executors;
@@ -118,6 +125,7 @@ public class GridCustomizationsProxy implements ProxyProvider {
private static final String SET_SHAPE = "/shape";
private static final String METHOD_GET_PREVIEW = "get_preview";
public static final String METHOD_GET_PREVIEW_BITMAP = "get_preview_bitmap";
private static final String GET_ICON_THEMED = "/get_icon_themed";
private static final String SET_ICON_THEMED = "/set_icon_themed";
@@ -128,6 +136,7 @@ public class GridCustomizationsProxy implements ProxyProvider {
private static final String KEY_CALLBACK = "callback";
public static final String KEY_HIDE_BOTTOM_ROW = "hide_bottom_row";
public static final String KEY_GRID_NAME = "grid_name";
public static final String KEY_IMAGE = "image";
private static final int MESSAGE_ID_UPDATE_PREVIEW = 1337;
private static final int MESSAGE_ID_UPDATE_SHAPE = 2586;
@@ -309,18 +318,45 @@ public class GridCustomizationsProxy implements ProxyProvider {
@Override
public Bundle call(@NonNull String method, String arg, Bundle extras) {
if (METHOD_GET_PREVIEW.equals(method)) {
return getPreview(extras);
} else {
return null;
return switch (method) {
case METHOD_GET_PREVIEW -> getPreview(extras);
case METHOD_GET_PREVIEW_BITMAP -> getPreviewBitmap(extras);
default -> null;
};
}
private Bundle getPreviewBitmap(Bundle request) {
RunnableList lifeCycleTracker = new RunnableList();
try {
int width = request.getInt(KEY_VIEW_WIDTH);
int height = request.getInt(KEY_VIEW_HEIGHT);
long previewDelay = Math.max(request.getLong(KEY_BITMAP_GENERATION_DELAY_MS, 0),
MIN_BITMAP_GENERATION_DELAY_MS);
PreviewSurfaceRenderer renderer = new PreviewSurfaceRenderer(
mContext, lifeCycleTracker, request, Binder.getCallingPid(),
true /* skip animations */);
renderer.loadAsync().thenRunAsync(
() -> { }, delayedExecutor(previewDelay, MILLISECONDS, MAIN_EXECUTOR)).get();
Bitmap previewBitmap = ApiWrapper.INSTANCE.get(mContext)
.captureSnapshot(renderer.getHost(), width, height);
Bundle result = new Bundle();
result.putParcelable(KEY_IMAGE, previewBitmap);
return result;
} catch (Exception e) {
Log.e(TAG, "Unable to generate preview", e);
}
MAIN_EXECUTOR.execute(lifeCycleTracker::executeAllAndDestroy);
return null;
}
private synchronized Bundle getPreview(Bundle request) {
RunnableList lifeCycleTracker = new RunnableList();
try {
PreviewSurfaceRenderer renderer = new PreviewSurfaceRenderer(
mContext, lifeCycleTracker, request, Binder.getCallingPid());
mContext, lifeCycleTracker, request, Binder.getCallingPid(),
false /* skip animations */);
PreviewLifecycleObserver observer =
new PreviewLifecycleObserver(lifeCycleTracker, renderer);
@@ -333,7 +369,7 @@ public class GridCustomizationsProxy implements ProxyProvider {
renderer.getHostToken().linkToDeath(observer, 0);
Bundle result = new Bundle();
result.putParcelable(KEY_SURFACE_PACKAGE, renderer.getSurfacePackage());
result.putParcelable(KEY_SURFACE_PACKAGE, renderer.getHost().getSurfacePackage());
mActivePreviews.add(observer);
lifeCycleTracker.add(() -> mActivePreviews.remove(observer));
@@ -68,7 +68,6 @@ import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.LauncherPrefs;
import com.android.launcher3.ProxyPrefs;
import com.android.launcher3.R;
import com.android.launcher3.Workspace;
import com.android.launcher3.WorkspaceLayoutManager;
import com.android.launcher3.celllayout.CellLayoutLayoutParams;
import com.android.launcher3.celllayout.CellPosMapper;
@@ -165,7 +164,11 @@ public class LauncherPreviewRenderer extends BaseContext
emptyDbDir();
mDbDir.mkdirs();
builder.bindParserFactory(new XmlLayoutParserFactory(this, layoutXml))
.bindWidgetsFactory(c -> new LauncherWidgetHolder(c, widgetHostId));
.bindWidgetsFactory(c -> {
LauncherWidgetHolder holder = new LauncherWidgetHolder(c, widgetHostId);
holder.startListening();
return holder;
});
}
initDaggerComponent(builder);
@@ -212,14 +215,17 @@ public class LauncherPreviewRenderer extends BaseContext
public LauncherPreviewRenderer(Context context,
InvariantDeviceProfile idp,
WallpaperColors wallpaperColorsOverride,
int workspaceScreenId,
@Nullable final SparseArray<Size> launcherWidgetSpanInfo) {
this(context, idp, null, wallpaperColorsOverride, launcherWidgetSpanInfo);
this(context, idp, null, wallpaperColorsOverride, workspaceScreenId,
launcherWidgetSpanInfo);
}
public LauncherPreviewRenderer(Context context,
InvariantDeviceProfile idp,
SparseIntArray previewColorOverride,
WallpaperColors wallpaperColorsOverride,
int workspaceScreenId,
@Nullable final SparseArray<Size> launcherWidgetSpanInfo) {
super(context, Themes.getActivityThemeRes(context));
@@ -262,7 +268,6 @@ public class LauncherPreviewRenderer extends BaseContext
: (mDp.workspacePadding.right + mDp.cellLayoutPaddingPx.right),
mDp.workspacePadding.bottom + mDp.cellLayoutPaddingPx.bottom
);
mWorkspaceScreens.put(FIRST_SCREEN_ID, firstScreen);
if (mDp.isTwoPanels) {
CellLayout rightPanel = mRootView.findViewById(R.id.workspace_right);
@@ -272,7 +277,12 @@ public class LauncherPreviewRenderer extends BaseContext
mDp.workspacePadding.right + mDp.cellLayoutPaddingPx.right,
mDp.workspacePadding.bottom + mDp.cellLayoutPaddingPx.bottom
);
mWorkspaceScreens.put(Workspace.SECOND_SCREEN_ID, rightPanel);
int closestEvenPageId = workspaceScreenId - (workspaceScreenId % 2);
mWorkspaceScreens.put(closestEvenPageId, firstScreen);
mWorkspaceScreens.put(closestEvenPageId + 1, rightPanel);
} else {
mWorkspaceScreens.put(workspaceScreenId, firstScreen);
}
SparseIntArray wallpaperColorResources;
@@ -462,12 +472,15 @@ public class LauncherPreviewRenderer extends BaseContext
// Add first page QSB
if (BuildConfig.QSB_ON_FIRST_SCREEN) {
CellLayout firstScreen = mWorkspaceScreens.get(FIRST_SCREEN_ID);
View qsb = mHomeElementInflater.inflate(R.layout.qsb_preview, firstScreen, false);
// TODO: set bgHandler on qsb when it is BaseTemplateCard, which requires API changes.
CellLayoutLayoutParams lp = new CellLayoutLayoutParams(
0, 0, firstScreen.getCountX(), 1);
lp.canReorder = false;
firstScreen.addViewToCellLayout(qsb, 0, R.id.search_container_workspace, lp, true);
if (firstScreen != null) {
View qsb = mHomeElementInflater.inflate(R.layout.qsb_preview, firstScreen, false);
// TODO: set bgHandler on qsb when it is BaseTemplateCard, which requires API
// changes.
CellLayoutLayoutParams lp = new CellLayoutLayoutParams(
0, 0, firstScreen.getCountX(), 1);
lp.canReorder = false;
firstScreen.addViewToCellLayout(qsb, 0, R.id.search_container_workspace, lp, true);
}
}
measureView(mRootView, mDp.widthPx, mDp.heightPx);
@@ -24,7 +24,6 @@ import static com.android.launcher3.Flags.extendibleThemeManager;
import static com.android.launcher3.LauncherPrefs.GRID_NAME;
import static com.android.launcher3.LauncherPrefs.NON_FIXED_LANDSCAPE_GRID_NAME;
import static com.android.launcher3.WorkspaceLayoutManager.FIRST_SCREEN_ID;
import static com.android.launcher3.WorkspaceLayoutManager.SECOND_SCREEN_ID;
import static com.android.launcher3.graphics.ThemeManager.PREF_ICON_SHAPE;
import static com.android.launcher3.graphics.ThemeManager.THEMED_ICONS;
import static com.android.launcher3.provider.LauncherDbUtils.selectionForWorkspaceScreen;
@@ -48,7 +47,6 @@ import android.util.SparseIntArray;
import android.view.ContextThemeWrapper;
import android.view.Display;
import android.view.SurfaceControlViewHost;
import android.view.SurfaceControlViewHost.SurfacePackage;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.FrameLayout;
@@ -77,6 +75,7 @@ import com.android.launcher3.widget.LocalColorExtractor;
import com.android.systemui.shared.Flags;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
/** Render preview using surface view. */
@@ -84,17 +83,21 @@ import java.util.concurrent.TimeUnit;
public class PreviewSurfaceRenderer {
private static final String TAG = "PreviewSurfaceRenderer";
private static final int FADE_IN_ANIMATION_DURATION = 200;
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_COLORS = "wallpaper_colors";
private static final String KEY_COLOR_RESOURCE_IDS = "color_resource_ids";
private static final String KEY_COLOR_VALUES = "color_values";
private static final String KEY_DARK_MODE = "use_dark_mode";
private static final String KEY_LAYOUT_XML = "layout_xml";
public static final String KEY_SKIP_ANIMATIONS = "skip_animations";
public static final int FADE_IN_ANIMATION_DURATION = 200;
public static final String KEY_HOST_TOKEN = "host_token";
public static final String KEY_VIEW_WIDTH = "width";
public static final String KEY_VIEW_HEIGHT = "height";
public static final String KEY_DISPLAY_ID = "display_id";
public static final String KEY_COLORS = "wallpaper_colors";
public static final String KEY_COLOR_RESOURCE_IDS = "color_resource_ids";
public static final String KEY_COLOR_VALUES = "color_values";
public static final String KEY_DARK_MODE = "use_dark_mode";
public static final String KEY_LAYOUT_XML = "layout_xml";
public static final String KEY_BITMAP_GENERATION_DELAY_MS = "bitmap_delay_ms";
// Wait for some time before capturing screenshot to allow the surface to be laid out
public static final long MIN_BITMAP_GENERATION_DELAY_MS = 100L;
public static final String KEY_WORKSPACE_PAGE_ID = "workspace_page_id";
public static final String FIXED_LANDSCAPE_GRID = "fixed_landscape_mode";
private final Context mContext;
@@ -103,6 +106,7 @@ public class PreviewSurfaceRenderer {
private String mLastSelectedGridName;
private String mShapeKey;
private String mLayoutXml;
private int mWorkspacePageId;
private boolean mIsMonoThemeEnabled;
@Nullable private Boolean mDarkMode;
@@ -127,7 +131,7 @@ public class PreviewSurfaceRenderer {
@Nullable private SurfaceControlViewHost.SurfacePackage mSurfacePackage;
public PreviewSurfaceRenderer(Context context, RunnableList lifecycleTracker, Bundle bundle,
int callingPid) throws Exception {
int callingPid, boolean skipAnimations) throws Exception {
mContext = context;
mLifeCycleTracker = lifecycleTracker;
mCallingPid = callingPid;
@@ -151,11 +155,12 @@ public class PreviewSurfaceRenderer {
mHostToken = bundle.getBinder(KEY_HOST_TOKEN);
mWidth = bundle.getInt(KEY_VIEW_WIDTH);
mHeight = bundle.getInt(KEY_VIEW_HEIGHT);
mSkipAnimations = bundle.getBoolean(KEY_SKIP_ANIMATIONS, false);
mSkipAnimations = skipAnimations;
mDisplayId = bundle.getInt(KEY_DISPLAY_ID);
mDisplay = context.getSystemService(DisplayManager.class)
.getDisplay(mDisplayId);
mLayoutXml = bundle.getString(KEY_LAYOUT_XML);
mWorkspacePageId = bundle.getInt(KEY_WORKSPACE_PAGE_ID, FIRST_SCREEN_ID);
if (mDisplay == null) {
throw new IllegalArgumentException("Display ID does not match any displays.");
}
@@ -177,11 +182,8 @@ public class PreviewSurfaceRenderer {
return mHostToken;
}
public SurfacePackage getSurfacePackage() {
if (mSurfacePackage == null) {
mSurfacePackage = mSurfaceControlViewHost.getSurfacePackage();
}
return mSurfacePackage;
public SurfaceControlViewHost getHost() {
return mSurfaceControlViewHost;
}
private void setCurrentRenderer(LauncherPreviewRenderer renderer) {
@@ -241,10 +243,12 @@ public class PreviewSurfaceRenderer {
}
/**
* Generates the preview in background
* Generates the preview in background and returns the generated view
*/
public void loadAsync() {
MODEL_EXECUTOR.execute(this::loadModelData);
public CompletableFuture<View> loadAsync() {
CompletableFuture<View> result = new CompletableFuture<>();
MODEL_EXECUTOR.execute(() -> loadModelData(result));
return result;
}
/**
@@ -379,7 +383,7 @@ public class PreviewSurfaceRenderer {
}
@WorkerThread
private void loadModelData() {
private void loadModelData(CompletableFuture<View> onCompleteCallback) {
final Context inflationContext = getPreviewContext();
if (shouldReloadModelData()) {
boolean isCustomLayout = extendibleThemeManager() && !TextUtils.isEmpty(mLayoutXml);
@@ -409,21 +413,26 @@ public class PreviewSurfaceRenderer {
InvariantDeviceProfile idp = appComponent.getIDP();
DeviceProfile deviceProfile = idp.getDeviceProfile(previewContext);
int closestEvenPageId = mWorkspacePageId - (mWorkspacePageId % 2);
String query = deviceProfile.isTwoPanels
? selectionForWorkspaceScreen(FIRST_SCREEN_ID, SECOND_SCREEN_ID)
: selectionForWorkspaceScreen(FIRST_SCREEN_ID);
? selectionForWorkspaceScreen(closestEvenPageId, closestEvenPageId + 1)
: selectionForWorkspaceScreen(mWorkspacePageId);
task.loadWorkspaceForPreview(query);
final SparseArray<Size> spanInfo = getLoadedLauncherWidgetInfo();
MAIN_EXECUTOR.execute(() -> {
renderView(previewContext, appComponent.getDataModel(), spanInfo, idp);
renderView(previewContext, appComponent.getDataModel(), spanInfo, idp,
onCompleteCallback);
mLifeCycleTracker.add(previewContext::onDestroy);
});
} else {
LauncherAppState.getInstance(inflationContext).getModel().loadAsync(dataModel -> {
if (dataModel != null) {
MAIN_EXECUTOR.execute(() -> renderView(inflationContext, dataModel,
null, LauncherAppState.getIDP(inflationContext)));
null, LauncherAppState.getIDP(inflationContext), onCompleteCallback));
} else {
onCompleteCallback.completeExceptionally(
new RuntimeException("Model loading failed"));
Log.e(TAG, "Model loading failed");
}
});
@@ -433,17 +442,19 @@ public class PreviewSurfaceRenderer {
@UiThread
private void renderView(Context inflationContext, BgDataModel dataModel,
@Nullable final SparseArray<Size> launcherWidgetSpanInfo, InvariantDeviceProfile idp) {
@Nullable final SparseArray<Size> launcherWidgetSpanInfo, InvariantDeviceProfile idp,
CompletableFuture<View> onCompleteCallback) {
if (mDestroyed) {
onCompleteCallback.completeExceptionally(new RuntimeException("Renderer destroyed"));
return;
}
LauncherPreviewRenderer renderer;
if (Flags.newCustomizationPickerUi()) {
renderer = new LauncherPreviewRenderer(inflationContext, idp,
mPreviewColorOverride, mWallpaperColors, launcherWidgetSpanInfo);
renderer = new LauncherPreviewRenderer(inflationContext, idp, mPreviewColorOverride,
mWallpaperColors, mWorkspacePageId, launcherWidgetSpanInfo);
} else {
renderer = new LauncherPreviewRenderer(inflationContext, idp,
mWallpaperColors, launcherWidgetSpanInfo);
mWallpaperColors, mWorkspacePageId, launcherWidgetSpanInfo);
}
renderer.hideBottomRow(mHideQsb);
renderer.populate(dataModel);
@@ -472,6 +483,7 @@ public class PreviewSurfaceRenderer {
view.getMeasuredWidth(),
view.getMeasuredHeight()
);
onCompleteCallback.complete(view);
return;
}
@@ -497,6 +509,7 @@ public class PreviewSurfaceRenderer {
mViewRoot.removeAllViews();
mViewRoot.addView(view);
}
onCompleteCallback.complete(view);
}
private static class MySurfaceControlViewHost extends SurfaceControlViewHost {
@@ -15,8 +15,12 @@
*/
package com.android.launcher3.touch;
import static android.multiuser.Flags.enableMovingContentIntoPrivateSpace;
import static com.android.launcher3.LauncherConstants.ActivityCodes.REQUEST_BIND_PENDING_APPWIDGET;
import static com.android.launcher3.LauncherConstants.ActivityCodes.REQUEST_RECONFIGURE_APPWIDGET;
import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT;
import static com.android.launcher3.allapps.AlphabeticalAppsList.PRIVATE_SPACE_PACKAGE;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_FOLDER_OPEN;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_PRIVATE_SPACE_INSTALL_APP_BUTTON_TAP;
import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_DISABLED_BY_PUBLISHER;
@@ -72,6 +76,7 @@ import com.android.launcher3.widget.WidgetAddFlowHandler;
import com.android.launcher3.widget.WidgetManagerHelper;
import java.util.Collections;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
@@ -392,6 +397,15 @@ public class ItemClickHandler {
LAUNCHER_PRIVATE_SPACE_INSTALL_APP_BUTTON_TAP);
}
}
if (enableMovingContentIntoPrivateSpace() &&
Objects.equals(item.getTargetPackage(), PRIVATE_SPACE_PACKAGE)
&& item.itemType != ITEM_TYPE_DEEP_SHORTCUT) {
// Only show the popup menu when clicking on the icon itself.
if (v instanceof BubbleTextView btv) {
btv.startLongPressAction();
return;
}
}
if (intent == null) {
throw new IllegalArgumentException("Input must have a valid intent");
}
@@ -25,12 +25,14 @@ import android.content.Context;
import android.content.Intent;
import android.content.pm.LauncherActivityInfo;
import android.content.pm.ShortcutInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Process;
import android.os.UserHandle;
import android.os.UserManager;
import android.util.ArrayMap;
import android.view.SurfaceControlViewHost;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
@@ -41,6 +43,7 @@ import com.android.launcher3.Utilities;
import com.android.launcher3.dagger.ApplicationContext;
import com.android.launcher3.dagger.LauncherAppComponent;
import com.android.launcher3.dagger.LauncherAppSingleton;
import com.android.launcher3.icons.BitmapRenderer;
import java.util.Collections;
import java.util.List;
@@ -207,6 +210,11 @@ public class ApiWrapper {
return false;
}
/** Captures a snapshot of the host content as a bitmap */
public Bitmap captureSnapshot(SurfaceControlViewHost host, int width, int height) {
return BitmapRenderer.createHardwareBitmap(width, height, host.getView()::draw);
}
private static class NoopDrawable extends ColorDrawable {
@Override
public int getIntrinsicHeight() {
@@ -209,14 +209,23 @@ public interface ActivityContext extends SavedStateRegistryOwner {
return null;
}
/** @return {@code true} if background blur is enabled */
default boolean isBackgroundBlurEnabled() {
/** @return {@code true} if all apps background blur is enabled */
default boolean isAllAppsBackgroundBlurEnabled() {
return false;
}
/** @return {@code true} if overview background blur is enabled */
default boolean isOverviewBackgroundBlurEnabled() {
return false;
}
/** @return the resource id of the style to apply for the current blur state. */
default int getBlurStyleResId() {
return isBackgroundBlurEnabled() ? R.style.BlurStyle : R.style.BlurFallbackStyle;
default int getAllAppsBlurStyleResId() {
return isAllAppsBackgroundBlurEnabled() ? R.style.BlurStyle : R.style.BlurFallbackStyle;
}
default int getOverviewBlurStyleResId() {
return View.NO_ID;
}
DeviceProfile getDeviceProfile();
@@ -538,13 +538,11 @@ public class BaseOverview extends LauncherInstrumentation.VisibleContainer {
)) {
if (isActionsViewVisible()) {
UiObject2 actionsButtons;
if (task.isGrouped()) {
actionsButtons = mLauncher.waitForOverviewObject("action_save_app_pair");
mLauncher.waitForOverviewObject("action_save_app_pair");
} else {
actionsButtons = mLauncher.waitForOverviewObject("action_buttons");
mLauncher.waitForOverviewObject("action_buttons");
}
mLauncher.assertTrue("Overview actions is disabled", actionsButtons.isEnabled());
} else {
mLauncher.waitUntilOverviewObjectGone("action_buttons");
mLauncher.waitUntilOverviewObjectGone("action_save_app_pair");