From 44db7c1fd211d23bf3d9ce1d1e0d552ebaca7ae7 Mon Sep 17 00:00:00 2001 From: TheSuperDragon <70206496+SuperDragonXD@users.noreply.github.com> Date: Tue, 23 Jun 2026 21:50:28 +0800 Subject: [PATCH] refactor: Migrate QSB to Compose (#6887) This commit migrates the dock and drawer QSB to use Jetpack Compose. This should open up greater customization possibilities, and also simplify implementation of certain features. --- lawnchair/res/drawable/search_input_fg.xml | 12 - .../res/layout/search_container_all_apps.xml | 75 +-- .../res/layout/search_container_hotseat.xml | 58 +- .../lawnchair/allapps/AllAppsSearchInput.kt | 183 ++++--- .../app/lawnchair/qsb/AssistantIconView.kt | 55 -- .../src/app/lawnchair/qsb/LawnQsbLayout.kt | 265 ++++----- lawnchair/src/app/lawnchair/qsb/LawnQsbUi.kt | 517 ++++++++++++++++++ .../src/app/lawnchair/qsb/QsbIconUtil.kt | 97 +++- .../theme/drawable/DrawableTokens.kt | 16 - .../search/DockSearchPreferences.kt | 101 +++- 10 files changed, 911 insertions(+), 468 deletions(-) delete mode 100644 lawnchair/res/drawable/search_input_fg.xml delete mode 100644 lawnchair/src/app/lawnchair/qsb/AssistantIconView.kt create mode 100644 lawnchair/src/app/lawnchair/qsb/LawnQsbUi.kt diff --git a/lawnchair/res/drawable/search_input_fg.xml b/lawnchair/res/drawable/search_input_fg.xml deleted file mode 100644 index a865951fa0..0000000000 --- a/lawnchair/res/drawable/search_input_fg.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - diff --git a/lawnchair/res/layout/search_container_all_apps.xml b/lawnchair/res/layout/search_container_all_apps.xml index b42573bd2e..ffc2025428 100644 --- a/lawnchair/res/layout/search_container_all_apps.xml +++ b/lawnchair/res/layout/search_container_all_apps.xml @@ -15,22 +15,31 @@ --> + + + + android:padding="0dp" + android:paddingStart="@dimen/qsb_g_icon_marginStart" + android:paddingEnd="@dimen/search_result_padding"> - - - - - - - - - - - diff --git a/lawnchair/res/layout/search_container_hotseat.xml b/lawnchair/res/layout/search_container_hotseat.xml index 4dec267458..76bd3749e7 100644 --- a/lawnchair/res/layout/search_container_hotseat.xml +++ b/lawnchair/res/layout/search_container_hotseat.xml @@ -1,65 +1,9 @@ - - - - - - - - - - - - - - - - + android:paddingVertical="@dimen/qsb_widget_vertical_padding" /> diff --git a/lawnchair/src/app/lawnchair/allapps/AllAppsSearchInput.kt b/lawnchair/src/app/lawnchair/allapps/AllAppsSearchInput.kt index 200cf34e68..fb69bbf6ed 100644 --- a/lawnchair/src/app/lawnchair/allapps/AllAppsSearchInput.kt +++ b/lawnchair/src/app/lawnchair/allapps/AllAppsSearchInput.kt @@ -12,13 +12,17 @@ import android.text.method.TextKeyListener import android.text.style.ForegroundColorSpan import android.util.AttributeSet import android.view.KeyEvent -import android.view.View -import android.view.View.OnFocusChangeListener import android.view.ViewTreeObserver import android.view.animation.DecelerateInterpolator import android.widget.FrameLayout -import android.widget.ImageButton import android.widget.TextView +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.platform.ViewCompositionStrategy import androidx.core.view.ViewCompat import androidx.core.view.isInvisible import androidx.core.view.isVisible @@ -28,20 +32,23 @@ import androidx.lifecycle.lifecycleScope import app.lawnchair.launcher import app.lawnchair.preferences.PreferenceManager import app.lawnchair.preferences2.PreferenceManager2 +import app.lawnchair.preferences2.asState import app.lawnchair.preferences2.firstCached -import app.lawnchair.preferences2.subscribeBlocking -import app.lawnchair.qsb.AssistantIconView import app.lawnchair.qsb.LawnQsbLayout.Companion.getLensIntent import app.lawnchair.qsb.LawnQsbLayout.Companion.getSearchProvider -import app.lawnchair.qsb.ThemingMethod +import app.lawnchair.qsb.LawnQsbLayout.Companion.getVoiceIntent +import app.lawnchair.qsb.LawnQsbUi +import app.lawnchair.qsb.QsbActions +import app.lawnchair.qsb.QsbIconId +import app.lawnchair.qsb.buildQsbStyle import app.lawnchair.qsb.providers.Google -import app.lawnchair.qsb.providers.GoogleGo import app.lawnchair.qsb.providers.PixelSearch -import app.lawnchair.qsb.setThemedIconResource +import app.lawnchair.qsb.rememberAllAppsQsbState import app.lawnchair.search.LawnchairRecentSuggestionProvider import app.lawnchair.search.algorithms.LawnchairSearchAlgorithm -import app.lawnchair.theme.drawable.DrawableTokens -import app.lawnchair.util.viewAttachedScope +import app.lawnchair.theme.color.tokens.ColorTokens +import app.lawnchair.ui.theme.LawnchairTheme +import app.lawnchair.util.ProvideLifecycleState import com.android.launcher3.Insettable import com.android.launcher3.InvariantDeviceProfile.OnIDPChangeListener import com.android.launcher3.LauncherState @@ -70,11 +77,7 @@ class AllAppsSearchInput(context: Context, attrs: AttributeSet?) : private lateinit var hint: TextView private lateinit var input: FallbackSearchInputView - private lateinit var actionButton: ImageButton - private lateinit var searchIcon: ImageButton - - private lateinit var micIcon: AssistantIconView - private lateinit var lensIcon: ImageButton + private lateinit var qsbShell: ComposeView private val qsbMarginTopAdjusting = resources.getDimensionPixelSize(R.dimen.qsb_margin_top_adjusting) private val allAppsSearchVerticalOffset = resources.getDimensionPixelSize(R.dimen.all_apps_search_vertical_offset) @@ -91,13 +94,10 @@ class AllAppsSearchInput(context: Context, attrs: AttributeSet?) : private var focusedResultTitle = "" private var canShowHint = false + private var queryEmpty by mutableStateOf(true) + private var bgAlphaState by mutableFloatStateOf(1f) private val supportBlur = BlurUtils.supportsBlursOnWindows() - private val bg = if (supportBlur) { - DrawableTokens.SearchInputFgBlur.resolve(context) - } else { - DrawableTokens.SearchInputFg.resolve(context) - } private val bgAlphaAnimator = ValueAnimator.ofFloat(0f, 1f).apply { duration = 300 interpolator = DecelerateInterpolator() @@ -114,8 +114,6 @@ class AllAppsSearchInput(context: Context, attrs: AttributeSet?) : override fun onFinishInflate() { super.onFinishInflate() - val wrapper = ViewCompat.requireViewById(this, R.id.search_wrapper) - wrapper.background = bg setupPadding() bgAlphaAnimator.addUpdateListener { updateBgAlpha() } @@ -123,72 +121,101 @@ class AllAppsSearchInput(context: Context, attrs: AttributeSet?) : input = ViewCompat.requireViewById(this, R.id.input) - searchIcon = ViewCompat.requireViewById(this, R.id.search_icon) - micIcon = ViewCompat.requireViewById(this, R.id.mic_btn) - lensIcon = ViewCompat.requireViewById(this, R.id.lens_btn) + qsbShell = ViewCompat.requireViewById(this, R.id.qsb_shell) - val shouldShowIcons = prefs2.matchHotseatQsbStyle.firstCached() + qsbShell.apply { + setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnDetachedFromWindow) - val searchProvider = getSearchProvider(context, prefs2) - val isGoogle = searchProvider == Google || searchProvider == GoogleGo || searchProvider == PixelSearch - val supportsLens = searchProvider == Google || searchProvider == PixelSearch + setContent { + val searchProviderPref by prefs2.hotseatQsbProvider.asState() + val searchProvider = remember(searchProviderPref, context) { + getSearchProvider(context, searchProviderPref) + } + val themedQsb by prefs2.themedHotseatQsb.asState() + val shouldShowIcons by prefs2.matchHotseatQsbStyle.asState() - val lensIntent = getLensIntent(context) - val voiceIntent = AssistantIconView.getVoiceIntent(searchProvider, context) + val supportsLens = searchProvider == Google || searchProvider == PixelSearch + val voiceIntent = remember(searchProvider, context) { + getVoiceIntent(searchProvider, context) + } + val lensIntent = remember(supportsLens, context) { + if (supportsLens) getLensIntent(context) else null + } - micIcon.isVisible = shouldShowIcons && voiceIntent != null - lensIcon.isVisible = shouldShowIcons && supportsLens && lensIntent != null - - actionButton = ViewCompat.requireViewById(this, R.id.action_btn) - with(actionButton) { - isVisible = false - setOnClickListener { - input.reset() - searchAlgorithm?.doZeroStateSearch(this@AllAppsSearchInput) - updateHint() - } - } - - prefs2.themedHotseatQsb.subscribeBlocking(prefs2 = prefs2, scope = viewAttachedScope) { themed -> - with(searchIcon) { - isVisible = true - - val iconRes = if (themed) searchProvider.themedIcon else searchProvider.icon - val resId = if (shouldShowIcons) iconRes else R.drawable.ic_qsb_search - val isThemed = themed || resId == R.drawable.ic_qsb_search - val method = if (shouldShowIcons) searchProvider.themingMethod else ThemingMethod.TINT - - setThemedIconResource( - resId = resId, - themed = isThemed, - method = method, + val state = rememberAllAppsQsbState( + searchProvider = searchProvider, + themed = themedQsb, + shouldShowIcons = shouldShowIcons, + queryEmpty = queryEmpty, + showMic = voiceIntent != null, + showLens = lensIntent != null, ) - setOnClickListener { - val launcher = context.launcher - launcher.lifecycleScope.launch { - searchProvider.launch(launcher) - } + val backgroundColor = if (supportBlur) { + ColorTokens.SearchboxHighlightBlur.resolveColor(context) + } else { + ColorTokens.SearchboxHighlight.resolveColor(context) } - } - with(micIcon) { - setIcon(isGoogle, themed) - setOnClickListener { - context.startActivity(voiceIntent) - } - } - with(lensIcon) { - if (lensIntent != null) { - setThemedIconResource(R.drawable.ic_lens_color, themed) - setOnClickListener { - runCatching { context.startActivity(lensIntent) } + + // Ignore other theme attributes to preserve existing behavior + val style = buildQsbStyle( + context = context, + themed = themedQsb, + backgroundColor = backgroundColor, + backgroundAlpha = (bgAlphaState * 100).toInt(), + cornerRadius = 1f, + strokeColor = null, + strokeWidth = 0f, + ) + + val actions = QsbActions( + onQsbClick = { + input.requestFocus() + input.showKeyboard() + }, + onStartIconClick = if (shouldShowIcons) { + { + val launcher = context.launcher + launcher.lifecycleScope.launch { + searchProvider.launch(launcher) + } + } + } else { + null + }, + onEndIconClick = { id -> + when (id) { + QsbIconId.MIC -> voiceIntent?.let { context.startActivity(it) } + + QsbIconId.LENS -> lensIntent?.let { context.startActivity(it) } + + QsbIconId.CLEAR -> { + input.reset() + searchAlgorithm?.doZeroStateSearch(this@AllAppsSearchInput) + updateHint() + } + + else -> Unit + } + }, + ) + + LawnchairTheme { + ProvideLifecycleState { + LawnQsbUi( + state = state, + style = style, + actions = actions, + ) } } } } + val currentPaddingLeft = initialPaddingLeft val currentPaddingRight = initialPaddingRight - input.onFocusChangeListener = OnFocusChangeListener { _, hasFocus -> + + input.onFocusChangeListener = { _, hasFocus -> if (hasFocus) { if (prefs2.searchAlgorithm.firstCached() != LawnchairSearchAlgorithm.APP_SEARCH) { input.setHint(R.string.all_apps_device_search_hint) @@ -240,9 +267,7 @@ class AllAppsSearchInput(context: Context, attrs: AttributeSet?) : launcher.stateManager.goToState(LauncherState.NORMAL) } - actionButton.isVisible = !it.isNullOrEmpty() - micIcon.isVisible = shouldShowIcons && voiceIntent != null && it.isNullOrEmpty() - lensIcon.isVisible = shouldShowIcons && supportsLens && lensIntent != null && it.isNullOrEmpty() + queryEmpty = it.isNullOrEmpty() }, ) @@ -453,7 +478,7 @@ class AllAppsSearchInput(context: Context, attrs: AttributeSet?) : private fun updateBgAlpha() { val fraction = bgAlphaAnimator.animatedFraction - bg.alpha = (Utilities.mapRange(fraction, 0f, bgAlpha) * 255).toInt() + bgAlphaState = Utilities.mapRange(fraction, 0f, bgAlpha) } override fun onIdpChanged(modelPropertiesChanged: Boolean) { diff --git a/lawnchair/src/app/lawnchair/qsb/AssistantIconView.kt b/lawnchair/src/app/lawnchair/qsb/AssistantIconView.kt deleted file mode 100644 index aa2853fe2d..0000000000 --- a/lawnchair/src/app/lawnchair/qsb/AssistantIconView.kt +++ /dev/null @@ -1,55 +0,0 @@ -package app.lawnchair.qsb - -import android.annotation.SuppressLint -import android.content.Context -import android.content.Intent -import android.util.AttributeSet -import android.widget.ImageButton -import androidx.core.view.isVisible -import app.lawnchair.preferences2.PreferenceManager2 -import app.lawnchair.qsb.providers.QsbSearchProvider -import com.android.launcher3.R - -@SuppressLint("AppCompatCustomView") -class AssistantIconView(context: Context, attrs: AttributeSet?) : ImageButton(context, attrs) { - - init { - val provider = LawnQsbLayout.getSearchProvider(context, PreferenceManager2.getInstance(context)) - - val intent = getVoiceIntent(provider, context) - isVisible = intent != null - - setOnClickListener { - context.startActivity(intent) - } - } - - fun setIcon(isGoogle: Boolean, themed: Boolean) { - clearColorFilter() - - val iconRes = if (isGoogle) R.drawable.ic_mic_color else R.drawable.ic_mic_flat - val themingMethod = if (isGoogle) ThemingMethod.THEME_BY_LAYER_ID else ThemingMethod.TINT - - setThemedIconResource( - resId = iconRes, - themed = isGoogle && themed || !isGoogle, - method = themingMethod, - ) - } - - companion object { - - fun getVoiceIntent( - provider: QsbSearchProvider, - context: Context, - ): Intent? { - val intent = if (provider.supportVoiceIntent) provider.createVoiceIntent() else null - - return if (intent == null || !LawnQsbLayout.resolveIntent(context, intent)) { - null - } else { - intent - } - } - } -} diff --git a/lawnchair/src/app/lawnchair/qsb/LawnQsbLayout.kt b/lawnchair/src/app/lawnchair/qsb/LawnQsbLayout.kt index f0a0f1cad3..09a9389582 100644 --- a/lawnchair/src/app/lawnchair/qsb/LawnQsbLayout.kt +++ b/lawnchair/src/app/lawnchair/qsb/LawnQsbLayout.kt @@ -1,45 +1,35 @@ package app.lawnchair.qsb -import android.app.PendingIntent -import android.appwidget.AppWidgetHostView import android.content.ComponentName import android.content.Context import android.content.Intent -import android.graphics.Color -import android.graphics.Paint -import android.graphics.drawable.LayerDrawable -import android.graphics.drawable.PaintDrawable import android.util.AttributeSet import android.widget.FrameLayout -import android.widget.ImageView -import androidx.core.view.ViewCompat +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.ViewCompositionStrategy import androidx.core.view.children -import androidx.core.view.descendants -import androidx.core.view.isVisible import androidx.lifecycle.lifecycleScope -import app.lawnchair.HeadlessWidgetsManager import app.lawnchair.animateToAllApps import app.lawnchair.launcher -import app.lawnchair.launcherNullable -import app.lawnchair.preferences.PreferenceManager +import app.lawnchair.preferences.observeAsState +import app.lawnchair.preferences.preferenceManager import app.lawnchair.preferences2.PreferenceManager2 +import app.lawnchair.preferences2.asState import app.lawnchair.preferences2.firstCached -import app.lawnchair.preferences2.subscribeBlocking import app.lawnchair.qsb.providers.AppSearch import app.lawnchair.qsb.providers.Google -import app.lawnchair.qsb.providers.GoogleGo import app.lawnchair.qsb.providers.PixelSearch import app.lawnchair.qsb.providers.QsbSearchProvider -import app.lawnchair.theme.color.ColorOption -import app.lawnchair.util.pendingIntent +import app.lawnchair.ui.theme.LawnchairTheme +import app.lawnchair.util.ProvideLifecycleState import app.lawnchair.util.repeatOnAttached -import app.lawnchair.util.viewAttachedScope import com.android.launcher3.BaseActivity import com.android.launcher3.DeviceProfile -import com.android.launcher3.R -import com.android.launcher3.qsb.QsbContainerView -import com.android.launcher3.util.Themes import com.android.launcher3.views.ActivityContext +import com.patrykmichalik.opto.core.firstBlocking import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.flatMapLatest @@ -49,70 +39,99 @@ import kotlinx.coroutines.launch class LawnQsbLayout(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs) { private val activity: ActivityContext = ActivityContext.lookupContext(context) - private lateinit var gIcon: ImageView - private lateinit var micIcon: AssistantIconView - private lateinit var lensIcon: ImageView - private lateinit var inner: FrameLayout - private lateinit var preferenceManager: PreferenceManager + private val composeView = ComposeView(context) private lateinit var preferenceManager2: PreferenceManager2 - private var searchPendingIntent: PendingIntent? = null - private var strokeColor: ColorOption? = null + private lateinit var searchProvider: QsbSearchProvider @OptIn(ExperimentalCoroutinesApi::class) override fun onFinishInflate() { super.onFinishInflate() - gIcon = ViewCompat.requireViewById(this, R.id.g_icon) - micIcon = ViewCompat.requireViewById(this, R.id.mic_icon) - lensIcon = ViewCompat.requireViewById(this, R.id.lens_icon) - inner = ViewCompat.requireViewById(this, R.id.inner) - preferenceManager = PreferenceManager.getInstance(context) preferenceManager2 = PreferenceManager2.getInstance(context) + searchProvider = getSearchProvider(context, preferenceManager2) - val attachedScope = viewAttachedScope - preferenceManager2.strokeColorStyle.subscribeBlocking(prefs2 = preferenceManager2, scope = attachedScope) { - strokeColor = it - setUpBackground() - } + composeView.apply { + setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnDetachedFromWindow) + setContent { + LawnchairTheme { + ProvideLifecycleState { + val context = LocalContext.current - clipIconRipples() + val prefs = preferenceManager() + val prefs2 = preferenceManager2 - val searchProvider = getSearchProvider(context, preferenceManager2) - val isGoogle = searchProvider == Google || searchProvider == GoogleGo || searchProvider == PixelSearch - val supportsLens = searchProvider == Google || searchProvider == PixelSearch + val searchProviderPref by prefs2.hotseatQsbProvider.asState() + val searchProvider = remember(searchProviderPref, context) { + getSearchProvider(context, searchProviderPref) + } + val themed by prefs2.themedHotseatQsb.asState() - preferenceManager2.themedHotseatQsb.subscribeBlocking(prefs2 = preferenceManager2, scope = attachedScope) { themed -> - setUpBackground(themed) + val supportsLens = searchProvider == Google || searchProvider == PixelSearch + val voiceIntent = remember(searchProvider, context) { + getVoiceIntent(searchProvider, context) + } + val lensIntent = remember(supportsLens, context) { + if (supportsLens) getLensIntent(context) else null + } - val iconRes = if (themed) searchProvider.themedIcon else searchProvider.icon + val state = rememberHotseatQsbState( + searchProvider = searchProvider, + themed = themed, + showMic = voiceIntent != null, + showLens = lensIntent != null, + ) - // The default search icon should always be themed - gIcon.setThemedIconResource( - resId = iconRes, - themed = themed || iconRes == R.drawable.ic_qsb_search, - method = searchProvider.themingMethod, - ) + val style = buildQsbStyle( + context = LocalContext.current, + themed = themed, + backgroundColor = getHotseatBackgroundColor(context, themed), + backgroundAlpha = prefs.hotseatQsbAlpha.observeAsState().value, + cornerRadius = prefs.hotseatQsbCornerRadius.observeAsState().value, + // Use light color as strokeColor is a static color that doesn't use darkColor + strokeColor = prefs2.strokeColorStyle.asState().value.colorPreferenceEntry.lightColor.invoke(context), + strokeWidth = prefs.hotseatQsbStrokeWidth.observeAsState().value, + ) - micIcon.setIcon(isGoogle, themed) - if (supportsLens) { - lensIcon.setThemedIconResource(R.drawable.ic_lens_color, themed) - } - } + val actions = QsbActions( + onQsbClick = { + val launcher = context.launcher + launcher.lifecycleScope.launch { + if (prefs2.matchHotseatQsbStyle.firstCached()) { + launcher.appsView.searchUiManager.editText?.showKeyboard() + launcher.animateToAllApps() + } else { + searchProvider.launch(launcher) + } + } + }, + onStartIconClick = null, + onEndIconClick = { id -> + runCatching { + when (id) { + QsbIconId.MIC -> voiceIntent?.let { context.startActivity(it) } + QsbIconId.LENS -> lensIntent?.let { context.startActivity(it) } + else -> null + } + } + }, + ) - if (supportsLens) setUpLensIcon() - - setOnClickListener { - val launcher = context.launcher - launcher.lifecycleScope.launch { - if (preferenceManager2.matchHotseatQsbStyle.firstCached()) { - launcher.appsView.searchUiManager.editText?.showKeyboard() - launcher.animateToAllApps() - } else { - searchProvider.launch(launcher) + LawnQsbUi( + state = state, + style = style, + actions = actions, + ) + } } } } + + addView( + composeView, + LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT), + ) + if (searchProvider == Google) { repeatOnAttached { val forceWebsite = preferenceManager2.hotseatQsbForceWebsite.get() @@ -122,11 +141,7 @@ class LawnQsbLayout(context: Context, attrs: AttributeSet?) : FrameLayout(contex } .collect() } - subscribeGoogleSearchWidget() } - - preferenceManager.hotseatQsbAlpha.subscribeChanges(this, ::setUpBackground) - preferenceManager.hotseatQsbStrokeWidth.subscribeChanges(this, ::setUpBackground) } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { @@ -144,87 +159,33 @@ class LawnQsbLayout(context: Context, attrs: AttributeSet?) : FrameLayout(contex val width = requestedWidth - widthReduction setMeasuredDimension(width, height) + if (!composeView.isAttachedToWindow) { + // Ignore to prevent crash on preview contexts + return + } + children.forEach { child -> measureChildWithMargins(child, widthMeasureSpec, widthReduction, heightMeasureSpec, 0) } } - private fun subscribeGoogleSearchWidget() { - val info = QsbContainerView.getSearchWidgetProviderInfo(context, Google.packageName) ?: return - context.launcherNullable?.lifecycleScope?.launch { - val headlessWidgetsManager = HeadlessWidgetsManager.INSTANCE.get(context) - headlessWidgetsManager.subscribeUpdates(info, "hotseatWidgetId") - .collect { findSearchIntent(it) } - } - } - - private fun findSearchIntent(view: AppWidgetHostView) { - view.measure( - MeasureSpec.makeMeasureSpec(1000, MeasureSpec.EXACTLY), - MeasureSpec.makeMeasureSpec(100, MeasureSpec.EXACTLY), - ) - searchPendingIntent = view.descendants - .filter { it.pendingIntent != null } - .sortedByDescending { it.measuredWidth * it.measuredHeight } - .firstOrNull() - ?.pendingIntent - } - - private fun setUpLensIcon() { - val lensIntent = getLensIntent(context) ?: return - - with(lensIcon) { - isVisible = true - setOnClickListener { - runCatching { context.startActivity(lensIntent) } - } - } - } - - private fun clipIconRipples() { - val cornerRadius = getCornerRadius(context, preferenceManager) - listOf(lensIcon, micIcon).forEach { - it.clipToOutline = cornerRadius > 0 - it.background = PaintDrawable(Color.TRANSPARENT).apply { - setCornerRadius(cornerRadius) - } - } - } - - private fun setUpBackground(themed: Boolean = false) { - val transparency = preferenceManager.hotseatQsbAlpha.get() - val cornerRadius = getCornerRadius(context, preferenceManager) - val baseColor = if (themed) Themes.getColorBackgroundFloating(context) else Themes.getAttrColor(context, R.attr.qsbFillColor) - val alphaValue = (transparency * 255) / 100 - val color = Color.argb(alphaValue, Color.red(baseColor), Color.green(baseColor), Color.blue(baseColor)) - val strokeColor = strokeColor - val strokeWidth = preferenceManager.hotseatQsbStrokeWidth.get() - - val backgroundDrawable = PaintDrawable(color).apply { - setCornerRadius(cornerRadius) - } - - val strokeDrawable = PaintDrawable().apply { - paint.style = Paint.Style.STROKE - paint.color = strokeColor?.colorPreferenceEntry?.lightColor?.invoke(context) ?: Themes.getColorAccent(context) - paint.strokeWidth = strokeWidth - setCornerRadius(cornerRadius) - } - - val combinedDrawable = LayerDrawable(arrayOf(backgroundDrawable, strokeDrawable)) - - val qsbBackground = if (strokeWidth != 0f) combinedDrawable else backgroundDrawable - - with(inner) { - clipToOutline = cornerRadius > 0 - background = qsbBackground - } - } - companion object { private const val LENS_PACKAGE = "com.google.ar.lens" private const val LENS_ACTIVITY = "com.google.vr.apps.ornament.app.lens.LensLauncherActivity" + fun getVoiceIntent( + provider: QsbSearchProvider, + context: Context, + ): Intent? { + val intent = if (provider.supportVoiceIntent) provider.createVoiceIntent() else null + + return if (intent == null || !resolveIntent(context, intent)) { + null + } else { + intent + } + } + fun getLensIntent(context: Context): Intent? { val lensIntent = Intent.makeMainActivity(ComponentName(LENS_PACKAGE, LENS_ACTIVITY)) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) @@ -235,10 +196,8 @@ class LawnQsbLayout(context: Context, attrs: AttributeSet?) : FrameLayout(contex fun getSearchProvider( context: Context, - preferenceManager: PreferenceManager2, + provider: QsbSearchProvider, ): QsbSearchProvider { - val provider = preferenceManager.hotseatQsbProvider.firstCached() - return if (provider == AppSearch || resolveIntent(context, provider.createSearchIntent()) || resolveIntent(context, provider.createWebsiteIntent()) @@ -249,17 +208,13 @@ class LawnQsbLayout(context: Context, attrs: AttributeSet?) : FrameLayout(contex } } - fun resolveIntent(context: Context, intent: Intent): Boolean = context.packageManager.resolveActivity(intent, 0) != null - - private fun getCornerRadius( + fun getSearchProvider( context: Context, - preferenceManager: PreferenceManager, - ): Float { - val resources = context.resources - val qsbWidgetHeight = resources.getDimension(R.dimen.qsb_widget_height) - val qsbWidgetPadding = resources.getDimension(R.dimen.qsb_widget_vertical_padding) - val innerHeight = qsbWidgetHeight - 2 * qsbWidgetPadding - return innerHeight / 2 * preferenceManager.hotseatQsbCornerRadius.get() + preferenceManager: PreferenceManager2, + ): QsbSearchProvider { + return getSearchProvider(context, preferenceManager.hotseatQsbProvider.firstCached()) } + + fun resolveIntent(context: Context, intent: Intent): Boolean = context.packageManager.resolveActivity(intent, 0) != null } } diff --git a/lawnchair/src/app/lawnchair/qsb/LawnQsbUi.kt b/lawnchair/src/app/lawnchair/qsb/LawnQsbUi.kt new file mode 100644 index 0000000000..43de850e7b --- /dev/null +++ b/lawnchair/src/app/lawnchair/qsb/LawnQsbUi.kt @@ -0,0 +1,517 @@ +package app.lawnchair.qsb + +import android.content.Context +import androidx.annotation.ColorInt +import androidx.annotation.DrawableRes +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.requiredWidth +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ripple +import androidx.compose.runtime.Composable +import androidx.compose.runtime.Immutable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color as ComposeColor +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.res.dimensionResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import app.lawnchair.qsb.providers.Google +import app.lawnchair.qsb.providers.GoogleGo +import app.lawnchair.qsb.providers.PixelSearch +import app.lawnchair.qsb.providers.QsbSearchProvider +import app.lawnchair.ui.theme.LawnchairTheme +import app.lawnchair.ui.util.addIf +import app.lawnchair.ui.util.preview.PreviewLawnchair +import com.android.launcher3.R +import com.android.launcher3.util.Themes + +/** + * Enum representing the unique identifiers for icons displayed within the Quick Search Bar (QSB). + */ +enum class QsbIconId { + SEARCH, + MIC, + LENS, + CLEAR, +} + +/** + * Represents the state and visual configuration of an individual icon within the Quick Search Bar (QSB). + * + * @property id The unique identifier for the icon (e.g., SEARCH, MIC, LENS). + * @property resId The drawable resource ID used for the icon's imagery. + * @property themed Whether the icon should adapt its colors based on the current system or launcher theme. + * @property contentDescription The accessibility label for the icon. + * @property method The specific [ThemingMethod] to apply when rendering the icon (e.g., tinting or layer-based theming). + * @property visible Whether the icon should be displayed in the UI. + */ +@Immutable +data class QsbIconState( + val id: QsbIconId, + @param:DrawableRes val resId: Int, + val themed: Boolean, + val contentDescription: String, + val method: ThemingMethod = ThemingMethod.THEME_BY_LAYER_ID, + val visible: Boolean = true, +) + +/** + * Defines the visual appearance and styling of the Quick Search Bar (QSB). + * + * @property themed Whether the background and stroke should follow the system or launcher theme colors. + * @property backgroundAlpha The transparency level of the QSB background, ranging from 0.0 to 1.0. + * @property backgroundColor The color value used for the QSB background fill. + * @property strokeColor The color value used for the QSB's outline/border. + * @property strokeWidthPx The thickness of the QSB's border in pixels. + * @property cornerRadiusPx The radius used for the rounded corners of the QSB in pixels. + */ +@Immutable +data class QsbStyle( + val themed: Boolean, + val backgroundAlpha: Float, + @param:ColorInt val backgroundColor: Int, + @param:ColorInt val strokeColor: Int, + val strokeWidthPx: Float, + val cornerRadiusPx: Float, +) + +/** + * Represents the complete visual state of the Quick Search Bar (QSB). + * + * @property contentDescription The accessibility label for the entire search bar container. + * @property startIcon The state of the primary icon displayed at the beginning of the bar (usually the search provider logo). + * @property endIcons A list of icons to be displayed at the end of the bar (e.g., Microphone, Lens, or Clear). + */ +@Immutable +data class QsbState( + val contentDescription: String, + val startIcon: QsbIconState, + val endIcons: List, +) + +/** + * Defines the click handlers for the various interactive elements within the Quick Search Bar (QSB). + * + * @property onQsbClick Callback invoked when the main body of the search bar is clicked. + * @property onStartIconClick Optional callback invoked when the leading icon (e.g., search provider logo) is clicked. + * @property onEndIconClick Callback invoked when one of the trailing icons (e.g., Mic, Lens, or Clear) is clicked, + * passing the specific [QsbIconId] of the clicked icon. + */ +@Immutable +data class QsbActions( + val onQsbClick: () -> Unit, + val onStartIconClick: (() -> Unit)? = null, + val onEndIconClick: ((id: QsbIconId) -> Unit), +) + +/** + * Builds a [QsbStyle] instance based on the provided parameters. + * + * @param context The context used to resolve colors and dimensions. + * @param themed Whether the search bar background and components should follow the system theme. + * @param backgroundAlpha The background opacity, provided as a percentage (0-100). + * @param backgroundColor The integer color value for the search bar background. + * @param cornerRadius A factor used to calculate the final corner radius. + * @param strokeColor The color of the search bar border. If null, the theme's accent color is used. + * @param strokeWidth The width of the search bar border in pixels. + * @return A [QsbStyle] object containing the processed styling configuration. + */ +fun buildQsbStyle( + context: Context, + themed: Boolean, + backgroundAlpha: Int, + backgroundColor: Int, + cornerRadius: Float, + strokeColor: Int?, + strokeWidth: Float, +) = QsbStyle( + themed = themed, + backgroundAlpha = backgroundAlpha / 100f, + backgroundColor = backgroundColor, + strokeColor = strokeColor ?: Themes.getColorAccent(context), + strokeWidthPx = strokeWidth, + cornerRadiusPx = getHotseatQsbCornerRadius(context, cornerRadius), +) + +/** + * Creates and remembers a [QsbState] tailored for the Hotseat (dock) search bar. + * + * This function handles the logic for selecting appropriate icons and theming based on the + * chosen [searchProvider] and visibility settings for the microphone and lens icons. + * + * @param searchProvider The search engine provider currently selected. + * @param themed Whether the icons should use themed (monochrome) variants if available. + * @param showMic Whether the voice search (microphone) icon should be visible. + * @param showLens Whether the Google Lens icon should be visible. + * @return A remembered [QsbState] containing the configuration for the Hotseat QSB. + */ +@Composable +fun rememberHotseatQsbState( + searchProvider: QsbSearchProvider, + themed: Boolean, + showMic: Boolean, + showLens: Boolean, +): QsbState { + val searchLabel = stringResource(R.string.label_search) + val voiceSearchLabel = stringResource(R.string.label_voice_search) + val lensLabel = stringResource(R.string.label_lens) + + return remember(searchProvider, themed, showMic, showLens, searchLabel, voiceSearchLabel, lensLabel) { + val iconRes = if (themed) searchProvider.themedIcon else searchProvider.icon + val isGoogleProvider = searchProvider == Google || searchProvider == GoogleGo || searchProvider == PixelSearch + + QsbState( + contentDescription = searchLabel, + startIcon = QsbIconState( + id = QsbIconId.SEARCH, + resId = iconRes, + themed = themed || iconRes == R.drawable.ic_qsb_search, + method = searchProvider.themingMethod, + contentDescription = searchLabel, + ), + endIcons = listOf( + QsbIconState( + id = QsbIconId.MIC, + resId = if (isGoogleProvider) R.drawable.ic_mic_color else R.drawable.ic_mic_flat, + themed = (isGoogleProvider && themed) || !isGoogleProvider, + method = if (isGoogleProvider) ThemingMethod.THEME_BY_LAYER_ID else ThemingMethod.TINT, + contentDescription = voiceSearchLabel, + visible = showMic, + ), + QsbIconState( + id = QsbIconId.LENS, + resId = R.drawable.ic_lens_color, + themed = themed, + method = ThemingMethod.THEME_BY_LAYER_ID, + contentDescription = lensLabel, + visible = showLens, + ), + ), + ) + } +} + +/** + * Creates and remembers a [QsbState] tailored for the All Apps search bar. + * + * This function handles the logic for selecting appropriate icons and theming based on the + * chosen [searchProvider] and visibility settings for the microphone, lens, and clear icons. + * + * @param searchProvider The search engine provider currently selected. + * @param themed Whether the icons should use themed (monochrome) variants if available. + * @param shouldShowIcons Whether the icons should be visible. + * @param queryEmpty Whether the search query is empty. + * @param showMic Whether the voice search (microphone) icon should be visible. + * @param showLens Whether the Google Lens icon should be visible. + * @return A remembered [QsbState] containing the configuration for the All Apps QSB. + */ +@Composable +fun rememberAllAppsQsbState( + searchProvider: QsbSearchProvider, + themed: Boolean, + shouldShowIcons: Boolean, + queryEmpty: Boolean, + showMic: Boolean, + showLens: Boolean, +): QsbState { + val searchLabel = stringResource(R.string.label_search) + val voiceSearchLabel = stringResource(R.string.label_voice_search) + val lensLabel = stringResource(R.string.label_lens) + val clearLabel = stringResource(R.string.search_input_action_clear_results) + + return remember(searchProvider, themed, shouldShowIcons, queryEmpty, showMic, showLens, searchLabel, voiceSearchLabel, lensLabel, clearLabel) { + val iconRes = if (themed && shouldShowIcons) searchProvider.themedIcon else searchProvider.icon + val resId = if (shouldShowIcons) iconRes else R.drawable.ic_qsb_search + val isGoogleProvider = searchProvider == Google || searchProvider == GoogleGo || searchProvider == PixelSearch + + QsbState( + contentDescription = searchLabel, + startIcon = QsbIconState( + id = QsbIconId.SEARCH, + resId = resId, + themed = themed || resId == R.drawable.ic_qsb_search, + method = if (shouldShowIcons) searchProvider.themingMethod else ThemingMethod.TINT, + contentDescription = searchLabel, + ), + endIcons = listOf( + QsbIconState( + id = QsbIconId.MIC, + resId = if (isGoogleProvider) R.drawable.ic_mic_color else R.drawable.ic_mic_flat, + themed = (isGoogleProvider && themed) || !isGoogleProvider, + method = if (isGoogleProvider) ThemingMethod.THEME_BY_LAYER_ID else ThemingMethod.TINT, + contentDescription = voiceSearchLabel, + visible = shouldShowIcons && showMic && queryEmpty, + ), + QsbIconState( + id = QsbIconId.LENS, + resId = R.drawable.ic_lens_color, + themed = themed, + method = ThemingMethod.THEME_BY_LAYER_ID, + contentDescription = lensLabel, + visible = shouldShowIcons && showLens && queryEmpty, + ), + QsbIconState( + id = QsbIconId.CLEAR, + resId = R.drawable.ic_remove_no_shadow, + themed = true, + method = ThemingMethod.TINT, + contentDescription = clearLabel, + visible = !queryEmpty, + ), + ), + ) + } +} + +/** + * Calculates the corner radius for the Hotseat Quick Search Bar (QSB) based on a scaling factor. + */ +fun getHotseatQsbCornerRadius(context: Context, cornerRadiusFactor: Float): Float { + val resources = context.resources + val qsbWidgetHeight = resources.getDimension(R.dimen.qsb_widget_height) + val qsbWidgetPadding = resources.getDimension(R.dimen.qsb_widget_vertical_padding) + val innerHeight = qsbWidgetHeight - 2 * qsbWidgetPadding + return innerHeight / 2 * cornerRadiusFactor +} + +/** + * Calculates the default background color for the Hotseat Quick Search Bar (QSB). + */ +fun getHotseatBackgroundColor(context: Context, themed: Boolean, themedBackgroundColor: Int? = null): Int { + return if (themed) { + themedBackgroundColor ?: Themes.getColorBackgroundFloating(context) + } else { + Themes.getAttrColor(context, R.attr.qsbFillColor) + } +} + +/** + * A Composable that represents the UI for the Quick Search Bar (QSB). + * + * This component renders a search bar with a customizable background, optional border, + * a starting icon (typically the search provider logo), and a set of trailing icons + * (such as microphone or lens) based on the provided state. + * + * @param state The visual state of the QSB, including the icons and content descriptions. + * @param style The styling configuration, including colors, transparency, and corner radius. + * @param actions The click handlers for the main bar and individual icons. + * @param modifier The [Modifier] to be applied to the QSB container. + */ +@Composable +fun LawnQsbUi( + state: QsbState, + style: QsbStyle, + actions: QsbActions, + modifier: Modifier = Modifier, +) { + val density = LocalDensity.current + + val cornerRadius = with(density) { style.cornerRadiusPx.toDp() } + val strokeWidth = with(density) { style.strokeWidthPx.toDp() } + val shape = RoundedCornerShape(cornerRadius) + + val containerModifier = modifier + .fillMaxWidth() + .semantics { contentDescription = state.contentDescription } + .clip(shape) + .background(ComposeColor(style.backgroundColor).copy(alpha = style.backgroundAlpha), shape) + .clickable( + onClick = actions.onQsbClick, + interactionSource = remember { MutableInteractionSource() }, + indication = ripple( + color = MaterialTheme.colorScheme.onSurface, + focusRingShape = shape, + ), + ) + .addIf(style.strokeWidthPx > 0f) { + border(strokeWidth, ComposeColor(style.strokeColor), shape) + } + + Row( + modifier = containerModifier, + verticalAlignment = Alignment.CenterVertically, + ) { + Box( + modifier = Modifier + .requiredWidth(dimensionResource(R.dimen.qsb_icon_width)) + .fillMaxHeight() + .then( + if (actions.onStartIconClick != null) { + Modifier + .clip(shape) + .qsbClickable( + onClick = actions.onStartIconClick, + shape = shape, + ) + } else { + Modifier + }, + ), + contentAlignment = Alignment.Center, + ) { + Image( + painter = rememberThemedIconPainter( + resId = state.startIcon.resId, + themed = state.startIcon.themed, + method = state.startIcon.method, + ), + contentDescription = state.startIcon.contentDescription, + modifier = Modifier.size(24.dp), + ) + } + + Spacer(Modifier.weight(1f)) + + state.endIcons.forEachIndexed { index, icon -> + val isLastVisible = remember(state.endIcons, index) { + state.endIcons.drop(index + 1).none { it.visible } + } + AnimatedVisibility( + visible = icon.visible, + enter = fadeIn(), + exit = fadeOut(), + ) { + QsbIcon( + icon = icon, + shape = shape, + onClick = { actions.onEndIconClick(icon.id) }, + modifier = Modifier.addIf(isLastVisible) { + offset(x = (-6).dp) + }, + ) + } + } + } +} + +/** + * A composable representing an icon button within the Quick Search Bar (QSB). + * + * @param icon the state defining the icon's resource, theming, and accessibility description. + * @param shape the shape used for clipping and the ripple indication. + * @param onClick the callback to be invoked when the icon is clicked. + * @param modifier the [Modifier] to be applied to this icon container. + */ +@Composable +fun QsbIcon( + icon: QsbIconState, + shape: Shape, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + Box( + modifier = modifier + .requiredWidth(dimensionResource(R.dimen.qsb_icon_width)) + .fillMaxHeight() + .clip(shape) + .qsbClickable( + onClick = onClick, + shape = shape, + ) + .padding(dimensionResource(R.dimen.qsb_icon_padding)), + contentAlignment = Alignment.Center, + ) { + Icon( + painter = rememberThemedIconPainter( + resId = icon.resId, + themed = icon.themed, + method = icon.method, + ), + contentDescription = icon.contentDescription, + tint = ComposeColor.Unspecified, + modifier = Modifier.fillMaxSize(), + ) + } +} + +@Composable +private fun Modifier.qsbClickable( + onClick: () -> Unit, + shape: Shape, +) = this.clickable( + onClick = onClick, + role = Role.Button, + interactionSource = remember { MutableInteractionSource() }, + indication = ripple( + color = MaterialTheme.colorScheme.onSurface, + focusRingShape = shape, + ), +) + +@PreviewLawnchair +@Composable +private fun LawnQsbUiPreview() { + LawnchairTheme { + LawnQsbUi( + state = QsbState( + contentDescription = "Search", + startIcon = QsbIconState( + id = QsbIconId.SEARCH, + resId = R.drawable.ic_qsb_search, + themed = false, + contentDescription = "Search", + method = ThemingMethod.TINT, + ), + endIcons = listOf( + QsbIconState( + id = QsbIconId.MIC, + resId = R.drawable.ic_mic_flat, + themed = false, + contentDescription = "Voice Search", + method = ThemingMethod.TINT, + ), + QsbIconState( + id = QsbIconId.LENS, + resId = R.drawable.ic_lens_color, + themed = false, + contentDescription = "Lens", + method = ThemingMethod.THEME_BY_LAYER_ID, + ), + ), + ), + style = QsbStyle( + themed = false, + backgroundAlpha = 1f, + backgroundColor = MaterialTheme.colorScheme.surfaceVariant.toArgb(), + strokeColor = MaterialTheme.colorScheme.outline.toArgb(), + strokeWidthPx = 1f, + cornerRadiusPx = 100f, + ), + actions = QsbActions( + onQsbClick = {}, + onStartIconClick = {}, + onEndIconClick = {}, + ), + modifier = Modifier + .padding(16.dp) + .height(52.dp), + ) + } +} diff --git a/lawnchair/src/app/lawnchair/qsb/QsbIconUtil.kt b/lawnchair/src/app/lawnchair/qsb/QsbIconUtil.kt index af9cae16b2..fc57658816 100644 --- a/lawnchair/src/app/lawnchair/qsb/QsbIconUtil.kt +++ b/lawnchair/src/app/lawnchair/qsb/QsbIconUtil.kt @@ -1,45 +1,84 @@ package app.lawnchair.qsb +import android.content.Context +import android.graphics.drawable.Drawable import android.graphics.drawable.LayerDrawable -import android.widget.ImageView import androidx.annotation.DrawableRes +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.graphics.painter.Painter +import androidx.compose.ui.platform.LocalContext import androidx.core.content.res.ResourcesCompat import app.lawnchair.theme.color.tokens.ColorTokens import com.android.launcher3.R +import com.google.accompanist.drawablepainter.rememberDrawablePainter -fun ImageView.setThemedIconResource( +/** + * Loads a drawable resource and applies theming based on the specified [ThemingMethod]. + * + * If [themed] is true, the function will apply colors based on the chosen method: + * - [ThemingMethod.THEME_BY_LAYER_ID]: If the drawable is a [LayerDrawable], it searches for specific + * layer IDs (e.g., `R.id.qsbIconTintPrimary`) and applies corresponding QSB color tokens. + * - [ThemingMethod.TINT]: Applies accent color tinting to the entire drawable. + */ +fun setThemedIconResource( + context: Context, @DrawableRes resId: Int, themed: Boolean, method: ThemingMethod = ThemingMethod.THEME_BY_LAYER_ID, -) { - if (themed && method == ThemingMethod.THEME_BY_LAYER_ID) { - val drawable = ResourcesCompat.getDrawable(resources, resId, null)!! - if (drawable is LayerDrawable) { - drawable.mutate() - val primary = ColorTokens.QsbIconTintPrimary.resolveColor(context) - val secondary = ColorTokens.QsbIconTintSecondary.resolveColor(context) - val tertiary = ColorTokens.QsbIconTintTertiary.resolveColor(context) - val quaternary = ColorTokens.QsbIconTintQuaternary.resolveColor(context) +): Drawable { + val drawable = requireNotNull(ResourcesCompat.getDrawable(context.resources, resId, context.theme)) { + "Unable to resolve icon drawable for resId=$resId" + }.mutate() - for (i in (0 until drawable.numberOfLayers)) { - val color = when (drawable.getId(i)) { - R.id.qsbIconTintPrimary -> primary - R.id.qsbIconTintSecondary -> secondary - R.id.qsbIconTintTertiary -> tertiary - R.id.qsbIconTintQuaternary -> quaternary - else -> 0 - } - if (color == 0) continue - - val layer = drawable.getDrawable(i) - layer.setTint(color) - } - } - setImageDrawable(drawable) - } else { - setImageResource(resId) - if (themed) setColorFilter(ColorTokens.ColorAccent.resolveColor(context)) + if (!themed) { + return drawable } + + if (method == ThemingMethod.THEME_BY_LAYER_ID && drawable is LayerDrawable) { + val primary = ColorTokens.QsbIconTintPrimary.resolveColor(context) + val secondary = ColorTokens.QsbIconTintSecondary.resolveColor(context) + val tertiary = ColorTokens.QsbIconTintTertiary.resolveColor(context) + val quaternary = ColorTokens.QsbIconTintQuaternary.resolveColor(context) + + for (i in (0 until drawable.numberOfLayers)) { + val color = when (drawable.getId(i)) { + R.id.qsbIconTintPrimary -> primary + R.id.qsbIconTintSecondary -> secondary + R.id.qsbIconTintTertiary -> tertiary + R.id.qsbIconTintQuaternary -> quaternary + else -> 0 + } + if (color == 0) continue + + drawable.getDrawable(i).setTint(color) + } + } else { + drawable.setTint(ColorTokens.ColorAccent.resolveColor(context)) + } + + return drawable +} + +/** + * Remembers a [Painter] for a themed icon resource. + * + * @param resId The drawable resource ID to load. + * @param themed Whether the icon should have theming applied. + * @param method The strategy to use for applying theme colors. + * @return A [Painter] that draws the (potentially themed) drawable resource. + */ +@Composable +fun rememberThemedIconPainter( + @DrawableRes resId: Int, + themed: Boolean, + method: ThemingMethod = ThemingMethod.THEME_BY_LAYER_ID, +): Painter { + val context = LocalContext.current + val drawable = remember(context, resId, themed, method) { + setThemedIconResource(context, resId, themed, method) + } + return rememberDrawablePainter(drawable) } enum class ThemingMethod { diff --git a/lawnchair/src/app/lawnchair/theme/drawable/DrawableTokens.kt b/lawnchair/src/app/lawnchair/theme/drawable/DrawableTokens.kt index 133734f376..7012dd9dd8 100644 --- a/lawnchair/src/app/lawnchair/theme/drawable/DrawableTokens.kt +++ b/lawnchair/src/app/lawnchair/theme/drawable/DrawableTokens.kt @@ -1,11 +1,9 @@ package app.lawnchair.theme.drawable import android.content.res.ColorStateList -import android.graphics.Color import android.graphics.drawable.Drawable import android.graphics.drawable.GradientDrawable import android.graphics.drawable.InsetDrawable -import android.graphics.drawable.LayerDrawable import android.graphics.drawable.RippleDrawable import android.graphics.drawable.StateListDrawable import androidx.appcompat.content.res.AppCompatResources @@ -61,20 +59,6 @@ object DrawableTokens { val RoundRectPrimary = ResourceDrawableToken(R.drawable.round_rect_primary) .setColor(ColorTokens.ColorPrimary) - @JvmField - val SearchInputFg = ResourceDrawableToken(R.drawable.search_input_fg) - .mutate { context, scheme, darkTheme -> - val shape = getDrawable(0) as GradientDrawable - shape.setColor(ColorTokens.SearchboxHighlight.resolveColor(context, scheme, darkTheme)) - } - - @JvmField - val SearchInputFgBlur = ResourceDrawableToken(R.drawable.search_input_fg) - .mutate { context, scheme, darkTheme -> - val shape = getDrawable(0) as GradientDrawable - shape.setColor(ColorTokens.SearchboxHighlightBlur.resolveColor(context, scheme, darkTheme)) - } - @JvmField val SingleItemPrimary = ResourceDrawableToken(R.drawable.single_item_primary) .setColor(ColorTokens.PopupColorPrimary) diff --git a/lawnchair/src/app/lawnchair/ui/preferences/components/search/DockSearchPreferences.kt b/lawnchair/src/app/lawnchair/ui/preferences/components/search/DockSearchPreferences.kt index 443f1a2530..679d2208ca 100644 --- a/lawnchair/src/app/lawnchair/ui/preferences/components/search/DockSearchPreferences.kt +++ b/lawnchair/src/app/lawnchair/ui/preferences/components/search/DockSearchPreferences.kt @@ -2,7 +2,10 @@ package app.lawnchair.ui.preferences.components.search import androidx.compose.animation.Crossfade import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.TipsAndUpdates @@ -11,8 +14,10 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import app.lawnchair.hotseat.DisabledHotseat @@ -22,7 +27,18 @@ import app.lawnchair.preferences.PreferenceAdapter import app.lawnchair.preferences.getAdapter import app.lawnchair.preferences.preferenceManager import app.lawnchair.preferences2.preferenceManager2 +import app.lawnchair.qsb.LawnQsbLayout +import app.lawnchair.qsb.LawnQsbUi +import app.lawnchair.qsb.QsbActions +import app.lawnchair.qsb.buildQsbStyle +import app.lawnchair.qsb.getHotseatBackgroundColor +import app.lawnchair.qsb.providers.Google +import app.lawnchair.qsb.providers.PixelSearch import app.lawnchair.qsb.providers.QsbSearchProvider +import app.lawnchair.qsb.rememberHotseatQsbState +import app.lawnchair.theme.UiColorMode +import app.lawnchair.theme.color.ColorOption +import app.lawnchair.theme.color.tokens.ColorTokens import app.lawnchair.ui.preferences.components.NavigationActionPreference import app.lawnchair.ui.preferences.components.colorpreference.ColorPreference import app.lawnchair.ui.preferences.components.controls.ListPreference @@ -32,8 +48,8 @@ import app.lawnchair.ui.preferences.components.controls.SwitchPreference import app.lawnchair.ui.preferences.components.layout.ExpandAndShrink import app.lawnchair.ui.preferences.components.layout.PreferenceGroup import app.lawnchair.ui.preferences.components.layout.PreferenceTemplate -import app.lawnchair.ui.preferences.destinations.DockPreferencesPreview import app.lawnchair.ui.preferences.navigation.DockSearchProvider +import app.lawnchair.ui.theme.isSelectedThemeDark import com.android.launcher3.R @Composable @@ -49,6 +65,8 @@ fun DockSearchPreference( val qsbCornerAdapter = prefs.hotseatQsbCornerRadius.getAdapter() val qsbAlphaAdapter = prefs.hotseatQsbAlpha.getAdapter() val qsbHotseatStrokeWidth = prefs.hotseatQsbStrokeWidth.getAdapter() + val strokeColorStyleAdapter = prefs2.strokeColorStyle.getAdapter() + val hotseatQsbProviderAdapter by prefs2.hotseatQsbProvider.getAdapter() Crossfade(isHotseatEnabled.state.value, label = "transition", modifier = modifier) { hotseatEnabled -> val isLawnchairHotseat = hotseatModeAdapter.state.value == LawnchairHotseat @@ -63,12 +81,18 @@ fun DockSearchPreference( } ExpandAndShrink(visible = hotseatModeAdapter.state.value != DisabledHotseat) { Column { - DockPreferencesPreview() + DockSearchBarPreview( + provider = hotseatQsbProviderAdapter, + themed = themeQsbAdapter.state.value, + cornerRadiusFactor = qsbCornerAdapter.state.value, + transparency = qsbAlphaAdapter.state.value, + strokeWidth = qsbHotseatStrokeWidth.state.value, + strokeColor = strokeColorStyleAdapter.state.value, + ) } } ExpandAndShrink(visible = isLawnchairHotseat) { Column { - val hotseatQsbProviderAdapter by preferenceManager2().hotseatQsbProvider.getAdapter() PreferenceGroup( heading = stringResource(R.string.search_bar_settings), ) { @@ -153,6 +177,69 @@ fun DockSearchPreference( } } +@Composable +private fun DockSearchBarPreview( + provider: QsbSearchProvider, + themed: Boolean, + cornerRadiusFactor: Float, + transparency: Int, + strokeWidth: Float, + strokeColor: ColorOption, + modifier: Modifier = Modifier, +) { + val context = LocalContext.current + val searchProvider = provider + val supportsLens = searchProvider == Google || searchProvider == PixelSearch + val voiceIntent = remember(searchProvider, context) { + LawnQsbLayout.getVoiceIntent(searchProvider, context) + } + val lensIntent = remember(supportsLens, context) { + if (supportsLens) LawnQsbLayout.getLensIntent(context) else null + } + + PreferenceGroup( + heading = stringResource(id = R.string.preview_label), + ) { + Item { + Box( + modifier = modifier + .padding(horizontal = 16.dp) + .fillMaxWidth() + .height(dimensionResource(id = R.dimen.qsb_widget_height) + 24.dp), + contentAlignment = Alignment.Center, + ) { + LawnQsbUi( + state = rememberHotseatQsbState( + searchProvider, + themed, + showMic = voiceIntent != null, + showLens = lensIntent != null, + ), + style = buildQsbStyle( + context = context, + themed = themed, + backgroundColor = getHotseatBackgroundColor( + context, + themed, + getThemedQsbBackgroundColor(), + ), + cornerRadius = cornerRadiusFactor, + backgroundAlpha = transparency, + strokeWidth = strokeWidth, + // Use light color as strokeColor is a static color that doesn't use darkColor + strokeColor = strokeColor.colorPreferenceEntry.lightColor.invoke(context), + ), + actions = QsbActions( + onQsbClick = {}, + onEndIconClick = {}, + ), + modifier = Modifier.height(48.dp), + ) + } + } + } +} + @Composable private fun HotseatModePreference( adapter: PreferenceAdapter, @@ -177,3 +264,11 @@ private fun HotseatModePreference( modifier = modifier, ) } + +@Composable +private fun getThemedQsbBackgroundColor(): Int { + return ColorTokens.ColorBackground.resolveColor( + LocalContext.current, + if (isSelectedThemeDark) UiColorMode.Dark else UiColorMode.Light, + ) +}