Snap for 13579076 from bb41fe629a to 25Q3-release

Change-Id: Id4290d9cc7818589c5322ddd5913a31b5ede2dfa
This commit is contained in:
Android Build Coastguard Worker committed 2025-05-30 18:20:42 -07:00
commit 01751c09fc
116 files changed
+2269 -374

No files matched your search

+11 -9
View File
@@ -47,8 +47,8 @@ filegroup {
filegroup {
name: "launcher-compose-enabled-src",
srcs: [
"compose/facade/enabled/*.kt",
"compose/facade/core/*.kt",
"compose/facade/enabled/**/*.kt",
"compose/facade/core/**/*.kt",
"compose/features/**/*.kt",
],
}
@@ -56,8 +56,8 @@ filegroup {
filegroup {
name: "launcher-compose-disabled-src",
srcs: [
"compose/facade/core/*.kt",
"compose/facade/disabled/*.kt",
"compose/facade/core/**/*.kt",
"compose/facade/disabled/**/*.kt",
],
}
@@ -223,8 +223,9 @@ launcher_compose_java_defaults {
":launcher-compose-enabled-src",
],
// Compose dependencies
static_libs: [
"widget_picker_component",
// Compose dependencies
"androidx.compose.runtime_runtime",
"androidx.compose.material3_material3",
"androidx.compose.ui_ui-tooling-preview",
@@ -263,6 +264,7 @@ launcher_compose_tests_java_defaults {
],
// Compose dependencies
static_libs: [
"widget_picker_component",
"androidx.compose.runtime_runtime",
"androidx.compose.ui_ui-test-junit4",
"androidx.compose.ui_ui-test-manifest",
@@ -392,9 +394,6 @@ java_library {
// Library with all the dependencies for building Launcher3
android_library {
name: "Launcher3ResLib",
defaults: [
"launcher_compose_defaults",
],
srcs: [],
resource_dirs: ["res"],
static_libs: [
@@ -448,7 +447,10 @@ android_library {
//
android_app {
name: "Launcher3",
defaults: ["launcher-non-platform-apis-defaults"],
defaults: [
"launcher-non-platform-apis-defaults",
"launcher_compose_defaults",
],
static_libs: [
"Launcher3ResLib",
-7
View File
@@ -517,13 +517,6 @@ flag {
bug: "394651876"
}
flag {
name: "extendible_theme_manager"
namespace: "launcher"
description: "Enables custom theme manager in Launcher"
bug: "381897614"
}
flag {
name: "enable_alt_tab_kqs_flatenning"
namespace: "lse_desktop_experience"
@@ -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.compose.core.widgetpicker
import dagger.Binds
import dagger.Module
/**
* A module that provides a no-op [WidgetPickerComposeWrapper] for dagger graph that doesn't
* involve widget picker e.g. launcher preview OR when compose is disabled via build flag.
*/
@Module
interface NoOpWidgetPickerModule {
@Binds
fun bindWidgetPickerWrapper(noOp: NoOpWidgetPickerComposeWrapper): WidgetPickerComposeWrapper
}
@@ -0,0 +1,38 @@
/*
* 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.compose.core.widgetpicker
import com.android.launcher3.widgetpicker.WidgetPickerActivity
import javax.inject.Inject
/**
* A wrapper for widget picker activity that is responsible for displaying the compose based
* widget picker in [WidgetPickerActivity] when compose is enabled via build flag.
*/
interface WidgetPickerComposeWrapper {
fun showAllWidgets(activity: WidgetPickerActivity)
}
/**
* A No-op [WidgetPickerComposeWrapper] that doesn't include widget picker in dagger graph that
* don't involve widget picker e.g. launcher preview OR when compose is disabled via build flag.
*/
class NoOpWidgetPickerComposeWrapper @Inject constructor() : WidgetPickerComposeWrapper {
override fun showAllWidgets(activity: WidgetPickerActivity) {
error("Widget picker with compose is not supported")
}
}
@@ -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.compose.widgetpicker
import com.android.launcher3.compose.core.widgetpicker.NoOpWidgetPickerModule
import dagger.Module
/**
* A no-op module that is used when compose is disabled in launcher.
*/
@Module(includes = [NoOpWidgetPickerModule::class])
class LauncherWidgetPickerModule
@@ -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.compose.widgetpicker
import com.android.launcher3.compose.core.widgetpicker.WidgetPickerComposeWrapper
import com.android.launcher3.widgetpicker.WidgetPickerComponent
import com.android.launcher3.widgetpicker.WidgetPickerComposeWrapperImpl
import com.android.launcher3.widgetpicker.data.repository.WidgetAppIconsRepository
import com.android.launcher3.widgetpicker.data.repository.WidgetUsersRepository
import com.android.launcher3.widgetpicker.data.repository.WidgetsRepository
import com.android.launcher3.widgetpicker.datasource.ConfigResourceFeaturedWidgetsDataSource
import com.android.launcher3.widgetpicker.datasource.FeaturedWidgetsDataSource
import com.android.launcher3.widgetpicker.datasource.InMemoryWidgetSearchAlgorithm
import com.android.launcher3.widgetpicker.datasource.WidgetsSearchAlgorithm
import com.android.launcher3.widgetpicker.repository.WidgetsRepositoryImpl
import com.android.launcher3.widgetpicker.repository.WidgetAppIconsRepositoryImpl
import com.android.launcher3.widgetpicker.repository.WidgetUsersRepositoryImpl
import dagger.Binds
import dagger.Module
/**
* A module that installs widget picker for launcher.
*/
@Module(subcomponents = [WidgetPickerComponent::class])
interface LauncherWidgetPickerModule {
@Binds
fun bindWidgetPickerComposeWrapper(
impl: WidgetPickerComposeWrapperImpl
): WidgetPickerComposeWrapper
@Binds
fun bindWidgetUsersRepository(impl: WidgetUsersRepositoryImpl): WidgetUsersRepository
@Binds
fun bindWidgetsRepository(impl: WidgetsRepositoryImpl): WidgetsRepository
@Binds
fun bindWidgetAppIconsRepository(impl: WidgetAppIconsRepositoryImpl): WidgetAppIconsRepository
@Binds
fun bindFeaturedWidgetsDataSource(
impl: ConfigResourceFeaturedWidgetsDataSource
): FeaturedWidgetsDataSource
@Binds
fun bindWidgetsSearchAlgorithm(
impl: InMemoryWidgetSearchAlgorithm
): WidgetsSearchAlgorithm
}
@@ -0,0 +1,119 @@
/*
* 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 android.content.Context
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalView
import com.android.launcher3.R
import com.android.launcher3.widgetpicker.WidgetPickerActivity
import com.android.launcher3.compose.ComposeFacade
import com.android.launcher3.compose.core.widgetpicker.WidgetPickerComposeWrapper
import com.android.launcher3.concurrent.annotations.BackgroundContext
import com.android.launcher3.dagger.ApplicationContext
import com.android.launcher3.widgetpicker.WidgetPickerComponent
import com.android.launcher3.widgetpicker.WidgetPickerEventListeners
import com.android.launcher3.widgetpicker.data.repository.WidgetAppIconsRepository
import com.android.launcher3.widgetpicker.data.repository.WidgetUsersRepository
import com.android.launcher3.widgetpicker.data.repository.WidgetsRepository
import com.android.launcher3.widgetpicker.shared.model.WidgetHostInfo
import kotlinx.coroutines.launch
import javax.inject.Inject
import javax.inject.Provider
import kotlin.coroutines.CoroutineContext
/**
* An helper that bootstraps widget picker UI (from [WidgetPickerComponent]) in to
* [WidgetPickerActivity].
*
* Sets up the bindings necessary for widget picker component.
*/
class WidgetPickerComposeWrapperImpl @Inject constructor(
private val widgetPickerComponentProvider: Provider<WidgetPickerComponent.Factory>,
private val widgetsRepository: WidgetsRepository,
private val widgetUsersRepository: WidgetUsersRepository,
private val widgetAppIconsRepository: WidgetAppIconsRepository,
@BackgroundContext
private val backgroundContext: CoroutineContext,
@ApplicationContext
private val appContext: Context,
) : WidgetPickerComposeWrapper {
override fun showAllWidgets(
activity: WidgetPickerActivity,
) {
val widgetPickerComponent = newWidgetPickerComponent()
val callbacks = object : WidgetPickerEventListeners {
override fun onClose() {
activity.finish()
}
}
val fullWidgetsCatalog = widgetPickerComponent.getFullWidgetsCatalog()
val composeView = ComposeFacade.initComposeView(activity.asContext()) as ComposeView
composeView.apply {
setContent {
val scope = rememberCoroutineScope()
val view = LocalView.current
MaterialTheme { // TODO(b/408283627): Use launcher theme.
val eventListeners = remember { callbacks }
fullWidgetsCatalog.Content(eventListeners)
}
DisposableEffect(view) {
scope.launch {
initializeRepositories()
}
onDispose {
cleanUpRepositories()
}
}
}
}
activity.dragLayer?.addView(composeView)
}
private fun newWidgetPickerComponent(): WidgetPickerComponent =
widgetPickerComponentProvider.get()
.build(
widgetsRepository = widgetsRepository,
widgetUsersRepository = widgetUsersRepository,
widgetAppIconsRepository = widgetAppIconsRepository,
widgetHostInfo = WidgetHostInfo(
appContext.resources.getString(R.string.widget_button_text)
),
backgroundContext = backgroundContext
)
private fun initializeRepositories() {
widgetsRepository.initialize()
widgetUsersRepository.initialize()
widgetAppIconsRepository.initialize()
}
private fun cleanUpRepositories() {
widgetsRepository.cleanUp()
widgetUsersRepository.cleanUp()
widgetAppIconsRepository.cleanUp()
}
}
@@ -0,0 +1,89 @@
/*
* 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.datasource
import android.content.Context
import com.android.launcher3.InvariantDeviceProfile
import com.android.launcher3.R
import com.android.launcher3.dagger.ApplicationContext
import com.android.launcher3.dagger.LauncherAppSingleton
import com.android.launcher3.widget.picker.util.WidgetPreviewContainerSize
import com.android.launcher3.widgetpicker.shared.model.PickableWidget
import com.android.launcher3.widgetpicker.shared.model.WidgetApp
import java.util.Arrays
import java.util.stream.Collectors
import javax.inject.Inject
/**
* An implementation of [FeaturedWidgetsDataSource] that provides featured widgets based on a static
* configuration from resources and pre-defined size templates.
*/
@LauncherAppSingleton
class ConfigResourceFeaturedWidgetsDataSource @Inject constructor(
@ApplicationContext private val appContext: Context,
private val idp: InvariantDeviceProfile
) : FeaturedWidgetsDataSource {
// the package part in component name e.g. "com.example" in {com.example/widget.Provider}
private var eligiblePackages: Set<String> = emptySet()
override suspend fun initialize() {
if (eligiblePackages.isEmpty()) {
eligiblePackages = Arrays.stream(
appContext.resources.getStringArray(R.array.default_featured_widget_apps)
).collect(Collectors.toSet())
}
}
override suspend fun getFeaturedWidgets(widgetApps: List<WidgetApp>): List<PickableWidget> {
val widgetsByContainerSize = widgetApps
.shuffled()
// pick only one of user profiles
.distinctBy { Pair(it.id.packageName, it.id.category) }
.flatMap { it.widgets }
.filter { eligiblePackages.contains(it.id.componentName.packageName) }
.groupBy {
WidgetPreviewContainerSize(
it.sizeInfo.containerSpanX,
it.sizeInfo.containerSpanY
)
}
val selected: MutableList<PickableWidget> = mutableListOf()
val usedAppIds: MutableSet<String> = mutableSetOf()
val sizesToPick = WidgetPreviewContainerSize.pickTemplateForFeaturedWidgets(
idp.getDeviceProfile(appContext)
)
for (sizeToPick in sizesToPick) {
widgetsByContainerSize[sizeToPick]?.shuffled()?.let { items ->
for (item in items) {
if (!usedAppIds.contains(item.appId.packageName)) {
selected.add(item)
usedAppIds.add(item.appId.packageName)
break
}
}
}
}
return selected
}
override fun cleanup() {
eligiblePackages = emptySet()
}
}
@@ -0,0 +1,40 @@
/*
* 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.datasource
import com.android.launcher3.widgetpicker.shared.model.PickableWidget
import com.android.launcher3.widgetpicker.shared.model.WidgetApp
/**
* An interface representing a datasource that provides featured widgets.
*/
interface FeaturedWidgetsDataSource {
/**
* Perform any initializations here.
*/
suspend fun initialize()
/**
* Provides widgets from the given list that can be featured in widget picker.
*/
suspend fun getFeaturedWidgets(widgetApps: List<WidgetApp>): List<PickableWidget>
/**
* Clear any service bindings or state here.
*/
fun cleanup()
}
@@ -0,0 +1,168 @@
/*
* 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.datasource
import com.android.launcher3.concurrent.annotations.BackgroundContext
import com.android.launcher3.dagger.LauncherAppSingleton
import com.android.launcher3.widgetpicker.shared.model.WidgetApp
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import javax.inject.Inject
import kotlin.coroutines.CoroutineContext
/**
* A simple in-memory implementation of [WidgetsSearchAlgorithm] that matches input query against
* the app labels, widget title and description.
*
* More weight is given to app names than widget title; and description has lowest weight in scoring
* the results.
*/
@LauncherAppSingleton
class InMemoryWidgetSearchAlgorithm @Inject constructor(
@BackgroundContext
private val backgroundContext: CoroutineContext,
) : WidgetsSearchAlgorithm {
override suspend fun initialize() {}
override suspend fun searchWidgets(
query: String,
corpus: List<WidgetApp>
): List<WidgetApp> = coroutineScope {
// Ideally, uses search only one word, but supporting multiple words.
val queryWords = query.trim().lowercase().split("\\s+".toRegex())
.filter { it.isNotBlank() }
if (queryWords.isEmpty()) {
return@coroutineScope emptyList()
}
val results = corpus.map { widgetApp ->
async(backgroundContext) {
matchAndScoreWidgetApp(widgetApp, queryWords)
}
}
results.awaitAll()
.filter { it.first.widgets.isNotEmpty() && it.second > 0 }
.sortedByDescending { it.second }
.map { it.first } // Return just the WidgetApp
}
private fun matchAndScoreWidgetApp(
widgetApp: WidgetApp,
queryWords: List<String>
): Pair<WidgetApp, Int> {
val appTitleScore = widgetApp.title?.let {
matchAndCalculateScore(
queryWords = queryWords,
targetText = widgetApp.title.toString(),
matchType = MatchType.APP_TITLE
)
} ?: 0
val scoredWidgets = widgetApp.widgets.map { widget ->
val labelScore =
matchAndCalculateScore(
queryWords = queryWords,
targetText = widget.label,
matchType = MatchType.WIDGET_LABEL
)
val descriptionScore = widget.description?.let {
matchAndCalculateScore(
queryWords = queryWords,
targetText = it.toString(),
matchType = MatchType.WIDGET_DESCRIPTION
)
} ?: 0
val totalWidgetScore = labelScore + descriptionScore
widget to totalWidgetScore
}
.filter { it.second > 0 }
.sortedByDescending { it.second }
val totalAppScore = appTitleScore + scoredWidgets.sumOf { it.second }
return if (appTitleScore > 0) {
widgetApp to appTitleScore + totalAppScore
} else {
widgetApp.copy(
widgets = scoredWidgets.map { it.first }
) to totalAppScore
}
}
private fun matchAndCalculateScore(
queryWords: List<String>,
targetText: String,
matchType: MatchType
): Int {
var totalScore = 0
val wordsInTarget = targetText
.lowercase()
.split("\\s+".toRegex()).filter { it.isNotBlank() }
for (queryWord in queryWords) {
var wordScore = 0
for (targetWord in wordsInTarget) {
wordScore = wordScore.coerceAtLeast(
calculateSingleWordScore(
queryWord,
targetWord,
matchType
)
)
}
totalScore += wordScore
}
return totalScore
}
private fun calculateSingleWordScore(
queryWord: String,
targetWord: String,
matchType: MatchType
): Int {
val baseScore = when {
// exact matches are score higher.
targetWord == queryWord -> 2
// Then the matches that begin with given input as prefix
targetWord.startsWith(queryWord) -> 1
else -> 0
}
return baseScore * matchType.weightFactor
}
private enum class MatchType(val weightFactor: Int) {
// Highest weight to app title matches; users are likely to search for apps
APP_TITLE(12),
// Medium weight to widget labels (lower than app title as some widgets might have app title
// in name and based on number of items, might add unnecessary weight).
WIDGET_LABEL(3),
// Lowest weight to description; description might might not be as impactful as the labels
// or app title; but, it might still help in cases where alternate words for the widgets
// functionality are used (e.g. stocks vs watchlist).
WIDGET_DESCRIPTION(1)
}
override fun cleanup() {}
}
@@ -0,0 +1,39 @@
/*
* 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.datasource
import com.android.launcher3.widgetpicker.shared.model.WidgetApp
/**
* An interface representing algorithm used to search widgets for widget picker.
*/
interface WidgetsSearchAlgorithm {
/**
* Perform any initializations here
*/
suspend fun initialize()
/**
* Returns apps and its widgets that match the given input string.
*/
suspend fun searchWidgets(query: String, corpus: List<WidgetApp>): List<WidgetApp>
/**
* Clear any service bindings or state here.
*/
fun cleanup()
}
@@ -0,0 +1,79 @@
/*
* 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.repository
import com.android.launcher3.icons.IconCache
import com.android.launcher3.icons.cache.CacheLookupFlag
import com.android.launcher3.model.data.PackageItemInfo
import com.android.launcher3.widgetpicker.data.repository.WidgetAppIconsRepository
import com.android.launcher3.widgetpicker.shared.model.AppIcon
import com.android.launcher3.widgetpicker.shared.model.AppIconBadge
import com.android.launcher3.widgetpicker.shared.model.WidgetAppIcon
import com.android.launcher3.widgetpicker.shared.model.WidgetAppId
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import javax.inject.Inject
/**
* An implementation of [WidgetAppIconsRepository] that provides the app icons for the widget picker
* using the [IconCache].
*/
class WidgetAppIconsRepositoryImpl @Inject constructor(
private val iconCache: IconCache
) : WidgetAppIconsRepository {
override fun initialize() {} // nothing to do here.
override fun getAppIcon(widgetAppId: WidgetAppId) = callbackFlow {
trySend(WidgetAppIcon(AppIcon.PlaceHolderAppIcon, AppIconBadge.NoBadge))
val category = widgetAppId.category
val packageItemInfo = if (category != null) {
PackageItemInfo(widgetAppId.packageName, category, widgetAppId.userHandle)
} else {
PackageItemInfo(widgetAppId.packageName, widgetAppId.userHandle)
}
iconCache.updateIconInBackground({ itemInfoWithIcon ->
itemInfoWithIcon?.let {
if (itemInfoWithIcon.bitmap.isLowRes) {
trySend(
WidgetAppIcon(
icon = AppIcon.LowResColorIcon(itemInfoWithIcon.bitmap.color),
badge = AppIconBadge.NoBadge
)
)
} else {
trySend(
WidgetAppIcon(
icon = AppIcon.HighResBitmapIcon(itemInfoWithIcon.bitmap.icon),
badge = itemInfoWithIcon.bitmap.badgeDrawableInfo?.let {
AppIconBadge.DrawableBadge(
it.drawableRes,
it.colorRes
)
} ?: AppIconBadge.NoBadge
)
)
}
}
}, packageItemInfo, CacheLookupFlag.DEFAULT_LOOKUP_FLAG)
awaitClose()
}
override fun cleanUp() {} // nothing to do here.
}
@@ -0,0 +1,125 @@
/*
* 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.repository
import android.content.Context
import android.os.UserHandle
import android.os.UserManager
import com.android.launcher3.concurrent.annotations.BackgroundContext
import com.android.launcher3.dagger.ApplicationContext
import com.android.launcher3.model.StringCache
import com.android.launcher3.pm.UserCache
import com.android.launcher3.util.SafeCloseable
import com.android.launcher3.widgetpicker.data.repository.WidgetUsersRepository
import com.android.launcher3.widgetpicker.shared.model.WidgetUserProfile
import com.android.launcher3.widgetpicker.shared.model.WidgetUserProfileType
import com.android.launcher3.widgetpicker.shared.model.WidgetUserProfiles
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import javax.inject.Inject
import kotlin.coroutines.CoroutineContext
/**
* An implementation of [WidgetUsersRepository] that provides user profile info to widget picker
* by looking up the [UserCache].
*/
class WidgetUsersRepositoryImpl @Inject constructor(
@ApplicationContext private val appContext: Context,
private val userCache: UserCache,
@BackgroundContext
private val backgroundContext: CoroutineContext
) : WidgetUsersRepository {
private val userManagerService = appContext.getSystemService(UserManager::class.java)
private var stringCache: StringCache = StringCache()
private var closableUseChangeListener: SafeCloseable? = null
private val _userProfiles = MutableStateFlow<WidgetUserProfiles?>(null)
private var workProfileUser: UserHandle? = null
private var backgroundScope = CoroutineScope(
SupervisorJob() +
backgroundContext +
CoroutineName("widgetUsersRepositoryBackgroundWork")
)
override fun initialize() {
backgroundScope.launch {
stringCache.loadStrings(appContext)
maybeUpdate(changedUser = null)
closableUseChangeListener?.close()
closableUseChangeListener = userCache.addUserEventListener { userHandle, _ ->
maybeUpdate(userHandle)
}
}
}
override fun observeUserProfiles(): Flow<WidgetUserProfiles?> = _userProfiles.asStateFlow()
override fun getWorkProfileUser(): UserHandle? = workProfileUser
override fun cleanUp() {
closableUseChangeListener?.close()
backgroundScope.apply {
if (isActive) {
cancel()
}
}
}
private fun maybeUpdate(changedUser: UserHandle?) {
check(userManagerService != null)
workProfileUser =
userCache.userProfiles.firstOrNull { userCache.getUserInfo(it).isWork }
val needsUpdate = changedUser == null || changedUser == workProfileUser
if (needsUpdate) {
val isUserQuiet =
workProfileUser?.let {
userManagerService.isQuietModeEnabled(
workProfileUser
)
} ?: false
_userProfiles.update {
WidgetUserProfiles(
personal = WidgetUserProfile(
type = WidgetUserProfileType.PERSONAL,
label = stringCache.widgetsPersonalTab,
paused = false,
pausedProfileMessage = null,
),
work = workProfileUser?.let {
WidgetUserProfile(
type = WidgetUserProfileType.WORK,
label = stringCache.widgetsWorkTab,
paused = isUserQuiet,
pausedProfileMessage = stringCache.workProfilePausedTitle,
)
}
)
}
}
}
}
@@ -0,0 +1,198 @@
/*
* 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.repository
import android.content.Context
import com.android.launcher3.DeviceProfile
import com.android.launcher3.InvariantDeviceProfile
import com.android.launcher3.concurrent.annotations.BackgroundContext
import com.android.launcher3.dagger.ApplicationContext
import com.android.launcher3.model.WidgetItem
import com.android.launcher3.model.WidgetsModel
import com.android.launcher3.model.data.PackageItemInfo
import com.android.launcher3.util.ComponentKey
import com.android.launcher3.util.Executors.MODEL_EXECUTOR
import com.android.launcher3.widget.DatabaseWidgetPreviewLoader
import com.android.launcher3.widget.picker.util.WidgetPreviewContainerSize
import com.android.launcher3.widget.util.WidgetSizes
import com.android.launcher3.widgetpicker.data.repository.WidgetsRepository
import com.android.launcher3.widgetpicker.datasource.FeaturedWidgetsDataSource
import com.android.launcher3.widgetpicker.datasource.WidgetsSearchAlgorithm
import com.android.launcher3.widgetpicker.shared.model.PickableWidget
import com.android.launcher3.widgetpicker.shared.model.WidgetApp
import com.android.launcher3.widgetpicker.shared.model.WidgetAppId
import com.android.launcher3.widgetpicker.shared.model.WidgetId
import com.android.launcher3.widgetpicker.shared.model.WidgetPreview
import com.android.launcher3.widgetpicker.shared.model.WidgetSizeInfo
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
import kotlin.coroutines.CoroutineContext
/**
* An implementation of the [WidgetsRepository] that provides widgets for widget picker using the
* [WidgetsModel], [FeaturedWidgetsDataSource] & enables search using the provided
* [WidgetsSearchAlgorithm].
*/
class WidgetsRepositoryImpl @Inject constructor(
@ApplicationContext private val appContext: Context,
idp: InvariantDeviceProfile,
private val widgetsModel: WidgetsModel,
private val featuredWidgetsDataSource: FeaturedWidgetsDataSource,
private val searchAlgorithm: WidgetsSearchAlgorithm,
@BackgroundContext
private val backgroundContext: CoroutineContext,
) : WidgetsRepository {
private val deviceProfile = idp.getDeviceProfile(appContext)
private val backgroundScope = CoroutineScope(
SupervisorJob() + backgroundContext + CoroutineName("WidgetsRepository")
)
private val _widgetItemsByPackage =
MutableStateFlow<List<WidgetApp>>(emptyList())
private val databaseWidgetPreviewLoader = DatabaseWidgetPreviewLoader(appContext, deviceProfile)
override fun initialize() {
// TODO(b/419495339): Remove the model executor requirement from widgets model and replace
// with scope.launch
MODEL_EXECUTOR.execute {
widgetsModel.update(/*packageUser=*/ null)
_widgetItemsByPackage.update {
widgetsModel.widgetsByPackageItemForPicker.toPickableWidgets(deviceProfile)
}
}
backgroundScope.launch {
featuredWidgetsDataSource.initialize()
}
}
override fun observeWidgets(): Flow<List<WidgetApp>> = _widgetItemsByPackage.asStateFlow()
override suspend fun getWidgetPreview(id: WidgetId): WidgetPreview {
val componentKey = ComponentKey(id.componentName, id.userHandle)
val widgetItem = widgetsModel.widgetsByComponentKey[componentKey]
?: return WidgetPreview.PlaceholderWidgetPreview
val previewSizePx =
WidgetSizes.getWidgetSizePx(deviceProfile, widgetItem.spanX, widgetItem.spanY)
val preview = withContext(backgroundContext) {
val result =
databaseWidgetPreviewLoader.generatePreviewInfoBg(
widgetItem,
previewSizePx.width,
previewSizePx.height
)
when {
result.remoteViews != null ->
WidgetPreview.RemoteViewsWidgetPreview(result.remoteViews)
result.providerInfo != null ->
WidgetPreview.ProviderInfoWidgetPreview(result.providerInfo)
result.previewBitmap != null ->
WidgetPreview.BitmapWidgetPreview(result.previewBitmap)
else -> WidgetPreview.PlaceholderWidgetPreview
}
}
return preview
}
override suspend fun searchWidgets(query: String): List<WidgetApp> =
searchAlgorithm.searchWidgets(query, _widgetItemsByPackage.value)
override fun cleanUp() {
_widgetItemsByPackage.update { emptyList() }
backgroundScope.apply {
if (isActive) {
cancel()
}
}
}
override fun getFeaturedWidgets(): Flow<List<PickableWidget>> {
return _widgetItemsByPackage.map { widgets ->
featuredWidgetsDataSource.getFeaturedWidgets(widgets)
}.flowOn(backgroundContext)
}
companion object {
private fun Map<PackageItemInfo, List<WidgetItem>>.toPickableWidgets(deviceProfile: DeviceProfile) =
map { (packageItemInfo, widgetItems) ->
val widgetAppId = WidgetAppId(
packageName = packageItemInfo.packageName,
userHandle = packageItemInfo.user,
category = packageItemInfo.widgetCategory
)
WidgetApp(
id = widgetAppId,
title = packageItemInfo.title,
widgets = widgetItems.filter { it.widgetInfo != null }.map { widgetItem ->
val previewSize =
WidgetSizes.getWidgetSizePx(
deviceProfile,
widgetItem.spanX,
widgetItem.spanY
)
val containerSpan =
WidgetPreviewContainerSize.forItem(widgetItem, deviceProfile)
val containerSize =
WidgetSizes.getWidgetSizePx(
deviceProfile,
containerSpan.spanX,
containerSpan.spanY
)
PickableWidget(
id = WidgetId(
componentName = widgetItem.componentName,
userHandle = widgetItem.user
),
appId = widgetAppId,
label = widgetItem.label,
description = widgetItem.description,
appWidgetProviderInfo = widgetItem.widgetInfo.clone(),
sizeInfo = WidgetSizeInfo(
spanX = widgetItem.widgetInfo.spanX,
spanY = widgetItem.widgetInfo.spanY,
widthPx = previewSize.width,
heightPx = previewSize.height,
containerSpanX = containerSpan.spanX,
containerSpanY = containerSpan.spanY,
containerWidthPx = containerSize.width,
containerHeightPx = containerSize.height
)
)
}
)
}
}
}
+2
View File
@@ -124,6 +124,7 @@ android_library {
name: "widget_picker_ui_components",
sdk_version: "current",
min_sdk_version: min_launcher3_sdk_version,
plugins: ["dagger2-compiler"],
srcs: [
"src/com/android/launcher3/widgetpicker/ui/components/ScrollableFloatingToolbar.kt",
"src/com/android/launcher3/widgetpicker/ui/components/LeadingIconToolbarTab.kt",
@@ -164,6 +165,7 @@ android_library {
android_library {
name: "widget_picker_ui",
sdk_version: "current",
plugins: ["dagger2-compiler"],
min_sdk_version: min_launcher3_sdk_version,
srcs: [
"src/com/android/launcher3/widgetpicker/ui/ViewModel.kt",
@@ -55,6 +55,8 @@ data class PickableWidget(
* grid
* @param heightPx the height in pixels that the widget should ideally be sized at based on host's
* grid
* @param spanX the number of horizontal cells that the container for the widget will use.
* @param spanY the number of vertical cells that the container for the widget will use.
* @param containerWidthPx the width of container in which the widget may need to be fit to; For
* instance, for visual coherence, widgets of sizes like 3x2 are shown in 2x2 container based on a
* predefined mapping logic. This allows us to show them in a single row when space permits.
@@ -66,6 +68,8 @@ data class WidgetSizeInfo(
val spanY: Int,
val widthPx: Int,
val heightPx: Int,
val containerSpanX: Int,
val containerSpanY: Int,
val containerWidthPx: Int,
val containerHeightPx: Int,
)
@@ -20,6 +20,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.android.launcher3.widgetpicker.WidgetPickerHostInfo
import com.android.launcher3.widgetpicker.WidgetPickerSingleton
import com.android.launcher3.widgetpicker.shared.model.WidgetHostInfo
import com.android.launcher3.widgetpicker.ui.ViewModel
import com.android.launcher3.widgetpicker.ui.fullcatalog.screens.landing.LandingScreenViewModel
@@ -61,6 +62,7 @@ class FullWidgetsCatalogViewModel @AssistedInject constructor(
}
@AssistedFactory
@WidgetPickerSingleton
interface Factory {
fun create(): FullWidgetsCatalogViewModel
}
@@ -22,6 +22,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import com.android.launcher3.widgetpicker.WidgetPickerSingleton
import com.android.launcher3.widgetpicker.domain.interactor.WidgetAppIconsInteractor
import com.android.launcher3.widgetpicker.domain.interactor.WidgetsInteractor
import com.android.launcher3.widgetpicker.shared.model.WidgetAppIcon
@@ -233,6 +234,7 @@ class LandingScreenViewModel @AssistedInject constructor(
/** A factory that should be injected whenever [LandingScreenViewModel] is required. */
@AssistedFactory
@WidgetPickerSingleton
interface Factory {
fun create(): LandingScreenViewModel
}
@@ -22,6 +22,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import com.android.launcher3.widgetpicker.WidgetPickerSingleton
import com.android.launcher3.widgetpicker.domain.interactor.WidgetAppIconsInteractor
import com.android.launcher3.widgetpicker.domain.interactor.WidgetsInteractor
import com.android.launcher3.widgetpicker.shared.model.WidgetAppId
@@ -142,6 +143,7 @@ class SearchScreenViewModel @AssistedInject constructor(
/** A factory that should be injected whenever [SearchScreenViewModel] is required. */
@AssistedFactory
@WidgetPickerSingleton
interface Factory {
fun create(): SearchScreenViewModel
}
@@ -248,6 +248,8 @@ object WidgetsGridTestSamples {
spanY = 1,
widthPx = cellWidth,
heightPx = cellHeight,
containerSpanX = 1,
containerSpanY = 1,
containerWidthPx = cellWidth,
containerHeightPx = cellHeight,
),
@@ -267,6 +269,8 @@ object WidgetsGridTestSamples {
spanY = 2,
widthPx = cellWidth * 2,
heightPx = cellHeight * 2,
containerSpanX = 2,
containerSpanY = 2,
// container same as size
containerWidthPx = cellWidth * 2,
containerHeightPx = cellHeight * 2,
@@ -286,6 +290,8 @@ object WidgetsGridTestSamples {
spanY = 2,
widthPx = cellWidth * 3,
heightPx = cellHeight * 2,
containerSpanX = 2,
containerSpanY = 2,
// 3x2s are bucketed to 2x2 container
containerWidthPx = cellWidth * 2,
containerHeightPx = cellHeight * 2,
@@ -305,6 +311,8 @@ object WidgetsGridTestSamples {
spanY = 2,
widthPx = cellWidth * 4,
heightPx = cellHeight * 2,
containerSpanX = 4,
containerSpanY = 2,
// container same as size
containerWidthPx = cellWidth * 4,
containerHeightPx = cellHeight * 2,
@@ -121,6 +121,8 @@ object TestUtils {
spanY = 2,
widthPx = 200,
heightPx = 200,
containerSpanX = 2,
containerSpanY = 2,
containerWidthPx = 200,
containerHeightPx = 200,
),
+1
View File
@@ -91,6 +91,7 @@
<dimen name="task_thumbnail_header_padding_start_end">12dp</dimen>
<dimen name="task_thumbnail_header_margin_between_views">8dp</dimen>
<dimen name="task_thumbnail_header_icon_size">18dp</dimen>
<dimen name="task_thumbnail_header_close_button_hit_rect_size">32dp</dimen>
<dimen name="task_thumbnail_header_round_corner_radius">16dp</dimen>
<!-- The size for non-overlapping layout in desktop tile -->
<dimen name="desktop_vertical_padding_between_tasks">24dp</dimen>
+5
View File
@@ -389,12 +389,17 @@
<item name="overviewScrimColor">?attr/overviewScrimColorBlur</item>
<item name="overviewActionsContainerStyle">@style/OverviewActionsContainerBlur</item>
<item name="overviewActionButtonStyle">@style/OverviewActionButton.Blur</item>
<item name="overviewScrimForegroundPrimary">?attr/overviewScrimForegroundPrimaryBlur</item>
<item name="overviewScrimForegroundSecondary">?attr/overviewScrimForegroundSecondaryBlur
</item>
</style>
<style name="OverviewBlurFallbackStyle">
<item name="overviewScrimColor">?attr/overviewScrimColorFallback</item>
<item name="overviewActionsContainerStyle">@style/OverviewActionsContainer</item>
<item name="overviewActionButtonStyle">@style/OverviewActionButton</item>
<item name="overviewScrimForegroundPrimary">@android:color/transparent</item>
<item name="overviewScrimForegroundSecondary">@android:color/transparent</item>
</style>
</resources>
@@ -172,8 +172,9 @@ public class KeyboardQuickSwitchViewController {
// Calculate the additional margin space that the KQS should move up for the transient
// taskbar. The value of spaceForTaskbar is the distance between the bottom of the KQS
// view with 0 bottom margin to the top of the transient taskbar view.
final int spaceForTaskbar = isTransientTaskbar ? dp.taskbarHeight + dp.taskbarBottomMargin
- dp.stashedTaskbarHeight : 0;
final int spaceForTaskbar = isTransientTaskbar ? dp.getTaskbarProfile().getHeight()
+ dp.getTaskbarProfile().getBottomMargin()
- dp.getTaskbarProfile().getStashedTaskbarHeight() : 0;
final int marginBottom = spaceForTaskbar + resources.getDimensionPixelSize(
R.dimen.keyboard_quick_switch_margin_bottom);
@@ -366,7 +366,7 @@ public class NavbarButtonsViewController implements TaskbarControllers.LoggableT
flags -> (flags & flagsToRemoveTranslation) != 0, AnimatedFloat.VALUE,
1, 0));
// Center nav buttons in new height for IME.
float transForIme = (mContext.getDeviceProfile().taskbarHeight
float transForIme = (mContext.getDeviceProfile().getTaskbarProfile().getHeight()
- mControllers.taskbarInsetsController.getTaskbarHeightForIme()) / 2f;
// For gesture nav, nav buttons only show for IME anyway so keep them translated down.
float defaultButtonTransY = alwaysShowButtons ? 0 : transForIme;
@@ -130,11 +130,11 @@ public class StashedHandleViewController implements TaskbarControllers.LoggableT
mStashedHandleWidth =
resources.getDimensionPixelSize(R.dimen.taskbar_stashed_small_screen);
} else {
mTaskbarSize = deviceProfile.taskbarHeight;
mTaskbarSize = deviceProfile.getTaskbarProfile().getHeight();
mStashedHandleWidth = resources
.getDimensionPixelSize(R.dimen.taskbar_stashed_handle_width);
}
int taskbarBottomMargin = deviceProfile.taskbarBottomMargin;
int taskbarBottomMargin = deviceProfile.getTaskbarProfile().getBottomMargin();
mStashedHandleView.getLayoutParams().height = mTaskbarSize + taskbarBottomMargin;
mTaskbarStashedHandleAlpha.get(ALPHA_INDEX_STASHED).setValue(
@@ -472,7 +472,7 @@ public class TaskbarActivityContext extends BaseTaskbarContext {
deviceProfile.hotseatQsbWidth = originDeviceProfile.hotseatQsbWidth;
// Update icon size
deviceProfile.iconSizePx = deviceProfile.taskbarIconSize;
deviceProfile.iconSizePx = deviceProfile.getTaskbarProfile().getIconSize();
deviceProfile.updateIconSize(1f, this);
};
mDeviceProfile = originDeviceProfile.toBuilder(this)
@@ -816,7 +816,7 @@ public class TaskbarActivityContext extends BaseTaskbarContext {
/** Returns whether taskbar should start align. */
public boolean shouldStartAlignTaskbar() {
return isThreeButtonNav() && mDeviceProfile.startAlignTaskbar;
return isThreeButtonNav() && mDeviceProfile.getTaskbarProfile().isStartAlignTaskbar();
}
public boolean isGestureNav() {
@@ -1382,15 +1382,15 @@ public class TaskbarActivityContext extends BaseTaskbarContext {
DeviceProfile transientTaskbarDp = mDeviceProfile.toBuilder(this)
.setIsTransientTaskbar(true).build();
taskbarWindowSize = transientTaskbarDp.taskbarHeight
+ (2 * transientTaskbarDp.taskbarBottomMargin)
taskbarWindowSize = transientTaskbarDp.getTaskbarProfile().getHeight()
+ (2 * transientTaskbarDp.getTaskbarProfile().getBottomMargin())
+ Math.max(extraHeightForTaskbarTooltips, resources.getDimensionPixelSize(
R.dimen.transient_taskbar_shadow_blur));
return Math.max(taskbarWindowSize, bubbleBarTop);
}
taskbarWindowSize = mDeviceProfile.taskbarHeight
taskbarWindowSize = mDeviceProfile.getTaskbarProfile().getHeight()
+ getCornerRadius()
+ extraHeightForTaskbarTooltips;
return Math.max(taskbarWindowSize, bubbleBarTop);
@@ -40,9 +40,9 @@ class TaskbarBackgroundRenderer(private val context: TaskbarActivityContext) {
private val isInSetup: Boolean = !context.isUserSetupComplete
private val maxTransientTaskbarHeight =
context.transientTaskbarDeviceProfile.taskbarHeight.toFloat()
context.transientTaskbarDeviceProfile.taskbarProfile.height.toFloat()
private val maxPersistentTaskbarHeight =
context.persistentTaskbarDeviceProfile.taskbarHeight.toFloat()
context.persistentTaskbarDeviceProfile.taskbarProfile.height.toFloat()
var backgroundProgress =
if (context.isTransientTaskbar) {
PINNING_TRANSIENT
@@ -57,7 +57,7 @@ class TaskbarBackgroundRenderer(private val context: TaskbarActivityContext) {
val paint = Paint()
private val strokePaint = Paint()
val lastDrawnTransientRect = RectF()
var backgroundHeight = context.deviceProfile.taskbarHeight.toFloat()
var backgroundHeight = context.deviceProfile.taskbarProfile.height.toFloat()
var translationYForSwipe = 0f
var translationYForStash = 0f
var translationXForBubbleBar = 0f
@@ -195,10 +195,10 @@ class TaskbarBackgroundRenderer(private val context: TaskbarActivityContext) {
scale = Math.round(scale * 100f) / 100f
bottomMargin =
mapRange(
scale,
0f,
res.getDimensionPixelSize(R.dimen.transient_taskbar_bottom_margin).toFloat(),
)
scale,
0f,
res.getDimensionPixelSize(R.dimen.transient_taskbar_bottom_margin).toFloat(),
)
.toInt()
shadowBlur =
mapRange(scale, 0f, res.getDimension(R.dimen.transient_taskbar_shadow_blur))
@@ -267,8 +267,8 @@ constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
}
override fun getExtraVerticalOffset(): Int {
return (mActivityContext.deviceProfile.taskbarHeight -
mActivityContext.deviceProfile.taskbarIconSize) / 2 + verticalOffsetForPopupView
return (mActivityContext.deviceProfile.taskbarProfile.height -
mActivityContext.deviceProfile.taskbarProfile.iconSize) / 2 + verticalOffsetForPopupView
}
override fun onCreateCloseAnimation(anim: AnimatorSet?) {
@@ -163,9 +163,14 @@ public class TaskbarDragLayerController implements TaskbarControllers.LoggableTa
* @return Bounds (in TaskbarDragLayer coordinates) where an opened Folder can display.
*/
public Rect getFolderBoundingBox() {
Rect boundingBox = new Rect(0, 0, mTaskbarDragLayer.getWidth(),
mTaskbarDragLayer.getHeight() - mActivity.getDeviceProfile().taskbarHeight
- mActivity.getDeviceProfile().taskbarBottomMargin);
Rect boundingBox = new Rect(
0,
0,
mTaskbarDragLayer.getWidth(),
mTaskbarDragLayer.getHeight()
- mActivity.getDeviceProfile().getTaskbarProfile().getHeight()
- mActivity.getDeviceProfile().getTaskbarProfile().getBottomMargin()
);
boundingBox.inset(mFolderMargin, mFolderMargin);
return boundingBox;
}
@@ -352,7 +357,7 @@ public class TaskbarDragLayerController implements TaskbarControllers.LoggableTa
deviceProfile.getDisplayInfo().currentSize.y :
taskbarDimensions.y;
} else {
return deviceProfile.taskbarHeight;
return deviceProfile.getTaskbarProfile().getHeight();
}
}
@@ -85,7 +85,7 @@ constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
// constraint to reduce the number of lines of text and hopefully free up some height.
activityContext.dragLayer.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED)
if (
measuredHeight + activityContext.deviceProfile.taskbarHeight >=
measuredHeight + activityContext.deviceProfile.taskbarProfile.height >=
activityContext.deviceProfile.deviceProperties.availableHeightPx
) {
updateLayoutParams { width = MATCH_PARENT }
@@ -245,7 +245,7 @@ open class TaskbarEduTooltipController(context: Context) :
else R.dimen.taskbar_edu_features_tooltip_width_with_two_features
)
bottomMargin += activityContext.deviceProfile.taskbarHeight
bottomMargin += activityContext.deviceProfile.taskbarProfile.height
} else {
width =
resources.getDimensionPixelSize(
@@ -299,7 +299,7 @@ open class TaskbarEduTooltipController(context: Context) :
handleEduAnimations(listOf(pinningAnim))
updateLayoutParams<BaseDragLayer.LayoutParams> {
if (activityContext.isTransientTaskbar) {
bottomMargin += activityContext.deviceProfile.taskbarHeight
bottomMargin += activityContext.deviceProfile.taskbarProfile.height
}
// Unlike other tooltips, we want to align with taskbar divider rather than center.
gravity = Gravity.BOTTOM
@@ -356,7 +356,7 @@ open class TaskbarEduTooltipController(context: Context) :
showDisclosureText(eduSubtitle)
updateLayoutParams<BaseDragLayer.LayoutParams> {
if (activityContext.isTransientTaskbar) {
bottomMargin += activityContext.deviceProfile.taskbarHeight
bottomMargin += activityContext.deviceProfile.taskbarProfile.height
}
// Unlike other tooltips, we want to align with the all apps button rather than
// center.
@@ -804,8 +804,11 @@ public class TaskbarLauncherStateController {
taskbarBgOffsetStart,
taskbarBgOffsetEnd);
ObjectAnimator taskbarIconsYTranslation = null;
float taskbarHeight =
mControllers.taskbarActivityContext.getDeviceProfile().taskbarHeight;
float taskbarHeight = mControllers
.taskbarActivityContext
.getDeviceProfile()
.getTaskbarProfile()
.getHeight();
if (showTaskbar) {
taskbarIconsYTranslation = taskbarIconTranslationYForHome.animateToValue(
taskbarHeight, 0);
@@ -292,7 +292,10 @@ public class TaskbarPopupController implements TaskbarControllers.LoggableTaskba
// Move the icon to align with the center-top of the touch point
Point iconShift = new Point();
iconShift.x = mIconLastTouchPos.x - sv.getIconCenter().x;
iconShift.y = mIconLastTouchPos.y - mContext.getDeviceProfile().taskbarIconSize;
iconShift.y = mIconLastTouchPos.y
- mContext.getDeviceProfile()
.getTaskbarProfile()
.getIconSize();
((TaskbarDragController) ActivityContext.lookupContext(
v.getContext()).getDragController()).startDragOnLongClick(sv, iconShift);
@@ -322,8 +322,11 @@ public class TaskbarStashController implements TaskbarControllers.LoggableTaskba
mStashedHeight = mActivity.getResources().getDimensionPixelSize(
R.dimen.taskbar_stashed_size);
} else {
mUnstashedHeight = mActivity.getDeviceProfile().taskbarHeight;
mStashedHeight = mActivity.getDeviceProfile().stashedTaskbarHeight;
mUnstashedHeight = mActivity.getDeviceProfile().getTaskbarProfile().getHeight();
mStashedHeight = mActivity
.getDeviceProfile()
.getTaskbarProfile()
.getStashedTaskbarHeight();
}
}
@@ -512,7 +515,11 @@ public class TaskbarStashController implements TaskbarControllers.LoggableTaskba
public int getTouchableHeight() {
return mIsStashed
? mStashedHeight
: (mUnstashedHeight + mActivity.getDeviceProfile().taskbarBottomMargin);
: (mUnstashedHeight
+ mActivity.getDeviceProfile()
.getTaskbarProfile()
.getBottomMargin()
);
}
/**
@@ -47,7 +47,8 @@ class TaskbarStashViaTouchController(val controllers: TaskbarControllers) : Touc
private val maxVisualDisplacement =
activity.resources.getDimensionPixelSize(R.dimen.transient_taskbar_bottom_margin).toFloat()
/** How far the swipe could go, if user swiped from the very top of TaskbarView. */
private val maxTouchDisplacement = maxVisualDisplacement + activity.deviceProfile.taskbarHeight
private val maxTouchDisplacement =
maxVisualDisplacement + activity.deviceProfile.taskbarProfile.height
private val touchDisplacementToStash =
activity.resources.getDimensionPixelSize(R.dimen.taskbar_to_nav_threshold).toFloat()
@@ -162,10 +162,11 @@ public class TaskbarView extends FrameLayout implements FolderIcon.FolderIconPar
onDeviceProfileChanged(mActivityContext.getDeviceProfile());
int actualMargin = resources.getDimensionPixelSize(R.dimen.taskbar_icon_spacing);
int actualIconSize = mActivityContext.getDeviceProfile().taskbarIconSize;
int actualIconSize =
mActivityContext.getDeviceProfile().getTaskbarProfile().getIconSize();
if (enableTaskbarPinning() && canTransitionToTransientTaskbar()) {
DeviceProfile deviceProfile = mActivityContext.getTransientTaskbarDeviceProfile();
actualIconSize = deviceProfile.taskbarIconSize;
actualIconSize = deviceProfile.getTaskbarProfile().getIconSize();
}
int visualIconSize = (int) (actualIconSize * ICON_VISIBLE_AREA_FACTOR);
@@ -178,7 +179,10 @@ public class TaskbarView extends FrameLayout implements FolderIcon.FolderIconPar
// We always layout taskbar as a transient taskbar when we have taskbar pinning feature on,
// then we scale and translate the icons to match persistent taskbar designs, so we use
// taskbar icon size from current device profile to calculate correct item padding.
mItemPadding = (mIconTouchSize - mActivityContext.getDeviceProfile().taskbarIconSize) / 2;
mItemPadding = (mIconTouchSize - mActivityContext
.getDeviceProfile()
.getTaskbarProfile()
.getIconSize()) / 2;
mFolderLeaveBehindColor = Themes.getAttrColor(mActivityContext,
android.R.attr.textColorTertiary);
@@ -231,14 +231,14 @@ public class TaskbarViewController implements TaskbarControllers.LoggableTaskbar
mActivity = activity;
mTransientTaskbarDp = mActivity.getTransientTaskbarDeviceProfile();
mPersistentTaskbarDp = mActivity.getPersistentTaskbarDeviceProfile();
mTransientIconSize = mTransientTaskbarDp.taskbarIconSize;
mPersistentIconSize = mPersistentTaskbarDp.taskbarIconSize;
mTransientIconSize = mTransientTaskbarDp.getTaskbarProfile().getIconSize();
mPersistentIconSize = mPersistentTaskbarDp.getTaskbarProfile().getIconSize();
mTaskbarView = taskbarView;
mTaskbarIconAlpha = new MultiValueAlpha(mTaskbarView, NUM_ALPHA_CHANNELS);
mTaskbarIconAlpha.setUpdateVisibility(true);
mModelCallbacks = TaskbarModelCallbacksFactory.newInstance(mActivity)
.create(mActivity, mTaskbarView);
mTaskbarBottomMargin = activity.getDeviceProfile().taskbarBottomMargin;
mTaskbarBottomMargin = activity.getDeviceProfile().getTaskbarProfile().getBottomMargin();
mStashedHandleHeight = activity.getResources()
.getDimensionPixelSize(R.dimen.taskbar_stashed_handle_height);
@@ -271,7 +271,7 @@ public class TaskbarViewController implements TaskbarControllers.LoggableTaskbar
mControllers.runAfterInit(mTaskbarView::updatePinningPopupEventHandlers);
mTaskbarView.getLayoutParams().height = mActivity.isPhoneMode()
? mActivity.getResources().getDimensionPixelSize(R.dimen.taskbar_phone_size)
: mActivity.getDeviceProfile().taskbarHeight;
: mActivity.getDeviceProfile().getTaskbarProfile().getHeight();
mTaskbarIconScaleForStash.updateValue(1f);
float pinningValue =
@@ -687,17 +687,19 @@ public class TaskbarViewController implements TaskbarControllers.LoggableTaskbar
// finally placing the icon in the middle of new taskbar background height.
if (mControllers.getSharedState().startTaskbarVariantIsTransient) {
float transY =
mTransientTaskbarDp.taskbarBottomMargin + (mTransientTaskbarDp.taskbarHeight
mTransientTaskbarDp.getTaskbarProfile().getBottomMargin() + (
mTransientTaskbarDp.getTaskbarProfile().getHeight()
- mTaskbarView.getTransientTaskbarIconLayoutBounds().bottom)
- (mPersistentTaskbarDp.taskbarHeight
- mTransientTaskbarDp.taskbarIconSize) / 2f;
- (mPersistentTaskbarDp.getTaskbarProfile().getHeight()
- mTransientTaskbarDp.getTaskbarProfile().getIconSize()) / 2f;
taskbarIconTranslationYForPinningValue = mapRange(scale, 0f, transY);
} else {
float transY =
-mTransientTaskbarDp.taskbarBottomMargin + (mPersistentTaskbarDp.taskbarHeight
-mTransientTaskbarDp.getTaskbarProfile().getBottomMargin() + (
mPersistentTaskbarDp.getTaskbarProfile().getHeight()
- mTaskbarView.getTransientTaskbarIconLayoutBounds().bottom)
- (mTransientTaskbarDp.taskbarHeight
- mTransientTaskbarDp.taskbarIconSize) / 2f;
- (mTransientTaskbarDp.getTaskbarProfile().getHeight()
- mTransientTaskbarDp.getTaskbarProfile().getIconSize()) / 2f;
taskbarIconTranslationYForPinningValue = mapRange(scale, transY, 0f);
}
return taskbarIconTranslationYForPinningValue;
@@ -982,12 +984,16 @@ public class TaskbarViewController implements TaskbarControllers.LoggableTaskbar
Rect hotseatPadding = launcherDp.getHotseatLayoutPadding(mActivity);
boolean isTransientTaskbar = mActivity.isTransientTaskbar();
float scaleUp = ((float) launcherDp.iconSizePx) / taskbarDp.taskbarIconSize;
float scaleUp = ((float) launcherDp.iconSizePx)
/ taskbarDp.getTaskbarProfile().getIconSize();
int borderSpacing = launcherDp.hotseatBorderSpace;
int hotseatCellSize = DeviceProfile.calculateCellWidth(
launcherDp.getDeviceProperties().getAvailableWidthPx() - hotseatPadding.left - hotseatPadding.right,
launcherDp.getDeviceProperties().getAvailableWidthPx()
- hotseatPadding.left
- hotseatPadding.right,
borderSpacing,
launcherDp.numShownHotseatIcons);
launcherDp.numShownHotseatIcons
);
boolean isToHome = mControllers.uiController.isIconAlignedWithHotseat();
boolean isDeviceLocked = mControllers.taskbarStashController.isDeviceLocked();
@@ -1012,13 +1018,14 @@ public class TaskbarViewController implements TaskbarControllers.LoggableTaskbar
}
}
int collapsedHeight = mActivity.getDefaultTaskbarWindowSize();
int expandedHeight = Math.max(collapsedHeight, taskbarDp.taskbarHeight + offsetY);
int expandedHeight = Math.max(collapsedHeight,
taskbarDp.getTaskbarProfile().getHeight() + offsetY);
setter.addOnFrameListener(anim -> mActivity.setTaskbarWindowSize(
anim.getAnimatedFraction() > 0 ? expandedHeight : collapsedHeight));
mTaskbarBottomMargin = isTransientTaskbar
? mTransientTaskbarDp.taskbarBottomMargin
: mPersistentTaskbarDp.taskbarBottomMargin;
? mTransientTaskbarDp.getTaskbarProfile().getBottomMargin()
: mPersistentTaskbarDp.getTaskbarProfile().getBottomMargin();
int firstRecentTaskIndex = -1;
int hotseatNavBarTranslationX = 0;
@@ -1078,8 +1085,9 @@ public class TaskbarViewController implements TaskbarControllers.LoggableTaskbar
INDEX_TASKBAR_PINNING_ANIM).getValue();
}
float halfQsbIconWidthDiff =
(launcherDp.hotseatQsbWidth - taskbarDp.taskbarIconSize) / 2f;
float scale = ((float) taskbarDp.taskbarIconSize)
(launcherDp.hotseatQsbWidth - taskbarDp.getTaskbarProfile().getIconSize())
/ 2f;
float scale = ((float) taskbarDp.getTaskbarProfile().getIconSize())
/ launcherDp.getHotseatProfile().getQsbVisualHeight();
setter.addFloat(child, SCALE_PROPERTY, scale, 1f, interpolator);
@@ -565,6 +565,7 @@ public class BubbleBarViewController {
mBarView.showDropTarget(showingDropTarget);
}
//TODO(b/411505605) remove unused IPC calls and code
/**
* Notifies the controller that a drag event is over the Bubble Bar drop zone. The controller
* will display the appropriate drop target and enter drop target mode. The controller will also
@@ -859,7 +860,7 @@ public class BubbleBarViewController {
float mediumIconSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
APP_ICON_MEDIUM_DP, dm);
float smallMediumThreshold = (smallIconSize + mediumIconSize) / 2f;
int taskbarIconSize = deviceProfile.taskbarIconSize;
int taskbarIconSize = deviceProfile.getTaskbarProfile().getIconSize();
return taskbarIconSize <= smallMediumThreshold
? res.getDimensionPixelSize(R.dimen.bubblebar_icon_size_small) :
res.getDimensionPixelSize(R.dimen.bubblebar_icon_size);
@@ -877,7 +878,7 @@ public class BubbleBarViewController {
float largeIconSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
APP_ICON_LARGE_DP, dm);
float mediumLargeThreshold = (mediumIconSize + largeIconSize) / 2f;
return deviceProfile.taskbarIconSize >= mediumLargeThreshold
return deviceProfile.getTaskbarProfile().getIconSize() >= mediumLargeThreshold
? res.getDimensionPixelSize(R.dimen.bubblebar_icon_spacing_large) :
res.getDimensionPixelSize(R.dimen.bubblebar_icon_spacing);
}
@@ -954,9 +955,11 @@ public class BubbleBarViewController {
int persistentSpacingSize = res
.getDimensionPixelSize(R.dimen.bubblebar_icon_spacing_persistent_taskbar);
int persistentBubbleBarSize = persistentBubbleSize + persistentSpacingSize * 2;
int persistentTaskbarHeight = activity.getPersistentTaskbarDeviceProfile().taskbarHeight;
int persistentTaskbarHeight =
activity.getPersistentTaskbarDeviceProfile().getTaskbarProfile().getHeight();
int persistentBubbleBarY = (persistentTaskbarHeight - persistentBubbleBarSize) / 2;
int transientBubbleBarY = activity.getTransientTaskbarDeviceProfile().taskbarBottomMargin;
int transientBubbleBarY =
activity.getTransientTaskbarDeviceProfile().getTaskbarProfile().getBottomMargin();
return transientBubbleBarY - persistentBubbleBarY;
}
@@ -118,7 +118,7 @@ public class BubbleControllers {
.get(ALPHA_INDEX_BUBBLE_BAR);
}
});
bubbleDragController.init(/* bubbleControllers = */ this);
bubbleDragController.init(/* bubbleControllers = */ this, bubbleBarLocationListeners);
bubbleDismissController.init(/* bubbleControllers = */ this);
bubbleBarPinController.init(this, bubbleBarLocationListeners);
bubblePinController.init(this);
@@ -140,6 +140,7 @@ public class BubbleControllers {
return -(int) bubbleStashController.getBubbleBarTranslationY();
}
},
bubbleBarLocationListeners,
SystemUiProxy.INSTANCE.get(taskbarControllers.taskbarActivityContext));
mPostInitRunnables.executeAllAndDestroy();
}
@@ -30,6 +30,7 @@ import androidx.annotation.Nullable;
import androidx.dynamicanimation.animation.FloatPropertyCompat;
import com.android.launcher3.taskbar.TaskbarActivityContext;
import com.android.launcher3.taskbar.bubbles.BubbleBarController.BubbleBarLocationListener;
import com.android.wm.shell.shared.bubbles.BaseBubblePinController.LocationChangeListener;
import com.android.wm.shell.shared.bubbles.BubbleAnythingFlagHelper;
import com.android.wm.shell.shared.bubbles.BubbleBarLocation;
@@ -89,6 +90,7 @@ public class BubbleDragController {
private BubbleDismissController mBubbleDismissController;
private BubbleBarPinController mBubbleBarPinController;
private BubblePinController mBubblePinController;
private BubbleBarLocationListener mBubbleBarLocationListener;
private final DropTargetManager mDropTargetManager;
private final DragZoneFactory mDragZoneFactory;
private final BubbleDragZoneChangedListener mBubbleDragZoneChangedListener;
@@ -143,12 +145,14 @@ public class BubbleDragController {
* Should be careful to only access things that were created in constructors for now, as some
* controllers may still be waiting for init().
*/
public void init(@NonNull BubbleControllers bubbleControllers) {
public void init(@NonNull BubbleControllers bubbleControllers,
BubbleBarLocationListener bubbleBarLocationListener) {
mBubbleBarController = bubbleControllers.bubbleBarController;
mBubbleBarViewController = bubbleControllers.bubbleBarViewController;
mBubbleDismissController = bubbleControllers.bubbleDismissController;
mBubbleBarPinController = bubbleControllers.bubbleBarPinController;
mBubblePinController = bubbleControllers.bubblePinController;
mBubbleBarLocationListener = bubbleBarLocationListener;
mBubbleDismissController.setListener(
stuck -> {
if (stuck) {
@@ -690,13 +694,19 @@ public class BubbleDragController {
if (to instanceof DragZone.Bubble.Left
&& mBubbleBarLocation != BubbleBarLocation.LEFT) {
if (draggedObject instanceof DraggedObject.Bubble) {
// listener will be notified by BubbleBarController
mBubbleBarController.animateBubbleBarLocation(BubbleBarLocation.LEFT);
} else {
// otherwise notify listener manually
mBubbleBarLocationListener.onBubbleBarLocationAnimated(BubbleBarLocation.LEFT);
}
mBubbleBarLocation = BubbleBarLocation.LEFT;
} else if (to instanceof DragZone.Bubble.Right
&& mBubbleBarLocation != BubbleBarLocation.RIGHT) {
if (draggedObject instanceof DraggedObject.Bubble) {
mBubbleBarController.animateBubbleBarLocation(BubbleBarLocation.RIGHT);
} else {
mBubbleBarLocationListener.onBubbleBarLocationAnimated(BubbleBarLocation.RIGHT);
}
mBubbleBarLocation = BubbleBarLocation.RIGHT;
}
@@ -104,7 +104,7 @@ public class BubbleStashedHandleViewController {
// Use values directly from device profile to avoid referencing other bubble controllers
// during init flow.
int maxTy = Math.max(deviceProfile.hotseatBarBottomSpacePx,
deviceProfile.taskbarBottomMargin);
deviceProfile.getTaskbarProfile().getBottomMargin());
// Adjust handle view size to accommodate the handle morphing into the bubble bar
mStashedHandleView.getLayoutParams().height = barSize + maxTy;
@@ -25,10 +25,13 @@ import com.android.launcher3.dragndrop.DragController
import com.android.launcher3.dragndrop.DragOptions
import com.android.launcher3.model.data.ItemInfo
import com.android.launcher3.model.data.WorkspaceItemInfo
import com.android.launcher3.taskbar.bubbles.BubbleBarController.BubbleBarLocationListener
import com.android.launcher3.taskbar.bubbles.BubbleBarLocationDropTarget.BubbleBarDropTargetController
import com.android.quickstep.SystemUiProxy
import com.android.wm.shell.shared.bubbles.BubbleBarLocation
import com.android.wm.shell.shared.bubbles.ContextUtils.isRtl
import com.android.wm.shell.shared.bubbles.DeviceConfig
import com.android.wm.shell.shared.bubbles.DragToBubblesZoneChangeListener
import com.android.wm.shell.shared.bubbles.DragZone
import com.android.wm.shell.shared.bubbles.DragZoneFactory
import com.android.wm.shell.shared.bubbles.DragZoneFactory.BubbleBarPropertiesProvider
@@ -41,20 +44,18 @@ import com.android.wm.shell.shared.bubbles.DropTargetManager
import com.android.wm.shell.shared.bubbles.DropTargetManager.DragZoneChangedListener
import com.google.common.annotations.VisibleForTesting
class DragToBubbleController(
private val context: Context,
private val bubbleBarContainer: FrameLayout,
) : DragController.DragListener {
class DragToBubbleController(private val context: Context, bubbleBarContainer: FrameLayout) :
DragController.DragListener {
@VisibleForTesting val dropTargetManager: DropTargetManager
@VisibleForTesting lateinit var bubbleBarLeftDropTarget: BubbleBarLocationDropTarget
@VisibleForTesting lateinit var bubbleBarRightDropTarget: BubbleBarLocationDropTarget
@VisibleForTesting lateinit var dragZoneFactory: DragZoneFactory
// If item drop is handled the next sysui update will set the bubble bar location
@VisibleForTesting var isItemDropHandled = false
private lateinit var bubbleBarLocationListener: BubbleBarLocationListener
private lateinit var systemUiProxy: SystemUiProxy
private lateinit var bubbleBarViewController: BubbleBarViewController
private val isRtl: Boolean
get() = bubbleBarContainer.isLayoutRtl
init {
dropTargetManager = createDropTargetManager(bubbleBarContainer)
@@ -63,10 +64,12 @@ class DragToBubbleController(
fun init(
bubbleBarViewController: BubbleBarViewController,
bubbleBarPropertiesProvider: BubbleBarPropertiesProvider,
bubbleBarLocationListener: BubbleBarLocationListener,
systemUiProxy: SystemUiProxy,
) {
this.bubbleBarViewController = bubbleBarViewController
this.systemUiProxy = systemUiProxy
this.bubbleBarLocationListener = bubbleBarLocationListener
val dropController: BubbleBarDropTargetController = createDropController()
dragZoneFactory = createDragZoneFactory(bubbleBarPropertiesProvider)
bubbleBarLeftDropTarget = createDropTarget(dropController, isLeftDropTarget = true)
@@ -97,6 +100,7 @@ class DragToBubbleController(
}
override fun onDragStart(dragObject: DragObject, options: DragOptions) {
isItemDropHandled = false
val launcherIcon: DraggedObject = LauncherIcon(bubbleBarViewController.hasBubbles()) {}
val dragZones: List<DragZone> = dragZoneFactory.createSortedDragZones(launcherIcon)
dropTargetManager.onDragStarted(launcherIcon, dragZones)
@@ -108,79 +112,42 @@ class DragToBubbleController(
private fun createDropTargetManager(bubbleBarContainer: FrameLayout): DropTargetManager {
val listener: DragZoneChangedListener =
object : DragZoneChangedListener {
DragToBubblesZoneChangeListener(
context.isRtl,
object : DragToBubblesZoneChangeListener.Callback {
private var lastUpdateLocation: BubbleBarLocation? = null
private val isLocationChangedFromOriginal: Boolean
get() =
lastUpdateLocation != null &&
isDifferentSides(
lastUpdateLocation,
bubbleBarViewController.bubbleBarLocation,
)
private var currentBarLocation: BubbleBarLocation? = null
override fun onInitialDragZoneSet(dragZone: DragZone?) {}
override fun onDragZoneChanged(
draggedObject: DraggedObject,
from: DragZone?,
to: DragZone?,
) {
if (!bubbleBarViewController.hasBubbles()) {
return
override fun onDragEnteredLocation(bubbleBarLocation: BubbleBarLocation?) {
bubbleBarViewController.isShowingDropTarget = bubbleBarLocation != null
if (isItemDropHandled) return
val updatedLocation = bubbleBarLocation ?: getStartingBubbleBarLocation()
currentBarLocation = currentBarLocation ?: getStartingBubbleBarLocation()
if (updatedLocation != currentBarLocation) {
currentBarLocation = updatedLocation
bubbleBarLocationListener.onBubbleBarLocationAnimated(updatedLocation)
}
}
bubbleBarViewController.isShowingDropTarget = true
val updateLocation = getBarLocation(to)
updateBubbleBarLocation(updateLocation)
lastUpdateLocation = updateLocation
}
override fun onDragEnded(zone: DragZone?) {
if (isLocationChangedFromOriginal) {
bubbleBarViewController.animateBubbleBarLocation(
bubbleBarViewController.bubbleBarLocation
)
override fun getStartingBubbleBarLocation(): BubbleBarLocation {
return bubbleBarViewController.bubbleBarLocation
?: BubbleBarLocation.DEFAULT
}
bubbleBarViewController.isShowingDropTarget = false
}
fun updateBubbleBarLocation(updateLocation: BubbleBarLocation?) {
val updatedBefore = lastUpdateLocation != null
val originalLocation = bubbleBarViewController.bubbleBarLocation
if (updateLocation == null && isLocationChangedFromOriginal) {
bubbleBarViewController.animateBubbleBarLocation(originalLocation)
return
}
if (updatedBefore && isDifferentSides(lastUpdateLocation, updateLocation)) {
// updated before and location changed - update to new location
bubbleBarViewController.animateBubbleBarLocation(updateLocation)
return
}
if (!updatedBefore && isDifferentSides(originalLocation, updateLocation)) {
// not updated before and location changed from original
bubbleBarViewController.animateBubbleBarLocation(updateLocation)
}
}
override fun hasBubbles(): Boolean = bubbleBarViewController.hasBubbles()
fun getBarLocation(dragZone: DragZone?): BubbleBarLocation? {
return when (dragZone) {
is DragZone.Bubble.Left -> BubbleBarLocation.LEFT
is DragZone.Bubble.Right -> BubbleBarLocation.RIGHT
else -> null
override fun animateBubbleBarLocation(bubbleBarLocation: BubbleBarLocation) {
if (isItemDropHandled) return
bubbleBarViewController.animateBubbleBarLocation(bubbleBarLocation)
}
}
fun isDifferentSides(f: BubbleBarLocation?, s: BubbleBarLocation?): Boolean {
return f != null && s != null && f.isOnLeft(isRtl) != s.isOnLeft(isRtl)
}
}
},
)
return DropTargetManager(context, bubbleBarContainer, listener)
}
private fun createDragZoneFactory(
bubbleBarPropertiesProvider: BubbleBarPropertiesProvider
): DragZoneFactory {
// TODO(b/411506181) remove IPC call to display drop target in shell
val splitScreenModeChecker = SplitScreenModeChecker { SplitScreenMode.NONE }
val desktopWindowModeChecker = DesktopWindowModeChecker { false }
val windowManager: WindowManager = context.getSystemService(WindowManager::class.java)!!
@@ -197,6 +164,18 @@ class DragToBubbleController(
private fun createDropController(): BubbleBarDropTargetController {
return object : BubbleBarDropTargetController {
override fun onDrop(itemInfo: ItemInfo, isLeftDropTarget: Boolean) {
isItemDropHandled = handleDrop(itemInfo, isLeftDropTarget)
}
override fun acceptDrop(itemInfo: ItemInfo): Boolean {
return hasShortcutInfo(itemInfo) || itemInfo.intent?.component != null
}
fun hasShortcutInfo(itemInfo: ItemInfo): Boolean {
return itemInfo is WorkspaceItemInfo && itemInfo.deepShortcutInfo != null
}
private fun handleDrop(itemInfo: ItemInfo, isLeftDropTarget: Boolean): Boolean {
val location =
if (isLeftDropTarget) {
BubbleBarLocation.LEFT
@@ -206,20 +185,13 @@ class DragToBubbleController(
if (hasShortcutInfo(itemInfo)) {
val si = (itemInfo as WorkspaceItemInfo).deepShortcutInfo
systemUiProxy.showShortcutBubble(si, location)
return
return true
}
val itemIntent: Intent = itemInfo.intent ?: return
val packageName = itemIntent.component?.packageName ?: return
val itemIntent: Intent = itemInfo.intent ?: return false
val packageName = itemIntent.component?.packageName ?: return false
itemIntent.setPackage(packageName)
systemUiProxy.showAppBubble(itemIntent, itemInfo.user, location)
}
override fun acceptDrop(itemInfo: ItemInfo): Boolean {
return hasShortcutInfo(itemInfo) || itemInfo.intent?.component != null
}
fun hasShortcutInfo(itemInfo: ItemInfo): Boolean {
return itemInfo is WorkspaceItemInfo && itemInfo.deepShortcutInfo != null
return true
}
}
}
@@ -27,9 +27,9 @@ import com.android.launcher3.taskbar.bubbles.stashing.BubbleStashController.Task
class DeviceProfileDimensionsProviderAdapter(
private val taskbarActivityContext: TaskbarActivityContext
) : TaskbarHotseatDimensionsProvider {
override fun getTaskbarBottomSpace(): Int = taskbarDp().taskbarBottomMargin
override fun getTaskbarBottomSpace(): Int = taskbarDp().taskbarProfile.bottomMargin
override fun getTaskbarHeight(): Int = taskbarDp().taskbarHeight
override fun getTaskbarHeight(): Int = taskbarDp().taskbarProfile.height
private fun taskbarDp(): DeviceProfile = taskbarActivityContext.deviceProfile
}
@@ -68,7 +68,7 @@ constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
// constraint to reduce the number of lines of text and hopefully free up some height.
activityContext.dragLayer.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED)
if (
measuredHeight + activityContext.deviceProfile.taskbarHeight >=
measuredHeight + activityContext.deviceProfile.taskbarProfile.height >=
activityContext.deviceProfile.deviceProperties.availableHeightPx
) {
updateLayoutParams { width = LayoutParams.MATCH_PARENT }
@@ -20,6 +20,7 @@ import static com.android.launcher3.Flags.enableScalingRevealHomeAnimation;
import static com.android.launcher3.logging.StatsLogManager.LAUNCHER_STATE_ALLAPPS;
import android.content.Context;
import android.graphics.Color;
import com.android.internal.jank.Cuj;
import com.android.launcher3.DeviceProfile;
@@ -29,6 +30,7 @@ import com.android.launcher3.LauncherState;
import com.android.launcher3.R;
import com.android.launcher3.util.Themes;
import com.android.launcher3.views.ActivityContext;
import com.android.launcher3.views.ScrimColors;
import com.android.quickstep.util.BaseDepthController;
import com.android.systemui.shared.system.InteractionJankMonitorWrapper;
@@ -203,14 +205,17 @@ public class AllAppsState extends LauncherState {
}
@Override
public int getWorkspaceScrimColor(Launcher launcher) {
public ScrimColors getWorkspaceScrimColor(Launcher launcher) {
int backgroundColor;
if (!launcher.getDeviceProfile().shouldShowAllAppsOnSheet()) {
// Always use an opaque scrim if there's no sheet.
return launcher.getResources().getColor(R.color.materialColorSurfaceDim);
backgroundColor = launcher.getResources().getColor(R.color.materialColorSurfaceDim);
} else if (!Flags.allAppsBlur()) {
// If there's a sheet but no blur, use the old scrim color.
return launcher.getResources().getColor(R.color.widgets_picker_scrim);
backgroundColor = launcher.getResources().getColor(R.color.widgets_picker_scrim);
} else {
backgroundColor = Themes.getAttrColor(launcher, R.attr.allAppsScrimColor);
}
return Themes.getAttrColor(launcher, R.attr.allAppsScrimColor);
return new ScrimColors(backgroundColor, /* foregroundColor */ Color.TRANSPARENT);
}
}
@@ -24,6 +24,7 @@ import android.graphics.Color;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.Launcher;
import com.android.launcher3.allapps.AllAppsTransitionController;
import com.android.launcher3.views.ScrimColors;
import com.android.quickstep.util.BaseDepthController;
import com.android.quickstep.util.LayoutUtils;
import com.android.quickstep.views.RecentsView;
@@ -108,8 +109,10 @@ public class BackgroundAppState extends OverviewState {
}
@Override
public int getWorkspaceScrimColor(Launcher launcher) {
return Color.TRANSPARENT;
public ScrimColors getWorkspaceScrimColor(Launcher launcher) {
return new ScrimColors(
/* backgroundColor= */ Color.TRANSPARENT,
/* foregroundColor= */ Color.TRANSPARENT);
}
@Override
@@ -26,6 +26,7 @@ import androidx.core.graphics.ColorUtils;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherState;
import com.android.launcher3.views.ActivityContext;
import com.android.launcher3.views.ScrimColors;
/**
* Scale down workspace/hotseat to hint at going to either overview (on pause) or first home screen.
@@ -60,10 +61,14 @@ public class HintState extends LauncherState {
}
@Override
public int getWorkspaceScrimColor(Launcher launcher) {
int overviewStateColor = OVERVIEW.getWorkspaceScrimColor(launcher);
return ColorUtils.setAlphaComponent(overviewStateColor,
Math.round(Color.valueOf(overviewStateColor).alpha() * 100));
public ScrimColors getWorkspaceScrimColor(Launcher launcher) {
ScrimColors overviewStateColor = OVERVIEW.getWorkspaceScrimColor(launcher);
return new ScrimColors(
/* backgroundColor */
ColorUtils.setAlphaComponent(overviewStateColor.getBackgroundColor(),
Math.round(Color.valueOf(overviewStateColor.getBackgroundColor()).alpha()
* 100)),
/* foregroundColor */ Color.TRANSPARENT);
}
@Override
@@ -24,6 +24,8 @@ import android.content.Context;
import android.graphics.Rect;
import android.os.SystemProperties;
import androidx.core.graphics.ColorUtils;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherState;
@@ -31,6 +33,7 @@ import com.android.launcher3.R;
import com.android.launcher3.util.DisplayController;
import com.android.launcher3.util.Themes;
import com.android.launcher3.views.ActivityContext;
import com.android.launcher3.views.ScrimColors;
import com.android.quickstep.util.BaseDepthController;
import com.android.quickstep.util.LayoutUtils;
import com.android.quickstep.views.RecentsView;
@@ -157,8 +160,12 @@ public class OverviewState extends LauncherState {
}
@Override
public int getWorkspaceScrimColor(Launcher launcher) {
return Themes.getAttrColor(launcher, R.attr.overviewScrimColor);
public ScrimColors getWorkspaceScrimColor(Launcher launcher) {
return new ScrimColors(
/* backgroundColor */ Themes.getAttrColor(launcher, R.attr.overviewScrimColor),
/* foregroundColor */ ColorUtils.compositeColors(
Themes.getAttrColor(launcher, R.attr.overviewScrimForegroundPrimary),
Themes.getAttrColor(launcher, R.attr.overviewScrimForegroundSecondary)));
}
@Override
@@ -17,7 +17,7 @@
package com.android.launcher3.uioverrides.touchcontrollers;
import static com.android.app.animation.Interpolators.ACCELERATE_DECELERATE;
import static com.android.launcher3.LauncherAnimUtils.VIEW_BACKGROUND_COLOR;
import static com.android.launcher3.LauncherAnimUtils.SCRIM_COLORS;
import static com.android.launcher3.LauncherAnimUtils.newSingleUseCancelListener;
import static com.android.launcher3.LauncherState.ALL_APPS;
import static com.android.launcher3.LauncherState.HINT_STATE;
@@ -47,6 +47,7 @@ import com.android.launcher3.taskbar.LauncherTaskbarUIController;
import com.android.launcher3.uioverrides.QuickstepLauncher;
import com.android.launcher3.util.DisplayController;
import com.android.launcher3.util.VibratorWrapper;
import com.android.launcher3.views.ScrimColorsEvaluator;
import com.android.quickstep.SystemUiProxy;
import com.android.quickstep.util.AnimatorControllerWithResistance;
import com.android.quickstep.util.MotionPauseDetector;
@@ -86,7 +87,7 @@ public class NoButtonNavbarToOverviewTouchController extends PortraitStatesTouch
private AnimatorPlaybackController mOverviewResistYAnim;
// Normal to Hint animation has flag SKIP_OVERVIEW, so we update this scrim with this animator.
private ObjectAnimator mNormalToHintOverviewScrimAnimator;
private ValueAnimator mNormalToHintOverviewScrimAnimator;
private final QuickstepLauncher mLauncher;
private boolean mIsTrackpadSwipe;
@@ -163,9 +164,10 @@ public class NoButtonNavbarToOverviewTouchController extends PortraitStatesTouch
}
if (mFromState == NORMAL && mToState == HINT_STATE) {
mNormalToHintOverviewScrimAnimator = ObjectAnimator.ofArgb(
mNormalToHintOverviewScrimAnimator = ObjectAnimator.ofObject(
mLauncher.getScrimView(),
VIEW_BACKGROUND_COLOR,
SCRIM_COLORS,
ScrimColorsEvaluator.INSTANCE,
mFromState.getWorkspaceScrimColor(mLauncher),
mToState.getWorkspaceScrimColor(mLauncher));
}
@@ -278,8 +278,9 @@ public class NoButtonQuickSwitchTouchController implements TouchController,
xAnim.setFloat(mRecentsView, ADJACENT_PAGE_HORIZONTAL_OFFSET, scaleAndOffset[1], LINEAR);
// Use QuickSwitchState instead of OverviewState to determine scrim color,
// since we need to take potential taskbar into account.
xAnim.setViewBackgroundColor(mLauncher.getScrimView(),
QUICK_SWITCH_FROM_HOME.getWorkspaceScrimColor(mLauncher), LINEAR);
xAnim.setScrimColors(mLauncher.getScrimView(),
QUICK_SWITCH_FROM_HOME.getWorkspaceScrimColor(mLauncher),
LINEAR);
if (!mRecentsView.hasTaskViews()) {
xAnim.addFloat(mRecentsView, CONTENT_ALPHA, 0f, 1f, LINEAR);
}
@@ -17,7 +17,7 @@ package com.android.quickstep;
import static com.android.app.animation.Interpolators.INSTANT;
import static com.android.app.animation.Interpolators.LINEAR;
import static com.android.launcher3.LauncherAnimUtils.VIEW_BACKGROUND_COLOR;
import static com.android.launcher3.LauncherAnimUtils.SCRIM_COLORS;
import static com.android.launcher3.MotionEventsUtils.isTrackpadMultiFingerSwipe;
import static com.android.launcher3.util.OverviewReleaseFlags.enableGridOnlyOverview;
import static com.android.quickstep.GestureState.GestureEndTarget.LAST_TASK;
@@ -47,7 +47,9 @@ import com.android.launcher3.statemanager.StatefulContainer;
import com.android.launcher3.taskbar.TaskbarUIController;
import com.android.launcher3.util.DisplayController;
import com.android.launcher3.util.WindowBounds;
import com.android.launcher3.views.ScrimColors;
import com.android.launcher3.views.ScrimView;
import com.android.launcher3.views.ScrimColorsEvaluator;
import com.android.quickstep.orientation.RecentsPagedOrientationHandler;
import com.android.quickstep.util.AnimatorControllerWithResistance;
import com.android.quickstep.util.ContextInitListener;
@@ -108,7 +110,7 @@ public abstract class BaseContainerInterface<STATE_TYPE extends BaseState<STATE_
* Returns the color of the scrim behind overview when at rest in this state.
* Return {@link Color#TRANSPARENT} for no scrim.
*/
protected abstract int getOverviewScrimColorForState(CONTAINER_TYPE container,
protected abstract ScrimColors getOverviewScrimColorForState(CONTAINER_TYPE container,
STATE_TYPE state);
public abstract int getSwipeUpDestinationAndLength(
@@ -214,12 +216,14 @@ public abstract class BaseContainerInterface<STATE_TYPE extends BaseState<STATE_
RecentsView recentsView = container.getOverviewPanel();
STATE_TYPE state = stateFromGestureEndTarget(endTarget);
ScrimView scrimView = container.getScrimView();
ObjectAnimator anim = ObjectAnimator.ofArgb(scrimView, VIEW_BACKGROUND_COLOR,
getOverviewScrimColorForState(container, state));
anim.setDuration(duration);
anim.setInterpolator(recentsView == null || !recentsView.isKeyboardTaskFocusPending()
? LINEAR : INSTANT);
return anim;
ObjectAnimator animScrim = ObjectAnimator.ofObject(scrimView, SCRIM_COLORS,
ScrimColorsEvaluator.INSTANCE, getOverviewScrimColorForState(container, state));
animScrim.setDuration(duration);
animScrim.setInterpolator(
recentsView == null || !recentsView.isKeyboardTaskFocusPending()
? LINEAR : INSTANT);
return animScrim;
}
return null;
}
@@ -367,7 +371,7 @@ public abstract class BaseContainerInterface<STATE_TYPE extends BaseState<STATE_
out.x = dp.getDeviceProperties().getWidthPx();
out.y = dp.getDeviceProperties().getHeightPx();
if (dp.getDeviceProperties().isTablet() && !DisplayController.isTransientTaskbar(context)) {
out.y -= dp.taskbarHeight;
out.y -= dp.getTaskbarProfile().getHeight();
}
}
@@ -418,7 +422,8 @@ public abstract class BaseContainerInterface<STATE_TYPE extends BaseState<STATE_
boolean isGridOnlyOverview = dp.getDeviceProperties().isTablet() && enableGridOnlyOverview();
int claimedSpaceBelow = isGridOnlyOverview
? dp.getOverviewProfile().getActionsTopMarginPx()
+ dp.getOverviewProfile().getActionsHeight() + dp.stashedTaskbarHeight
+ dp.getOverviewProfile().getActionsHeight()
+ dp.getTaskbarProfile().getStashedTaskbarHeight()
: (dp.getDeviceProperties().getHeightPx() - outRect.bottom - dp.getInsets().bottom);
int minimumHorizontalPadding = 0;
if (!isGridOnlyOverview) {
@@ -34,6 +34,7 @@ import com.android.launcher3.DeviceProfile;
import com.android.launcher3.statemanager.StateManager;
import com.android.launcher3.taskbar.FallbackTaskbarUIController;
import com.android.launcher3.util.DisplayController;
import com.android.launcher3.views.ScrimColors;
import com.android.quickstep.GestureState.GestureEndTarget;
import com.android.quickstep.fallback.RecentsState;
import com.android.quickstep.orientation.RecentsPagedOrientationHandler;
@@ -227,7 +228,8 @@ public final class FallbackActivityInterface extends
}
@Override
protected int getOverviewScrimColorForState(RecentsActivity activity, RecentsState state) {
protected ScrimColors getOverviewScrimColorForState(RecentsActivity activity,
RecentsState state) {
return state.getScrimColor(activity);
}
}
@@ -34,6 +34,7 @@ import com.android.launcher3.statemanager.StateManager;
import com.android.launcher3.taskbar.TaskbarUIController;
import com.android.launcher3.util.DaggerSingletonObject;
import com.android.launcher3.util.DisplayController;
import com.android.launcher3.views.ScrimColors;
import com.android.quickstep.GestureState.GestureEndTarget;
import com.android.quickstep.dagger.QuickstepBaseAppComponent;
import com.android.quickstep.fallback.RecentsState;
@@ -48,6 +49,7 @@ import dagger.assisted.AssistedInject;
import java.util.function.Consumer;
import java.util.function.Predicate;
/**
* {@link BaseWindowInterface} for recents when the default launcher is different than the
* currently running one and apps should interact with the {@link RecentsWindowManager} as opposed
@@ -143,7 +145,7 @@ public final class FallbackWindowInterface extends BaseWindowInterface {
}
@Override
protected int getOverviewScrimColorForState(RecentsWindowManager container,
protected ScrimColors getOverviewScrimColorForState(RecentsWindowManager container,
RecentsState state) {
return state.getScrimColor(container.asContext());
}
@@ -44,6 +44,7 @@ import com.android.launcher3.taskbar.LauncherTaskbarUIController;
import com.android.launcher3.uioverrides.QuickstepLauncher;
import com.android.launcher3.util.DisplayController;
import com.android.launcher3.util.NavigationMode;
import com.android.launcher3.views.ScrimColors;
import com.android.quickstep.GestureState.GestureEndTarget;
import com.android.quickstep.orientation.RecentsPagedOrientationHandler;
import com.android.quickstep.util.AnimatorControllerWithResistance;
@@ -326,7 +327,8 @@ public final class LauncherActivityInterface extends
}
@Override
protected int getOverviewScrimColorForState(QuickstepLauncher activity, LauncherState state) {
protected ScrimColors getOverviewScrimColorForState(QuickstepLauncher activity,
LauncherState state) {
return state.getWorkspaceScrimColor(activity);
}
@@ -908,8 +908,6 @@ public class TouchInteractionService extends Service {
private void onOverviewTargetChanged(boolean isHomeAndOverviewSame) {
mAllAppsActionManager.setHomeAndOverviewSame(isHomeAndOverviewSame);
// TODO (b/399089118): how will this work with per-display Taskbars? Is using the
// default-display container ok?
RecentsViewContainer newOverviewContainer =
mOverviewComponentObserver.getContainerInterface(
DEFAULT_DISPLAY).getCreatedContainer();
@@ -140,7 +140,7 @@ public class FallbackRecentsStateController implements StateHandler<RecentsState
getOverviewInterpolator(state));
}
setter.setViewBackgroundColor(mRecentsViewContainer.getScrimView(),
setter.setScrimColors(mRecentsViewContainer.getScrimView(),
state.getScrimColor(mRecentsViewContainer.asContext()),
config.getInterpolator(ANIM_SCRIM_FADE, LINEAR));
if (isSplitSelectionState(state)) {
@@ -16,10 +16,10 @@
package com.android.quickstep.fallback;
import static com.android.launcher3.Flags.enableDesktopExplodedView;
import static com.android.launcher3.util.OverviewReleaseFlags.enableGridOnlyOverview;
import static com.android.launcher3.LauncherState.FLAG_CLOSE_POPUPS;
import static com.android.launcher3.uioverrides.states.BackgroundAppState.getOverviewScaleAndOffsetForBackgroundState;
import static com.android.launcher3.uioverrides.states.OverviewModalTaskState.getOverviewScaleAndOffsetForModalState;
import static com.android.launcher3.util.OverviewReleaseFlags.enableGridOnlyOverview;
import android.content.Context;
import android.graphics.Color;
@@ -29,6 +29,7 @@ import com.android.launcher3.R;
import com.android.launcher3.statemanager.BaseState;
import com.android.launcher3.util.Themes;
import com.android.launcher3.views.ActivityContext;
import com.android.launcher3.views.ScrimColors;
import com.android.quickstep.views.RecentsViewContainer;
/**
@@ -164,10 +165,12 @@ public class RecentsState implements BaseState<RecentsState> {
/**
* For this state, what color scrim should be drawn behind overview.
*/
public int getScrimColor(Context context) {
return hasFlag(FLAG_SCRIM)
public ScrimColors getScrimColor(Context context) {
return new ScrimColors(
/* backgroundColor */ hasFlag(FLAG_SCRIM)
? Themes.getAttrColor(context, R.attr.overviewScrimColor)
: Color.TRANSPARENT;
: Color.TRANSPARENT,
/* foregroundColor */ Color.TRANSPARENT);
}
public float[] getOverviewScaleAndOffset(RecentsViewContainer container) {
@@ -372,7 +372,8 @@ public class TaskbarUnstashInputConsumer extends DelegateInputConsumer {
DeviceProfile dp = mTaskbarActivityContext.getDeviceProfile();
mStashedTaskbarHandleBounds.set(
(dp.getDeviceProperties().getWidthPx() - (int) mUnstashArea) / 2,
dp.getDeviceProperties().getHeightPx() - dp.stashedTaskbarHeight,
dp.getDeviceProperties().getHeightPx()
- dp.getTaskbarProfile().getStashedTaskbarHeight(),
(int) (((dp.getDeviceProperties().getWidthPx() - mUnstashArea) / 2) + mUnstashArea),
dp.getDeviceProperties().getHeightPx());
return mStashedTaskbarHandleBounds.contains(x, y);
@@ -556,7 +556,8 @@ class PortraitPagedViewHandler : DefaultPagedViewHandler(), RecentsPagedOrientat
val topLeftTaskPercent = splitInfo.leftTopTaskPercent
val dividerBarPercent = splitInfo.dividerPercent
val taskbarHeight = if (dp.isTransientTaskbar) 0 else dp.taskbarHeight
val taskbarHeight =
if (dp.taskbarProfile.isTransientTaskbar) 0 else dp.taskbarProfile.height
val scale =
outRect.height().toFloat() / (dp.deviceProperties.availableHeightPx - taskbarHeight)
val topTaskHeight = dp.deviceProperties.availableHeightPx * topLeftTaskPercent
@@ -669,7 +670,8 @@ class PortraitPagedViewHandler : DefaultPagedViewHandler(), RecentsPagedOrientat
secondTaskViewSize.x = parentWidth - firstTaskViewSize.x - scaledDividerBar
secondTaskViewSize.y = totalThumbnailHeight
} else {
val taskbarHeight = if (dp.isTransientTaskbar) 0 else dp.taskbarHeight
val taskbarHeight =
if (dp.taskbarProfile.isTransientTaskbar) 0 else dp.taskbarProfile.height
val scale =
totalThumbnailHeight.toFloat() /
(dp.deviceProperties.availableHeightPx - taskbarHeight)
@@ -22,7 +22,7 @@ import kotlinx.coroutines.flow.Flow
interface RecentTasksRepository {
/** Gets all the recent tasks, refreshing from data sources if [forceRefresh] is true. */
fun getAllTaskData(forceRefresh: Boolean = false): Flow<List<Task>>
fun getAllTaskData(displayId: Int, forceRefresh: Boolean = false): Flow<List<Task>>
/**
* Gets the data associated with a task that has id [taskId]. Flow will settle on null if the
@@ -46,5 +46,5 @@ interface RecentTasksRepository {
* Sets the tasks that are visible, indicating that properties relating to visuals need to be
* populated e.g. icons/thumbnails etc.
*/
fun setVisibleTasks(visibleTaskIdList: Set<Int>)
fun setVisibleTasks(displayId: Int, visibleTaskIdList: Set<Int>)
}
@@ -18,6 +18,8 @@ package com.android.quickstep.recents.data
import android.graphics.drawable.Drawable
import android.util.Log
import android.util.SparseArray
import androidx.core.util.valueIterator
import com.android.launcher3.util.coroutines.DispatcherProvider
import com.android.quickstep.recents.data.TaskVisualsChangedDelegate.TaskIconChangedCallback
import com.android.quickstep.recents.data.TaskVisualsChangedDelegate.TaskThumbnailChangedCallback
@@ -46,10 +48,13 @@ class TasksRepository(
private val dispatcherProvider: DispatcherProvider,
) : RecentTasksRepository {
private val tasks = MutableStateFlow(MapForStateFlow<Int, Task>(emptyMap()))
private var visibleTaskIds = emptySet<Int>()
private var visibleTaskIdsPerDisplay = SparseArray<Set<Int>>()
private val taskRequests = HashMap<Int, Pair<Task.TaskKey, Job>>()
override fun getAllTaskData(forceRefresh: Boolean): Flow<List<Task>> {
override fun getAllTaskData(displayId: Int, forceRefresh: Boolean): Flow<List<Task>> {
if (!visibleTaskIdsPerDisplay.contains(displayId)) {
visibleTaskIdsPerDisplay.put(displayId, emptySet())
}
if (forceRefresh) {
recentsModel.getTasks { newTaskList ->
val recentTasks =
@@ -72,7 +77,7 @@ class TasksRepository(
updateTaskRequests()
}
}
return tasks.map { it.values.toList() }
return tasks.map { it.values.filter { it.key.displayId == displayId }.toList() }
}
override fun getTaskDataById(taskId: Int) = tasks.map { it[taskId] }
@@ -82,14 +87,20 @@ class TasksRepository(
override fun getCurrentThumbnailById(taskId: Int) = tasks.value[taskId]?.thumbnail
override fun setVisibleTasks(visibleTaskIdList: Set<Int>) {
visibleTaskIds = visibleTaskIdList
override fun setVisibleTasks(displayId: Int, visibleTaskIdList: Set<Int>) {
if (visibleTaskIdList.isEmpty()) {
visibleTaskIdsPerDisplay.remove(displayId)
} else {
visibleTaskIdsPerDisplay.put(displayId, visibleTaskIdList)
}
updateTaskRequests()
}
@Synchronized
private fun updateTaskRequests() {
val requestsNeeded = visibleTaskIds.intersect(tasks.value.keys)
val allVisibleTaskIds =
visibleTaskIdsPerDisplay.valueIterator().asSequence().flatMap { it }.toSet()
val requestsNeeded = allVisibleTaskIds.intersect(tasks.value.keys)
val taskRequestIds = taskRequests.keys
val requestsNoLongerNeeded = taskRequestIds.subtract(requestsNeeded)
@@ -25,16 +25,17 @@ import kotlinx.coroutines.flow.first
class RecentsViewModel(
private val recentsTasksRepository: RecentTasksRepository,
private val recentsViewData: RecentsViewData,
private val displayId: Int,
) {
private var visibleTaskIds = emptySet<Int>()
fun refreshAllTaskData() {
recentsTasksRepository.getAllTaskData(true)
recentsTasksRepository.getAllTaskData(displayId, true)
}
fun updateVisibleTasks(visibleTaskIdList: List<Int>) {
visibleTaskIds = visibleTaskIdList.toSet()
recentsTasksRepository.setVisibleTasks(visibleTaskIds)
recentsTasksRepository.setVisibleTasks(displayId, visibleTaskIds)
}
fun updateTasksFullyVisible(taskIds: Set<Int>) {
@@ -59,6 +59,10 @@ class TaskGridNavHelper(
cycle: Boolean,
): Int {
val inTop = topRowIds.contains(currentPageTaskViewId)
val inBottom = bottomRowIds.contains(currentPageTaskViewId)
if (!inTop && !inBottom) {
return currentPageTaskViewId
}
val index =
if (inTop) topRowIds.indexOf(currentPageTaskViewId)
else bottomRowIds.indexOf(currentPageTaskViewId)
@@ -385,7 +385,7 @@ public class OverviewActionsView<T extends OverlayUICallbacks> extends FrameLayo
}
if (mDp.getDeviceProperties().isTablet() && enableGridOnlyOverview()) {
return mDp.stashedTaskbarHeight;
return mDp.getTaskbarProfile().getStashedTaskbarHeight();
}
// Align to bottom of task Rect.
@@ -910,7 +910,8 @@ public abstract class RecentsView<
String scopeId = recentsDependencies.createRecentsViewScope(context);
mRecentsViewModel = new RecentsViewModel(
recentsDependencies.inject(RecentTasksRepository.class, scopeId),
recentsDependencies.inject(RecentsViewData.class, scopeId)
recentsDependencies.inject(RecentsViewData.class, scopeId),
mContainer.getDisplayId()
);
mHelper = new RecentsViewModelHelper(
mRecentsViewModel,
@@ -17,7 +17,9 @@
package com.android.quickstep.views
import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.TouchDelegate
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
@@ -33,6 +35,29 @@ class TaskHeaderView @JvmOverloads constructor(context: Context, attrs: Attribut
private val headerIconView: ImageView by lazy { findViewById(R.id.header_app_icon) }
private val headerCloseButton: ImageButton by lazy { findViewById(R.id.header_close_button) }
override fun onFinishInflate() {
super.onFinishInflate()
// Post to ensure the button has been laid out and has its dimensions.
headerCloseButton.post {
val delegateArea = Rect()
headerCloseButton.getHitRect(delegateArea)
// Calculate the desired touch area size in pixels.
val touchTargetSize =
resources.getDimensionPixelSize(
R.dimen.task_thumbnail_header_close_button_hit_rect_size
)
// Expand the hit rect to the desired touch target size, centered on the button.
val sizeDifferenceX = (touchTargetSize - delegateArea.width()) / 2
val sizeDifferenceY = (touchTargetSize - delegateArea.height()) / 2
delegateArea.inset(-sizeDifferenceX, -sizeDifferenceY)
// The TouchDelegate is set on the parent `TaskHeaderView`.
touchDelegate = TouchDelegate(delegateArea, headerCloseButton)
}
}
fun setState(taskHeaderState: TaskHeaderUiState) {
when (taskHeaderState) {
is TaskHeaderUiState.ShowHeader -> {
@@ -325,7 +325,7 @@ class TaskbarStashControllerTest {
}
val expectedHeight =
activityContext.deviceProfile.run { taskbarHeight + taskbarBottomMargin }
activityContext.deviceProfile.taskbarProfile.run { height + bottomMargin }
assertThat(stashController.touchableHeight).isEqualTo(expectedHeight)
}
@@ -333,7 +333,7 @@ class TaskbarStashControllerTest {
@TaskbarMode(PINNED)
fun testGetTouchableHeight_pinnedMode_taskbarHeight() {
assertThat(stashController.touchableHeight)
.isEqualTo(activityContext.deviceProfile.taskbarHeight)
.isEqualTo(activityContext.deviceProfile.taskbarProfile.height)
}
@Test
@@ -347,14 +347,14 @@ class TaskbarStashControllerTest {
@TaskbarMode(THREE_BUTTONS)
fun testGetContentHeightToReportToApps_threeButtonsMode_taskbarHeight() {
assertThat(stashController.contentHeightToReportToApps)
.isEqualTo(activityContext.deviceProfile.taskbarHeight)
.isEqualTo(activityContext.deviceProfile.taskbarProfile.height)
}
@Test
@TaskbarMode(PINNED)
fun testGetContentHeightToReportToApps_pinnedMode_taskbarHeight() {
assertThat(stashController.contentHeightToReportToApps)
.isEqualTo(activityContext.deviceProfile.taskbarHeight)
.isEqualTo(activityContext.deviceProfile.taskbarProfile.height)
}
@Test
@@ -406,7 +406,7 @@ class TaskbarStashControllerTest {
@TaskbarMode(PINNED)
fun testGetTappableHeightToReportToApps_pinnedMode_taskbarHeight() {
assertThat(stashController.tappableHeightToReportToApps)
.isEqualTo(activityContext.deviceProfile.taskbarHeight)
.isEqualTo(activityContext.deviceProfile.taskbarProfile.height)
}
@Test
@@ -31,6 +31,7 @@ import com.android.launcher3.DropTarget
import com.android.launcher3.DropTarget.DragObject
import com.android.launcher3.dragndrop.DragOptions
import com.android.launcher3.model.data.AppInfo
import com.android.launcher3.taskbar.bubbles.BubbleBarController.BubbleBarLocationListener
import com.android.quickstep.SystemUiProxy
import com.android.wm.shell.shared.bubbles.BubbleBarLocation
import com.android.wm.shell.shared.bubbles.DeviceConfig
@@ -44,7 +45,9 @@ import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.kotlin.any
import org.mockito.kotlin.clearInvocations
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.inOrder
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
import org.mockito.kotlin.stub
@@ -61,6 +64,7 @@ class DragToBubbleControllerTest {
private val container = FrameLayout(context)
private val bubbleBarViewController: BubbleBarViewController = mock()
private val systemUiProxy: SystemUiProxy = mock()
private val bubbleBarLocationListener: BubbleBarLocationListener = mock()
private val bubbleBarPropertiesProvider = FakeBubbleBarPropertiesProvider()
private val testDragZonesFactory = createTestDragZoneFactory()
private val dragObject = DragObject(context)
@@ -86,10 +90,12 @@ class DragToBubbleControllerTest {
@Before
fun setUp() {
prepareBubbleBarViewController()
dragToBubbleController = DragToBubbleController(context, container)
dragToBubbleController.init(
bubbleBarViewController,
bubbleBarPropertiesProvider,
bubbleBarLocationListener,
systemUiProxy,
)
dragToBubbleController.dragZoneFactory = testDragZonesFactory
@@ -104,6 +110,7 @@ class DragToBubbleControllerTest {
assertThat(secondDropTargetView!!.parent).isEqualTo(container)
assertThat(dropTargetView.alpha).isEqualTo(0f)
assertThat(secondDropTargetView!!.alpha).isEqualTo(0f)
assertThat(dragToBubbleController.isItemDropHandled).isFalse()
}
@Test
@@ -235,13 +242,168 @@ class DragToBubbleControllerTest {
InstrumentationRegistry.getInstrumentation().runOnMainSync {
dragObject.updateXYToCenterOf(leftDropTargetRect)
bubbleBarLeftDropTarget.onDragEnter(dragObject)
bubbleBarLeftDropTarget.onDragExit(dragObject)
bubbleBarLeftDropTarget.onDrop(dragObject, DragOptions())
assertThat(dragToBubbleController.isItemDropHandled).isTrue()
bubbleBarLeftDropTarget.onDragExit(dragObject)
}
verify(systemUiProxy).showAppBubble(itemIntent, appInfo.user, BubbleBarLocation.LEFT)
}
@Test
fun dragExitRightZone_noBubbles_listenerNotNotified() {
// Scenario: No bubbles. Drag enters RIGHT, then exits to no particular zone.
// This is distinct as it starts on the default side.
prepareBubbleBarViewController(
hasBubbles = false,
bubbleBarLocation = BubbleBarLocation.RIGHT,
)
dragToBubbleController.onDragStart(dragObject, DragOptions())
InstrumentationRegistry.getInstrumentation().runOnMainSync {
dragObject.updateXYToCenterOf(rightDropTargetRect)
bubbleBarRightDropTarget.onDragEnter(dragObject) // Location is the same
}
verify(bubbleBarLocationListener, never())
.onBubbleBarLocationAnimated(BubbleBarLocation.RIGHT)
InstrumentationRegistry.getInstrumentation().runOnMainSync {
dragObject.updateXY(0, 0) // Move out of all zones
bubbleBarRightDropTarget.onDragExit(dragObject)
}
// Exiting the RIGHT zone (which is the default) should not re-notify of RIGHT
verify(bubbleBarLocationListener, never())
.onBubbleBarLocationAnimated(BubbleBarLocation.RIGHT)
}
@Test
fun onDragEnd_noBubbles_wasDraggingLeft_listenerNotifiedWithDefaultRightLocationAnimated() {
val startingLocation = BubbleBarLocation.RIGHT
// Scenario: No bubbles. Drag was over LEFT zone. Drag ends.
prepareBubbleBarViewController(hasBubbles = false, bubbleBarLocation = startingLocation)
dragToBubbleController.onDragStart(dragObject, DragOptions())
InstrumentationRegistry.getInstrumentation().runOnMainSync {
dragObject.updateXYToCenterOf(leftDropTargetRect)
bubbleBarLeftDropTarget.onDragEnter(dragObject)
}
// Notifies onBubbleBarLocationAnimated(LEFT)
verify(bubbleBarLocationListener).onBubbleBarLocationAnimated(BubbleBarLocation.LEFT)
clearInvocations(bubbleBarLocationListener)
InstrumentationRegistry.getInstrumentation().runOnMainSync {
dragToBubbleController.onDragEnd()
}
assertThat(dragToBubbleController.isItemDropHandled).isFalse()
// After drag ends (and no bubbles), the listener should be notified of the default location
verify(bubbleBarLocationListener).onBubbleBarLocationAnimated(startingLocation)
}
@Test
fun onDragEnd_noBubbles_wasDraggingRight_listenerNotifiedWithDefaultRightLocationAnimated() {
// Scenario: No bubbles. Drag was over RIGHT zone (default side). Drag ends.
prepareBubbleBarViewController(hasBubbles = false)
dragToBubbleController.onDragStart(dragObject, DragOptions())
InstrumentationRegistry.getInstrumentation().runOnMainSync {
dragObject.updateXYToCenterOf(rightDropTargetRect)
}
verify(bubbleBarLocationListener, never())
.onBubbleBarLocationAnimated(BubbleBarLocation.RIGHT)
clearInvocations(bubbleBarLocationListener)
InstrumentationRegistry.getInstrumentation().runOnMainSync {
dragObject.updateXY(0, 0)
bubbleBarLeftDropTarget.onDragExit(dragObject)
dragToBubbleController.onDragEnd()
}
// After drag ends (and no bubbles), listener should not be notified of the default
// location.
verify(bubbleBarLocationListener, never())
.onBubbleBarLocationAnimated(BubbleBarLocation.RIGHT)
}
@Test
fun dragEnterLeftZone_bubblesOnLeft_listenerNotNotified() {
// Scenario: Bubbles on LEFT. Drag enters LEFT zone.
prepareBubbleBarViewController(
hasBubbles = true,
bubbleBarLocation = BubbleBarLocation.LEFT,
)
dragToBubbleController.onDragStart(dragObject, DragOptions())
InstrumentationRegistry.getInstrumentation().runOnMainSync {
dragObject.updateXYToCenterOf(leftDropTargetRect)
bubbleBarLeftDropTarget.onDragEnter(dragObject)
}
// Bubbles are already on the LEFT, and drag enters LEFT.
// No new animation to LEFT should be triggered by the zone entry itself.
verify(bubbleBarLocationListener, never())
.onBubbleBarLocationAnimated(BubbleBarLocation.LEFT)
}
@Test
fun onDragEnd_bubblesOnLeft_defaultIsLeft_wasDraggingRight_listenerNotifiedLeftAnimated() {
// Scenario: Bubbles on LEFT. Drag was over RIGHT zone. Drag ends.
prepareBubbleBarViewController(
hasBubbles = true,
bubbleBarLocation = BubbleBarLocation.LEFT,
)
dragToBubbleController.onDragStart(dragObject, DragOptions())
InstrumentationRegistry.getInstrumentation().runOnMainSync {
dragObject.updateXYToCenterOf(rightDropTargetRect)
bubbleBarRightDropTarget.onDragEnter(dragObject) // Notifies Animated(RIGHT)
}
verify(bubbleBarLocationListener).onBubbleBarLocationAnimated(BubbleBarLocation.RIGHT)
clearInvocations(bubbleBarLocationListener) // Clear the Animated(RIGHT)
InstrumentationRegistry.getInstrumentation().runOnMainSync {
dragObject.updateXY(0, 0)
bubbleBarLeftDropTarget.onDragExit(dragObject)
dragToBubbleController.onDragEnd()
}
// Bubble bar's final animated location should be LEFT.
verify(bubbleBarLocationListener).onBubbleBarLocationAnimated(BubbleBarLocation.LEFT)
}
@Test
fun dragEnterLeftThenExitToNoZoneThenEnterRight_noBubbles_listenerSequenceCorrectAnimated() {
// Scenario: No bubbles. Complex drag path: Left -> None -> Right
prepareBubbleBarViewController(hasBubbles = false)
dragToBubbleController.onDragStart(dragObject, DragOptions())
clearInvocations(bubbleBarLocationListener)
val inOrder = inOrder(bubbleBarLocationListener)
InstrumentationRegistry.getInstrumentation().runOnMainSync {
// 1. Enter Left
dragObject.updateXYToCenterOf(leftDropTargetRect)
bubbleBarLeftDropTarget.onDragEnter(dragObject)
// 2. Exit Left to no zone
dragObject.updateXY(0, 0)
bubbleBarLeftDropTarget.onDragExit(dragObject)
// 3. Enter Right
dragObject.updateXYToCenterOf(rightDropTargetRect)
bubbleBarRightDropTarget.onDragEnter(dragObject)
}
inOrder
.verify(bubbleBarLocationListener)
.onBubbleBarLocationAnimated(BubbleBarLocation.LEFT)
// Revert to default, following enter of the same zone should not trigger updated
inOrder
.verify(bubbleBarLocationListener)
.onBubbleBarLocationAnimated(BubbleBarLocation.RIGHT)
}
private fun prepareBubbleBarViewController(
hasBubbles: Boolean = false,
bubbleBarLocation: BubbleBarLocation = BubbleBarLocation.RIGHT,
@@ -49,7 +49,7 @@ class TaskbarModeRuleTest {
@TaskbarMode(TRANSIENT)
fun testTaskbarMode_transient_overridesDeviceProfile() {
val dp = InvariantDeviceProfile.INSTANCE.get(context).getDeviceProfile(context)
assertThat(dp.isTransientTaskbar).isTrue()
assertThat(dp.taskbarProfile.isTransientTaskbar).isTrue()
assertThat(dp.deviceProperties.isGestureMode).isTrue()
}
@@ -65,7 +65,7 @@ class TaskbarModeRuleTest {
@TaskbarMode(PINNED)
fun testTaskbarMode_pinned_overridesDeviceProfile() {
val dp = InvariantDeviceProfile.INSTANCE.get(context).getDeviceProfile(context)
assertThat(dp.isTransientTaskbar).isFalse()
assertThat(dp.taskbarProfile.isTransientTaskbar).isFalse()
assertThat(dp.deviceProperties.isGestureMode).isTrue()
}
@@ -82,7 +82,7 @@ class TaskbarModeRuleTest {
@TaskbarMode(THREE_BUTTONS)
fun testTaskbarMode_threeButtons_overridesDeviceProfile() {
val dp = InvariantDeviceProfile.INSTANCE.get(context).getDeviceProfile(context)
assertThat(dp.isTransientTaskbar).isFalse()
assertThat(dp.taskbarProfile.isTransientTaskbar).isFalse()
assertThat(dp.deviceProperties.isGestureMode).isFalse()
}
}
@@ -22,6 +22,7 @@ import com.android.launcher3.Flags
import com.android.launcher3.LauncherPrefChangeListener
import com.android.launcher3.LauncherPrefs
import com.android.launcher3.LauncherPrefs.Companion.TASKBAR_PINNING
import com.android.launcher3.compose.core.widgetpicker.NoOpWidgetPickerModule
import com.android.launcher3.concurrent.ExecutorsModule
import com.android.launcher3.dagger.ApiWrapperModule
import com.android.launcher3.dagger.AppModule
@@ -86,6 +87,7 @@ interface TaskbarSandboxComponent : LauncherAppComponent {
TaskbarSandboxWmProxyModule::class,
TaskbarPerDisplayReposModule::class,
DesktopVisibilityControllerModule::class,
NoOpWidgetPickerModule::class,
]
)
interface AllTaskbarSandboxModules
@@ -21,7 +21,7 @@ import com.android.quickstep.TaskIconCache.TaskCacheEntry
import com.android.quickstep.task.thumbnail.data.TaskIconDataSource
import com.android.systemui.shared.recents.model.Task
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.yield
import kotlinx.coroutines.delay
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
@@ -34,7 +34,8 @@ class FakeTaskIconDataSource : TaskIconDataSource {
/** Retrieves and sets an icon on [task] from [taskIdToDrawable]. */
override suspend fun getIcon(task: Task): TaskCacheEntry {
while (task.key.id in completionPrevented) {
yield()
// yield doesn't work here with an UnconfinedTestDispatcher
delay(1L)
}
return TaskCacheEntry(
taskIdToDrawable.getValue(task.key.id),
@@ -20,7 +20,7 @@ import android.graphics.Bitmap
import com.android.quickstep.task.thumbnail.data.TaskThumbnailDataSource
import com.android.systemui.shared.recents.model.Task
import com.android.systemui.shared.recents.model.ThumbnailData
import kotlinx.coroutines.yield
import kotlinx.coroutines.delay
import org.mockito.kotlin.mock
class FakeTaskThumbnailDataSource : TaskThumbnailDataSource {
@@ -37,7 +37,8 @@ class FakeTaskThumbnailDataSource : TaskThumbnailDataSource {
getThumbnailCalls[task.key.id] = (getThumbnailCalls[task.key.id] ?: 0) + 1
while (task.key.id in completionPrevented) {
yield()
// yield doesn't work here with an UnconfinedTestDispatcher
delay(1L)
}
return ThumbnailData(
thumbnail = taskIdToBitmap[task.key.id],
@@ -54,4 +55,8 @@ class FakeTaskThumbnailDataSource : TaskThumbnailDataSource {
fun completeLoadingForTask(taskId: Int) {
completionPrevented.remove(taskId)
}
fun completeLoading() {
completionPrevented.clear()
}
}
@@ -17,24 +17,30 @@
package com.android.quickstep.recents.data
import android.graphics.drawable.Drawable
import androidx.core.util.forEach
import androidx.core.util.putAll
import com.android.systemui.shared.recents.model.Task
import com.android.systemui.shared.recents.model.ThumbnailData
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
class FakeTasksRepository : RecentTasksRepository {
private var thumbnailDataMap: Map<Int, ThumbnailData> = emptyMap()
private var taskIconDataMap: Map<Int, FakeIconData> = emptyMap()
private var tasks: MutableStateFlow<List<Task>> = MutableStateFlow(emptyList())
private var visibleTasks: MutableStateFlow<Set<Int>> = MutableStateFlow(emptySet())
private var visibleTasks: MutableStateFlow<Map<Int, Set<Int>>> = MutableStateFlow(mapOf())
override fun getAllTaskData(forceRefresh: Boolean): Flow<List<Task>> = tasks
override fun getAllTaskData(displayId: Int, forceRefresh: Boolean): Flow<List<Task>> =
tasks.map { it.filter { it.key.displayId == displayId }.toList() }
override fun getTaskDataById(taskId: Int): Flow<Task?> =
combine(getAllTaskData(), visibleTasks) { taskList, visibleTasks ->
taskList.filter { visibleTasks.contains(it.key.id) }
combine(tasks, visibleTasks) { taskList, visibleTasks ->
val allVisibleTasks = mutableSetOf<Int>()
visibleTasks.forEach { _, value -> allVisibleTasks.addAll(value) }
taskList.filter { allVisibleTasks.contains(it.key.id) }
}
.map { taskList ->
val task = taskList.firstOrNull { it.key.id == taskId } ?: return@map null
@@ -52,8 +58,13 @@ class FakeTasksRepository : RecentTasksRepository {
override fun getCurrentThumbnailById(taskId: Int): ThumbnailData? =
tasks.value.firstOrNull { it.key.id == taskId }?.thumbnail
override fun setVisibleTasks(visibleTaskIdList: Set<Int>) {
visibleTasks.value = visibleTaskIdList
override fun setVisibleTasks(displayId: Int, visibleTaskIdList: Set<Int>) {
visibleTasks.update {
val newVisibleTasks = mutableMapOf<Int, Set<Int>>()
newVisibleTasks.putAll(it)
newVisibleTasks[displayId] = visibleTaskIdList
newVisibleTasks
}
tasks.value =
tasks.value.map {
it.apply {
@@ -39,7 +39,9 @@ import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.spy
@@ -51,6 +53,7 @@ import org.mockito.kotlin.whenever
@RunWith(AndroidJUnit4::class)
class TasksRepositoryTest {
private val tasks = (0..5).map(::createTaskWithId)
private val secondaryTasks = (6..11).map(::createTaskWithIdForSecondaryDisplay)
private val defaultTaskList =
listOf(
SingleTask(tasks[0]),
@@ -67,6 +70,22 @@ class TasksRepositoryTest {
),
DesktopTask(deskId = 0, DEFAULT_DISPLAY, tasks.subList(3, 6)),
)
private val secondaryTaskList =
listOf(
SingleTask(secondaryTasks[0]),
SplitTask(
secondaryTasks[1],
secondaryTasks[2],
SplitBounds(
/* leftTopBounds = */ Rect(),
/* rightBottomBounds = */ Rect(),
/* leftTopTaskId = */ 7,
/* rightBottomTaskId = */ 8,
/* snapPosition = */ SNAP_TO_2_50_50,
),
),
DesktopTask(deskId = 1, SECONDARY_DISPLAY, secondaryTasks.subList(3, 6)),
)
private val recentsModel = FakeRecentTasksDataSource()
private val taskThumbnailDataSource = FakeTaskThumbnailDataSource()
private val taskIconDataSource = FakeTaskIconDataSource()
@@ -87,18 +106,25 @@ class TasksRepositoryTest {
TestDispatcherProvider(dispatcher),
)
@Before
fun cleanupDataSources() {
taskThumbnailDataSource.completeLoading()
taskIconDataSource.completeLoading()
}
@Test
fun getAllTaskDataReturnsFlattenedListOfTasks() =
testScope.runTest {
recentsModel.seedTasks(defaultTaskList)
assertThat(systemUnderTest.getAllTaskData(forceRefresh = true).first()).isEqualTo(tasks)
assertThat(systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true).first())
.isEqualTo(tasks)
}
@Test
fun getTaskDataByIdReturnsSpecificTask() =
testScope.runTest {
recentsModel.seedTasks(defaultTaskList)
systemUnderTest.getAllTaskData(forceRefresh = true)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
assertThat(systemUnderTest.getTaskDataById(2).first()).isEqualTo(tasks[2])
}
@@ -107,7 +133,7 @@ class TasksRepositoryTest {
fun getThumbnailByIdReturnsNullWithNoLoadedThumbnails() =
testScope.runTest {
recentsModel.seedTasks(defaultTaskList)
systemUnderTest.getAllTaskData(forceRefresh = true)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
assertThat(systemUnderTest.getThumbnailById(1).first()).isNull()
}
@@ -116,7 +142,7 @@ class TasksRepositoryTest {
fun getCurrentThumbnailByIdReturnsNullWithNoLoadedThumbnails() =
testScope.runTest {
recentsModel.seedTasks(defaultTaskList)
systemUnderTest.getAllTaskData(forceRefresh = true)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
assertThat(systemUnderTest.getCurrentThumbnailById(1)).isNull()
}
@@ -125,10 +151,10 @@ class TasksRepositoryTest {
fun getThumbnailByIdReturnsThumbnailWithLoadedThumbnails() =
testScope.runTest {
recentsModel.seedTasks(defaultTaskList)
systemUnderTest.getAllTaskData(forceRefresh = true)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
val bitmap1 = taskThumbnailDataSource.taskIdToBitmap[1]
systemUnderTest.setVisibleTasks(setOf(1))
systemUnderTest.setVisibleTasks(DEFAULT_DISPLAY, setOf(1))
assertThat(systemUnderTest.getThumbnailById(1).first()!!.thumbnail).isEqualTo(bitmap1)
}
@@ -137,13 +163,13 @@ class TasksRepositoryTest {
fun whenThumbnailIsLoaded_getAllTaskData_usesPreviousLoadedThumbnailAndIcon() =
testScope.runTest {
recentsModel.seedTasks(defaultTaskList)
systemUnderTest.getAllTaskData(forceRefresh = true)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
val bitmap1 = taskThumbnailDataSource.taskIdToBitmap[1]
systemUnderTest.setVisibleTasks(setOf(1))
systemUnderTest.setVisibleTasks(DEFAULT_DISPLAY, setOf(1))
assertThat(systemUnderTest.getThumbnailById(1).first()!!.thumbnail).isEqualTo(bitmap1)
systemUnderTest.getAllTaskData(forceRefresh = true)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
assertThat(systemUnderTest.getThumbnailById(1).first()!!.thumbnail).isEqualTo(bitmap1)
}
@@ -151,8 +177,8 @@ class TasksRepositoryTest {
fun getAllTaskData_copiesPreviouslyLoadedImagesForTasksStillPresent() =
testScope.runTest {
recentsModel.seedTasks(defaultTaskList)
systemUnderTest.getAllTaskData(forceRefresh = true)
systemUnderTest.setVisibleTasks(setOf(0, 1))
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
systemUnderTest.setVisibleTasks(DEFAULT_DISPLAY, setOf(0, 1))
// Seed new task with same id
val newTask0 = SingleTask(createTaskWithId(0))
@@ -161,7 +187,7 @@ class TasksRepositoryTest {
if (it is SingleTask && it.task.key.id == 0) newTask0 else it
}
recentsModel.seedTasks(newSeededTasks)
systemUnderTest.getAllTaskData(forceRefresh = true)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
// Assert no additional loads, assert images present
assertThat(systemUnderTest.getThumbnailById(0).first()?.thumbnail)
@@ -174,18 +200,18 @@ class TasksRepositoryTest {
testScope.runTest {
// Setup data
recentsModel.seedTasks(defaultTaskList)
systemUnderTest.getAllTaskData(forceRefresh = true)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
val bitmap1 = taskThumbnailDataSource.taskIdToBitmap[1]
// Load images for task 1
systemUnderTest.setVisibleTasks(setOf(1))
systemUnderTest.setVisibleTasks(DEFAULT_DISPLAY, setOf(1))
assertThat(systemUnderTest.getThumbnailById(1).first()!!.thumbnail).isEqualTo(bitmap1)
// Remove task 1 from "all data"
recentsModel.seedTasks(
defaultTaskList.filterNot { groupTask -> groupTask.tasks.any { it.key.id == 1 } }
)
systemUnderTest.getAllTaskData(forceRefresh = true)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
// Assert task 1 was fully removed
assertThat(systemUnderTest.getThumbnailById(1).first()?.thumbnail).isNull()
@@ -196,10 +222,10 @@ class TasksRepositoryTest {
fun getCurrentThumbnailByIdReturnsThumbnailWithLoadedThumbnails() =
testScope.runTest {
recentsModel.seedTasks(defaultTaskList)
systemUnderTest.getAllTaskData(forceRefresh = true)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
val bitmap1 = taskThumbnailDataSource.taskIdToBitmap[1]
systemUnderTest.setVisibleTasks(setOf(1))
systemUnderTest.setVisibleTasks(DEFAULT_DISPLAY, setOf(1))
assertThat(systemUnderTest.getCurrentThumbnailById(1)?.thumbnail).isEqualTo(bitmap1)
}
@@ -210,9 +236,9 @@ class TasksRepositoryTest {
recentsModel.seedTasks(defaultTaskList)
val bitmap1 = taskThumbnailDataSource.taskIdToBitmap[1]
val bitmap2 = taskThumbnailDataSource.taskIdToBitmap[2]
systemUnderTest.getAllTaskData(forceRefresh = true)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
systemUnderTest.setVisibleTasks(setOf(1, 2))
systemUnderTest.setVisibleTasks(DEFAULT_DISPLAY, setOf(1, 2))
assertThat(systemUnderTest.getTaskDataById(1).first()!!.thumbnail!!.thumbnail)
.isEqualTo(bitmap1)
@@ -224,9 +250,9 @@ class TasksRepositoryTest {
fun setVisibleTasksPopulatesIcons() =
testScope.runTest {
recentsModel.seedTasks(defaultTaskList)
systemUnderTest.getAllTaskData(forceRefresh = true)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
systemUnderTest.setVisibleTasks(setOf(1, 2))
systemUnderTest.setVisibleTasks(DEFAULT_DISPLAY, setOf(1, 2))
systemUnderTest
.getTaskDataById(1)
@@ -243,16 +269,16 @@ class TasksRepositoryTest {
testScope.runTest {
recentsModel.seedTasks(defaultTaskList)
val bitmap2 = taskThumbnailDataSource.taskIdToBitmap[2]
systemUnderTest.getAllTaskData(forceRefresh = true)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
systemUnderTest.setVisibleTasks(setOf(1, 2))
systemUnderTest.setVisibleTasks(DEFAULT_DISPLAY, setOf(1, 2))
assertThat(systemUnderTest.getTaskDataById(2).first()!!.thumbnail!!.thumbnail)
.isEqualTo(bitmap2)
// Prevent new loading of Bitmaps
taskThumbnailDataSource.preventThumbnailLoad(2)
systemUnderTest.setVisibleTasks(setOf(2, 3))
systemUnderTest.setVisibleTasks(DEFAULT_DISPLAY, setOf(2, 3))
assertThat(systemUnderTest.getTaskDataById(2).first()!!.thumbnail!!.thumbnail)
.isEqualTo(bitmap2)
@@ -262,9 +288,9 @@ class TasksRepositoryTest {
fun changingVisibleTasksContainsAlreadyPopulatedIcons() =
testScope.runTest {
recentsModel.seedTasks(defaultTaskList)
systemUnderTest.getAllTaskData(forceRefresh = true)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
systemUnderTest.setVisibleTasks(setOf(1, 2))
systemUnderTest.setVisibleTasks(DEFAULT_DISPLAY, setOf(1, 2))
systemUnderTest
.getTaskDataById(2)
@@ -273,7 +299,7 @@ class TasksRepositoryTest {
// Prevent new loading of Drawables
taskIconDataSource.preventIconLoad(2)
systemUnderTest.setVisibleTasks(setOf(2, 3))
systemUnderTest.setVisibleTasks(DEFAULT_DISPLAY, setOf(2, 3))
systemUnderTest
.getTaskDataById(2)
@@ -286,15 +312,15 @@ class TasksRepositoryTest {
testScope.runTest {
recentsModel.seedTasks(defaultTaskList)
val bitmap2 = taskThumbnailDataSource.taskIdToBitmap[2]
systemUnderTest.getAllTaskData(forceRefresh = true)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
systemUnderTest.setVisibleTasks(setOf(1, 2))
systemUnderTest.setVisibleTasks(DEFAULT_DISPLAY, setOf(1, 2))
val task2 = systemUnderTest.getTaskDataById(2).first()!!
assertThat(task2.thumbnail!!.thumbnail).isEqualTo(bitmap2)
task2.assertHasIconDataFromSource(taskIconDataSource)
systemUnderTest.setVisibleTasks(setOf(0, 1))
systemUnderTest.setVisibleTasks(DEFAULT_DISPLAY, setOf(0, 1))
val task2AfterVisibleTasksChanged = systemUnderTest.getTaskDataById(2).first()!!
assertThat(task2AfterVisibleTasksChanged.thumbnail).isNull()
@@ -311,7 +337,7 @@ class TasksRepositoryTest {
val bitmap2 = taskThumbnailDataSource.taskIdToBitmap[2]
// Setup TasksRepository
systemUnderTest.getAllTaskData(forceRefresh = true)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
val task2DataFlow = systemUnderTest.getTaskDataById(2)
val task2BitmapValues = mutableListOf<Bitmap?>()
@@ -322,7 +348,7 @@ class TasksRepositoryTest {
// Check for first emission
assertThat(task2BitmapValues.single()).isNull()
systemUnderTest.setVisibleTasks(setOf(2))
systemUnderTest.setVisibleTasks(DEFAULT_DISPLAY, setOf(2))
// Check for second emission
assertThat(task2BitmapValues).isEqualTo(listOf(null, bitmap2))
}
@@ -331,8 +357,8 @@ class TasksRepositoryTest {
fun onTaskThumbnailChanged_setsNewThumbnailDataOnTask() =
testScope.runTest {
recentsModel.seedTasks(defaultTaskList)
systemUnderTest.getAllTaskData(forceRefresh = true)
systemUnderTest.setVisibleTasks(setOf(1))
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
systemUnderTest.setVisibleTasks(DEFAULT_DISPLAY, setOf(1))
val expectedThumbnailData = createThumbnailData()
val expectedPreviousBitmap = taskThumbnailDataSource.taskIdToBitmap[1]
@@ -353,9 +379,9 @@ class TasksRepositoryTest {
testScope.runTest {
taskThumbnailDataSource.highResEnabled = false
recentsModel.seedTasks(defaultTaskList)
systemUnderTest.getAllTaskData(forceRefresh = true)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
systemUnderTest.setVisibleTasks(setOf(1))
systemUnderTest.setVisibleTasks(DEFAULT_DISPLAY, setOf(1))
val expectedBitmap = mock<Bitmap>()
val expectedPreviousBitmap = taskThumbnailDataSource.taskIdToBitmap[1]
@@ -384,9 +410,9 @@ class TasksRepositoryTest {
testScope.runTest {
taskThumbnailDataSource.highResEnabled = false
recentsModel.seedTasks(defaultTaskList)
systemUnderTest.getAllTaskData(forceRefresh = true)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
systemUnderTest.setVisibleTasks(setOf(1))
systemUnderTest.setVisibleTasks(DEFAULT_DISPLAY, setOf(1))
val invisibleTaskId = 2
val taskDataFlow = systemUnderTest.getTaskDataById(invisibleTaskId)
@@ -408,9 +434,9 @@ class TasksRepositoryTest {
testScope.runTest {
taskThumbnailDataSource.highResEnabled = true
recentsModel.seedTasks(defaultTaskList)
systemUnderTest.getAllTaskData(forceRefresh = true)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
systemUnderTest.setVisibleTasks(setOf(1))
systemUnderTest.setVisibleTasks(DEFAULT_DISPLAY, setOf(1))
val expectedBitmap = mock<Bitmap>()
val expectedPreviousBitmap = taskThumbnailDataSource.taskIdToBitmap[1]
@@ -438,9 +464,9 @@ class TasksRepositoryTest {
fun onTaskIconChanged_setsNewIconOnTask() =
testScope.runTest {
recentsModel.seedTasks(defaultTaskList)
systemUnderTest.getAllTaskData(forceRefresh = true)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
systemUnderTest.setVisibleTasks(setOf(1))
systemUnderTest.setVisibleTasks(DEFAULT_DISPLAY, setOf(1))
val expectedIcon = FakeTaskIconDataSource.mockCopyableDrawable()
val expectedPreviousIcon = taskIconDataSource.taskIdToDrawable[1]
@@ -461,7 +487,7 @@ class TasksRepositoryTest {
fun setVisibleTasks_multipleTimesWithDifferentTasks_reusesThumbnailRequests() =
testScope.runTest {
recentsModel.seedTasks(defaultTaskList)
systemUnderTest.getAllTaskData(forceRefresh = true)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
val taskDataFlow = systemUnderTest.getTaskDataById(1)
val task1IconValues = mutableListOf<Drawable?>()
@@ -469,16 +495,115 @@ class TasksRepositoryTest {
taskDataFlow.map { it?.icon }.toList(task1IconValues)
}
systemUnderTest.setVisibleTasks(setOf(1))
systemUnderTest.setVisibleTasks(DEFAULT_DISPLAY, setOf(1))
assertThat(taskThumbnailDataSource.getNumberOfGetThumbnailCalls(1)).isEqualTo(1)
systemUnderTest.setVisibleTasks(setOf(1, 2))
systemUnderTest.setVisibleTasks(DEFAULT_DISPLAY, setOf(1, 2))
assertThat(taskThumbnailDataSource.getNumberOfGetThumbnailCalls(1)).isEqualTo(1)
}
@Test
fun getTaskData_forSecondaryDisplay() =
testScope.runTest {
recentsModel.seedTasks(defaultTaskList + secondaryTaskList)
assertThat(systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true).first())
.isEqualTo(tasks)
assertThat(
systemUnderTest.getAllTaskData(SECONDARY_DISPLAY, forceRefresh = true).first()
)
.isEqualTo(secondaryTasks)
}
@Test
fun setVisibleTasks_secondaryDisplayConnected() =
testScope.runTest {
recentsModel.seedTasks(defaultTaskList + secondaryTaskList)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
systemUnderTest.getAllTaskData(SECONDARY_DISPLAY, forceRefresh = true)
val bitmap1 = taskThumbnailDataSource.taskIdToBitmap[1]
val bitmap6 = taskThumbnailDataSource.taskIdToBitmap[6]
systemUnderTest.setVisibleTasks(DEFAULT_DISPLAY, setOf(1))
systemUnderTest.setVisibleTasks(SECONDARY_DISPLAY, setOf(6))
val actualThumbnails =
(0..11).map { systemUnderTest.getThumbnailById(it).first()?.thumbnail }.toList()
val expectedThumbnails =
arrayOfNulls<Bitmap>(12)
.apply {
set(1, bitmap1)
set(6, bitmap6)
}
.toList()
assertThat(actualThumbnails).isEqualTo(expectedThumbnails)
}
@Test
fun setVisibleTasks_displayDisconnectedBeforeImageReturns_doesNotPopulateThumbnailOrIcon() =
testScope.runTest {
recentsModel.seedTasks(defaultTaskList + secondaryTaskList)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
systemUnderTest.getAllTaskData(SECONDARY_DISPLAY, forceRefresh = true)
taskThumbnailDataSource.preventThumbnailLoad(6)
taskIconDataSource.preventIconLoad(6)
val task6DataFlow = systemUnderTest.getTaskDataById(6)
val task6Values = mutableListOf<Pair<Bitmap?, Drawable?>>()
testScope.backgroundScope.launch {
task6DataFlow.map { Pair(it?.thumbnail?.thumbnail, it?.icon) }.toList(task6Values)
}
launch { systemUnderTest.setVisibleTasks(SECONDARY_DISPLAY, setOf(6)) }
// Check we prevented the resources from loading
assertThat(task6Values.distinct()).isEqualTo(listOf(Pair(null, null)))
// Display disconnects
launch { systemUnderTest.setVisibleTasks(SECONDARY_DISPLAY, emptySet()) }
taskThumbnailDataSource.completeLoadingForTask(6)
taskIconDataSource.completeLoadingForTask(6)
testScope.advanceUntilIdle()
// Still should not be loaded
assertThat(task6Values.distinct()).isEqualTo(listOf(Pair(null, null)))
}
@Test
fun onDisplayRemoved_removesAllDataForDisplay() =
testScope.runTest {
recentsModel.seedTasks(defaultTaskList + secondaryTaskList)
systemUnderTest.getAllTaskData(DEFAULT_DISPLAY, forceRefresh = true)
systemUnderTest.getAllTaskData(SECONDARY_DISPLAY, forceRefresh = true)
systemUnderTest.setVisibleTasks(DEFAULT_DISPLAY, setOf(1))
systemUnderTest.setVisibleTasks(SECONDARY_DISPLAY, setOf(6))
recentsModel.seedTasks(defaultTaskList)
systemUnderTest.setVisibleTasks(SECONDARY_DISPLAY, emptySet())
for (t in 6..11) {
assertThat(systemUnderTest.getThumbnailById(t).first()?.thumbnail).isNull()
assertThat(systemUnderTest.getTaskDataById(t).first()?.icon).isNull()
}
}
private fun createTaskWithId(taskId: Int) =
Task(Task.TaskKey(taskId, 0, Intent(), ComponentName("", ""), 0, 2000))
private fun createTaskWithIdForSecondaryDisplay(taskId: Int) =
Task(
Task.TaskKey(
taskId,
0,
Intent(),
ComponentName("", ""),
0,
2000,
SECONDARY_DISPLAY,
null,
0,
false,
false,
)
)
private fun createThumbnailData(): ThumbnailData {
val bitmap = mock<Bitmap>()
whenever(bitmap.width).thenReturn(THUMBNAIL_WIDTH)
@@ -490,5 +615,6 @@ class TasksRepositoryTest {
companion object {
const val THUMBNAIL_WIDTH = 100
const val THUMBNAIL_HEIGHT = 200
const val SECONDARY_DISPLAY = 1
}
}
@@ -24,6 +24,7 @@ import android.os.UserHandle
import android.platform.test.annotations.DisableFlags
import android.platform.test.annotations.EnableFlags
import android.platform.test.flag.junit.SetFlagsRule
import android.view.Display.DEFAULT_DISPLAY
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.android.launcher3.Flags
import com.android.quickstep.recents.data.FakeAppTimersRepository
@@ -95,7 +96,7 @@ class GetTaskUseCaseTest {
@EnableFlags(Flags.FLAG_ENABLE_REFACTOR_DIGITAL_WELLBEING_TOAST)
fun taskVisible_returnsData() =
testScope.runTest {
tasksRepository.setVisibleTasks(setOf(TASK_1_ID))
tasksRepository.setVisibleTasks(DEFAULT_DISPLAY, setOf(TASK_1_ID))
val result = sut.invoke(TASK_1_ID).firstOrNull()
@@ -120,7 +121,7 @@ class GetTaskUseCaseTest {
@EnableFlags(Flags.FLAG_ENABLE_REFACTOR_DIGITAL_WELLBEING_TOAST)
fun taskVisible_noAppTimer_returnsDataWithoutTimer() =
testScope.runTest {
tasksRepository.setVisibleTasks(setOf(TASK_1_ID))
tasksRepository.setVisibleTasks(DEFAULT_DISPLAY, setOf(TASK_1_ID))
timersRepository.resetTimer(PACKAGE_1, UserHandle(USER_1))
val result = sut.invoke(TASK_1_ID).firstOrNull()
@@ -148,7 +149,7 @@ class GetTaskUseCaseTest {
@DisableFlags(Flags.FLAG_ENABLE_REFACTOR_DIGITAL_WELLBEING_TOAST)
fun taskVisible_dwbFlagOff_doesNotFetchTimer() =
testScope.runTest {
tasksRepository.setVisibleTasks(setOf(TASK_1_ID))
tasksRepository.setVisibleTasks(DEFAULT_DISPLAY, setOf(TASK_1_ID))
val result = sut.invoke(TASK_1_ID).firstOrNull()
@@ -20,6 +20,7 @@ import android.content.ComponentName
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.view.Display.DEFAULT_DISPLAY
import android.view.Surface
import com.android.quickstep.recents.data.FakeTasksRepository
import com.android.systemui.shared.recents.model.Task
@@ -34,7 +35,8 @@ import org.mockito.kotlin.whenever
class RecentsViewModelTest {
private val tasksRepository = FakeTasksRepository()
private val recentsViewData = RecentsViewData()
private val systemUnderTest = RecentsViewModel(tasksRepository, recentsViewData)
private val systemUnderTest =
RecentsViewModel(tasksRepository, recentsViewData, DEFAULT_DISPLAY)
private val tasks = (0..5).map(::createTaskWithId)
@@ -97,7 +99,7 @@ class RecentsViewModelTest {
)
// setVisibleTasks forces FakeTasksRepository to update the flows returned by
// getThumbnailById
tasksRepository.setVisibleTasks(setOf(1, 2))
tasksRepository.setVisibleTasks(DEFAULT_DISPLAY, setOf(1, 2))
// Then wait for thumbnailData should complete, and the previous getThumbnailById flow
// should return updated values
@@ -786,6 +786,17 @@ class TaskGridNavHelperTest {
.isEqualTo(ADD_DESK_PLACEHOLDER_ID)
}
/*
5 3 1 |
CLEAR_ALL | Invalid ID:
6 4 2 | [25] --> [25]
*/
@Test
fun nextGridPage_invalidId_pressTab_noCycle_returnsCurrentPage() {
assertThat(getNextGridPage(currentPageTaskViewId = 25, TAB, delta = -1, cycle = false))
.isEqualTo(25)
}
// Col offset: 0 1 2
// -----------
// ID grid: 4 2 0 start
@@ -0,0 +1,18 @@
<?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.
-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:alpha="0.10" android:color="@android:color/system_accent1_100"/>
</selector>
@@ -0,0 +1,18 @@
<?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.
-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:alpha="0.32" android:color="@android:color/system_accent1_800" />
</selector>
@@ -0,0 +1,18 @@
<?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.
-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:alpha="0.20" android:color="@android:color/system_neutral1_500" android:lStar="98" />
</selector>
@@ -0,0 +1,18 @@
<?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.
-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:alpha="0.32" android:color="@android:color/system_neutral1_500" android:lStar="98" />
</selector>
+4
View File
@@ -48,6 +48,10 @@
<attr name="overviewScrimColor" format="color" />
<attr name="overviewScrimColorFallback" format="color" />
<attr name="overviewScrimColorBlur" format="color" />
<attr name="overviewScrimForegroundPrimaryBlur" format="color" />
<attr name="overviewScrimForegroundPrimary" format="color" />
<attr name="overviewScrimForegroundSecondaryBlur" format="color" />
<attr name="overviewScrimForegroundSecondary" format="color" />
<attr name="overviewActionsContainerStyle" format="reference" />
<attr name="overviewActionButtonStyle" format="reference" />
<attr name="popupNotificationDotColor" format="color" />
+9
View File
@@ -142,6 +142,15 @@
</array>
<string-array name="filtered_components" ></string-array>
<string-array name="default_featured_widget_apps" translatable="false">
<item>com.google.android.calendar</item>
<item>com.google.android.deskclock</item>
<item>com.google.android.apps.maps</item>
<item>com.google.android.contacts</item>
<item>com.google.android.apps.chromecast.app</item>
<item>com.google.android.gm</item>
<item>com.google.android.videos</item>
</string-array>
<!-- Swipe back to home related -->
<dimen name="swipe_back_window_scale_x_margin">10dp</dimen>
+4
View File
@@ -84,6 +84,8 @@
<item name="dropTargetHoverTextColor">@color/drop_target_hover_text_color_light</item>
<item name="dropTargetHoverButtonColor">@color/drop_target_hover_button_color_light</item>
<item name="overviewScrimColorFallback">@color/overview_scrim</item>
<item name="overviewScrimForegroundPrimaryBlur">@color/overview_scrim_foreground_primary</item>
<item name="overviewScrimForegroundSecondaryBlur">@color/overview_scrim_foreground_secondary</item>
<item name="overviewScrimColorBlur">#80FFFFFF</item>
<item name="preloadIconAccentColor">@color/preload_icon_accent_color_light</item>
<item name="preloadIconBackgroundColor">@color/preload_icon_background_color_light</item>
@@ -149,6 +151,8 @@
<item name="iconOnlyShortcutColor">#B3FFFFFF</item>
<item name="eduHalfSheetBGColor">#DD000000</item>
<item name="overviewScrimColorFallback">@color/overview_scrim_dark</item>
<item name="overviewScrimForegroundPrimaryBlur">@color/overview_scrim_foreground_primary_dark</item>
<item name="overviewScrimForegroundSecondaryBlur">@color/overview_scrim_foreground_secondary_dark</item>
<item name="overviewScrimColorBlur">#80000000</item>
<item name="preloadIconAccentColor">@color/preload_icon_accent_color_dark</item>
<item name="preloadIconBackgroundColor">@color/preload_icon_background_color_dark</item>
@@ -175,7 +175,6 @@ public final class TestProtocol {
public static final String PERMANENT_DIAG_TAG = "TaplTarget";
public static final String ICON_MISSING = "b/282963545";
public static final String SEARCH_CONTEXT_NULL = "b/399112039";
public static final String REQUEST_FLAG_ENABLE_GRID_ONLY_OVERVIEW = "enable-grid-only-overview";
public static final String REQUEST_IS_RECENTS_WINDOW_ENABLED = "recents-window-enabled";
@@ -287,7 +287,7 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
defaultIconSize = getResources().getDimensionPixelSize(
R.dimen.search_row_small_icon_size);
} else if (mDisplay == DISPLAY_TASKBAR) {
defaultIconSize = mDeviceProfile.taskbarIconSize;
defaultIconSize = mDeviceProfile.getTaskbarProfile().getIconSize();
} else {
// widget_selection or shortcut_popup
defaultIconSize = mDeviceProfile.iconSizePx;
+27 -50
View File
@@ -48,7 +48,6 @@ import android.view.Surface;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.core.content.res.ResourcesCompat;
import com.android.launcher3.CellLayout.ContainerType;
import com.android.launcher3.DevicePaddings.DevicePadding;
@@ -58,6 +57,7 @@ import com.android.launcher3.deviceprofile.DeviceProperties;
import com.android.launcher3.deviceprofile.DropTargetProfile;
import com.android.launcher3.deviceprofile.HotseatProfile;
import com.android.launcher3.deviceprofile.OverviewProfile;
import com.android.launcher3.deviceprofile.TaskbarProfile;
import com.android.launcher3.graphics.ThemeManager;
import com.android.launcher3.icons.DotRenderer;
import com.android.launcher3.model.data.ItemInfo;
@@ -254,17 +254,10 @@ public class DeviceProfile {
public final DotRenderer mDotRendererAllApps;
// Taskbar
private final TaskbarProfile mTaskbarProfile;
public boolean isTaskbarPresent;
// Whether Taskbar will inset the bottom of apps by taskbarSize.
public boolean isTaskbarPresentInApps;
public final int taskbarHeight;
public final int stashedTaskbarHeight;
public final int taskbarBottomMargin;
public final int taskbarIconSize;
private final int mTransientTaskbarClaimedSpace;
// If true, used to layout taskbar in 3 button navigation mode.
public final boolean startAlignTaskbar;
public final boolean isTransientTaskbar;
// DragController
public int flingToDeleteThresholdVelocity;
@@ -300,6 +293,7 @@ public class DeviceProfile {
0
);
hotseatProfile = new HotseatProfile(false, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
mTaskbarProfile = new TaskbarProfile(0, 0, 0, 0, 0, false, false);
inv = null;
mDisplayOptionSpec = null;
mInfo = null;
@@ -329,13 +323,6 @@ public class DeviceProfile {
mViewScaleProvider = null;
mDotRendererWorkSpace = null;
mDotRendererAllApps = null;
taskbarHeight = 0;
stashedTaskbarHeight = 0;
taskbarBottomMargin = 0;
taskbarIconSize = 0;
mTransientTaskbarClaimedSpace = 0;
startAlignTaskbar = false;
isTransientTaskbar = false;
}
/** TODO: Once we fully migrate to staged split, remove "isMultiWindowMode" */
@@ -399,33 +386,15 @@ public class DeviceProfile {
mTypeIndex = displayOptionSpec.typeIndex;
this.isTransientTaskbar = isTransientTaskbar;
int transientTaskbarIconSize = pxFromDp(inv.transientTaskbarIconSize[mTypeIndex], mMetrics);
int transientTaskbarBottomMargin =
res.getDimensionPixelSize(R.dimen.transient_taskbar_bottom_margin);
int transientTaskbarHeight =
Math.round((transientTaskbarIconSize * ICON_VISIBLE_AREA_FACTOR)
+ (2 * res.getDimensionPixelSize(R.dimen.transient_taskbar_padding)));
mTransientTaskbarClaimedSpace = transientTaskbarHeight + 2 * transientTaskbarBottomMargin;
if (!isTaskbarPresent) {
taskbarIconSize = taskbarHeight = stashedTaskbarHeight = taskbarBottomMargin = 0;
startAlignTaskbar = false;
} else if (isTransientTaskbar) {
taskbarIconSize = transientTaskbarIconSize;
taskbarHeight = transientTaskbarHeight;
stashedTaskbarHeight =
res.getDimensionPixelSize(R.dimen.transient_taskbar_stashed_height);
taskbarBottomMargin = transientTaskbarBottomMargin;
startAlignTaskbar = false;
} else {
taskbarIconSize = pxFromDp(ResourcesCompat.getFloat(res, R.dimen.taskbar_icon_size),
mMetrics);
taskbarHeight = res.getDimensionPixelSize(R.dimen.taskbar_size);
stashedTaskbarHeight = res.getDimensionPixelSize(R.dimen.taskbar_stashed_size);
taskbarBottomMargin = 0;
startAlignTaskbar = displayOptionSpec.startAlignTaskbar;
}
mTaskbarProfile = TaskbarProfile.Factory.createTaskbarProfile(
res,
isTransientTaskbar,
isTaskbarPresent,
mMetrics,
displayOptionSpec,
mTypeIndex,
inv
);
edgeMarginPx = res.getDimensionPixelSize(R.dimen.dynamic_grid_edge_margin);
workspaceContentScale = res.getFloat(R.dimen.workspace_content_scale);
@@ -2026,7 +1995,7 @@ public class DeviceProfile {
* Returns the number of pixels the taskbar is translated from the bottom of the screen.
*/
public int getTaskbarOffsetY() {
int taskbarIconBottomSpace = (taskbarHeight - iconSizePx) / 2;
int taskbarIconBottomSpace = (getTaskbarProfile().getHeight() - iconSizePx) / 2;
int launcherIconBottomSpace =
Math.min((hotseatCellHeightPx - iconSizePx) / 2, gridVisualizationPaddingY);
return getHotseatBarBottomPadding() + launcherIconBottomSpace - taskbarIconBottomSpace;
@@ -2034,7 +2003,9 @@ public class DeviceProfile {
/** Returns the number of pixels required below OverviewActions. */
public int getOverviewActionsClaimedSpaceBelow() {
return isTaskbarPresent ? mTransientTaskbarClaimedSpace : mInsets.bottom;
return isTaskbarPresent
? getTaskbarProfile().getTransientTaskbarClaimedSpace()
: mInsets.bottom;
}
/** Gets the space that the overview actions will take, including bottom margin. */
@@ -2071,7 +2042,7 @@ public class DeviceProfile {
mInsets.top + mDeviceProperties.getAvailableHeightPx());
} else {
// Folders should only appear below the drop target bar and above the hotseat
int hotseatTop = isTaskbarPresent ? taskbarHeight : hotseatBarSizePx;
int hotseatTop = isTaskbarPresent ? getTaskbarProfile().getHeight() : hotseatBarSizePx;
return new Rect(mInsets.left + edgeMarginPx,
mInsets.top + getDropTargetProfile().getBarSizePx() + edgeMarginPx,
mInsets.left + mDeviceProperties.getAvailableWidthPx() - edgeMarginPx,
@@ -2272,10 +2243,12 @@ public class DeviceProfile {
writer.println(prefix + "\tisTaskbarPresent:" + isTaskbarPresent);
writer.println(prefix + "\tisTaskbarPresentInApps:" + isTaskbarPresentInApps);
writer.println(prefix + pxToDpStr("taskbarHeight", taskbarHeight));
writer.println(prefix + pxToDpStr("stashedTaskbarHeight", stashedTaskbarHeight));
writer.println(prefix + pxToDpStr("taskbarBottomMargin", taskbarBottomMargin));
writer.println(prefix + pxToDpStr("taskbarIconSize", taskbarIconSize));
writer.println(prefix + pxToDpStr("taskbarHeight", getTaskbarProfile().getHeight()));
writer.println(prefix + pxToDpStr("stashedTaskbarHeight",
getTaskbarProfile().getStashedTaskbarHeight()));
writer.println(prefix + pxToDpStr("taskbarBottomMargin",
getTaskbarProfile().getBottomMargin()));
writer.println(prefix + pxToDpStr("taskbarIconSize", getTaskbarProfile().getIconSize()));
writer.println(prefix + pxToDpStr("desiredWorkspaceHorizontalMarginPx",
desiredWorkspaceHorizontalMarginPx));
@@ -2392,6 +2365,10 @@ public class DeviceProfile {
}
}
public TaskbarProfile getTaskbarProfile() {
return mTaskbarProfile;
}
public DropTargetProfile getDropTargetProfile() {
return mDropTargetProfile;
}
+25 -6
View File
@@ -165,6 +165,7 @@ import com.android.launcher3.celllayout.CellPosMapper;
import com.android.launcher3.celllayout.CellPosMapper.CellPos;
import com.android.launcher3.celllayout.CellPosMapper.TwoPanelCellPosMapper;
import com.android.launcher3.compat.AccessibilityManagerCompat;
import com.android.launcher3.compose.ComposeFacade;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.dagger.LauncherComponentProvider;
import com.android.launcher3.debug.TestEventEmitter;
@@ -293,6 +294,9 @@ public class Launcher extends StatefulActivity<LauncherState>
public static final String INTENT_ACTION_ALL_APPS_TOGGLE =
"launcher.intent_action_all_apps_toggle";
private static final String EXCLUDE_CLOSE_WIDGET_PICKER =
"launcher.extra.EXCLUDE_CLOSE_WIDGET_PICKER";
private StateManager<LauncherState, Launcher> mStateManager;
private static final int ON_ACTIVITY_RESULT_ANIMATION_DELAY = 500;
@@ -403,7 +407,6 @@ public class Launcher extends StatefulActivity<LauncherState>
protected WallpaperThemeManager mWallpaperThemeManager;
private boolean mIsTopResumedActivity;
public static Launcher getLauncher(Context context) {
@@ -1527,8 +1530,12 @@ public class Launcher extends StatefulActivity<LauncherState>
if (isActionMain) {
if (!internalStateHandled) {
// In all these cases, only animate if we're already on home
AbstractFloatingView.closeAllOpenViewsExcept(
this, isStarted(), AbstractFloatingView.TYPE_LISTENER);
int excludedViews = AbstractFloatingView.TYPE_LISTENER;
if (intent.getBooleanExtra(EXCLUDE_CLOSE_WIDGET_PICKER, false)) {
excludedViews |= TYPE_WIDGETS_FULL_SHEET;
}
AbstractFloatingView.closeAllOpenViewsExcept(this, isStarted(), excludedViews);
if (!isInState(NORMAL)) {
// Only change state, if not already the same. This prevents cancelling any
@@ -2872,14 +2879,19 @@ public class Launcher extends StatefulActivity<LauncherState>
// Overridden
}
/**
* Opens the widget picker UI. Returns true if opened.
*/
/** Opens the widget picker UI. Returns true if opened. */
public boolean openWidgetPicker() {
if (getPackageManager().isSafeMode()) {
Toast.makeText(this, R.string.safemode_widget_error, Toast.LENGTH_SHORT).show();
return false;
} else {
if (com.android.launcher3.Flags.enableWidgetPickerRefactor() &&
ComposeFacade.INSTANCE.isComposeAvailable()) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setPackage(asContext().getPackageName());
asContext().startActivity(intent);
return true;
}
openWidgetsFullSheet();
return true;
}
@@ -2893,6 +2905,13 @@ public class Launcher extends StatefulActivity<LauncherState>
if (floatingView != null) {
return (WidgetsFullSheet) floatingView;
}
if (shouldShowHomeBehindDesktop() && !mIsTopResumedActivity) {
Intent intent = new Intent(Intent.ACTION_MAIN)
.addCategory(Intent.CATEGORY_HOME)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra(EXCLUDE_CLOSE_WIDGET_PICKER, true);
startActivity(intent);
}
return WidgetsFullSheet.show(this, true /* animated */);
}
@@ -24,12 +24,15 @@ import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.FloatProperty;
import android.util.IntProperty;
import android.util.Property;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.launcher3.util.MultiScalePropertyFactory;
import com.android.launcher3.views.ScrimColors;
import com.android.launcher3.views.ScrimView;
public class LauncherAnimUtils {
/**
@@ -201,6 +204,19 @@ public class LauncherAnimUtils {
}
};
public static final Property<ScrimView, ScrimColors> SCRIM_COLORS =
new Property<ScrimView, ScrimColors>(ScrimColors.class, "scrimColors") {
@Override
public void set(ScrimView scrimView, ScrimColors scrimColors) {
scrimView.setScrimColors(scrimColors);
}
@Override
public ScrimColors get(ScrimView scrimView) {
return scrimView.getScrimColors();
}
};
public static final FloatProperty<ImageView> ROTATION_DRAWABLE_PERCENT =
new FloatProperty<ImageView>("drawableRotationPercent") {
// RotateDrawable linearly interpolates the rotation degrees between fromDegrees
@@ -46,6 +46,58 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.ToIntFunction;
/**
* This provider facilitates the import and export of home screen metadata within the
* Launcher's database. This includes managing shortcut placement, launch intents, and labels.
* Each row in the Launcher3 database corresponds to a single item on the workspace (often
* referred to as "favorites").
*
* <p>Only applications installed on the system partition or those possessing the platform's
* signature can access this provider.
*
* <p>After data insertion into the Launcher's database, a row may be deleted during Launcher
* startup if any of these conditions are true. This list is not exhaustive:
* <ul>
* <li>Missing or invalid launch intent: This includes a null intent, one without a target
* package, or one referencing a non-existent activity.</li>
* <li>When an app previously installed doesn't exist or fails to restore properly.</li>
* <li>If ShortcutManager/WidgetManager haven't finished restoring by the time Launcher loads</li>
* <li>If the App Store hasn't finished restoring when Launcher starts loading.</li>
* <li>The item is linked to a profile that no longer exists (e.g., a deleted work profile).</li>
* <li>A widget's metadata specifies an invalid height or width.</li>
* <li>Incorrect item container: For instance, widgets can only be on the desktop or hotseat<li>
* <li>If the launcher is restoring, but the item isn't flagged as restoring/installing.</li>
* <li>If a widget fails to inflate within AppWidgetManagerService for any reason.</li>
* <li>When items in the database occupy the same or overlapping positions.</li>
* </ul>
*
* <p>Although query, bulkInsert, and insert methods are available, their direct use is not
* recommended. Instead, prefer the XML-based insertion methods accessible via the
* {@code call()} method. This preference is due to several reasons, including:
* <ul>
* <li>The insert methods can can lead to unpredictable behavior if invoked while Launcher
* is in the process of loading.</li>
* <li>The XML approach allows for custom tags which can be ingested for proprietary variants
* of workspace items.</li>
* <li>The XML method clears old data and inserts new data as a single, atomic action. Direct
* Delete/Insert usage requires at least 2 binder calls that are not atomic.</li>
* </ul>
*
* <p>It's important to note that the XML format has non-obvious and strict requirements. For
* instance:
* <ul>
* <li>The Launcher uses the "screen" value to determine hot seat placement order.</li>
* <li>Conversely, for items within a folder, the rank db column dictates their placement
* order.</li>
* <li>When an item is on the top-level workspace (i.e., not in the hot seat), the "screen"
* value signifies its workspace page.</li>
* </ul>
*
* <p>During a launcher restore, a grid migration might occur, either due to user preference or
* design updates. This migration can cause items to be repositioned or moved to different pages,
* depending on the old and new grid sizes. Therefore, precise placement cannot be guaranteed
* in all situations.
*/
public class LauncherProvider extends ContentProvider {
private static final String TAG = "LauncherProvider";
+4 -2
View File
@@ -49,6 +49,7 @@ import com.android.launcher3.uioverrides.states.AllAppsState;
import com.android.launcher3.uioverrides.states.HintState;
import com.android.launcher3.uioverrides.states.OverviewState;
import com.android.launcher3.views.ActivityContext;
import com.android.launcher3.views.ScrimColors;
import java.util.Arrays;
@@ -317,8 +318,9 @@ public abstract class LauncherState implements BaseState<LauncherState> {
* What color should the workspace scrim be in when at rest in this state.
* Return {@link Color#TRANSPARENT} for no scrim.
*/
public int getWorkspaceScrimColor(Launcher launcher) {
return Color.TRANSPARENT;
public ScrimColors getWorkspaceScrimColor(Launcher launcher) {
return new ScrimColors(/* backgroundColor */ Color.TRANSPARENT,
/* foregroundColor */ Color.TRANSPARENT);
}
/**
@@ -207,7 +207,7 @@ public class WorkspaceStateTransitionAnimation {
propertySetter.setFloat(sysUiScrim.getSysUIProgress(), AnimatedFloat.VALUE,
state.hasFlag(FLAG_HAS_SYS_UI_SCRIM) ? 1 : 0, LINEAR);
propertySetter.setViewBackgroundColor(mLauncher.getScrimView(),
propertySetter.setScrimColors(mLauncher.getScrimView(),
state.getWorkspaceScrimColor(mLauncher),
config.getInterpolator(ANIM_SCRIM_FADE, ACCELERATE_2));
}
@@ -166,7 +166,7 @@ public class WorkUtilityView extends LinearLayout implements Insettable,
}
if (!dp.getDeviceProperties().isGestureMode() && dp.isTaskbarPresent) {
bottomMargin += dp.taskbarHeight;
bottomMargin += dp.getTaskbarProfile().getHeight();
}
lp.bottomMargin = bottomMargin;
@@ -16,7 +16,7 @@
package com.android.launcher3.anim;
import static com.android.launcher3.LauncherAnimUtils.VIEW_BACKGROUND_COLOR;
import static com.android.launcher3.LauncherAnimUtils.SCRIM_COLORS;
import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
@@ -25,13 +25,16 @@ import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.graphics.drawable.ColorDrawable;
import android.util.FloatProperty;
import android.util.IntProperty;
import android.view.View;
import androidx.annotation.NonNull;
import com.android.launcher3.views.ScrimColors;
import com.android.launcher3.views.ScrimView;
import com.android.launcher3.views.ScrimColorsEvaluator;
import java.util.function.Consumer;
/**
@@ -63,15 +66,16 @@ public class AnimatedPropertySetter extends PropertySetter {
}
@Override
public Animator setViewBackgroundColor(View view, int color, TimeInterpolator interpolator) {
if (view == null || (view.getBackground() instanceof ColorDrawable
&& ((ColorDrawable) view.getBackground()).getColor() == color)) {
public Animator setScrimColors(ScrimView view, ScrimColors scrimColors,
TimeInterpolator interpolator) {
if (view == null || view.getScrimColors().equals(scrimColors)) {
return NO_OP;
}
ObjectAnimator anim = ObjectAnimator.ofArgb(view, VIEW_BACKGROUND_COLOR, color);
anim.setInterpolator(interpolator);
add(anim);
return anim;
ObjectAnimator animator = ObjectAnimator.ofObject(view, SCRIM_COLORS,
ScrimColorsEvaluator.INSTANCE, scrimColors);
animator.setInterpolator(interpolator);
add(animator);
return animator;
}
@Override
@@ -19,12 +19,16 @@ package com.android.launcher3.anim;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.TimeInterpolator;
import android.graphics.drawable.ColorDrawable;
import android.util.FloatProperty;
import android.util.IntProperty;
import android.view.View;
import androidx.annotation.NonNull;
import com.android.launcher3.views.ScrimColors;
import com.android.launcher3.views.ScrimView;
import java.util.function.Consumer;
/**
@@ -59,12 +63,14 @@ public abstract class PropertySetter {
}
/**
* Sets the background color of the provided view using the provided interpolator.
* Sets the background and foreground color of the provided view using the provided
* interpolator.
*/
@NonNull
public Animator setViewBackgroundColor(View view, int color, TimeInterpolator interpolator) {
public Animator setScrimColors(ScrimView view, ScrimColors scrimColors,
TimeInterpolator interpolator) {
if (view != null) {
view.setBackgroundColor(color);
view.setScrimColors(scrimColors);
}
return NO_OP;
}
@@ -16,6 +16,7 @@
package com.android.launcher3.dagger;
import com.android.launcher3.compose.widgetpicker.LauncherWidgetPickerModule;
import com.android.launcher3.concurrent.ExecutorsModule;
import com.android.launcher3.util.dagger.LauncherExecutorsModule;
@@ -33,6 +34,7 @@ import dagger.Module;
LauncherConcurrencyModule.class,
ExecutorsModule.class,
LauncherExecutorsModule.class,
LauncherWidgetPickerModule.class
},
subcomponents = ActivityContextComponent.class)
public class LauncherAppModule { }
@@ -25,6 +25,7 @@ import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherPrefs;
import com.android.launcher3.RemoveAnimationSettingsTracker;
import com.android.launcher3.backuprestore.LauncherRestoreEventLogger;
import com.android.launcher3.compose.core.widgetpicker.WidgetPickerComposeWrapper;
import com.android.launcher3.folder.FolderNameSuggestionLoader;
import com.android.launcher3.graphics.GridCustomizationsProxy;
import com.android.launcher3.graphics.ThemeManager;
@@ -100,7 +101,9 @@ public interface LauncherBaseAppComponent {
InstantAppResolver getInstantAppResolver();
DumpManager getDumpManager();
StatsLogManager.StatsLogManagerFactory getStatsLogManagerFactory();
ActivityContextComponent.Builder getActivityContextComponentBuilder();
ActivityContextComponent.Builder getActivityContextComponentBuilder();
WidgetPickerComposeWrapper getWidgetPickerComposeWrapper();
/** Builder for LauncherBaseAppComponent. */
interface Builder {
@@ -0,0 +1,93 @@
/*
* 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.deviceprofile
import android.content.res.Resources
import android.util.DisplayMetrics
import androidx.core.content.res.ResourcesCompat
import com.android.launcher3.InvariantDeviceProfile
import com.android.launcher3.R
import com.android.launcher3.icons.IconNormalizer.ICON_VISIBLE_AREA_FACTOR
import com.android.launcher3.testing.shared.ResourceUtils.pxFromDp
data class TaskbarProfile(
val height: Int,
val stashedTaskbarHeight: Int,
val bottomMargin: Int,
val iconSize: Int,
val transientTaskbarClaimedSpace: Int,
// If true, used to layout taskbar in 3 button navigation mode.
val isStartAlignTaskbar: Boolean,
val isTransientTaskbar: Boolean,
) {
companion object Factory {
fun createTaskbarProfile(
res: Resources,
isTransientTaskbar: Boolean,
isTaskbarPresent: Boolean,
metrics: DisplayMetrics,
displayOptionSpec: InvariantDeviceProfile.DisplayOptionSpec,
typeIndex: Int,
inv: InvariantDeviceProfile,
): TaskbarProfile {
val transientTaskbarIconSize =
pxFromDp(inv.transientTaskbarIconSize.get(typeIndex), metrics)
val transientTaskbarBottomMargin: Int =
res.getDimensionPixelSize(R.dimen.transient_taskbar_bottom_margin)
val transientTaskbarHeight =
Math.round(
(transientTaskbarIconSize * ICON_VISIBLE_AREA_FACTOR) +
(2 * res.getDimensionPixelSize(R.dimen.transient_taskbar_padding))
)
val transientTaskbarClaimedSpace =
transientTaskbarHeight + 2 * transientTaskbarBottomMargin
return when {
!isTaskbarPresent -> TaskbarProfile(
bottomMargin = 0,
stashedTaskbarHeight = 0,
height = 0,
iconSize = 0,
isStartAlignTaskbar = false,
transientTaskbarClaimedSpace = transientTaskbarClaimedSpace,
isTransientTaskbar = isTransientTaskbar,
)
isTransientTaskbar -> TaskbarProfile(
iconSize = transientTaskbarIconSize,
height = transientTaskbarHeight,
stashedTaskbarHeight =
res.getDimensionPixelSize(R.dimen.transient_taskbar_stashed_height),
bottomMargin = transientTaskbarBottomMargin,
isStartAlignTaskbar = false,
transientTaskbarClaimedSpace = transientTaskbarClaimedSpace,
isTransientTaskbar = isTransientTaskbar,
)
else -> TaskbarProfile(
iconSize =
pxFromDp(ResourcesCompat.getFloat(res, R.dimen.taskbar_icon_size), metrics),
height = res.getDimensionPixelSize(R.dimen.taskbar_size),
stashedTaskbarHeight = res.getDimensionPixelSize(R.dimen.taskbar_stashed_size),
bottomMargin = 0,
isStartAlignTaskbar = displayOptionSpec.startAlignTaskbar,
isTransientTaskbar = isTransientTaskbar,
transientTaskbarClaimedSpace = transientTaskbarClaimedSpace,
)
}
}
}
}
@@ -20,7 +20,6 @@ import static android.view.View.MeasureSpec.EXACTLY;
import static android.view.View.MeasureSpec.makeMeasureSpec;
import static android.view.View.VISIBLE;
import static com.android.launcher3.Flags.extendibleThemeManager;
import static com.android.launcher3.Hotseat.ALPHA_CHANNEL_PREVIEW_RENDERER;
import static com.android.launcher3.LauncherPrefs.FIXED_LANDSCAPE_MODE;
import static com.android.launcher3.LauncherPrefs.GRID_NAME;
@@ -29,6 +28,7 @@ import static com.android.launcher3.graphics.ThemeManager.PREF_ICON_SHAPE;
import static com.android.launcher3.graphics.ThemeManager.THEMED_ICONS;
import static com.android.launcher3.model.ModelUtils.currentScreenContentFilter;
import static com.android.launcher3.widget.LauncherWidgetHolder.APPWIDGET_HOST_ID;
import static com.android.systemui.shared.Flags.extendibleThemeManager;
import static java.util.Comparator.comparingDouble;
@@ -71,6 +71,7 @@ import com.android.launcher3.R;
import com.android.launcher3.WorkspaceLayoutManager;
import com.android.launcher3.celllayout.CellLayoutLayoutParams;
import com.android.launcher3.celllayout.CellPosMapper;
import com.android.launcher3.compose.core.widgetpicker.NoOpWidgetPickerModule;
import com.android.launcher3.concurrent.ExecutorsModule;
import com.android.launcher3.dagger.ApiWrapperModule;
import com.android.launcher3.dagger.AppModule;
@@ -546,6 +547,7 @@ public class LauncherPreviewRenderer extends BaseContext
LauncherConcurrencyModule.class,
ExecutorsModule.class,
LauncherExecutorsModule.class,
NoOpWidgetPickerModule.class
})
public interface PreviewAppComponent extends LauncherAppComponent {
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff. Show more