Merge branch '12-device-search' into 12-dev

This commit is contained in:
Suphon Thanakornpakapong committed 2021-11-03 18:49:01 +07:00
commit b93878528e
22 files changed
+558 -92

No files matched your search

+1
View File
@@ -20,6 +20,7 @@
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="com.google.android.apps.nexuslauncher.permission.QSB"/>
<permission
android:name="${packageName}.permission.READ_SETTINGS"
@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<app.lawnchair.allapps.SearchResultIconRow xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:launcher="http://schemas.android.com/apk/res-auto"
android:id="@+id/search_result_small_icon_row"
android:layout_width="match_parent"
android:layout_height="@dimen/search_result_small_row_height"
android:orientation="horizontal"
@@ -47,7 +48,7 @@
android:textSize="@dimen/search_result_hero_title_size" />
<TextView
android:id="@+id/delimeter"
android:id="@+id/delimiter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="start|center"
@@ -26,7 +26,7 @@
android:paddingStart="@dimen/search_result_padding">
<TextView
android:id="@id/title"
android:id="@+id/title"
style="@style/AllAppsSearchResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
@@ -39,7 +39,7 @@
android:textSize="@dimen/search_result_hero_title_size" />
<TextView
android:id="@id/subtitle"
android:id="@+id/subtitle"
style="@style/AllAppsSearchResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
+2
View File
@@ -54,7 +54,9 @@
<dimen name="search_result_padding">16dp</dimen>
<dimen name="search_result_radius">4dp</dimen>
<dimen name="search_result_row_height">88dp</dimen>
<dimen name="search_result_row_medium_height">72dp</dimen>
<dimen name="search_result_small_row_height">56dp</dimen>
<dimen name="search_result_subtitle_padding_start">4dp</dimen>
<!-- smartspace -->
<dimen name="smartspaceAmbientShadowBlur">1.5dp</dimen>
+7
View File
@@ -190,4 +190,11 @@
<string name="corner_radius_label">Corner Radius</string>
<string name="search_bar_label">Search Bar</string>
<string name="apply_accent_color_label">Apply Accent Color</string>
<string name="show_search_result_types">Show in Search Results</string>
<string name="search_pref_result_people_desc">Contacts, conversations, and more</string>
<string name="search_pref_result_people_title">People</string>
<string name="search_pref_result_shortcuts_desc">Show Shortcuts for Apps and People</string>
<string name="search_pref_result_shortcuts_title">Shortcuts</string>
<string name="search_pref_result_tips_title">Pixel Tips</string>
</resources>
@@ -21,7 +21,7 @@ import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import app.lawnchair.launcher
import app.lawnchair.preferences.PreferenceManager
import app.lawnchair.search.LawnchairAppSearchAlgorithm
import app.lawnchair.search.LawnchairSearchAlgorithm
import com.android.launcher3.Insettable
import com.android.launcher3.LauncherState
import com.android.launcher3.R
@@ -30,7 +30,6 @@ import com.android.launcher3.allapps.search.AllAppsSearchBarController
import com.android.launcher3.search.SearchCallback
import com.android.launcher3.util.Themes
import java.util.*
import kotlin.collections.ArrayList
import kotlin.math.max
class AllAppsSearchInput(context: Context, attrs: AttributeSet?) : LinearLayout(context, attrs),
@@ -139,7 +138,7 @@ class AllAppsSearchInput(context: Context, attrs: AttributeSet?) : LinearLayout(
apps = appsView.apps
this.appsView = appsView
searchBarController.initialize(
LawnchairAppSearchAlgorithm(launcher),
LawnchairSearchAlgorithm.create(context),
input, launcher, this
)
input.initialize(appsView)
@@ -2,9 +2,11 @@ package app.lawnchair.allapps
import android.content.ComponentName
import android.content.Context
import android.content.pm.PackageManager
import android.content.pm.ShortcutInfo
import android.os.UserHandle
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isInvisible
@@ -16,8 +18,13 @@ import com.android.launcher3.BubbleTextView
import com.android.launcher3.LauncherAppState
import com.android.launcher3.LauncherSettings
import com.android.launcher3.R
import com.android.launcher3.icons.BitmapInfo
import com.android.launcher3.icons.IconProvider
import com.android.launcher3.icons.LauncherIcons
import com.android.launcher3.model.data.ItemInfoWithIcon
import com.android.launcher3.model.data.PackageItemInfo
import com.android.launcher3.model.data.SearchActionItemInfo
import com.android.launcher3.model.data.SearchActionItemInfo.*
import com.android.launcher3.model.data.WorkspaceItemInfo
import com.android.launcher3.touch.ItemClickHandler
import com.android.launcher3.touch.ItemLongClickListener
@@ -63,10 +70,12 @@ class SearchResultIcon(context: Context, attrs: AttributeSet?) : BubbleTextView(
setForceHideDot(true)
val extras = target.extras
val iconComponentKey = extras.getString(SearchResultView.EXTRA_ICON_COMPONENT_KEY)
?.let { ComponentKey.fromString(it) }
when {
target.searchAction != null -> {
allowLongClick = false
bindFromAction(target)
bindFromAction(target, iconComponentKey == null)
}
target.shortcutInfo != null -> {
allowLongClick = true
@@ -79,8 +88,6 @@ class SearchResultIcon(context: Context, attrs: AttributeSet?) : BubbleTextView(
bindFromApp(componentName, target.userHandle)
}
}
val iconComponentKey = extras.getString(SearchResultView.EXTRA_ICON_COMPONENT_KEY)
?.let { ComponentKey.fromString(it) }
if (iconComponentKey != null) {
bindIconComponentKey(iconComponentKey)
}
@@ -104,7 +111,7 @@ class SearchResultIcon(context: Context, attrs: AttributeSet?) : BubbleTextView(
}
}
private fun bindFromAction(target: SearchTargetCompat) {
private fun bindFromAction(target: SearchTargetCompat, bindIcon: Boolean) {
val action = target.searchAction ?: return
val info = SearchActionItemInfo(
action.icon,
@@ -119,8 +126,30 @@ class SearchResultIcon(context: Context, attrs: AttributeSet?) : BubbleTextView(
if (action.pendingIntent != null) {
info.pendingIntent = action.pendingIntent
}
applyFromSearchActionItemInfo(info)
val extras = action.extras
if (extras != null) {
if (extras.getBoolean("should_start_for_result") || target.resultType == 16 /* settings */) {
info.setFlags(FLAG_SHOULD_START_FOR_RESULT)
} else if (extras.getBoolean("should_start")) {
info.setFlags(FLAG_SHOULD_START)
}
if (extras.getBoolean("badge_with_package")) {
info.setFlags(FLAG_BADGE_WITH_PACKAGE)
}
if (extras.getBoolean("badge_with_component_name")) {
info.setFlags(FLAG_BADGE_WITH_COMPONENT_NAME)
}
if (extras.getBoolean("primary_icon_from_title")) {
info.setFlags(FLAG_PRIMARY_ICON_FROM_TITLE)
}
}
notifyApplied(info)
if (bindIcon) {
MODEL_EXECUTOR.handler.postAtFrontOfQueue {
populateSearchActionItemInfo(target, info)
runOnMainThread { applyFromSearchActionItemInfo(info) }
}
}
}
private fun bindIconComponentKey(iconComponentKey: ComponentKey) {
@@ -163,10 +192,54 @@ class SearchResultIcon(context: Context, attrs: AttributeSet?) : BubbleTextView(
ItemClickHandler.INSTANCE.onClick(v)
}
private fun populateSearchActionItemInfo(
target: SearchTargetCompat,
info: SearchActionItemInfo
) {
val action = target.searchAction!!
LauncherIcons.obtain(context).use { li ->
val icon = action.icon
val packageIcon = getPackageIcon(target.packageName, target.userHandle)
info.bitmap = when {
info.hasFlags(FLAG_PRIMARY_ICON_FROM_TITLE) ->
li.createIconBitmap("${info.title[0]}", packageIcon.color)
icon == null -> packageIcon
else -> li.createBadgedIconBitmap(icon.loadDrawable(context), info.user, false)
}
if (info.hasFlags(FLAG_BADGE_WITH_COMPONENT_NAME) && target.extras.containsKey("class")) {
try {
val iconProvider = IconProvider(context)
val componentName = ComponentName(target.packageName, target.extras.getString("class")!!)
val activityInfo = context.packageManager.getActivityInfo(componentName, 0)
val activityIcon = iconProvider.getIcon(activityInfo)
val bitmap = li.createIconBitmap(activityIcon, 1f, iconSize)
val bitmapInfo = BitmapInfo.of(bitmap, packageIcon.color)
info.bitmap = li.badgeBitmap(info.bitmap.icon, bitmapInfo)
} catch (ignore: PackageManager.NameNotFoundException) {
}
} else if (info.hasFlags(FLAG_BADGE_WITH_PACKAGE) && info.bitmap != packageIcon) {
info.bitmap = li.badgeBitmap(info.bitmap.icon, packageIcon)
}
}
}
private fun getPackageIcon(packageName: String, user: UserHandle): BitmapInfo {
val las = LauncherAppState.getInstance(context)
val info = PackageItemInfo(packageName)
info.user = user
las.iconCache.getTitleAndIconForApp(info, false)
return info.bitmap
}
override fun onLongClick(v: View): Boolean {
if (!allowLongClick) {
return false
}
return ItemLongClickListener.INSTANCE_ALL_APPS.onLongClick(v)
}
fun hasFlag(flag: Int) = hasFlag(flags, flag)
}
@@ -1,12 +1,17 @@
package app.lawnchair.allapps
import android.content.Context
import android.text.TextUtils
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.ViewCompat
import androidx.core.view.isVisible
import androidx.core.view.setPadding
import app.lawnchair.allapps.SearchResultView.Companion.FLAG_HIDE_SUBTITLE
import app.lawnchair.search.SearchTargetCompat
import com.android.app.search.LayoutType
import com.android.launcher3.R
import com.android.launcher3.touch.ItemClickHandler
import com.android.launcher3.views.BubbleTextHolder
@@ -14,9 +19,11 @@ import com.android.launcher3.views.BubbleTextHolder
class SearchResultIconRow(context: Context, attrs: AttributeSet?) :
LinearLayout(context, attrs), SearchResultView, BubbleTextHolder {
private var isSmall = false
private lateinit var icon: SearchResultIcon
private lateinit var title: TextView
private lateinit var subtitle: TextView
private var delimiter: View? = null
private lateinit var shortcutIcons: Array<SearchResultIcon>
private var boundId = ""
@@ -24,6 +31,7 @@ class SearchResultIconRow(context: Context, attrs: AttributeSet?) :
override fun onFinishInflate() {
super.onFinishInflate()
isSmall = id == R.id.search_result_small_icon_row
icon = ViewCompat.requireViewById(this, R.id.icon)
icon.importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO
val iconSize = icon.iconSize
@@ -35,6 +43,7 @@ class SearchResultIconRow(context: Context, attrs: AttributeSet?) :
title = ViewCompat.requireViewById(this, R.id.title)
subtitle = ViewCompat.requireViewById(this, R.id.subtitle)
subtitle.isVisible = false
delimiter = findViewById(R.id.delimiter)
setOnClickListener(icon)
shortcutIcons = listOf(
@@ -71,6 +80,33 @@ class SearchResultIconRow(context: Context, attrs: AttributeSet?) :
tag = it
}
bindShortcuts(shortcuts)
var showDelimiter = true
if (isSmall) {
val textRows = ViewCompat.requireViewById<LinearLayout>(this, R.id.text_rows)
if (target.layoutType == LayoutType.HORIZONTAL_MEDIUM_TEXT) {
showDelimiter = false
layoutParams.height = resources.getDimensionPixelSize(R.dimen.search_result_row_medium_height)
textRows.orientation = VERTICAL
subtitle.setPadding(0, 0, 0, 0)
} else {
layoutParams.height = resources.getDimensionPixelSize(R.dimen.search_result_small_row_height)
textRows.orientation = HORIZONTAL
val subtitleStartPadding = resources.getDimensionPixelSize(R.dimen.search_result_subtitle_padding_start)
subtitle.setPaddingRelative(subtitleStartPadding, 0, 0, 0)
}
}
setSubtitleText(target.searchAction?.subtitle, showDelimiter)
}
private fun setSubtitleText(subtitleText: CharSequence?, showDelimiter: Boolean) {
if (TextUtils.isEmpty(subtitleText) || icon.hasFlag(FLAG_HIDE_SUBTITLE)) {
subtitle.isVisible = false
delimiter?.isVisible = false
} else {
subtitle.text = subtitleText
subtitle.isVisible = true
delimiter?.isVisible = showDelimiter
}
}
private fun bindShortcuts(shortcuts: List<SearchTargetCompat>) {
@@ -116,6 +116,12 @@ class PreferenceManager private constructor(private val context: Context) : Base
private val fontCache = FontCache.INSTANCE.get(context)
val workspaceFont = FontPref("pref_workspaceFont", fontCache.uiText, recreate)
val deviceSearch = BoolPref("device_search", false, recreate)
val searchResultShortcuts = BoolPref("pref_searchResultShortcuts", true)
val searchResultPeople = BoolPref("pref_searchResultPeople", true)
val searchResultPixelTips = BoolPref("pref_searchResultPixelTips", true)
val searchResultSettings = BoolPref("pref_searchResultSettings", false)
val enableIconSelection = BoolPref("pref_enableIconSelection", false)
val themedIcons = BoolPref("themed_icons", false)
val hotseatQsbCornerRadius = FloatPref("pref_hotseatQsbCornerRadius", 1F, recreate)
@@ -4,55 +4,60 @@ import android.content.Context
import android.content.pm.ShortcutInfo
import android.graphics.drawable.Icon
import android.os.Bundle
import android.os.Handler
import android.os.Process
import app.lawnchair.allapps.SearchItemBackground
import app.lawnchair.allapps.SearchResultView
import app.lawnchair.launcher
import app.lawnchair.preferences.PreferenceManager
import com.android.app.search.LayoutType
import com.android.launcher3.LauncherAppState
import com.android.launcher3.R
import com.android.launcher3.allapps.AllAppsGridAdapter.AdapterItem
import com.android.launcher3.allapps.search.DefaultAppSearchAlgorithm
import com.android.launcher3.allapps.AllAppsGridAdapter
import com.android.launcher3.model.AllAppsList
import com.android.launcher3.model.BaseModelUpdateTask
import com.android.launcher3.model.BgDataModel
import com.android.launcher3.model.data.AppInfo
import com.android.launcher3.popup.PopupPopulator
import com.android.launcher3.search.SearchCallback
import com.android.launcher3.search.StringMatcherUtility
import com.android.launcher3.shortcuts.ShortcutRequest
import com.android.launcher3.util.ComponentKey
import com.android.launcher3.util.Executors
import com.android.launcher3.util.PackageManagerHelper
import me.xdrop.fuzzywuzzy.FuzzySearch
import me.xdrop.fuzzywuzzy.algorithms.WeightedRatio
import java.util.*
import kotlin.collections.ArrayList
class LawnchairAppSearchAlgorithm(private val context: Context) :
DefaultAppSearchAlgorithm(context) {
class LawnchairAppSearchAlgorithm(context: Context) : LawnchairSearchAlgorithm(context) {
private val appState = LauncherAppState.getInstance(context)
private val resultHandler = Handler(Executors.MAIN_EXECUTOR.looper)
private val useFuzzySearch by PreferenceManager.getInstance(context).useFuzzySearch
private val iconBackground = SearchItemBackground(
context, showBackground = false,
roundTop = true, roundBottom = true
)
private val normalBackground = SearchItemBackground(
context, showBackground = true,
roundTop = true, roundBottom = true
)
private val topBackground = SearchItemBackground(
context, showBackground = true,
roundTop = true, roundBottom = false
)
private val centerBackground = SearchItemBackground(
context, showBackground = true,
roundTop = false, roundBottom = false
)
private val bottomBackground = SearchItemBackground(
context, showBackground = true,
roundTop = false, roundBottom = true
)
private val marketSearchComponent = resolveMarketSearchActivity()
override fun getResult(
override fun doSearch(query: String, callback: SearchCallback<AllAppsGridAdapter.AdapterItem>) {
appState.model.enqueueModelUpdateTask(object : BaseModelUpdateTask() {
override fun execute(
app: LauncherAppState?,
dataModel: BgDataModel?,
apps: AllAppsList?
) {
val result = getResult(apps!!.data, query)
resultHandler.post { callback.onSearchResult(query, result) }
}
})
}
override fun cancel(interruptActiveRequests: Boolean) {
if (interruptActiveRequests) {
resultHandler.removeCallbacksAndMessages(null)
}
}
private fun getResult(
apps: MutableList<AppInfo>,
query: String
): ArrayList<AdapterItem> {
): ArrayList<AllAppsGridAdapter.AdapterItem> {
val appResults = if (useFuzzySearch) {
fuzzySearch(apps, query)
} else {
@@ -70,21 +75,9 @@ class LawnchairAppSearchAlgorithm(private val context: Context) :
if (results.isEmpty()) {
results.add(getEmptySearchItem(query))
}
val items = results
.mapIndexed { index, target ->
val isFirst = index == 0
val isLast = index == results.lastIndex
val isIcon = target.layoutType == LayoutType.ICON_SINGLE_VERTICAL_TEXT
val background = when {
isIcon -> iconBackground
isFirst && isLast -> normalBackground
isFirst -> topBackground
isLast -> bottomBackground
else -> centerBackground
}
SearchAdapterItem.createAdapterItem(index, target, background)
}
return ArrayList(LawnchairSearchAdapterProvider.decorateSearchResults(items))
val adapterItems = transformSearchResults(results)
LawnchairSearchAdapterProvider.setFirstItemQuickLaunch(adapterItems)
return ArrayList(adapterItems)
}
private fun getShortcuts(app: AppInfo): List<ShortcutInfo> {
@@ -102,7 +95,7 @@ class LawnchairAppSearchAlgorithm(private val context: Context) :
return apps.asSequence()
.filter { StringMatcherUtility.matches(queryTextLower, it.title.toString(), matcher) }
.take(MAX_RESULTS_COUNT)
.take(maxResultsCount)
.toList()
}
@@ -112,7 +105,7 @@ class LawnchairAppSearchAlgorithm(private val context: Context) :
{ it.title.toString() }, WeightedRatio(), 65
)
return matches.take(MAX_RESULTS_COUNT)
return matches.take(maxResultsCount)
.map { it.referent }
}
@@ -143,4 +136,8 @@ class LawnchairAppSearchAlgorithm(private val context: Context) :
}
return createSearchTarget(id, action, extras)
}
companion object {
private const val maxResultsCount = 5
}
}
@@ -0,0 +1,163 @@
package app.lawnchair.search;
import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
import static com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR;
import android.app.search.Query;
import android.app.search.SearchContext;
import android.app.search.SearchSession;
import android.app.search.SearchTarget;
import android.app.search.SearchUiManager;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.allapps.AllAppsGridAdapter;
import com.android.launcher3.search.SearchCallback;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import app.lawnchair.preferences.PreferenceChangeListener;
import app.lawnchair.preferences.PreferenceManager;
public class LawnchairDeviceSearchAlgorithm extends LawnchairSearchAlgorithm implements PreferenceChangeListener {
private final PreferenceManager mPrefs;
private SearchSession mSearchSession;
private PendingQuery mActiveQuery;
public LawnchairDeviceSearchAlgorithm(@NonNull Context context) {
super(context);
mPrefs = PreferenceManager.getInstance(context);
createSearchSession();
mPrefs.getSearchResultShortcuts().addListener(this);
mPrefs.getSearchResultPeople().addListener(this);
mPrefs.getSearchResultPixelTips().addListener(this);
mPrefs.getSearchResultSettings().addListener(this);
}
@Override
public void onPreferenceChange() {
createSearchSession();
}
private void createSearchSession() {
UI_HELPER_EXECUTOR.execute(() -> {
if (mSearchSession != null) {
mSearchSession.destroy();
}
Context context = getContext();
Bundle extras = new Bundle();
InvariantDeviceProfile idp = LauncherAppState.getIDP(context);
extras.putInt("launcher.gridSize", idp.numDatabaseAllAppsColumns);
extras.putBoolean("allowlist_enabled", false);
extras.putInt("launcher.maxInlineIcons", 3);
int resultTypes = 1 /* apps */ | 2 /* shortcuts */;
if (mPrefs.getSearchResultShortcuts().get()) {
resultTypes = resultTypes | 1546;
}
if (mPrefs.getSearchResultPeople().get()) {
resultTypes = resultTypes | 4;
}
if (mPrefs.getSearchResultPixelTips().get()) {
resultTypes = resultTypes | 8192;
extras.putString("tips_source", "superpacks_tips_source");
}
if (mPrefs.getSearchResultSettings().get()) {
resultTypes = resultTypes | 80;
extras.putString("settings_source", "superpacks_settings_source");
}
SearchContext searchContext = new SearchContext(resultTypes, 200, extras);
SearchUiManager searchManager = context.getSystemService(SearchUiManager.class);
SearchSession searchSession = searchManager.createSearchSession(searchContext);
MAIN_EXECUTOR.post(() -> mSearchSession = searchSession);
});
}
@Override
public void doSearch(String query, SearchCallback<AllAppsGridAdapter.AdapterItem> callback) {
if (mActiveQuery != null) {
mActiveQuery.cancel();
}
if (mSearchSession == null) {
return;
}
mActiveQuery = new PendingQuery(query, callback);
Query searchQuery = new Query(query, System.currentTimeMillis(), null);
mSearchSession.query(searchQuery, MAIN_EXECUTOR, mActiveQuery);
}
@Override
public void cancel(boolean interruptActiveRequests) {
if (mActiveQuery != null) {
mActiveQuery.cancel();
}
}
@Override
public void destroy() {
super.destroy();
UI_HELPER_EXECUTOR.execute(() -> {
if (mSearchSession != null) {
mSearchSession.destroy();
}
});
mPrefs.getSearchResultShortcuts().removeListener(this);
mPrefs.getSearchResultPeople().removeListener(this);
mPrefs.getSearchResultPixelTips().removeListener(this);
mPrefs.getSearchResultSettings().removeListener(this);
}
private class PendingQuery implements Consumer<List<SearchTarget>> {
private final String mQuery;
private final SearchCallback<AllAppsGridAdapter.AdapterItem> mCallback;
private boolean mCanceled;
public PendingQuery(String query, SearchCallback<AllAppsGridAdapter.AdapterItem> callback) {
mQuery = query;
mCallback = callback;
}
@Override
public void accept(List<SearchTarget> platformTargets) {
if (!mCanceled) {
Log.d("DeviceSearchAlg", "got search results");
List<SearchTargetCompat> targets = platformTargets
.stream()
.map(SearchTargetCompat::wrap)
.collect(Collectors.toList());
targets.forEach(target -> {
//noinspection StringBufferReplaceableByString
String itemInfo = new StringBuilder()
.append("type=")
.append(target.getResultType())
.append(", layout=")
.append(target.getLayoutType())
.append(", id=")
.append(target.getId())
.toString();
Log.d("DeviceSearchAlg", itemInfo);
});
List<SearchAdapterItem> adapterItems = transformSearchResults(targets);
LawnchairSearchAdapterProvider.setFirstItemQuickLaunch(adapterItems);
mCallback.onSearchResult(mQuery, new ArrayList<>(adapterItems));
}
}
public void cancel() {
mCanceled = true;
}
}
}
@@ -8,6 +8,7 @@ import androidx.core.util.containsKey
import app.lawnchair.LawnchairLauncher
import app.lawnchair.allapps.SearchItemDecorator
import app.lawnchair.allapps.SearchResultView
import app.lawnchair.allapps.SearchResultView.Companion.EXTRA_QUICK_LAUNCH
import com.android.app.search.LayoutType
import com.android.launcher3.R
import com.android.launcher3.allapps.AllAppsContainerView
@@ -71,14 +72,18 @@ class LawnchairSearchAdapterProvider(
LayoutType.ICON_SINGLE_VERTICAL_TEXT to SEARCH_RESULT_ICON,
LayoutType.ICON_HORIZONTAL_TEXT to SEARCH_RESULT_ICON_ROW,
LayoutType.SMALL_ICON_HORIZONTAL_TEXT to SEARCH_RESULT_SMALL_ICON_ROW,
LayoutType.DIVIDER to SEARCH_RESULT_DIVIDER,
LayoutType.HORIZONTAL_MEDIUM_TEXT to SEARCH_RESULT_SMALL_ICON_ROW,
LayoutType.EMPTY_DIVIDER to SEARCH_RESULT_DIVIDER,
)
fun decorateSearchResults(items: List<SearchAdapterItem>): List<SearchAdapterItem> {
items.firstOrNull()?.searchTarget?.extras?.apply {
putBoolean(SearchResultView.EXTRA_QUICK_LAUNCH, true)
@JvmStatic
fun setFirstItemQuickLaunch(items: List<SearchAdapterItem>) {
val hasQuickLaunch = items.any { it.searchTarget.extras.getBoolean(EXTRA_QUICK_LAUNCH, false) }
if (!hasQuickLaunch) {
items.firstOrNull()?.searchTarget?.extras?.apply {
putBoolean(EXTRA_QUICK_LAUNCH, true)
}
}
return items
}
}
}
@@ -0,0 +1,88 @@
package app.lawnchair.search
import android.content.Context
import app.lawnchair.LawnchairApp
import app.lawnchair.allapps.SearchItemBackground
import app.lawnchair.preferences.PreferenceManager
import app.lawnchair.search.SearchTargetCompat.RESULT_TYPE_APPLICATION
import app.lawnchair.search.SearchTargetCompat.RESULT_TYPE_SHORTCUT
import com.android.app.search.LayoutType
import com.android.app.search.LayoutType.*
import com.android.launcher3.BuildConfig
import com.android.launcher3.Utilities
import com.android.launcher3.allapps.AllAppsGridAdapter
import com.android.launcher3.search.SearchAlgorithm
abstract class LawnchairSearchAlgorithm(
val context: Context
) : SearchAlgorithm<AllAppsGridAdapter.AdapterItem> {
private val iconBackground = SearchItemBackground(
context, showBackground = false,
roundTop = true, roundBottom = true
)
private val normalBackground = SearchItemBackground(
context, showBackground = true,
roundTop = true, roundBottom = true
)
private val topBackground = SearchItemBackground(
context, showBackground = true,
roundTop = true, roundBottom = false
)
private val centerBackground = SearchItemBackground(
context, showBackground = true,
roundTop = false, roundBottom = false
)
private val bottomBackground = SearchItemBackground(
context, showBackground = true,
roundTop = false, roundBottom = true
)
protected fun transformSearchResults(results: List<SearchTargetCompat>): List<SearchAdapterItem> {
val filtered = results
.filter { it.packageName != BuildConfig.APPLICATION_ID }
.filter { LawnchairSearchAdapterProvider.viewTypeMap[it.layoutType] != null }
.removeDuplicateDividers()
return filtered
.mapIndexedNotNull { index, target ->
val isFirst = index == 0 || filtered[index - 1].isDivider
val isLast = index == filtered.lastIndex || filtered[index + 1].isDivider
val background = when {
target.layoutType == ICON_SINGLE_VERTICAL_TEXT -> iconBackground
target.layoutType == EMPTY_DIVIDER -> iconBackground
isFirst && isLast -> normalBackground
isFirst -> topBackground
isLast -> bottomBackground
else -> centerBackground
}
SearchAdapterItem.createAdapterItem(index, target, background)
}
}
companion object {
fun isDeviceSearchEnabled(context: Context): Boolean {
val prefs = PreferenceManager.getInstance(context)
return prefs.deviceSearch.get() && Utilities.ATLEAST_S && LawnchairApp.isRecentsEnabled
}
fun create(context: Context): LawnchairSearchAlgorithm = when {
isDeviceSearchEnabled(context) -> LawnchairDeviceSearchAlgorithm(context)
else -> LawnchairAppSearchAlgorithm(context)
}
}
}
private fun Iterable<SearchTargetCompat>.removeDuplicateDividers(): List<SearchTargetCompat> {
var previousWasDivider = true
return filter { item ->
val isDivider = item.layoutType == EMPTY_DIVIDER
val remove = isDivider && previousWasDivider
previousWasDivider = isDivider
!remove
}
}
private val SearchTargetCompat.isApp get() = resultType == RESULT_TYPE_APPLICATION
private val SearchTargetCompat.isShortcut get() = resultType == RESULT_TYPE_SHORTCUT
private val SearchTargetCompat.isDivider get() = layoutType == EMPTY_DIVIDER
@@ -18,6 +18,7 @@ package app.lawnchair.search;
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.app.search.SearchAction;
import android.content.Intent;
import android.graphics.drawable.Icon;
import android.os.Bundle;
@@ -108,6 +109,20 @@ public final class SearchActionCompat implements Parcelable {
}
}
private SearchActionCompat(SearchAction from) {
this(
from.getId(),
from.getTitle(),
from.getIcon(),
from.getSubtitle(),
from.getContentDescription(),
from.getPendingIntent(),
from.getIntent(),
from.getUserHandle(),
from.getExtras()
);
}
/**
* Returns the unique id of this object.
*/
@@ -216,6 +231,14 @@ public final class SearchActionCompat implements Parcelable {
return str;
}
public static SearchActionCompat wrap(SearchAction action) {
if (action != null) {
return new SearchActionCompat(action);
} else {
return null;
}
}
public static final @NonNull Parcelable.Creator<SearchActionCompat> CREATOR =
new Parcelable.Creator<SearchActionCompat>() {
public SearchActionCompat createFromParcel(Parcel in) {
@@ -14,9 +14,10 @@ data class SearchAdapterItem(
pos: Int,
target: SearchTargetCompat,
background: SearchItemBackground?
): SearchAdapterItem {
): SearchAdapterItem? {
val type = LawnchairSearchAdapterProvider.viewTypeMap[target.layoutType] ?: return null
return SearchAdapterItem(target, background).apply {
viewType = LawnchairSearchAdapterProvider.viewTypeMap[target.layoutType]!!
viewType = type
position = pos
}
}
@@ -15,6 +15,8 @@
*/
package app.lawnchair.search;
import android.app.search.SearchAction;
import android.app.search.SearchTarget;
import android.app.slice.SliceManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.pm.PackageManager;
@@ -187,6 +189,23 @@ public final class SearchTargetCompat implements Parcelable {
}
}
private SearchTargetCompat(SearchTarget from) {
this(
from.getResultType(),
from.getLayoutType(),
from.getId(),
from.getParentId(),
from.getScore(), from.isHidden(),
from.getPackageName(),
from.getUserHandle(),
SearchActionCompat.wrap(from.getSearchAction()),
from.getShortcutInfo(),
from.getSliceUri(),
from.getAppWidgetProviderInfo(),
from.getExtras()
);
}
/**
* Retrieves the result type {@see SearchResultType}.
*/
@@ -321,6 +340,10 @@ public final class SearchTargetCompat implements Parcelable {
parcel.writeBundle(mExtras);
}
public static SearchTargetCompat wrap(SearchTarget target) {
return new SearchTargetCompat(target);
}
/**
* @see Parcelable.Creator
*/
@@ -42,7 +42,7 @@ fun createSearchTarget(id: String, action: SearchActionCompat, extras: Bundle =
LayoutType.ICON_HORIZONTAL_TEXT,
id
)
.setPackageName(BuildConfig.APPLICATION_ID)
.setPackageName("")
.setUserHandle(Process.myUserHandle())
.setSearchAction(action)
.setExtras(extras)
@@ -55,7 +55,7 @@ fun createDividerTarget(): SearchTargetCompat {
LayoutType.DIVIDER,
"divider"
)
.setPackageName(BuildConfig.APPLICATION_ID)
.setPackageName("")
.setUserHandle(Process.myUserHandle())
.build()
}
@@ -2,6 +2,7 @@ package app.lawnchair.ui
import android.util.TypedValue
import android.widget.TextView
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.LocalTextStyle
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
@@ -23,7 +24,7 @@ fun <T : TextView> AndroidText(
style: TextStyle = LocalTextStyle.current
) {
val mergedStyle = LocalTextStyle.current.merge(style)
val textColor = toIntColor(mergedStyle.color)
val textColor = toIntColor(LocalContentColor.current)
val textSize = with(LocalDensity.current) { mergedStyle.fontSize.toPx() }
AndroidView(
factory = { textView.apply { text = "" } },
@@ -24,6 +24,7 @@ import androidx.navigation.NavGraphBuilder
import app.lawnchair.preferences.getAdapter
import app.lawnchair.preferences.not
import app.lawnchair.preferences.preferenceManager
import app.lawnchair.search.LawnchairSearchAlgorithm
import app.lawnchair.ui.preferences.components.*
import com.android.launcher3.R
@@ -59,8 +60,9 @@ fun AppDrawerPreferences() {
)
SuggestionsPreference()
}
val deviceSearchEnabled = LawnchairSearchAlgorithm.isDeviceSearchEnabled(LocalContext.current)
val showSearchBar = !prefs.hideAppSearchBar.getAdapter()
PreferenceGroup(heading = stringResource(id = R.string.pref_category_search)) {
val showSearchBar = !prefs.hideAppSearchBar.getAdapter()
SwitchPreference(
label = stringResource(id = R.string.show_app_search_bar),
adapter = showSearchBar
@@ -75,10 +77,36 @@ fun AppDrawerPreferences() {
adapter = prefs.searchAutoShowKeyboard.getAdapter(),
label = stringResource(id = R.string.pref_search_auto_show_keyboard),
)
if (!deviceSearchEnabled) {
SwitchPreference(
adapter = prefs.useFuzzySearch.getAdapter(),
label = stringResource(id = R.string.fuzzy_search_title),
description = stringResource(id = R.string.fuzzy_search_desc)
)
}
}
}
}
if (deviceSearchEnabled) {
AnimatedVisibility(
visible = showSearchBar.state.value,
enter = expandVertically() + fadeIn(),
exit = shrinkVertically() + fadeOut()
) {
PreferenceGroup(heading = stringResource(id = R.string.show_search_result_types)) {
SwitchPreference(
adapter = prefs.useFuzzySearch.getAdapter(),
label = stringResource(id = R.string.fuzzy_search_title),
description = stringResource(id = R.string.fuzzy_search_desc)
adapter = prefs.searchResultShortcuts.getAdapter(),
label = stringResource(id = R.string.search_pref_result_shortcuts_title),
description = stringResource(id = R.string.search_pref_result_shortcuts_desc)
)
SwitchPreference(
adapter = prefs.searchResultPeople.getAdapter(),
label = stringResource(id = R.string.search_pref_result_people_title),
description = stringResource(id = R.string.search_pref_result_people_desc)
)
SwitchPreference(
adapter = prefs.searchResultPixelTips.getAdapter(),
label = stringResource(id = R.string.search_pref_result_tips_title)
)
}
}
@@ -60,5 +60,10 @@ private fun PreferenceManager.getDebugFlags(): List<PrefEntry<Boolean>> {
return listOf(
enableIconSelection,
themedIcons,
deviceSearch,
searchResultShortcuts,
searchResultPeople,
searchResultPixelTips,
searchResultSettings,
)
}
@@ -7,6 +7,11 @@ import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ArrowDropDown
import androidx.compose.material.icons.rounded.Clear
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -179,7 +184,7 @@ private fun VariantDropdown(
TextButton(
onClick = { showVariants = true },
colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colors.onBackground),
colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onBackground),
contentPadding = VariantButtonContentPadding
) {
AndroidText(
@@ -43,29 +43,31 @@ fun PreferenceGroup(
dividersToSkip: Int = 0,
content: @Composable () -> Unit
) {
PreferenceGroupHeading(heading, isFirstChild)
val columnModifier = Modifier
.padding(horizontal = 16.dp)
.smartBorder(
1.dp,
color = Material3Theme.colorScheme.onBackground.copy(alpha = 0.16f),
shape = MaterialTheme.shapes.large
)
.clip(shape = MaterialTheme.shapes.large)
if (showDividers) {
DividerColumn(
modifier = columnModifier,
startIndent = dividerStartIndent,
endIndent = dividerEndIndent,
content = content,
dividersToSkip = dividersToSkip
)
} else {
Column(modifier = columnModifier) {
content()
Column {
PreferenceGroupHeading(heading, isFirstChild)
val columnModifier = Modifier
.padding(horizontal = 16.dp)
.smartBorder(
1.dp,
color = Material3Theme.colorScheme.onBackground.copy(alpha = 0.16f),
shape = MaterialTheme.shapes.large
)
.clip(shape = MaterialTheme.shapes.large)
if (showDividers) {
DividerColumn(
modifier = columnModifier,
startIndent = dividerStartIndent,
endIndent = dividerEndIndent,
content = content,
dividersToSkip = dividersToSkip
)
} else {
Column(modifier = columnModifier) {
content()
}
}
PreferenceGroupDescription(description, showDescription)
}
PreferenceGroupDescription(description, showDescription)
}
@Composable