Add image buttons and exclusive launcher actions
This commit is contained in:
1 parent
8d604a5807
commit
74c725e8d7
23 files changed
+871
-107
No files matched your search
@@ -48,14 +48,6 @@ class LauncherViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _degraded = MutableStateFlow<String?>(null)
|
||||
val degraded: StateFlow<String?> = _degraded.asStateFlow()
|
||||
|
||||
val statusBarPx: Float by lazy {
|
||||
systemDimen("status_bar_height", fallbackDp = 24f)
|
||||
}
|
||||
|
||||
val navBarPx: Float by lazy {
|
||||
systemDimen("navigation_bar_height", fallbackDp = 16f)
|
||||
}
|
||||
|
||||
init {
|
||||
// 壁纸与布局并行:壁纸解码比 JSON 解析慢得多,串行会让首帧多等 100ms+
|
||||
viewModelScope.launch {
|
||||
@@ -78,15 +70,9 @@ class LauncherViewModel(app: Application) : AndroidViewModel(app) {
|
||||
|
||||
fun onItemClick(def: ItemDef) {
|
||||
val ctx = getApplication<Application>()
|
||||
val opened = when (def.type) {
|
||||
"app_icon" -> AppLaunch.launchPackage(ctx, def.payload.pkg.orEmpty())
|
||||
"shortcut" -> {
|
||||
val target = def.payload.intent?.takeIf { it.isNotBlank() }
|
||||
?: def.payload.pkg.orEmpty()
|
||||
AppLaunch.launchUriOrAction(ctx, target)
|
||||
}
|
||||
else -> return
|
||||
}
|
||||
if (def.type !in setOf("app_icon", "shortcut", "image")) return
|
||||
if (def.type == "image" && !def.payload.hasLaunchTarget()) return
|
||||
val opened = AppLaunch.launch(ctx, def.payload, appIcon = def.type == "app_icon")
|
||||
if (!opened) Toast.makeText(ctx, "找不到应用或无法启动", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
|
||||
@@ -116,17 +102,7 @@ class LauncherViewModel(app: Application) : AndroidViewModel(app) {
|
||||
page.items.filter { it.type == "app_icon" }.forEach { item ->
|
||||
val pkg = item.payload.pkg ?: return@forEach
|
||||
val px = (item.w * s * 0.78f).toInt().coerceIn(24, 384)
|
||||
icons.load(pkg, px)
|
||||
}
|
||||
}
|
||||
|
||||
private fun systemDimen(name: String, fallbackDp: Float): Float {
|
||||
val res = getApplication<Application>().resources
|
||||
val id = res.getIdentifier(name, "dimen", "android")
|
||||
return if (id > 0) {
|
||||
res.getDimensionPixelSize(id).toFloat()
|
||||
} else {
|
||||
fallbackDp * res.displayMetrics.density
|
||||
if (item.payload.iconStyle != "image") icons.load(pkg, px, item.payload.iconStyle ?: layout.iconStyle)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.ttstd.compose.launcher
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
@@ -11,10 +12,14 @@ import androidx.activity.ComponentActivity
|
||||
import androidx.activity.OnBackPressedCallback
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.activity.SystemBarStyle
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.navigationBars
|
||||
import androidx.compose.foundation.layout.statusBars
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
@@ -25,6 +30,7 @@ import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
@@ -77,7 +83,11 @@ class MainActivity : ComponentActivity() {
|
||||
val t0 = SystemClock.uptimeMillis()
|
||||
|
||||
// 状态栏/导航条透明,让壁纸铺满整屏 —— 留白不可见的前提
|
||||
enableEdgeToEdge()
|
||||
enableEdgeToEdge(
|
||||
statusBarStyle = SystemBarStyle.dark(android.graphics.Color.TRANSPARENT),
|
||||
navigationBarStyle = SystemBarStyle.dark(android.graphics.Color.TRANSPARENT),
|
||||
)
|
||||
if (Build.VERSION.SDK_INT >= 29) window.isNavigationBarContrastEnforced = false
|
||||
|
||||
// 桌面按返回键什么都不该发生(默认会退出到上一个应用,体验上像"桌面崩了")
|
||||
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
|
||||
@@ -91,17 +101,22 @@ class MainActivity : ComponentActivity() {
|
||||
val wallpaper by vm.wallpaper.collectAsState()
|
||||
val degraded by vm.degraded.collectAsState()
|
||||
|
||||
val density = LocalDensity.current
|
||||
val statusBar = WindowInsets.statusBars.getTop(density).toFloat()
|
||||
val navigationBar = WindowInsets.navigationBars.getBottom(density).toFloat()
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
LauncherCanvas(
|
||||
layout = layout,
|
||||
icons = vm.icons,
|
||||
statusBarPx = vm.statusBarPx,
|
||||
bottomInsetPx = vm.navBarPx,
|
||||
statusBarPx = statusBar,
|
||||
bottomInsetPx = navigationBar,
|
||||
wallpaper = wallpaper,
|
||||
widgetHost = widgets,
|
||||
onWidgetBind = { key, provider ->
|
||||
try {
|
||||
widgets.requestBind(key, provider, { bindWidget.launch(it) }, ::configureWidget)
|
||||
if (!widgets.requestBind(key, provider, { bindWidget.launch(it) }, ::configureWidget)) {
|
||||
Toast.makeText(this@MainActivity, "此设备找不到该微件", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
} catch (error: RuntimeException) {
|
||||
Toast.makeText(this@MainActivity, "无法打开小组件授权", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.ttstd.compose.launcher.core
|
||||
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
@@ -19,30 +20,67 @@ object AppLaunch {
|
||||
|
||||
private const val TAG = "AppLaunch"
|
||||
|
||||
fun launchPackage(context: Context, pkg: String): Boolean {
|
||||
if (pkg.isBlank()) return false
|
||||
val intent = context.packageManager.getLaunchIntentForPackage(pkg) ?: run {
|
||||
Log.w(TAG, "no launch intent for $pkg")
|
||||
return false
|
||||
}
|
||||
intent.addFlags(
|
||||
Intent.FLAG_ACTIVITY_NEW_TASK or
|
||||
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED,
|
||||
)
|
||||
return start(context, intent)
|
||||
}
|
||||
private val settingsActions = mapOf(
|
||||
"ACTION_SETTINGS" to Settings.ACTION_SETTINGS,
|
||||
"ACTION_WIFI_SETTINGS" to Settings.ACTION_WIFI_SETTINGS,
|
||||
"ACTION_BLUETOOTH_SETTINGS" to Settings.ACTION_BLUETOOTH_SETTINGS,
|
||||
"ACTION_WIRELESS_SETTINGS" to Settings.ACTION_WIRELESS_SETTINGS,
|
||||
"ACTION_AIRPLANE_MODE_SETTINGS" to Settings.ACTION_AIRPLANE_MODE_SETTINGS,
|
||||
"ACTION_DISPLAY_SETTINGS" to Settings.ACTION_DISPLAY_SETTINGS,
|
||||
"ACTION_SOUND_SETTINGS" to Settings.ACTION_SOUND_SETTINGS,
|
||||
"ACTION_LOCATION_SOURCE_SETTINGS" to Settings.ACTION_LOCATION_SOURCE_SETTINGS,
|
||||
"ACTION_APPLICATION_SETTINGS" to Settings.ACTION_APPLICATION_SETTINGS,
|
||||
"ACTION_DATE_SETTINGS" to Settings.ACTION_DATE_SETTINGS,
|
||||
"ACTION_ACCESSIBILITY_SETTINGS" to Settings.ACTION_ACCESSIBILITY_SETTINGS,
|
||||
)
|
||||
|
||||
/** 快捷方式里的 intent 字段:支持 action://uri 形式,解析失败就当包名处理 */
|
||||
fun launchUriOrAction(context: Context, raw: String): Boolean {
|
||||
if (raw.isBlank()) return false
|
||||
val intent = runCatching {
|
||||
if (raw.contains("://")) Intent.parseUri(raw, Intent.URI_INTENT_SCHEME)
|
||||
else null
|
||||
}.getOrNull()
|
||||
?: context.packageManager.getLaunchIntentForPackage(raw)
|
||||
?: return false
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
return start(context, intent)
|
||||
fun launch(context: Context, payload: PayloadDef, appIcon: Boolean): Boolean {
|
||||
val pkg = payload.pkg.orEmpty().trim()
|
||||
val cls = payload.className.orEmpty().trim()
|
||||
val action = payload.settingsAction.orEmpty()
|
||||
val raw = payload.intent.orEmpty()
|
||||
val intent = when (payload.launchMode(appIcon)) {
|
||||
"settings" -> Intent(settingsActions[action] ?: return false)
|
||||
"component" -> {
|
||||
val component = ComponentName.unflattenFromString(payload.componentName.orEmpty().trim())
|
||||
?: return false
|
||||
Intent(Intent.ACTION_MAIN).setComponent(component)
|
||||
}
|
||||
"application" -> {
|
||||
if (pkg.isEmpty()) return false
|
||||
if (cls.isEmpty()) {
|
||||
context.packageManager.getLaunchIntentForPackage(pkg)
|
||||
?.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)
|
||||
} else {
|
||||
val target = when {
|
||||
cls.startsWith(".") -> pkg + cls
|
||||
'.' !in cls -> "$pkg.$cls"
|
||||
else -> cls
|
||||
}
|
||||
Intent(Intent.ACTION_MAIN).setComponent(ComponentName(pkg, target))
|
||||
}
|
||||
}
|
||||
"intent" -> runCatching {
|
||||
if (raw.contains("://")) Intent.parseUri(raw, Intent.URI_INTENT_SCHEME)
|
||||
else context.packageManager.getLaunchIntentForPackage(raw)
|
||||
}.getOrNull()
|
||||
else -> null
|
||||
} ?: return false
|
||||
|
||||
for (extra in payload.extras) {
|
||||
val key = extra.key.trim()
|
||||
if (key.isEmpty()) return false
|
||||
val value = extra.value.trim()
|
||||
when (extra.type) {
|
||||
"string" -> intent.putExtra(key, extra.value)
|
||||
"boolean" -> intent.putExtra(key, value.toBooleanStrictOrNull() ?: return false)
|
||||
"int" -> intent.putExtra(key, value.toIntOrNull() ?: return false)
|
||||
"long" -> intent.putExtra(key, value.toLongOrNull() ?: return false)
|
||||
"double" -> intent.putExtra(key, value.toDoubleOrNull()?.takeIf { it.isFinite() } ?: return false)
|
||||
else -> return false
|
||||
}
|
||||
}
|
||||
return start(context, intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}
|
||||
|
||||
private fun start(context: Context, intent: Intent): Boolean {
|
||||
|
||||
+42
-6
@@ -6,6 +6,10 @@ import android.appwidget.AppWidgetManager
|
||||
import android.appwidget.AppWidgetProviderInfo
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.util.AttributeSet
|
||||
import android.widget.FrameLayout
|
||||
import android.widget.TextView
|
||||
import android.view.Gravity
|
||||
import android.content.Intent
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import android.os.Build
|
||||
@@ -19,7 +23,10 @@ class AppWidgetHostController(
|
||||
hostId: Int = loadOrCreateHostId(context),
|
||||
) : WidgetHostProvider {
|
||||
|
||||
private val host = AppWidgetHost(context, hostId)
|
||||
private val host = object : AppWidgetHost(context, hostId) {
|
||||
override fun onCreateView(context: Context, appWidgetId: Int, info: AppWidgetProviderInfo): AppWidgetHostView =
|
||||
CompatibleWidgetView(context)
|
||||
}
|
||||
private val manager = AppWidgetManager.getInstance(context)
|
||||
|
||||
private val bindings = context.getSharedPreferences("widget_bindings", Context.MODE_PRIVATE)
|
||||
@@ -51,19 +58,21 @@ class AppWidgetHostController(
|
||||
}
|
||||
}
|
||||
|
||||
fun requestBind(key: String, provider: String, launch: (Intent) -> Unit, configure: (Int) -> Unit) {
|
||||
val info = resolveProvider(provider) ?: return
|
||||
if (pending != null || boundId(key, info) != null) return
|
||||
fun requestBind(key: String, provider: String, launch: (Intent) -> Unit, configure: (Int) -> Unit): Boolean {
|
||||
val info = resolveProvider(provider) ?: return false
|
||||
if (pending != null || boundId(key, info) != null) return true
|
||||
val id = host.allocateAppWidgetId()
|
||||
pending = PendingBinding(key, provider, id)
|
||||
try {
|
||||
if (manager.bindAppWidgetIdIfAllowed(id, info.provider)) {
|
||||
completeAuthorization(true, configure)
|
||||
return
|
||||
return true
|
||||
}
|
||||
launch(Intent(AppWidgetManager.ACTION_APPWIDGET_BIND)
|
||||
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id)
|
||||
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.provider))
|
||||
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.provider)
|
||||
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER_PROFILE, info.profile))
|
||||
return true
|
||||
} catch (error: RuntimeException) {
|
||||
finishBinding(false)
|
||||
throw error
|
||||
@@ -173,6 +182,33 @@ class AppWidgetHostController(
|
||||
return manager.installedProviders.firstOrNull { it.provider == cn }
|
||||
}
|
||||
|
||||
private class CompatibleWidgetView(context: Context) : AppWidgetHostView(context) {
|
||||
override fun generateLayoutParams(attrs: AttributeSet): FrameLayout.LayoutParams =
|
||||
try {
|
||||
super.generateLayoutParams(attrs)
|
||||
} catch (_: UnsupportedOperationException) {
|
||||
// Some providers omit a root size in RemoteViews. Use the host's assigned bounds.
|
||||
val dimensions = context.obtainStyledAttributes(attrs, intArrayOf(
|
||||
android.R.attr.layout_width, android.R.attr.layout_height,
|
||||
))
|
||||
try {
|
||||
FrameLayout.LayoutParams(
|
||||
dimensions.getLayoutDimension(0, LayoutParams.MATCH_PARENT),
|
||||
dimensions.getLayoutDimension(1, LayoutParams.MATCH_PARENT),
|
||||
Gravity.CENTER,
|
||||
)
|
||||
} finally {
|
||||
dimensions.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
override fun getErrorView(): View = TextView(context).apply {
|
||||
text = "微件暂时无法显示"
|
||||
setTextColor(android.graphics.Color.WHITE)
|
||||
gravity = Gravity.CENTER
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val PREF = "widget_host"
|
||||
private const val KEY_HOST_ID = "host_id"
|
||||
|
||||
@@ -3,8 +3,12 @@ package com.ttstd.compose.launcher.core
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.Path
|
||||
import android.graphics.RectF
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.drawable.BitmapDrawable
|
||||
import android.graphics.drawable.AdaptiveIconDrawable
|
||||
import android.graphics.drawable.ColorDrawable
|
||||
import android.graphics.drawable.Drawable
|
||||
import android.util.LruCache
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -21,11 +25,11 @@ import kotlinx.coroutines.withContext
|
||||
* ===========================================================================*/
|
||||
class IconLoader(private val context: Context) {
|
||||
|
||||
// 内存上限按 1/8 可用内存给,最多 256 张
|
||||
// 图标和图片共享按 KiB 计量的缓存。
|
||||
private val cache = object : LruCache<String, Bitmap>(
|
||||
(Runtime.getRuntime().maxMemory() / 8 / 1024).toInt().coerceIn(32, 256)
|
||||
(Runtime.getRuntime().maxMemory() / 8 / 1024).toInt().coerceIn(4096, 32768)
|
||||
) {
|
||||
override fun sizeOf(key: String, value: Bitmap): Int = 1
|
||||
override fun sizeOf(key: String, value: Bitmap): Int = (value.byteCount / 1024).coerceAtLeast(1)
|
||||
}
|
||||
|
||||
private val pm: PackageManager get() = context.packageManager
|
||||
@@ -34,14 +38,14 @@ class IconLoader(private val context: Context) {
|
||||
* @param sizePx 目标边长的**像素**值,由 CanvasMapper 算出的 item 宽度决定,
|
||||
* 不要在调用处写死 dp —— 这是不同分辨率下图标大小一致的唯一办法。
|
||||
*/
|
||||
suspend fun load(pkg: String, sizePx: Int): Bitmap? = withContext(Dispatchers.IO) {
|
||||
suspend fun load(pkg: String, sizePx: Int, style: String = "system"): Bitmap? = withContext(Dispatchers.IO) {
|
||||
val px = sizePx.coerceIn(24, 512)
|
||||
val key = "$pkg@$px"
|
||||
val key = "$pkg@$px:$style"
|
||||
cache.get(key)?.let { return@withContext it }
|
||||
|
||||
val bmp = runCatching {
|
||||
val drawable = pm.getApplicationIcon(pkg)
|
||||
drawable.toBitmap(px)
|
||||
drawable.toBitmap(px, style)
|
||||
}.getOrNull()
|
||||
|
||||
if (bmp != null) cache.put(key, bmp)
|
||||
@@ -55,17 +59,51 @@ class IconLoader(private val context: Context) {
|
||||
|
||||
fun clear() = cache.evictAll()
|
||||
|
||||
private fun Drawable.toBitmap(size: Int): Bitmap {
|
||||
if (this is BitmapDrawable && bitmap != null) {
|
||||
val src = bitmap
|
||||
if (src.width == size && src.height == size) return src
|
||||
return Bitmap.createScaledBitmap(src, size, size, true)
|
||||
}
|
||||
// 自适应图标要按目标尺寸重绘,直接 draw 到同一张画布上
|
||||
suspend fun loadImage(id: String): Bitmap? = withContext(Dispatchers.IO) {
|
||||
if (!LayoutImages.validId(id)) return@withContext null
|
||||
val key = "image:$id"
|
||||
cache.get(key) ?: BitmapFactory.decodeFile(LayoutImages.file(context, id).path)?.also { cache.put(key, it) }
|
||||
}
|
||||
|
||||
private fun Drawable.toBitmap(size: Int, style: String): Bitmap {
|
||||
val out = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(out)
|
||||
setBounds(0, 0, size, size)
|
||||
draw(canvas)
|
||||
val side = size.toFloat()
|
||||
val adaptive = this as? AdaptiveIconDrawable
|
||||
if (style == "original" || style == "system" && adaptive != null) {
|
||||
drawFitted(canvas, size, 0)
|
||||
return out
|
||||
}
|
||||
val mask = Path()
|
||||
when (style) {
|
||||
"circle" -> mask.addCircle(side / 2, side / 2, side / 2, Path.Direction.CW)
|
||||
"rounded" -> mask.addRoundRect(RectF(0f, 0f, side, side), side * .24f, side * .24f, Path.Direction.CW)
|
||||
else -> {
|
||||
val shape = AdaptiveIconDrawable(ColorDrawable(0), ColorDrawable(0))
|
||||
shape.setBounds(0, 0, size, size)
|
||||
mask.set(shape.iconMask)
|
||||
}
|
||||
}
|
||||
canvas.clipPath(mask)
|
||||
if (adaptive != null) {
|
||||
adaptive.setBounds(0, 0, size, size)
|
||||
adaptive.background?.draw(canvas)
|
||||
adaptive.foreground?.draw(canvas)
|
||||
} else {
|
||||
canvas.drawColor(0xffe7ecf4.toInt())
|
||||
drawFitted(canvas, size, (size * .16f).toInt())
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private fun Drawable.drawFitted(canvas: Canvas, size: Int, padding: Int) {
|
||||
val usable = size - 2 * padding
|
||||
val ratio = intrinsicWidth.coerceAtLeast(1).toFloat() / intrinsicHeight.coerceAtLeast(1)
|
||||
val width = if (ratio >= 1f) usable else (usable * ratio).toInt().coerceAtLeast(1)
|
||||
val height = if (ratio <= 1f) usable else (usable / ratio).toInt().coerceAtLeast(1)
|
||||
val left = (size - width) / 2
|
||||
val top = (size - height) / 2
|
||||
setBounds(left, top, left + width, top + height)
|
||||
draw(canvas)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.ttstd.compose.launcher.core
|
||||
|
||||
import android.content.Context
|
||||
import java.io.File
|
||||
|
||||
internal object LayoutImages {
|
||||
private val idPattern = Regex("[a-f0-9]{64}")
|
||||
const val MAX_BYTES = 512 * 1024
|
||||
|
||||
fun validId(id: String?) = id != null && idPattern.matches(id)
|
||||
|
||||
fun file(context: Context, id: String): File {
|
||||
require(validId(id))
|
||||
return File(File(context.filesDir, "layout-images"), id)
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ data class LauncherLayout(
|
||||
val canvas: CanvasDef = CanvasDef(),
|
||||
val fit: FitDef = FitDef(),
|
||||
val pages: List<PageDef> = emptyList(),
|
||||
val iconStyle: String = "system",
|
||||
)
|
||||
|
||||
@Serializable
|
||||
@@ -87,7 +88,29 @@ data class PayloadDef(
|
||||
val provider: String? = null,
|
||||
val intent: String? = null,
|
||||
val radius: Int? = null,
|
||||
)
|
||||
val imageId: String? = null,
|
||||
val iconStyle: String? = null,
|
||||
val className: String? = null,
|
||||
val settingsAction: String? = null,
|
||||
val launchMode: String? = null,
|
||||
val componentName: String? = null,
|
||||
val extras: List<IntentExtra> = emptyList(),
|
||||
) {
|
||||
fun launchMode(appIcon: Boolean = false): String = launchMode ?: when {
|
||||
appIcon -> "application"
|
||||
!settingsAction.isNullOrBlank() -> "settings"
|
||||
!componentName.isNullOrBlank() -> "component"
|
||||
!className.isNullOrBlank() -> "application"
|
||||
!intent.isNullOrBlank() -> "intent"
|
||||
!pkg.isNullOrBlank() -> "application"
|
||||
else -> "none"
|
||||
}
|
||||
|
||||
fun hasLaunchTarget() = launchMode() != "none"
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class IntentExtra(val key: String, val type: String, val value: String)
|
||||
|
||||
/* =============================================================================
|
||||
* 解析:宽容但不放纵
|
||||
@@ -175,10 +198,15 @@ object LayoutValidator {
|
||||
"widget" -> if (!(it.payload.provider ?: "").contains('/')) {
|
||||
out += Issue(Level.ERROR, who, "provider 需形如 com.x/.Widget")
|
||||
}
|
||||
"shortcut", "dock_bg" -> Unit
|
||||
"image", "shortcut", "dock_bg" -> Unit
|
||||
else -> out += Issue(Level.WARN, who, "未知类型 ${it.type},将被跳过")
|
||||
}
|
||||
|
||||
val imageId = it.payload.imageId
|
||||
if ((imageId != null || it.type == "image" || it.payload.iconStyle == "image") &&
|
||||
!LayoutImages.validId(imageId)
|
||||
) out += Issue(Level.ERROR, who, "图片资源 ID 无效")
|
||||
|
||||
if (it.y < c.safeTop) out += Issue(Level.WARN, who, "顶部进入安全区")
|
||||
if (it.y + it.h > c.designHeight - c.safeBottom) {
|
||||
out += Issue(Level.WARN, who, "底部进入安全区")
|
||||
|
||||
@@ -25,7 +25,7 @@ import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.Response
|
||||
|
||||
class RemoteLayoutSync(context: Context, private val repo: LayoutRepository) {
|
||||
class RemoteLayoutSync(private val context: Context, private val repo: LayoutRepository) {
|
||||
data class Connection(val server: String, val token: String)
|
||||
|
||||
private val prefs = context.getSharedPreferences("layout_sync", Context.MODE_PRIVATE)
|
||||
@@ -150,6 +150,10 @@ class RemoteLayoutSync(context: Context, private val repo: LayoutRepository) {
|
||||
output.toByteArray().decodeToString(throwOnInvalidSequence = true)
|
||||
}
|
||||
currentCoroutineContext().ensureActive()
|
||||
val parsed = LayoutCodec.parse(payload)
|
||||
if (parsed !is LayoutCodec.ParseResult.Ok) throw IOException("布局验证失败")
|
||||
val imageIds = parsed.layout.pages.flatMap { page -> page.items.mapNotNull { it.payload.imageId } }.toSet()
|
||||
for (id in imageIds) downloadImage(config, id)
|
||||
repo.save(payload).getOrThrow()
|
||||
etag = connection.getHeaderField("ETag")
|
||||
repo.layout.value?.revision
|
||||
@@ -163,6 +167,49 @@ class RemoteLayoutSync(context: Context, private val repo: LayoutRepository) {
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun downloadImage(config: Connection, id: String) {
|
||||
val target = LayoutImages.file(context, id)
|
||||
if (target.isFile) return
|
||||
currentCoroutineContext().ensureActive()
|
||||
val url = endpoint(config.server).resolve("./images/$id").toURL()
|
||||
val request = url.openConnection() as HttpURLConnection
|
||||
try {
|
||||
request.instanceFollowRedirects = false
|
||||
request.connectTimeout = 5_000
|
||||
request.readTimeout = 5_000
|
||||
request.setRequestProperty("Authorization", "Bearer " + config.token)
|
||||
if (request.responseCode != 200) throw IOException("图片资源下载失败")
|
||||
val bytes = request.inputStream.use { input ->
|
||||
val output = ByteArrayOutputStream()
|
||||
val buffer = ByteArray(8192)
|
||||
val deadline = SystemClock.elapsedRealtime() + 15_000
|
||||
while (true) {
|
||||
currentCoroutineContext().ensureActive()
|
||||
if (SystemClock.elapsedRealtime() > deadline) throw IOException("图片下载超时")
|
||||
val count = input.read(buffer)
|
||||
if (count < 0) break
|
||||
if (output.size() + count > LayoutImages.MAX_BYTES) throw IOException("图片超过大小限制")
|
||||
output.write(buffer, 0, count)
|
||||
}
|
||||
output.toByteArray()
|
||||
}
|
||||
val digest = java.security.MessageDigest.getInstance("SHA-256").digest(bytes)
|
||||
if (digest.joinToString("") { "%02x".format(it) } != id) throw IOException("图片校验失败")
|
||||
target.parentFile?.mkdirs()
|
||||
val file = android.util.AtomicFile(target)
|
||||
val stream = file.startWrite()
|
||||
try {
|
||||
stream.write(bytes)
|
||||
file.finishWrite(stream)
|
||||
} catch (error: Exception) {
|
||||
file.failWrite(stream)
|
||||
throw error
|
||||
}
|
||||
} finally {
|
||||
request.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
private fun endpoint(address: String): URI {
|
||||
val base = runCatching { URI(address) }.getOrNull()
|
||||
val scheme = base?.scheme?.lowercase()
|
||||
|
||||
@@ -136,6 +136,7 @@ fun LauncherCanvas(
|
||||
beyondViewportPageCount = 1, // 预组合相邻页,翻页不白屏
|
||||
) { pageIndex ->
|
||||
CanvasPage(
|
||||
iconStyle = layout.iconStyle,
|
||||
page = pages[pageIndex],
|
||||
canvas = layout.canvas,
|
||||
fit = layout.fit.toFitConfig(),
|
||||
@@ -157,7 +158,7 @@ fun LauncherCanvas(
|
||||
current = pagerState.currentPage,
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomCenter)
|
||||
.padding(bottom = 18.dp),
|
||||
.padding(bottom = with(LocalDensity.current) { bottomInsetPx.toDp() } + 18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -165,6 +166,7 @@ fun LauncherCanvas(
|
||||
|
||||
@Composable
|
||||
private fun CanvasPage(
|
||||
iconStyle: String,
|
||||
page: PageDef,
|
||||
canvas: CanvasDef,
|
||||
fit: FitConfig,
|
||||
@@ -221,6 +223,7 @@ private fun CanvasPage(
|
||||
) {
|
||||
CanvasItemView(
|
||||
def = def,
|
||||
iconStyle = iconStyle,
|
||||
widgetKey = widgetBindingKey(page.index, def.id),
|
||||
placed = p,
|
||||
icons = icons,
|
||||
@@ -238,6 +241,7 @@ private fun CanvasPage(
|
||||
@Composable
|
||||
private fun CanvasItemView(
|
||||
def: ItemDef,
|
||||
iconStyle: String,
|
||||
widgetKey: String,
|
||||
placed: PlacedItem,
|
||||
icons: IconLoader,
|
||||
@@ -249,6 +253,8 @@ private fun CanvasItemView(
|
||||
when (def.type) {
|
||||
"app_icon" -> AppIconView(
|
||||
pkg = def.payload.pkg.orEmpty(),
|
||||
style = def.payload.iconStyle ?: iconStyle,
|
||||
imageId = def.payload.imageId,
|
||||
label = def.payload.label.orEmpty(),
|
||||
sizePx = (placed.width * 0.78f).roundToInt(),
|
||||
labelPx = placed.width * 0.19f,
|
||||
@@ -265,6 +271,23 @@ private fun CanvasItemView(
|
||||
onLongClick = onLongClick,
|
||||
)
|
||||
|
||||
"image" -> {
|
||||
val bitmap by produceState<Bitmap?>(null, def.payload.imageId) {
|
||||
value = def.payload.imageId?.let { icons.loadImage(it) }
|
||||
}
|
||||
val image = bitmap
|
||||
if (image != null) {
|
||||
val interactive = def.payload.hasLaunchTarget()
|
||||
Image(
|
||||
bitmap = image.asImageBitmap(),
|
||||
contentDescription = def.payload.label,
|
||||
contentScale = ContentScale.Fit,
|
||||
modifier = if (interactive) Modifier.fillMaxSize().clickable(onClick = onClick)
|
||||
else Modifier.fillMaxSize(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
"dock_bg" -> Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
@@ -344,6 +367,8 @@ private fun iconPressModifier(iconSize: Dp, onClick: () -> Unit, onLongClick: ()
|
||||
@Composable
|
||||
private fun AppIconView(
|
||||
pkg: String,
|
||||
style: String,
|
||||
imageId: String?,
|
||||
label: String,
|
||||
sizePx: Int,
|
||||
labelPx: Float,
|
||||
@@ -353,8 +378,9 @@ private fun AppIconView(
|
||||
) {
|
||||
val density = LocalDensity.current
|
||||
// key 里带上 sizePx:尺寸变了要重新取,否则会拿旧分辨率的图去拉伸
|
||||
val bmp by produceState<Bitmap?>(initialValue = null, pkg, sizePx) {
|
||||
value = icons.load(pkg, sizePx)
|
||||
val bmp by produceState<Bitmap?>(initialValue = null, pkg, sizePx, style, imageId) {
|
||||
value = if (style == "image") imageId?.let { icons.loadImage(it) }
|
||||
else icons.load(pkg, sizePx, style)
|
||||
}
|
||||
|
||||
val side = with(density) { sizePx.toDp() }
|
||||
@@ -363,12 +389,17 @@ private fun AppIconView(
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
val shape = RoundedCornerShape(side * 0.24f)
|
||||
val shape = when (style) {
|
||||
"circle" -> CircleShape
|
||||
"original", "image" -> androidx.compose.ui.graphics.RectangleShape
|
||||
else -> RoundedCornerShape(side * 0.24f)
|
||||
}
|
||||
if (bmp != null) {
|
||||
Image(
|
||||
bitmap = bmp!!.asImageBitmap(),
|
||||
contentDescription = label,
|
||||
modifier = Modifier.size(side).clip(shape),
|
||||
contentScale = ContentScale.Fit,
|
||||
modifier = Modifier.size(side),
|
||||
)
|
||||
} else {
|
||||
// 首字母兜底:包名还没解析出来时也不留白块
|
||||
|
||||
Reference in new issue
Block a user