Initialize Compose Launcher source and deployment
This commit is contained in:
commit
12a8c24441
77 files changed
+9594
No files matched your search
@@ -0,0 +1,90 @@
|
||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
id("org.jetbrains.kotlin.plugin.compose")
|
||||
id("org.jetbrains.kotlin.plugin.serialization")
|
||||
}
|
||||
|
||||
fun buildConfigString(value: String): String =
|
||||
"\"" + value.replace("\\", "\\\\").replace("\"", "\\\"") + "\""
|
||||
|
||||
val syncServer = providers.environmentVariable("LAUNCHER_SYNC_SERVER")
|
||||
.orElse(providers.gradleProperty("launcherSyncServer")).orNull.orEmpty()
|
||||
val deviceToken = providers.environmentVariable("LAUNCHER_DEVICE_TOKEN")
|
||||
.orElse(providers.gradleProperty("launcherDeviceToken")).orNull.orEmpty()
|
||||
|
||||
android {
|
||||
namespace = "com.ttstd.compose.launcher"
|
||||
compileSdk = 37
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "com.ttstd.compose.launcher"
|
||||
minSdk = 26
|
||||
targetSdk = 37
|
||||
versionCode = 2
|
||||
versionName = "1.1.0"
|
||||
buildConfigField("String", "SYNC_SERVER", buildConfigString(syncServer))
|
||||
buildConfigField("String", "DEVICE_TOKEN", buildConfigString(deviceToken))
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
debug {
|
||||
// 不加 applicationIdSuffix:Launcher 的包名一旦变化,
|
||||
// 系统会当成另一个 HOME 应用,且 widget hostId / 布局文件都不通用了
|
||||
isMinifyEnabled = false
|
||||
}
|
||||
release {
|
||||
isMinifyEnabled = false
|
||||
proguardFiles(
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
"proguard-rules.pro",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||
targetCompatibility = JavaVersion.VERSION_1_8
|
||||
}
|
||||
buildFeatures {
|
||||
compose = true
|
||||
buildConfig = true
|
||||
}
|
||||
|
||||
packaging {
|
||||
resources.excludes += setOf("/META-INF/{AL2.0,LGPL2.1}")
|
||||
}
|
||||
|
||||
testOptions {
|
||||
unitTests.isReturnDefaultValues = true
|
||||
}
|
||||
}
|
||||
|
||||
kotlin {
|
||||
compilerOptions {
|
||||
jvmTarget.set(JvmTarget.JVM_1_8)
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("androidx.core:core-ktx:1.13.1")
|
||||
implementation("androidx.activity:activity-compose:1.9.2")
|
||||
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.6")
|
||||
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.6")
|
||||
|
||||
implementation(platform("androidx.compose:compose-bom:2024.09.03"))
|
||||
implementation("androidx.compose.ui:ui")
|
||||
implementation("androidx.compose.ui:ui-graphics")
|
||||
implementation("androidx.compose.foundation:foundation")
|
||||
implementation("androidx.compose.material3:material3")
|
||||
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1")
|
||||
|
||||
debugImplementation("androidx.compose.ui:ui-tooling")
|
||||
|
||||
// 纯 Kotlin 逻辑(映射 / 协议校验)在这里跑,不需要真机
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
}
|
||||
Vendored
+10
@@ -0,0 +1,10 @@
|
||||
# kotlinx.serialization:@Serializable 生成的 serializer 必须保留
|
||||
-keepattributes *Annotation*, InnerClasses
|
||||
-dontnote kotlinx.serialization.**
|
||||
-keepclassmembers class com.ttstd.compose.launcher.core.** {
|
||||
*** Companion;
|
||||
}
|
||||
-keepclasseswithmembers class com.ttstd.compose.launcher.core.** {
|
||||
kotlinx.serialization.KSerializer serializer(...);
|
||||
}
|
||||
-keep,includedescriptorclasses class com.ttstd.compose.launcher.core.**$$serializer { *; }
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<application android:usesCleartextTraffic="true" />
|
||||
</manifest>
|
||||
@@ -0,0 +1,66 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
|
||||
<!-- 枚举已安装应用(图标 / 启动意图)。LauncherApps 本身不需要,但
|
||||
getLaunchIntentForPackage 在 Android 11+ 需要可见性声明 -->
|
||||
<uses-permission
|
||||
android:name="android.permission.QUERY_ALL_PACKAGES"
|
||||
tools:ignore="QueryAllPackagesPermission" />
|
||||
|
||||
<!-- 绑定第三方桌面小组件:signature|privileged 级。
|
||||
系统签名应用直接具备;普通安装需要在系统"选择小组件"弹窗里由用户手动授权,
|
||||
否则 bindAppWidgetIdIfAllowed 永远返回 false(表现为组件一片空白) -->
|
||||
<uses-permission
|
||||
android:name="android.permission.BIND_APPWIDGET"
|
||||
tools:ignore="ProtectedPermissions" />
|
||||
|
||||
<application
|
||||
android:name=".LauncherApp"
|
||||
android:allowBackup="false"
|
||||
android:icon="@drawable/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.VibeLauncher">
|
||||
|
||||
<activity
|
||||
android:name=".SyncSettingsActivity"
|
||||
android:exported="true"
|
||||
android:label="布局同步">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".WidgetTestActivity"
|
||||
android:exported="false"
|
||||
android:label="小组件测试" />
|
||||
|
||||
<!-- 关键配置,逐条都有原因:
|
||||
launchMode=singleTask + clearTaskOnLaunch : 按 Home 键回到的是同一个桌面实例
|
||||
stateNotNeeded=true : 被杀后重建不需要 savedInstanceState
|
||||
configChanges=... : 旋转/换字体不重建 Activity,避免闪烁
|
||||
windowSoftInputMode=adjustNothing : 桌面不因输入法改变布局 -->
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:clearTaskOnLaunch="true"
|
||||
android:configChanges="keyboard|keyboardHidden|navigation|orientation|screenSize|screenLayout|smallestScreenSize|uiMode|density|fontScale|locale|layoutDirection"
|
||||
android:exported="true"
|
||||
android:launchMode="singleTask"
|
||||
android:stateNotNeeded="true"
|
||||
android:theme="@style/Theme.VibeLauncher"
|
||||
android:windowSoftInputMode="adjustNothing">
|
||||
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.HOME" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,219 @@
|
||||
{
|
||||
"schemaVersion": 3,
|
||||
"revision": 1,
|
||||
"canvas": {
|
||||
"designWidth": 1080,
|
||||
"designHeight": 1920,
|
||||
"safeTop": 132,
|
||||
"safeBottom": 72
|
||||
},
|
||||
"fit": {
|
||||
"mode": "contain",
|
||||
"anchorY": 0.5
|
||||
},
|
||||
"pages": [
|
||||
{
|
||||
"index": 0,
|
||||
"background": {
|
||||
"type": "wallpaper"
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id": "w_clock",
|
||||
"type": "widget",
|
||||
"x": 108,
|
||||
"y": 196,
|
||||
"w": 864,
|
||||
"h": 320,
|
||||
"z": 1,
|
||||
"payload": {
|
||||
"provider": "com.android.deskclock/.ClockWidget",
|
||||
"label": "时钟"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "i0",
|
||||
"type": "app_icon",
|
||||
"x": 150,
|
||||
"y": 604,
|
||||
"w": 132,
|
||||
"h": 168,
|
||||
"z": 2,
|
||||
"payload": {
|
||||
"package": "com.demo.app0",
|
||||
"label": "微信"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "i1",
|
||||
"type": "app_icon",
|
||||
"x": 366,
|
||||
"y": 604,
|
||||
"w": 132,
|
||||
"h": 168,
|
||||
"z": 2,
|
||||
"payload": {
|
||||
"package": "com.demo.app1",
|
||||
"label": "相机"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "i2",
|
||||
"type": "app_icon",
|
||||
"x": 582,
|
||||
"y": 604,
|
||||
"w": 132,
|
||||
"h": 168,
|
||||
"z": 2,
|
||||
"payload": {
|
||||
"package": "com.demo.app2",
|
||||
"label": "相册"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "i3",
|
||||
"type": "app_icon",
|
||||
"x": 798,
|
||||
"y": 604,
|
||||
"w": 132,
|
||||
"h": 168,
|
||||
"z": 2,
|
||||
"payload": {
|
||||
"package": "com.demo.app3",
|
||||
"label": "设置"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "i4",
|
||||
"type": "app_icon",
|
||||
"x": 150,
|
||||
"y": 828,
|
||||
"w": 132,
|
||||
"h": 168,
|
||||
"z": 2,
|
||||
"payload": {
|
||||
"package": "com.demo.app4",
|
||||
"label": "浏览器"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "i5",
|
||||
"type": "app_icon",
|
||||
"x": 366,
|
||||
"y": 828,
|
||||
"w": 132,
|
||||
"h": 168,
|
||||
"z": 2,
|
||||
"payload": {
|
||||
"package": "com.demo.app5",
|
||||
"label": "音乐"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "i6",
|
||||
"type": "app_icon",
|
||||
"x": 582,
|
||||
"y": 828,
|
||||
"w": 132,
|
||||
"h": 168,
|
||||
"z": 2,
|
||||
"payload": {
|
||||
"package": "com.demo.app6",
|
||||
"label": "地图"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "i7",
|
||||
"type": "app_icon",
|
||||
"x": 798,
|
||||
"y": 828,
|
||||
"w": 132,
|
||||
"h": 168,
|
||||
"z": 2,
|
||||
"payload": {
|
||||
"package": "com.demo.app7",
|
||||
"label": "日历"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "w_weather",
|
||||
"type": "widget",
|
||||
"x": 108,
|
||||
"y": 1076,
|
||||
"w": 420,
|
||||
"h": 300,
|
||||
"z": 1,
|
||||
"payload": {
|
||||
"provider": "com.android.weather/.WeatherWidget",
|
||||
"label": "天气"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "w_music",
|
||||
"type": "widget",
|
||||
"x": 552,
|
||||
"y": 1076,
|
||||
"w": 420,
|
||||
"h": 300,
|
||||
"z": 1,
|
||||
"payload": {
|
||||
"provider": "com.spotify/.MusicWidget",
|
||||
"label": "音乐"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "s0",
|
||||
"type": "shortcut",
|
||||
"x": 150,
|
||||
"y": 1650,
|
||||
"w": 132,
|
||||
"h": 168,
|
||||
"z": 2,
|
||||
"payload": {
|
||||
"label": "扫一扫",
|
||||
"intent": "demo://0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "s1",
|
||||
"type": "shortcut",
|
||||
"x": 366,
|
||||
"y": 1650,
|
||||
"w": 132,
|
||||
"h": 168,
|
||||
"z": 2,
|
||||
"payload": {
|
||||
"label": "支付",
|
||||
"intent": "demo://1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "s2",
|
||||
"type": "shortcut",
|
||||
"x": 582,
|
||||
"y": 1650,
|
||||
"w": 132,
|
||||
"h": 168,
|
||||
"z": 2,
|
||||
"payload": {
|
||||
"label": "钱包",
|
||||
"intent": "demo://2"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "s3",
|
||||
"type": "shortcut",
|
||||
"x": 798,
|
||||
"y": 1650,
|
||||
"w": 132,
|
||||
"h": 168,
|
||||
"z": 2,
|
||||
"payload": {
|
||||
"label": "更多",
|
||||
"intent": "demo://3"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.ttstd.compose.launcher
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import com.ttstd.compose.launcher.core.AppWidgetHostController
|
||||
import com.ttstd.compose.launcher.core.IconLoader
|
||||
import com.ttstd.compose.launcher.core.LayoutRepository
|
||||
import com.ttstd.compose.launcher.core.RemoteLayoutSync
|
||||
|
||||
/**
|
||||
* 进程级依赖容器。
|
||||
*
|
||||
* 为什么放在 Application 而不是 ViewModel:
|
||||
* repo / icons / widgetHost 的生命周期应该等于进程,而不是 Activity。
|
||||
* widget host 尤其如此 —— 每次重建都新建 AppWidgetHost 会让已绑定的组件实例
|
||||
* 变成孤儿,表现为"重启后组件全空白"。
|
||||
*/
|
||||
class AppGraph(context: Context) {
|
||||
val repo = LayoutRepository(context)
|
||||
val remote = RemoteLayoutSync(context, repo)
|
||||
val icons = IconLoader(context)
|
||||
val widgets = AppWidgetHostController(context)
|
||||
}
|
||||
|
||||
class LauncherApp : Application() {
|
||||
|
||||
lateinit var graph: AppGraph
|
||||
private set
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
graph = AppGraph(this)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package com.ttstd.compose.launcher
|
||||
|
||||
import android.app.Application
|
||||
import android.graphics.Bitmap
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.ttstd.compose.launcher.core.AppLaunch
|
||||
import com.ttstd.compose.launcher.core.BackgroundDef
|
||||
import com.ttstd.compose.launcher.core.CanvasDef
|
||||
import com.ttstd.compose.launcher.core.FitDef
|
||||
import com.ttstd.compose.launcher.core.IconLoader
|
||||
import com.ttstd.compose.launcher.core.ItemDef
|
||||
import com.ttstd.compose.launcher.core.LauncherLayout
|
||||
import com.ttstd.compose.launcher.core.PageDef
|
||||
import com.ttstd.compose.launcher.core.WallpaperLoader
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.collectLatest
|
||||
import kotlinx.coroutines.flow.filterNotNull
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlin.math.min
|
||||
|
||||
/**
|
||||
* 桌面状态容器。
|
||||
*
|
||||
* 关键设计:`_layout` 的初值是**纯内存构造的空布局**,不是 null、也不等磁盘。
|
||||
* 这样 Compose 第一帧就能画出壁纸 + 空画布(T1),用户在 200ms 内就能看到画面,
|
||||
* 而不是白屏等到 JSON 解析完(T2)。
|
||||
*/
|
||||
class LauncherViewModel(app: Application) : AndroidViewModel(app) {
|
||||
|
||||
private val graph = (app as LauncherApp).graph
|
||||
private val repo = graph.repo
|
||||
|
||||
val icons: IconLoader = graph.icons
|
||||
|
||||
private val _layout = MutableStateFlow(placeholderLayout())
|
||||
val layout: StateFlow<LauncherLayout> = _layout.asStateFlow()
|
||||
|
||||
private val _wallpaper = MutableStateFlow<Bitmap?>(null)
|
||||
val wallpaper: StateFlow<Bitmap?> = _wallpaper.asStateFlow()
|
||||
|
||||
/** 非 null 表示发生了降级(主布局坏了 / 用了内置默认),仅 debug 下展示 */
|
||||
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 {
|
||||
val dm = getApplication<Application>().resources.displayMetrics
|
||||
_wallpaper.value = WallpaperLoader.load(getApplication(), dm.widthPixels)
|
||||
}
|
||||
viewModelScope.launch {
|
||||
repo.load()
|
||||
}
|
||||
viewModelScope.launch {
|
||||
repo.layout.filterNotNull().collectLatest { current ->
|
||||
_layout.value = current
|
||||
prefetchIcons(current)
|
||||
}
|
||||
}
|
||||
viewModelScope.launch(Dispatchers.Default) {
|
||||
repo.degraded.collect { _degraded.value = it }
|
||||
}
|
||||
}
|
||||
|
||||
fun onItemClick(def: ItemDef) {
|
||||
val ctx = getApplication<Application>()
|
||||
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 -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
fun onItemLongClick(def: ItemDef) {
|
||||
val pkg = def.payload.pkg ?: return
|
||||
AppLaunch.openAppInfo(getApplication(), pkg)
|
||||
}
|
||||
|
||||
fun onPageChanged(index: Int) {
|
||||
// 预留:埋点 / 预取下一页图标
|
||||
}
|
||||
|
||||
/**
|
||||
* T3 预取:进入桌面后先把当前页图标解出来。
|
||||
* 尺寸必须走和渲染完全相同的公式(width × 0.78),否则缓存 key 对不上、白取一遍。
|
||||
*/
|
||||
private suspend fun prefetchIcons(layout: LauncherLayout) = withContext(Dispatchers.IO) {
|
||||
val page = layout.pages.firstOrNull() ?: return@withContext
|
||||
val dm = getApplication<Application>().resources.displayMetrics
|
||||
val s = min(
|
||||
dm.widthPixels / layout.canvas.designWidth.toFloat(),
|
||||
dm.heightPixels / layout.canvas.designHeight.toFloat(),
|
||||
)
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** 首帧占位:一页、零元素、壁纸透出。绝不做 IO */
|
||||
fun placeholderLayout() = LauncherLayout(
|
||||
canvas = CanvasDef(1080, 1920, 132, 72),
|
||||
fit = FitDef("contain", 0.5f),
|
||||
pages = listOf(PageDef(0, BackgroundDef("wallpaper"), emptyList())),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package com.ttstd.compose.launcher
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import android.view.ViewTreeObserver
|
||||
import android.widget.Toast
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.OnBackPressedCallback
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
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.input.pointer.pointerInput
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import com.ttstd.compose.launcher.ui.LauncherCanvas
|
||||
import com.ttstd.compose.launcher.ui.theme.VibeLauncherTheme
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/* =============================================================================
|
||||
* Launcher 入口
|
||||
*
|
||||
* 冷启动分层,否则用户看到「白屏 400ms → 图标逐个跳出来」:
|
||||
* T0 窗口背景:themes.xml 里放一个和壁纸主色接近的深色,别用白
|
||||
* T1 首帧:纯内存的空布局 + 壁纸,先把画面占住(不做任何 IO)
|
||||
* T2 真实布局落地:磁盘解析完替换
|
||||
* T3 图标位图逐个替换首字母占位
|
||||
*
|
||||
* 关键:T1 不能 await T2。首帧必须用「此刻已有的东西」画出来。
|
||||
* ===========================================================================*/
|
||||
class MainActivity : ComponentActivity() {
|
||||
|
||||
private val widgets get() = (application as LauncherApp).graph.widgets
|
||||
|
||||
private val bindWidget = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
|
||||
try {
|
||||
widgets.completeAuthorization(it.resultCode == RESULT_OK, ::configureWidget)
|
||||
} catch (error: RuntimeException) {
|
||||
Toast.makeText(this, "无法打开小组件设置", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
|
||||
private fun configureWidget(id: Int) {
|
||||
widgets.launchConfiguration(this, id, WIDGET_CONFIGURATION)
|
||||
}
|
||||
|
||||
@Deprecated("AppWidgetHost delivers configuration through this activity callback")
|
||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||
super.onActivityResult(requestCode, resultCode, data)
|
||||
if (requestCode == WIDGET_CONFIGURATION) widgets.finishBinding(resultCode == RESULT_OK)
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
savedInstanceState?.let(widgets::restorePendingBinding)
|
||||
val t0 = SystemClock.uptimeMillis()
|
||||
|
||||
// 状态栏/导航条透明,让壁纸铺满整屏 —— 留白不可见的前提
|
||||
enableEdgeToEdge()
|
||||
|
||||
// 桌面按返回键什么都不该发生(默认会退出到上一个应用,体验上像"桌面崩了")
|
||||
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
|
||||
override fun handleOnBackPressed() = Unit
|
||||
})
|
||||
|
||||
setContent {
|
||||
VibeLauncherTheme {
|
||||
val vm: LauncherViewModel = viewModel()
|
||||
val layout by vm.layout.collectAsState()
|
||||
val wallpaper by vm.wallpaper.collectAsState()
|
||||
val degraded by vm.degraded.collectAsState()
|
||||
|
||||
Box(Modifier.fillMaxSize().pointerInput(Unit) {
|
||||
detectTapGestures(onLongPress = {
|
||||
startActivity(Intent(this@MainActivity, SyncSettingsActivity::class.java))
|
||||
})
|
||||
}) {
|
||||
LauncherCanvas(
|
||||
layout = layout,
|
||||
icons = vm.icons,
|
||||
statusBarPx = vm.statusBarPx,
|
||||
bottomInsetPx = vm.navBarPx,
|
||||
wallpaper = wallpaper,
|
||||
widgetHost = widgets,
|
||||
onWidgetBind = { key, provider ->
|
||||
try {
|
||||
widgets.requestBind(key, provider, { bindWidget.launch(it) }, ::configureWidget)
|
||||
} catch (error: RuntimeException) {
|
||||
Toast.makeText(this@MainActivity, "无法打开小组件授权", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
},
|
||||
onItemClick = vm::onItemClick,
|
||||
onItemLongClick = vm::onItemLongClick,
|
||||
onPageChanged = vm::onPageChanged,
|
||||
)
|
||||
|
||||
// 降级提示只在 debug 包里出现:线上不能因为一个坏包给用户看黄条
|
||||
if (BuildConfig.DEBUG && degraded != null) {
|
||||
DegradedBadge(
|
||||
text = degraded!!,
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopStart)
|
||||
.padding(top = 44.dp, start = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
val remote = (application as LauncherApp).graph.remote
|
||||
while (true) {
|
||||
try {
|
||||
remote.sync()
|
||||
} catch (error: CancellationException) {
|
||||
throw error
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "Layout sync failed: ${error.javaClass.simpleName}")
|
||||
}
|
||||
delay(60_000)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 首帧埋点:onPreDraw 比 onResume 准,它是"即将真正绘制"的时刻
|
||||
window.decorView.viewTreeObserver.addOnPreDrawListener(
|
||||
object : ViewTreeObserver.OnPreDrawListener {
|
||||
override fun onPreDraw(): Boolean {
|
||||
window.decorView.viewTreeObserver.removeOnPreDrawListener(this)
|
||||
Log.i(TAG, "first frame +${SystemClock.uptimeMillis() - t0}ms")
|
||||
return true
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
override fun onSaveInstanceState(outState: Bundle) {
|
||||
super.onSaveInstanceState(outState)
|
||||
widgets.savePendingBinding(outState)
|
||||
}
|
||||
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
widgets.startListening()
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
super.onStop()
|
||||
widgets.stopListening()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val WIDGET_CONFIGURATION = 4921
|
||||
private const val TAG = "LauncherBoot"
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DegradedBadge(text: String, modifier: Modifier = Modifier) {
|
||||
Row(
|
||||
modifier
|
||||
.background(Color(0xCC7A4A12), RoundedCornerShape(8.dp))
|
||||
.padding(horizontal = 8.dp, vertical = 4.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(text = "降级", color = Color(0xFFFFD08A), fontSize = 10.sp)
|
||||
Text(text = text, color = Color.White, fontSize = 10.sp, maxLines = 2)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.ttstd.compose.launcher
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.safeDrawingPadding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import com.ttstd.compose.launcher.ui.theme.VibeLauncherTheme
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class SyncSettingsActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
enableEdgeToEdge()
|
||||
val graph = (application as LauncherApp).graph
|
||||
val remote = graph.remote
|
||||
val config = remote.connection()
|
||||
lifecycleScope.launch { graph.repo.load() }
|
||||
|
||||
setContent {
|
||||
VibeLauncherTheme {
|
||||
var address by rememberSaveable { mutableStateOf(config.server) }
|
||||
// 令牌留在进程内,不放进 Activity 的 saved instance state。
|
||||
var token by remember { mutableStateOf(config.token) }
|
||||
var status by remember { mutableStateOf("") }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
val layout by graph.repo.layout.collectAsState()
|
||||
|
||||
Surface(Modifier.fillMaxSize()) {
|
||||
Column(
|
||||
Modifier.safeDrawingPadding().verticalScroll(rememberScrollState()).padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
Text("布局同步", style = MaterialTheme.typography.headlineMedium)
|
||||
Text(layout?.let { "当前布局 v${it.revision}" } ?: "正在读取本地布局")
|
||||
OutlinedTextField(
|
||||
value = address,
|
||||
onValueChange = { address = it },
|
||||
label = { Text("服务地址") },
|
||||
placeholder = { Text("https://launcher.example.com") },
|
||||
singleLine = true,
|
||||
enabled = !busy,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = token,
|
||||
onValueChange = { token = it },
|
||||
label = { Text("设备令牌") },
|
||||
singleLine = true,
|
||||
enabled = !busy,
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Button(
|
||||
enabled = !busy,
|
||||
onClick = {
|
||||
busy = true
|
||||
status = "正在同步…"
|
||||
lifecycleScope.launch {
|
||||
try {
|
||||
remote.saveConnection(address, token)
|
||||
val revision = remote.sync()
|
||||
status = if (revision == null) "已关闭同步,继续使用本地布局" else "已同步 v$revision"
|
||||
} catch (error: CancellationException) {
|
||||
throw error
|
||||
} catch (error: Exception) {
|
||||
status = error.message ?: "同步失败"
|
||||
} finally {
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
},
|
||||
) {
|
||||
Text("保存并同步")
|
||||
}
|
||||
if (status.isNotEmpty()) Text(status)
|
||||
TextButton(onClick = {
|
||||
startActivity(Intent(this@SyncSettingsActivity, WidgetTestActivity::class.java))
|
||||
}) { Text("测试第三方小组件") }
|
||||
TextButton(onClick = { finish() }) { Text("返回桌面") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package com.ttstd.compose.launcher
|
||||
|
||||
import android.appwidget.AppWidgetHost
|
||||
import android.appwidget.AppWidgetHostView
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.appwidget.AppWidgetProviderInfo
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.os.Process
|
||||
import android.view.ViewGroup
|
||||
import android.widget.FrameLayout
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.result.ActivityResultLauncher
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.safeDrawingPadding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import com.ttstd.compose.launcher.ui.theme.VibeLauncherTheme
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class WidgetTestActivity : ComponentActivity() {
|
||||
|
||||
private val status = mutableStateOf("选择一个已安装的小组件开始测试")
|
||||
private val preview = mutableStateOf<AppWidgetHostView?>(null)
|
||||
private var pendingProvider: AppWidgetProviderInfo? = null
|
||||
private var pendingSize: Pair<Int, Int> = 0 to 0
|
||||
private lateinit var controller: TestHost
|
||||
private lateinit var bindLauncher: ActivityResultLauncher<Intent>
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
controller = TestHost(this)
|
||||
bindLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
|
||||
val info = pendingProvider ?: return@registerForActivityResult
|
||||
val id = result.data?.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) ?: -1
|
||||
if (result.resultCode == RESULT_OK && id >= 0) {
|
||||
// ACTION_APPWIDGET_BIND 返回 OK 时系统已完成绑定,这里只检查结果
|
||||
val bound = runCatching {
|
||||
AppWidgetManager.getInstance(this).getAppWidgetInfo(id) != null
|
||||
}.getOrDefault(false)
|
||||
if (bound) showWidget(id, info) else {
|
||||
status.value = "绑定失败:系统未授予 BIND_APPWIDGET"
|
||||
controller.delete(id)
|
||||
}
|
||||
} else {
|
||||
status.value = "已取消授权"
|
||||
controller.delete(id)
|
||||
}
|
||||
}
|
||||
|
||||
setContent {
|
||||
VibeLauncherTheme {
|
||||
val providers = remember { controller.providers() }
|
||||
val density = LocalDensity.current
|
||||
val previewW = with(density) { 320.dp.toPx() }.roundToInt()
|
||||
val previewH = with(density) { 180.dp.toPx() }.roundToInt()
|
||||
|
||||
DisposableEffect(Unit) {
|
||||
controller.start()
|
||||
onDispose { controller.stop() }
|
||||
}
|
||||
|
||||
Surface(Modifier.fillMaxSize()) {
|
||||
Column(
|
||||
Modifier.safeDrawingPadding().padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Text("第三方 AppWidget 测试", style = MaterialTheme.typography.headlineSmall)
|
||||
Text(status.value, style = MaterialTheme.typography.bodySmall)
|
||||
|
||||
AndroidView(
|
||||
factory = { FrameLayout(it) },
|
||||
update = { container ->
|
||||
container.removeAllViews()
|
||||
preview.value?.let { view ->
|
||||
(view.parent as? ViewGroup)?.removeView(view)
|
||||
view.layoutParams = FrameLayout.LayoutParams(previewW, previewH)
|
||||
controller.updateSize(view, previewW, previewH)
|
||||
container.addView(view)
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth().height(180.dp),
|
||||
)
|
||||
|
||||
LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(providers, key = { it.provider.flattenToString() }) { info ->
|
||||
Row(
|
||||
Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(info.loadLabel(packageManager).toString())
|
||||
Text(
|
||||
info.provider.flattenToString(),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
Button(onClick = { bind(info, previewW, previewH) }) {
|
||||
Text("绑定")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun bind(info: AppWidgetProviderInfo, widthPx: Int, heightPx: Int) {
|
||||
val id = controller.allocate()
|
||||
if (id < 0) {
|
||||
status.value = "分配 appWidgetId 失败"
|
||||
return
|
||||
}
|
||||
preview.value = null
|
||||
pendingProvider = info
|
||||
pendingSize = widthPx to heightPx
|
||||
if (controller.tryBind(id, info)) {
|
||||
showWidget(id, info)
|
||||
} else {
|
||||
val intent = Intent(AppWidgetManager.ACTION_APPWIDGET_BIND).apply {
|
||||
putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id)
|
||||
putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.provider)
|
||||
}
|
||||
status.value = "请在系统弹窗中授权绑定…"
|
||||
bindLauncher.launch(intent)
|
||||
}
|
||||
}
|
||||
|
||||
private fun showWidget(id: Int, info: AppWidgetProviderInfo) {
|
||||
val (w, h) = pendingSize
|
||||
preview.value = controller.createView(id, info, w, h)
|
||||
status.value = "已绑定 ${info.provider.flattenToString()}"
|
||||
}
|
||||
|
||||
private class TestHost(private val context: Context) {
|
||||
private val manager = AppWidgetManager.getInstance(context)
|
||||
private val host: AppWidgetHost
|
||||
|
||||
init {
|
||||
val sp = context.getSharedPreferences("widget_test_host", Context.MODE_PRIVATE)
|
||||
var id = sp.getInt("host_id", -1)
|
||||
if (id < 0) {
|
||||
id = 2048 + (Process.myPid() % 512)
|
||||
sp.edit().putInt("host_id", id).apply()
|
||||
}
|
||||
host = AppWidgetHost(context, id)
|
||||
}
|
||||
|
||||
fun providers(): List<AppWidgetProviderInfo> =
|
||||
manager.installedProviders.sortedBy { it.provider.flattenToString() }
|
||||
|
||||
fun start() = runCatching { host.startListening() }
|
||||
fun stop() = runCatching { host.stopListening() }
|
||||
|
||||
fun allocate(): Int = runCatching { host.allocateAppWidgetId() }.getOrDefault(-1)
|
||||
|
||||
fun tryBind(id: Int, info: AppWidgetProviderInfo): Boolean = runCatching {
|
||||
manager.bindAppWidgetIdIfAllowed(id, info.provider)
|
||||
}.getOrDefault(false)
|
||||
|
||||
fun createView(id: Int, info: AppWidgetProviderInfo, w: Int, h: Int): AppWidgetHostView =
|
||||
host.createView(context, id, info).apply {
|
||||
setAppWidget(id, info)
|
||||
updateSize(this, w, h)
|
||||
}
|
||||
|
||||
fun updateSize(view: AppWidgetHostView, w: Int, h: Int) {
|
||||
val dp = (w / with(context.resources.displayMetrics) { density }).roundToInt()
|
||||
val dpHeight = (h / with(context.resources.displayMetrics) { density }).roundToInt()
|
||||
val options = Bundle().apply {
|
||||
putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, dp)
|
||||
putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH, dp)
|
||||
putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT, dpHeight)
|
||||
putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT, dpHeight)
|
||||
}
|
||||
view.updateAppWidgetOptions(options)
|
||||
@Suppress("DEPRECATION")
|
||||
view.updateAppWidgetSize(null, w, h, w, h)
|
||||
}
|
||||
|
||||
fun delete(id: Int) = runCatching { host.deleteAppWidgetId(id) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.ttstd.compose.launcher.core
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
|
||||
/**
|
||||
* 从桌面启动应用 / 快捷方式。
|
||||
*
|
||||
* 两个必须处理的点:
|
||||
* 1) FLAG_ACTIVITY_NEW_TASK —— 从非 Activity 上下文启动必须有
|
||||
* 2) getLaunchIntentForPackage 可能返回 null(应用被禁用、包名写错、被卸载)。
|
||||
* 这里返回 Boolean 让 UI 决定是否提示,绝不抛异常把桌面搞崩。
|
||||
*/
|
||||
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)
|
||||
}
|
||||
|
||||
/** 快捷方式里的 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)
|
||||
}
|
||||
|
||||
private fun start(context: Context, intent: Intent): Boolean = runCatching {
|
||||
context.startActivity(intent)
|
||||
true
|
||||
}.getOrElse {
|
||||
Log.w(TAG, "start failed: ${it.message}")
|
||||
false
|
||||
}
|
||||
|
||||
/** 长按图标 → 应用详情(卸载/强制停止)。桌面必备,否则用户装了就卸不掉 */
|
||||
fun openAppInfo(context: Context, pkg: String) {
|
||||
val intent = Intent(
|
||||
android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
|
||||
Uri.fromParts("package", pkg, null),
|
||||
).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
runCatching { context.startActivity(intent) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package com.ttstd.compose.launcher.core
|
||||
|
||||
import android.appwidget.AppWidgetHost
|
||||
import android.appwidget.AppWidgetHostView
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.appwidget.AppWidgetProviderInfo
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import android.os.Bundle
|
||||
import android.os.Process
|
||||
import android.view.View
|
||||
|
||||
class AppWidgetHostController(
|
||||
private val context: Context,
|
||||
hostId: Int = loadOrCreateHostId(context),
|
||||
) : WidgetHostProvider {
|
||||
|
||||
private val host = AppWidgetHost(context, hostId)
|
||||
private val manager = AppWidgetManager.getInstance(context)
|
||||
|
||||
private val bindings = context.getSharedPreferences("widget_bindings", Context.MODE_PRIVATE)
|
||||
private val bindingChanges = mutableIntStateOf(0)
|
||||
|
||||
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
|
||||
val id = host.allocateAppWidgetId()
|
||||
pending = PendingBinding(key, provider, id)
|
||||
try {
|
||||
if (manager.bindAppWidgetIdIfAllowed(id, info.provider)) {
|
||||
completeAuthorization(true, configure)
|
||||
return
|
||||
}
|
||||
launch(Intent(AppWidgetManager.ACTION_APPWIDGET_BIND)
|
||||
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id)
|
||||
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.provider))
|
||||
} catch (error: RuntimeException) {
|
||||
finishBinding(false)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private data class PendingBinding(val key: String, val provider: String, val id: Int)
|
||||
private var pending: PendingBinding? = null
|
||||
|
||||
fun savePendingBinding(state: Bundle) {
|
||||
val request = pending ?: return
|
||||
state.putString("widgetBindingKey", request.key)
|
||||
state.putString("widgetBindingProvider", request.provider)
|
||||
state.putInt("widgetBindingId", request.id)
|
||||
}
|
||||
|
||||
fun restorePendingBinding(state: Bundle) {
|
||||
if (pending != null) return
|
||||
val key = state.getString("widgetBindingKey") ?: return
|
||||
val provider = state.getString("widgetBindingProvider") ?: return
|
||||
val id = state.getInt("widgetBindingId", -1)
|
||||
if (id >= 0) pending = PendingBinding(key, provider, id)
|
||||
}
|
||||
|
||||
fun completeAuthorization(accepted: Boolean, configure: (Int) -> Unit) {
|
||||
val request = pending ?: return
|
||||
val info = manager.getAppWidgetInfo(request.id)
|
||||
if (!accepted || info == null || info.provider != ComponentName.unflattenFromString(request.provider)) {
|
||||
finishBinding(false)
|
||||
return
|
||||
}
|
||||
val optional = android.os.Build.VERSION.SDK_INT >= 31 &&
|
||||
info.widgetFeatures and AppWidgetProviderInfo.WIDGET_FEATURE_CONFIGURATION_OPTIONAL != 0
|
||||
if (info.configure == null || optional) {
|
||||
finishBinding(true)
|
||||
return
|
||||
}
|
||||
try {
|
||||
configure(request.id)
|
||||
} catch (error: RuntimeException) {
|
||||
finishBinding(false)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
fun launchConfiguration(activity: android.app.Activity, id: Int, requestCode: Int) {
|
||||
host.startAppWidgetConfigureActivityForResult(activity, id, 0, requestCode, null)
|
||||
}
|
||||
|
||||
fun finishBinding(accepted: Boolean) {
|
||||
val request = pending ?: return
|
||||
pending = null
|
||||
val provider = ComponentName.unflattenFromString(request.provider)
|
||||
if (accepted && manager.getAppWidgetInfo(request.id)?.provider == provider) {
|
||||
bindings.edit().putInt(request.key, request.id).apply()
|
||||
} else {
|
||||
host.deleteAppWidgetId(request.id)
|
||||
}
|
||||
bindingChanges.intValue++
|
||||
}
|
||||
|
||||
private fun boundId(key: String, info: AppWidgetProviderInfo): Int? {
|
||||
val id = bindings.getInt(key, -1)
|
||||
if (id < 0) return null
|
||||
if (manager.getAppWidgetInfo(id)?.provider == info.provider) return id
|
||||
bindings.edit().remove(key).apply()
|
||||
views.remove(id)
|
||||
sizes.remove(id)
|
||||
host.deleteAppWidgetId(id)
|
||||
return null
|
||||
}
|
||||
/** appWidgetId -> hostView,复用避免每次重组都新建 */
|
||||
private val views = HashMap<Int, AppWidgetHostView>()
|
||||
private val sizes = HashMap<Int, Pair<Int, Int>>()
|
||||
|
||||
fun startListening() {
|
||||
runCatching { host.startListening() }
|
||||
}
|
||||
|
||||
fun stopListening() {
|
||||
runCatching { host.stopListening() }
|
||||
}
|
||||
|
||||
override fun obtain(key: String, provider: String, widthDp: Int, heightDp: Int): View? {
|
||||
bindingChanges.intValue
|
||||
val info = resolveProvider(provider) ?: return null
|
||||
val id = boundId(key, info) ?: return null
|
||||
val view = views.getOrPut(id) { host.createView(context, id, info) }
|
||||
val size = widthDp to heightDp
|
||||
if (sizes[id] != size) {
|
||||
@Suppress("DEPRECATION")
|
||||
view.updateAppWidgetSize(Bundle(), widthDp, heightDp, widthDp, heightDp)
|
||||
sizes[id] = size
|
||||
}
|
||||
return view
|
||||
}
|
||||
|
||||
private fun resolveProvider(fullName: String): AppWidgetProviderInfo? {
|
||||
val cn = ComponentName.unflattenFromString(fullName) ?: return null
|
||||
// 只在「已安装且已声明」的 provider 里找,不能凭空造一个
|
||||
return manager.installedProviders.firstOrNull { it.provider == cn }
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val PREF = "widget_host"
|
||||
private const val KEY_HOST_ID = "host_id"
|
||||
|
||||
/**
|
||||
* hostId 必须跨启动稳定。用 SP 存,首次随机分配。
|
||||
* 丢失 hostId 等价于「放弃所有已绑定 widget」。
|
||||
*/
|
||||
fun loadOrCreateHostId(context: Context): Int {
|
||||
val sp = context.getSharedPreferences(PREF, Context.MODE_PRIVATE)
|
||||
val saved = sp.getInt(KEY_HOST_ID, -1)
|
||||
if (saved >= 0) return saved
|
||||
val id = 1024 + (Process.myPid() % 512)
|
||||
sp.edit().putInt(KEY_HOST_ID, id).apply()
|
||||
return id
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
package com.ttstd.compose.launcher.core
|
||||
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
|
||||
/* =============================================================================
|
||||
* 设计稿画布 · 坐标映射(纯 Kotlin,无 Android 依赖,可在 JVM 上单测)
|
||||
*
|
||||
* 核心不变式:
|
||||
* 1. 协议里的 x/y/w/h 是「设计稿像素」,与任何设备无关
|
||||
* 2. 渲染端只做一次映射:designPx → devicePx
|
||||
* 3. 横向与纵向使用同一个 scale(除 STRETCH 模式外),保证不变形
|
||||
* 4. 不重排、不断点、不按屏幕比例分配权重
|
||||
* =============================================================================*/
|
||||
|
||||
/** 设计稿基准。一旦发布不要再改,否则已存的布局会整体偏移 */
|
||||
data class DesignCanvas(
|
||||
val designWidth: Int = 1080,
|
||||
val designHeight: Int = 1920,
|
||||
/** 内容顶部安全区(设计稿坐标系内),防止内容压到状态栏 */
|
||||
val safeTop: Int = 132,
|
||||
/** 内容底部安全区,避让手势条 */
|
||||
val safeBottom: Int = 72,
|
||||
)
|
||||
|
||||
/**
|
||||
* 屏幕比例奇形怪状时的处理策略。
|
||||
*
|
||||
* | 模式 | 留白 | 变形 | 视觉一致性 | 适用 |
|
||||
* |-----------|------|------|-----------|------|
|
||||
* | CONTAIN | 有 | 无 | 100% | **默认**:双边等比居中,不裁不拉 |
|
||||
* | ELASTIC | 无 | 无 | ≈99% | 可选优化:留白转成行间距 |
|
||||
* | STRETCH | 无 | 有 | 100%(几何)/ 观感差 | 短屏差 5% 以内的轻微适配 |
|
||||
*/
|
||||
enum class FitMode { CONTAIN, ELASTIC, STRETCH }
|
||||
|
||||
data class FitConfig(
|
||||
val mode: FitMode = FitMode.CONTAIN,
|
||||
/** 仅 CONTAIN 生效:0=留白集中顶部,0.5=上下均分,1=集中底部 */
|
||||
val anchorY: Float = 0.5f,
|
||||
)
|
||||
|
||||
data class CanvasItem(
|
||||
val id: String,
|
||||
val type: String,
|
||||
val x: Float,
|
||||
val y: Float,
|
||||
val w: Float,
|
||||
val h: Float,
|
||||
)
|
||||
|
||||
/** 一行(或一组纵向重叠)内容的纵向区间 */
|
||||
data class Band(val top: Float, val bottom: Float)
|
||||
|
||||
data class PlacedItem(
|
||||
val source: CanvasItem,
|
||||
val left: Float,
|
||||
val top: Float,
|
||||
val width: Float,
|
||||
val height: Float,
|
||||
)
|
||||
|
||||
data class MappingResult(
|
||||
val scaleX: Float,
|
||||
val scaleY: Float,
|
||||
val offsetX: Float,
|
||||
val offsetY: Float,
|
||||
val placed: List<PlacedItem>,
|
||||
/** 视觉上剩余的整块留白(CONTAIN 才可能 > 0) */
|
||||
val visualGapPx: Float,
|
||||
/** ELASTIC 的空白放大系数,1.0 表示无需调整 */
|
||||
val gapScale: Float,
|
||||
/** 实际生效的模式(ELASTIC 在屏幕更宽扁时会自动退回 CONTAIN) */
|
||||
val effectiveMode: FitMode,
|
||||
/** 缩放后内容整体占用的高度,用于留白与安全区的二次修正 */
|
||||
val contentHeight: Float = 0f,
|
||||
) {
|
||||
/** 纵向变形率,STRETCH 下等于 scaleY/scaleX - 1 */
|
||||
val verticalDistortion: Float get() = scaleY / scaleX - 1f
|
||||
}
|
||||
|
||||
object CanvasMapper {
|
||||
|
||||
/**
|
||||
* 把元素按纵向区间聚成「行带」。只有真正重叠才合并,
|
||||
* 上下相邻但不重叠的两行必须分开,否则拿不到它们之间的间隙。
|
||||
*/
|
||||
fun rowBands(items: List<CanvasItem>): List<Band> {
|
||||
if (items.isEmpty()) return emptyList()
|
||||
val sorted = items.map { it.y to it.y + it.h }.sortedBy { it.first }
|
||||
val out = ArrayList<Band>(sorted.size)
|
||||
for ((a, b) in sorted) {
|
||||
val last = out.lastOrNull()
|
||||
if (last != null && a < last.bottom - 0.5f) {
|
||||
out[out.size - 1] = last.copy(bottom = max(last.bottom, b))
|
||||
} else {
|
||||
out += Band(a, b)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* 唯一的入口。screenW/screenH 是渲染区的真实像素尺寸
|
||||
* (已扣掉系统 UI 之外的可用区域,见 DesignCanvasRenderer 里的说明)。
|
||||
*/
|
||||
fun map(
|
||||
canvas: DesignCanvas,
|
||||
fit: FitConfig,
|
||||
items: List<CanvasItem>,
|
||||
screenW: Float,
|
||||
screenH: Float,
|
||||
): MappingResult {
|
||||
if (screenW <= 0f || screenH <= 0f || items.isEmpty()) {
|
||||
return MappingResult(1f, 1f, 0f, 0f, emptyList(), 0f, 1f, fit.mode, 0f)
|
||||
}
|
||||
val sxW = screenW / canvas.designWidth
|
||||
val syH = screenH / canvas.designHeight
|
||||
val maxS = max(sxW, syH)
|
||||
|
||||
fun contain(note: FitMode) : MappingResult {
|
||||
val s = min(sxW, syH)
|
||||
val cw = canvas.designWidth * s
|
||||
val ch = canvas.designHeight * s
|
||||
val ox = (screenW - cw) / 2f
|
||||
val oy = (screenH - ch) * fit.anchorY
|
||||
val placed = items.map {
|
||||
PlacedItem(it, ox + it.x * s, oy + it.y * s, it.w * s, it.h * s)
|
||||
}
|
||||
// 视觉留白取横向与纵向中较大的那块(一般只有一边不为 0)
|
||||
val gap = max(screenW - cw, screenH - ch)
|
||||
return MappingResult(s, s, ox, oy, placed, gap, 1f, note, ch)
|
||||
}
|
||||
|
||||
when (fit.mode) {
|
||||
FitMode.CONTAIN -> return contain(FitMode.CONTAIN)
|
||||
|
||||
FitMode.STRETCH -> {
|
||||
val placed = items.map {
|
||||
PlacedItem(it, it.x * sxW, it.y * syH, it.w * sxW, it.h * syH)
|
||||
}
|
||||
return MappingResult(sxW, syH, 0f, 0f, placed, 0f, 1f, FitMode.STRETCH, screenH)
|
||||
}
|
||||
|
||||
FitMode.ELASTIC -> {
|
||||
val sx = sxW
|
||||
val extra = screenH - canvas.designHeight * sx
|
||||
// 屏幕比画布更宽扁(平板 4:3、横屏):横铺必然纵向溢出,退回等比
|
||||
if (extra <= 0.5f) return contain(FitMode.CONTAIN)
|
||||
|
||||
val bands = rowBands(items)
|
||||
// 间隙段:顶部 → 各带之间 → 底部
|
||||
val segs = ArrayList<Pair<Float, Float>>(bands.size + 1)
|
||||
var prev = 0f
|
||||
for (b in bands) {
|
||||
segs += prev to b.top
|
||||
prev = b.bottom
|
||||
}
|
||||
segs += prev to canvas.designHeight.toFloat()
|
||||
|
||||
val totalBlank = segs.sumOf { max(0f, it.second - it.first).toDouble() }
|
||||
.toFloat().takeIf { it > 0.5f } ?: 1f
|
||||
// 按原空白比例放大,而不是平均分配 —— 保住设计稿的疏密节奏
|
||||
val k = (totalBlank + extra) / totalBlank
|
||||
|
||||
val deltas = FloatArray(bands.size)
|
||||
var acc = 0f
|
||||
segs.forEachIndexed { i, (a, b) ->
|
||||
acc += max(0f, b - a) * (k - 1f)
|
||||
if (i < bands.size) deltas[i] = acc
|
||||
}
|
||||
|
||||
fun shiftFor(y: Float): Float {
|
||||
var d = 0f
|
||||
for (i in bands.indices) if (y >= bands[i].top - 0.5f) d = deltas[i]
|
||||
return d
|
||||
}
|
||||
|
||||
val placed = items.map {
|
||||
PlacedItem(
|
||||
it,
|
||||
it.x * sx,
|
||||
it.y * sx + shiftFor(it.y),
|
||||
it.w * sx,
|
||||
it.h * sx,
|
||||
)
|
||||
}
|
||||
return MappingResult(sx, sx, 0f, 0f, placed, 0f, k, FitMode.ELASTIC, screenH)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* =============================================================================
|
||||
* 与协议的对齐校验:确保发布前不会把内容送进系统栏
|
||||
* =============================================================================*/
|
||||
object CanvasValidator {
|
||||
|
||||
data class Issue(val level: Level, val itemId: String, val message: String) {
|
||||
enum class Level { ERROR, WARN }
|
||||
}
|
||||
|
||||
fun validate(canvas: DesignCanvas, items: List<CanvasItem>, statusBarPx: Int, navBarPx: Int): List<Issue> {
|
||||
val out = ArrayList<Issue>()
|
||||
val w = canvas.designWidth
|
||||
val h = canvas.designHeight
|
||||
|
||||
val ids = HashSet<String>()
|
||||
for (it in items) {
|
||||
if (!ids.add(it.id)) out += Issue(Issue.Level.ERROR, it.id, "id 重复")
|
||||
if (it.w <= 0 || it.h <= 0) out += Issue(Issue.Level.ERROR, it.id, "尺寸非正数")
|
||||
if (it.x < -0.5f || it.y < -0.5f) out += Issue(Issue.Level.ERROR, it.id, "坐标为负")
|
||||
if (it.x + it.w > w + 0.5f) out += Issue(Issue.Level.ERROR, it.id, "右侧超出画布")
|
||||
if (it.y + it.h > h + 0.5f) out += Issue(Issue.Level.ERROR, it.id, "底部超出画布")
|
||||
if (it.y < canvas.safeTop) out += Issue(Issue.Level.WARN, it.id, "顶部进入安全区")
|
||||
if (it.y + it.h > h - canvas.safeBottom) out += Issue(Issue.Level.WARN, it.id, "底部进入安全区")
|
||||
}
|
||||
|
||||
// 重叠:自由画布允许「有意叠放」(比如图标压在 widget 上),
|
||||
// 但同类型整齐元素之间的重叠基本是误操作,只报 WARN 不拦。
|
||||
for (i in items.indices) for (j in i + 1 until items.size) {
|
||||
val a = items[i]; val b = items[j]
|
||||
val overlap = a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y
|
||||
if (overlap) out += Issue(Issue.Level.WARN, a.id, "与 ${b.id} 重叠")
|
||||
}
|
||||
|
||||
// 状态栏高度与设计稿 safeTop 的错配是最高频的真机问题
|
||||
if (canvas.safeTop * 1f < statusBarPx * 0.9f) {
|
||||
out += Issue(
|
||||
Issue.Level.WARN, "-",
|
||||
"safeTop=${canvas.safeTop} 小于真机状态栏 ${statusBarPx}px,内容可能被遮挡",
|
||||
)
|
||||
}
|
||||
if (navBarPx > 0 && canvas.safeBottom < navBarPx * 0.7f) {
|
||||
out += Issue(
|
||||
Issue.Level.WARN, "-",
|
||||
"safeBottom=${canvas.safeBottom} 偏小,可能被手势条压住",
|
||||
)
|
||||
}
|
||||
return out
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 状态栏/导航条与设计稿坐标系的错配修正。
|
||||
*
|
||||
* 为什么需要:设计稿的 safeTop 是「设计时的假设」,真机状态栏高度是「系统给的现实」。
|
||||
* 1080 屏约 132px、1440 屏约 176px、720 屏约 88px,三者与画布缩放并不同比,
|
||||
* 所以 CONTAIN 算完 anchor 还要做一次下限修正:内容顶部不得高于真实状态栏。
|
||||
*
|
||||
* 只修 CONTAIN:ELASTIC 已经用顶部间隙吸收,STRETCH 没有可移动空间。
|
||||
*/
|
||||
fun MappingResult.avoidSystemInsets(
|
||||
screenH: Float,
|
||||
statusBarPx: Float,
|
||||
): MappingResult {
|
||||
if (effectiveMode != FitMode.CONTAIN) return this
|
||||
val totalGap = max(0f, screenH - contentHeight)
|
||||
val minOffset = statusBarPx.coerceAtMost(totalGap)
|
||||
if (offsetY >= minOffset) return this
|
||||
val dy = minOffset - offsetY
|
||||
return copy(
|
||||
offsetY = minOffset,
|
||||
visualGapPx = totalGap,
|
||||
placed = placed.map { it.copy(top = it.top + dy) },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.ttstd.compose.launcher.core
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.drawable.BitmapDrawable
|
||||
import android.graphics.drawable.Drawable
|
||||
import android.util.LruCache
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/* =============================================================================
|
||||
* 图标加载
|
||||
*
|
||||
* 桌面启动时最贵的两件事:跨进程查 ApplicationInfo、Bitmap 解码。
|
||||
* 所以这里做三件事:
|
||||
* 1. LruCache 按「包名@目标像素」缓存,尺寸变了才重新解码(否则会糊)
|
||||
* 2. 全部在 IO 线程,主线程只拿结果
|
||||
* 3. 失败返回 null,由 UI 画首字母兜底 —— 绝不抛异常
|
||||
* ===========================================================================*/
|
||||
class IconLoader(private val context: Context) {
|
||||
|
||||
// 内存上限按 1/8 可用内存给,最多 256 张
|
||||
private val cache = object : LruCache<String, Bitmap>(
|
||||
(Runtime.getRuntime().maxMemory() / 8 / 1024).toInt().coerceIn(32, 256)
|
||||
) {
|
||||
override fun sizeOf(key: String, value: Bitmap): Int = 1
|
||||
}
|
||||
|
||||
private val pm: PackageManager get() = context.packageManager
|
||||
|
||||
/**
|
||||
* @param sizePx 目标边长的**像素**值,由 CanvasMapper 算出的 item 宽度决定,
|
||||
* 不要在调用处写死 dp —— 这是不同分辨率下图标大小一致的唯一办法。
|
||||
*/
|
||||
suspend fun load(pkg: String, sizePx: Int): Bitmap? = withContext(Dispatchers.IO) {
|
||||
val px = sizePx.coerceIn(24, 512)
|
||||
val key = "$pkg@$px"
|
||||
cache.get(key)?.let { return@withContext it }
|
||||
|
||||
val bmp = runCatching {
|
||||
val drawable = pm.getApplicationIcon(pkg)
|
||||
drawable.toBitmap(px)
|
||||
}.getOrNull()
|
||||
|
||||
if (bmp != null) cache.put(key, bmp)
|
||||
bmp
|
||||
}
|
||||
|
||||
/** 预热:进入桌面后按页分批预取,避免翻页时白块 */
|
||||
suspend fun prefetch(pkgs: List<String>, sizePx: Int) = withContext(Dispatchers.IO) {
|
||||
pkgs.distinct().forEach { load(it, sizePx) }
|
||||
}
|
||||
|
||||
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 到同一张画布上
|
||||
val out = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(out)
|
||||
setBounds(0, 0, size, size)
|
||||
draw(canvas)
|
||||
return out
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package com.ttstd.compose.launcher.core
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
/* =============================================================================
|
||||
* 协议 v3:设计稿坐标,与设备完全无关
|
||||
*
|
||||
* 设计原则(这几条决定了它能不能跨设备一致):
|
||||
* 1. 坐标是「设计稿像素」,不是 dp、不是格子索引、不是百分比
|
||||
* 2. 不携带任何样式(颜色/字号/圆角由 Launcher 端主题决定),只携带内容
|
||||
* 3. 版本号进协议,解析失败必须能降级,不能崩桌面
|
||||
* 4. 未知字段忽略(ignoreUnknownKeys),新版本字段旧版本也能读
|
||||
* ===========================================================================*/
|
||||
|
||||
@Serializable
|
||||
data class LauncherLayout(
|
||||
val schemaVersion: Int = 3,
|
||||
val revision: Int = 1,
|
||||
val canvas: CanvasDef = CanvasDef(),
|
||||
val fit: FitDef = FitDef(),
|
||||
val pages: List<PageDef> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class CanvasDef(
|
||||
val designWidth: Int = 1080,
|
||||
val designHeight: Int = 1920,
|
||||
val safeTop: Int = 132,
|
||||
val safeBottom: Int = 72,
|
||||
) {
|
||||
fun toDesignCanvas() = DesignCanvas(designWidth, designHeight, safeTop, safeBottom)
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class FitDef(
|
||||
/** contain | elastic | stretch;未知值一律按 contain 处理 */
|
||||
val mode: String = "contain",
|
||||
val anchorY: Float = 0.5f,
|
||||
) {
|
||||
fun toFitConfig() = FitConfig(
|
||||
mode = when (mode.lowercase()) {
|
||||
"elastic" -> FitMode.ELASTIC
|
||||
"stretch" -> FitMode.STRETCH
|
||||
else -> FitMode.CONTAIN // 未知值兜底,绝不让它决定渲染
|
||||
},
|
||||
anchorY = anchorY.coerceIn(0f, 1f),
|
||||
)
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class PageDef(
|
||||
val index: Int = 0,
|
||||
val background: BackgroundDef = BackgroundDef(),
|
||||
val items: List<ItemDef> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class BackgroundDef(
|
||||
/** wallpaper | solid | gradient。wallpaper 表示画布透明,交给壁纸 —— 让留白不可见的关键 */
|
||||
val type: String = "wallpaper",
|
||||
val color: String? = null,
|
||||
val from: String? = null,
|
||||
val to: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ItemDef(
|
||||
val id: String,
|
||||
val type: String,
|
||||
val x: Float,
|
||||
val y: Float,
|
||||
val w: Float,
|
||||
val h: Float,
|
||||
val z: Int = 1,
|
||||
val payload: PayloadDef = PayloadDef(),
|
||||
) {
|
||||
fun toCanvasItem() = CanvasItem(id, type, x, y, w, h)
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class PayloadDef(
|
||||
val label: String? = null,
|
||||
@SerialName("package") val pkg: String? = null,
|
||||
val provider: String? = null,
|
||||
val intent: String? = null,
|
||||
val radius: Int? = null,
|
||||
)
|
||||
|
||||
/* =============================================================================
|
||||
* 解析:宽容但不放纵
|
||||
* ===========================================================================*/
|
||||
object LayoutCodec {
|
||||
|
||||
val json = Json {
|
||||
ignoreUnknownKeys = true // 新版本加了字段,旧版本照样能读
|
||||
isLenient = true
|
||||
encodeDefaults = false // 不把默认值写进文件,减小体积
|
||||
prettyPrint = false
|
||||
}
|
||||
|
||||
sealed interface ParseResult {
|
||||
data class Ok(val layout: LauncherLayout) : ParseResult
|
||||
data class Bad(val reason: String) : ParseResult
|
||||
}
|
||||
|
||||
fun parse(text: String): ParseResult = try {
|
||||
val layout = json.decodeFromString<LauncherLayout>(text)
|
||||
val issues = LayoutValidator.validate(layout)
|
||||
val errors = issues.filter { it.level == LayoutValidator.Level.ERROR }
|
||||
when {
|
||||
errors.isNotEmpty() -> ParseResult.Bad(
|
||||
errors.take(3).joinToString(";") { it.message }
|
||||
)
|
||||
layout.pages.isEmpty() -> ParseResult.Bad("pages 为空")
|
||||
else -> ParseResult.Ok(layout)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
ParseResult.Bad("JSON 解析失败:${e.message?.take(120)}")
|
||||
}
|
||||
|
||||
fun encode(layout: LauncherLayout): String = json.encodeToString(layout)
|
||||
}
|
||||
|
||||
/* =============================================================================
|
||||
* 校验:与网页端 editor/canvas.html 的 validate() 规则逐条对齐
|
||||
* ===========================================================================*/
|
||||
object LayoutValidator {
|
||||
|
||||
enum class Level { ERROR, WARN }
|
||||
data class Issue(val level: Level, val itemId: String, val message: String)
|
||||
|
||||
private const val MAX_ITEMS_PER_PAGE = 80
|
||||
|
||||
fun validate(layout: LauncherLayout): List<Issue> {
|
||||
val out = ArrayList<Issue>()
|
||||
val c = layout.canvas
|
||||
|
||||
if (layout.schemaVersion != 3) {
|
||||
out += Issue(Level.ERROR, "-", "仅支持布局协议 v3")
|
||||
}
|
||||
if (c.designWidth !in 320..8192 || c.designHeight !in 480..8192) {
|
||||
out += Issue(Level.ERROR, "-", "画布尺寸异常:${c.designWidth}×${c.designHeight}")
|
||||
}
|
||||
if (layout.pages.size > 20) {
|
||||
out += Issue(Level.ERROR, "-", "页数超限:${layout.pages.size} > 20")
|
||||
}
|
||||
|
||||
layout.pages.forEachIndexed { pi, page ->
|
||||
val tag = if (layout.pages.size > 1) "P${pi + 1} " else ""
|
||||
if (page.items.size > MAX_ITEMS_PER_PAGE) {
|
||||
out += Issue(Level.ERROR, "-", "$tag 元素数超限:${page.items.size}")
|
||||
}
|
||||
val ids = HashSet<String>(page.items.size)
|
||||
for (it in page.items) {
|
||||
val who = tag + it.id
|
||||
if (it.id.isBlank()) out += Issue(Level.ERROR, who, "id 为空")
|
||||
if (!ids.add(it.id)) out += Issue(Level.ERROR, who, "id 重复")
|
||||
|
||||
if (!it.x.isFinite() || !it.y.isFinite() || !it.w.isFinite() || !it.h.isFinite()) {
|
||||
out += Issue(Level.ERROR, who, "坐标或尺寸不是有限数")
|
||||
}
|
||||
if (it.w <= 0f || it.h <= 0f) out += Issue(Level.ERROR, who, "尺寸非正数")
|
||||
if (it.x < 0f || it.y < 0f) out += Issue(Level.ERROR, who, "坐标为负")
|
||||
if (it.x + it.w > c.designWidth + 0.5f) out += Issue(Level.ERROR, who, "右侧超出画布")
|
||||
if (it.y + it.h > c.designHeight + 0.5f) out += Issue(Level.ERROR, who, "底部超出画布")
|
||||
|
||||
// 类型与必填字段:这两条是真机「白图标 / 空组件」的根因
|
||||
when (it.type) {
|
||||
"app_icon" -> if (it.payload.pkg.isNullOrBlank()) {
|
||||
out += Issue(Level.ERROR, who, "应用图标缺少 package")
|
||||
}
|
||||
"widget" -> if (!(it.payload.provider ?: "").contains('/')) {
|
||||
out += Issue(Level.ERROR, who, "provider 需形如 com.x/.Widget")
|
||||
}
|
||||
"shortcut", "dock_bg" -> Unit
|
||||
else -> out += Issue(Level.WARN, who, "未知类型 ${it.type},将被跳过")
|
||||
}
|
||||
|
||||
if (it.y < c.safeTop) out += Issue(Level.WARN, who, "顶部进入安全区")
|
||||
if (it.y + it.h > c.designHeight - c.safeBottom) {
|
||||
out += Issue(Level.WARN, who, "底部进入安全区")
|
||||
}
|
||||
}
|
||||
|
||||
// 重叠:自由画布允许有意叠放,只报 WARN
|
||||
for (i in page.items.indices) for (j in i + 1 until page.items.size) {
|
||||
val a = page.items[i]; val b = page.items[j]
|
||||
if (a.type == "dock_bg" || b.type == "dock_bg") continue
|
||||
val overlap = a.x < b.x + b.w && a.x + a.w > b.x &&
|
||||
a.y < b.y + b.h && a.y + a.h > b.y
|
||||
if (overlap) out += Issue(Level.WARN, tag + a.id, "与 ${b.id} 重叠")
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 渲染端只需要 ERROR 级别的判断,WARN 交给编辑器提示 */
|
||||
fun isRenderable(layout: LauncherLayout) =
|
||||
validate(layout).none { it.level == Level.ERROR }
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package com.ttstd.compose.launcher.core
|
||||
|
||||
import android.content.Context
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.StandardCopyOption
|
||||
|
||||
class LayoutRepository(private val context: Context) {
|
||||
private val mainFile = File(context.filesDir, "launcher_layout.json")
|
||||
private val lastGoodFile = File(context.filesDir, "last_good_layout.json")
|
||||
private val mutex = Mutex()
|
||||
|
||||
private val _layout = MutableStateFlow<LauncherLayout?>(null)
|
||||
val layout: StateFlow<LauncherLayout?> = _layout.asStateFlow()
|
||||
|
||||
private val _degraded = MutableStateFlow<String?>(null)
|
||||
val degraded: StateFlow<String?> = _degraded.asStateFlow()
|
||||
|
||||
suspend fun load(): LauncherLayout = withContext(Dispatchers.IO) {
|
||||
mutex.withLock {
|
||||
_layout.value ?: loadFromDisk().also { _layout.value = it }
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadFromDisk(): LauncherLayout {
|
||||
val main = readFile(mainFile)?.let(LayoutCodec::parse)
|
||||
if (main is LayoutCodec.ParseResult.Ok) {
|
||||
_degraded.value = null
|
||||
return main.layout
|
||||
}
|
||||
|
||||
val reason = (main as? LayoutCodec.ParseResult.Bad)?.reason?.let { "主布局不可用:$it → " }.orEmpty()
|
||||
val previous = readFile(lastGoodFile)?.let(LayoutCodec::parse)
|
||||
if (previous is LayoutCodec.ParseResult.Ok) {
|
||||
_degraded.value = reason + "已回退到上次可用布局"
|
||||
return previous.layout
|
||||
}
|
||||
|
||||
val defaultLayout = runCatching {
|
||||
context.assets.open("default_layout.json").bufferedReader().use { it.readText() }
|
||||
}.getOrNull()?.let(LayoutCodec::parse)
|
||||
if (defaultLayout is LayoutCodec.ParseResult.Ok) {
|
||||
_degraded.value = reason + "已使用内置默认布局"
|
||||
return defaultLayout.layout
|
||||
}
|
||||
_degraded.value = reason + "默认布局不可用"
|
||||
return LauncherLayout(pages = listOf(PageDef()))
|
||||
}
|
||||
|
||||
/** 校验通过且完成落盘后,才向桌面提交新布局。 */
|
||||
suspend fun save(jsonText: String): Result<Unit> = withContext(Dispatchers.IO) {
|
||||
mutex.withLock {
|
||||
when (val parsed = LayoutCodec.parse(jsonText)) {
|
||||
is LayoutCodec.ParseResult.Bad -> Result.failure(IllegalArgumentException(parsed.reason))
|
||||
is LayoutCodec.ParseResult.Ok -> runCatching {
|
||||
val current = readFile(mainFile)
|
||||
if (current != jsonText) {
|
||||
if (current != null && LayoutCodec.parse(current) is LayoutCodec.ParseResult.Ok) {
|
||||
writeFile(lastGoodFile, current)
|
||||
}
|
||||
writeFile(mainFile, jsonText)
|
||||
}
|
||||
_layout.value = parsed.layout
|
||||
_degraded.value = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun readFile(file: File): String? =
|
||||
runCatching { file.readText() }.getOrNull()
|
||||
|
||||
private fun writeFile(target: File, text: String) {
|
||||
val temp = File(target.parentFile, target.name + ".tmp")
|
||||
try {
|
||||
FileOutputStream(temp).use { stream ->
|
||||
stream.write(text.toByteArray())
|
||||
stream.fd.sync()
|
||||
}
|
||||
Files.move(
|
||||
temp.toPath(),
|
||||
target.toPath(),
|
||||
StandardCopyOption.ATOMIC_MOVE,
|
||||
StandardCopyOption.REPLACE_EXISTING,
|
||||
)
|
||||
} finally {
|
||||
temp.delete()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.ttstd.compose.launcher.core
|
||||
|
||||
import android.content.Context
|
||||
import android.os.SystemClock
|
||||
import com.ttstd.compose.launcher.BuildConfig
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.IOException
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URI
|
||||
|
||||
class RemoteLayoutSync(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)
|
||||
private val mutex = Mutex()
|
||||
private var etag: String? = null
|
||||
|
||||
fun connection(): Connection {
|
||||
val savedServer = prefs.getString("server", null)
|
||||
val savedToken = prefs.getString("token", null)
|
||||
// 全新安装使用编译期内置配置;用户显式清空并保存后仍能关闭同步。
|
||||
return if (savedServer == null && savedToken == null) {
|
||||
Connection(BuildConfig.SYNC_SERVER, BuildConfig.DEVICE_TOKEN)
|
||||
} else {
|
||||
Connection(savedServer.orEmpty(), savedToken.orEmpty())
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveConnection(server: String, token: String) = withContext(Dispatchers.IO) {
|
||||
val address = server.trim().trimEnd('/')
|
||||
val credential = token.trim()
|
||||
if (address.isNotEmpty() || credential.isNotEmpty()) {
|
||||
endpoint(address)
|
||||
require(credential.length in 24..256 && credential.all { it in '!'..'~' }) {
|
||||
"设备令牌须为 24–256 位可打印 ASCII 字符"
|
||||
}
|
||||
}
|
||||
|
||||
mutex.withLock {
|
||||
val saved = prefs.edit().putString("server", address).putString("token", credential).commit()
|
||||
if (!saved) throw IOException("连接设置保存失败")
|
||||
etag = null
|
||||
}
|
||||
}
|
||||
|
||||
/** 返回 null 表示设备尚未配置同步。 */
|
||||
suspend fun sync(): Int? = withContext(Dispatchers.IO) {
|
||||
mutex.withLock {
|
||||
val config = connection()
|
||||
if (config.server.isEmpty()) return@withLock null
|
||||
val connection = endpoint(config.server).toURL().openConnection() as HttpURLConnection
|
||||
try {
|
||||
val deadline = SystemClock.elapsedRealtime() + 15_000
|
||||
connection.instanceFollowRedirects = false
|
||||
connection.connectTimeout = 5_000
|
||||
connection.readTimeout = 5_000
|
||||
connection.useCaches = false
|
||||
connection.setRequestProperty("Authorization", "Bearer " + config.token)
|
||||
connection.setRequestProperty("Accept", "application/json")
|
||||
connection.setRequestProperty("Accept-Encoding", "identity")
|
||||
etag?.let { connection.setRequestProperty("If-None-Match", it) }
|
||||
|
||||
when (val status = connection.responseCode) {
|
||||
HttpURLConnection.HTTP_NOT_MODIFIED -> {
|
||||
if (etag == null) throw IOException("服务端未返回布局")
|
||||
repo.layout.value?.revision ?: throw IOException("本地没有可用的同步布局")
|
||||
}
|
||||
HttpURLConnection.HTTP_OK -> {
|
||||
if (connection.contentLength > MAX_LAYOUT_BYTES) throw IOException("布局超过 1 MiB")
|
||||
val payload = connection.inputStream.use { input ->
|
||||
val buffer = ByteArray(8192)
|
||||
val output = ByteArrayOutputStream()
|
||||
while (true) {
|
||||
currentCoroutineContext().ensureActive()
|
||||
if (SystemClock.elapsedRealtime() > deadline) throw IOException("布局下载超时")
|
||||
val count = input.read(buffer)
|
||||
if (count < 0) break
|
||||
if (output.size() + count > MAX_LAYOUT_BYTES) throw IOException("布局超过 1 MiB")
|
||||
output.write(buffer, 0, count)
|
||||
}
|
||||
output.toByteArray().decodeToString(throwOnInvalidSequence = true)
|
||||
}
|
||||
currentCoroutineContext().ensureActive()
|
||||
repo.save(payload).getOrThrow()
|
||||
etag = connection.getHeaderField("ETag")
|
||||
repo.layout.value?.revision
|
||||
}
|
||||
HttpURLConnection.HTTP_UNAUTHORIZED -> throw IOException("服务端拒绝设备令牌")
|
||||
else -> throw IOException("服务端返回 HTTP $status")
|
||||
}
|
||||
} finally {
|
||||
connection.disconnect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun endpoint(address: String): URI {
|
||||
val base = runCatching { URI(address) }.getOrNull()
|
||||
val scheme = base?.scheme?.lowercase()
|
||||
require(base != null && (scheme == "https" || BuildConfig.DEBUG && scheme == "http")) {
|
||||
if (BuildConfig.DEBUG) "请输入 HTTP 或 HTTPS 服务地址" else "请输入 HTTPS 服务地址"
|
||||
}
|
||||
require(base.host != null && base.userInfo == null && base.rawQuery == null &&
|
||||
base.rawFragment == null && (base.port == -1 || base.port in 1..65535)
|
||||
) { "服务地址示例:https://launcher.example.com" }
|
||||
return URI(address + "/api/layout")
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val MAX_LAYOUT_BYTES = 1024 * 1024
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.ttstd.compose.launcher.core
|
||||
|
||||
import android.app.WallpaperManager
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.util.Log
|
||||
import androidx.core.graphics.drawable.toBitmap
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* 取系统壁纸并降到屏幕宽度。
|
||||
*
|
||||
* 为什么必须缩放:原图常见 1440×3120,甚至 2160×3840,
|
||||
* 直接铺到 1080 宽的屏幕上等于白占 4 倍内存,而且绘制时还要再做一次缩放。
|
||||
*
|
||||
* 为什么失败要返回 null 而不是抛:桌面可以退化成纯色渐变背景,
|
||||
* 但绝不能因为读不到壁纸而启动失败。
|
||||
*/
|
||||
object WallpaperLoader {
|
||||
|
||||
private const val TAG = "Wallpaper"
|
||||
|
||||
suspend fun load(context: Context, targetWidthPx: Int): Bitmap? = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
val drawable = WallpaperManager.getInstance(context).drawable
|
||||
?: return@runCatching null
|
||||
|
||||
val iw = drawable.intrinsicWidth.takeIf { it > 0 } ?: targetWidthPx
|
||||
val ih = drawable.intrinsicHeight.takeIf { it > 0 } ?: targetWidthPx
|
||||
val scale = targetWidthPx.toFloat() / iw
|
||||
val w = (iw * scale).toInt().coerceIn(1, 4096)
|
||||
val h = (ih * scale).toInt().coerceIn(1, 8192)
|
||||
|
||||
drawable.toBitmap(width = w, height = h)
|
||||
}.onFailure {
|
||||
Log.w(TAG, "load failed: ${it.message}")
|
||||
}.getOrNull()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.ttstd.compose.launcher.core
|
||||
|
||||
import android.view.View
|
||||
|
||||
/**
|
||||
* widget 宿主的最小接口。
|
||||
*
|
||||
* 放在 core 而不是 ui:真机实现是 AppWidgetHostController(也属于 core),
|
||||
* 而 ui 只是消费者。接口留在 core 可以避免 core → ui 的反向依赖,
|
||||
* 单元测试里也能传 null 直接跳过 widget 渲染。
|
||||
*/
|
||||
interface WidgetHostProvider {
|
||||
fun obtain(key: String, provider: String, widthDp: Int, heightDp: Int): View?
|
||||
}
|
||||
@@ -0,0 +1,449 @@
|
||||
package com.ttstd.compose.launcher.ui
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.view.ViewGroup
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.offset
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.pager.HorizontalPager
|
||||
import androidx.compose.foundation.pager.rememberPagerState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.produceState
|
||||
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.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import com.ttstd.compose.launcher.core.CanvasMapper
|
||||
import com.ttstd.compose.launcher.core.CanvasDef
|
||||
import com.ttstd.compose.launcher.core.FitConfig
|
||||
import com.ttstd.compose.launcher.core.IconLoader
|
||||
import com.ttstd.compose.launcher.core.ItemDef
|
||||
import com.ttstd.compose.launcher.core.LauncherLayout
|
||||
import com.ttstd.compose.launcher.core.PageDef
|
||||
import com.ttstd.compose.launcher.core.PlacedItem
|
||||
import com.ttstd.compose.launcher.core.WidgetHostProvider
|
||||
import com.ttstd.compose.launcher.core.avoidSystemInsets
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/* =============================================================================
|
||||
* 渲染端:一份设计稿 + 一次映射 = 所有设备同一张画面
|
||||
*
|
||||
* 必须守住的四个实现细节(都是踩过的坑):
|
||||
*
|
||||
* 1) Modifier.offset { IntOffset(px) },不要 offset(x.dp, y.dp)
|
||||
* dp 换算有 0.1dp 级取整误差,几十个元素叠起来能看出不齐;lambda 版直接吃像素。
|
||||
*
|
||||
* 2) 不用 Modifier.scale() 整体缩放
|
||||
* scale 只影响绘制与命中测试,布局约束仍是原始尺寸;文字会被栅格化后放大,
|
||||
* 0.45 倍下明显发虚。逐元素乘系数才能让文字按真实像素渲染。
|
||||
*
|
||||
* 3) 壁纸铺满「整屏」,画布背景透明
|
||||
* 这是让留白不可见的关键:用户看到的边缘其实是壁纸,不会感知到"空了一块"。
|
||||
*
|
||||
* 4) 图标尺寸从映射结果推导,不写死 dp
|
||||
* 写死 dp 会让小屏图标占格 40%、大屏占 30%,视觉调性跑偏。
|
||||
* ===========================================================================*/
|
||||
|
||||
@Composable
|
||||
fun LauncherCanvas(
|
||||
layout: LauncherLayout,
|
||||
icons: IconLoader,
|
||||
statusBarPx: Float,
|
||||
modifier: Modifier = Modifier,
|
||||
/** 导航条/手势条高度:映射区域要扣掉它,壁纸仍然铺满整屏 */
|
||||
bottomInsetPx: Float = 0f,
|
||||
wallpaper: Bitmap? = null,
|
||||
widgetHost: WidgetHostProvider? = null,
|
||||
onWidgetBind: (String, String) -> Unit = { _, _ -> },
|
||||
onItemClick: (ItemDef) -> Unit = {},
|
||||
onItemLongClick: (ItemDef) -> Unit = {},
|
||||
onPageChanged: (Int) -> Unit = {},
|
||||
) {
|
||||
val pages = layout.pages
|
||||
if (pages.isEmpty()) {
|
||||
Box(modifier.fillMaxSize().background(Color(0xFF11151C)))
|
||||
return
|
||||
}
|
||||
|
||||
val pagerState = rememberPagerState(initialPage = 0, pageCount = { pages.size })
|
||||
LaunchedEffect(pagerState.currentPage) { onPageChanged(pagerState.currentPage) }
|
||||
|
||||
BoxWithConstraints(modifier.fillMaxSize()) {
|
||||
val screenW = constraints.maxWidth.toFloat()
|
||||
val screenH = constraints.maxHeight.toFloat()
|
||||
// 内容映射区 = 整屏高度 − 底部手势区。壁纸用整屏,内容不用,
|
||||
// 否则最后一排图标会被手势条压住(各机型手势条高度还不一样)
|
||||
val contentH = (screenH - bottomInsetPx).coerceAtLeast(1f)
|
||||
|
||||
// ① 壁纸层:铺满整屏,Crop 裁一点无妨(壁纸裁切没人看得出)
|
||||
if (wallpaper != null) {
|
||||
Image(
|
||||
bitmap = wallpaper.asImageBitmap(),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Crop,
|
||||
)
|
||||
} else {
|
||||
Box(
|
||||
Modifier.fillMaxSize().background(
|
||||
Brush.verticalGradient(
|
||||
listOf(Color(0xFF31507E), Color(0xFF10141C)),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// ② 页面层
|
||||
HorizontalPager(
|
||||
state = pagerState,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
beyondViewportPageCount = 1, // 预组合相邻页,翻页不白屏
|
||||
) { pageIndex ->
|
||||
CanvasPage(
|
||||
page = pages[pageIndex],
|
||||
canvas = layout.canvas,
|
||||
fit = layout.fit.toFitConfig(),
|
||||
screenW = screenW,
|
||||
screenH = contentH,
|
||||
statusBarPx = statusBarPx,
|
||||
icons = icons,
|
||||
widgetHost = widgetHost,
|
||||
onWidgetBind = onWidgetBind,
|
||||
onItemClick = onItemClick,
|
||||
onItemLongClick = onItemLongClick,
|
||||
)
|
||||
}
|
||||
|
||||
// ③ 页指示器:贴屏幕底部,不参与画布缩放
|
||||
if (pages.size > 1) {
|
||||
PageIndicator(
|
||||
count = pages.size,
|
||||
current = pagerState.currentPage,
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomCenter)
|
||||
.padding(bottom = 18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CanvasPage(
|
||||
page: PageDef,
|
||||
canvas: CanvasDef,
|
||||
fit: FitConfig,
|
||||
screenW: Float,
|
||||
screenH: Float,
|
||||
statusBarPx: Float,
|
||||
icons: IconLoader,
|
||||
widgetHost: WidgetHostProvider?,
|
||||
onWidgetBind: (String, String) -> Unit,
|
||||
onItemClick: (ItemDef) -> Unit,
|
||||
onItemLongClick: (ItemDef) -> Unit,
|
||||
) {
|
||||
val density = LocalDensity.current
|
||||
val items = remember(page) { page.items.map { it.toCanvasItem() } }
|
||||
|
||||
val mapped = remember(canvas, fit, items, screenW, screenH, statusBarPx) {
|
||||
if (items.isEmpty()) null
|
||||
else CanvasMapper
|
||||
.map(canvas.toDesignCanvas(), fit, items, screenW, screenH)
|
||||
.avoidSystemInsets(screenH, statusBarPx)
|
||||
}
|
||||
|
||||
// 必须用一个 Box 收住所有子元素:否则它们会成为 Pager 页的直接子节点,
|
||||
// 被父布局按「顺序排列」而不是按 offset 绝对定位,表现为只看到第一个元素。
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
// 背景:wallpaper = 透明(交给最底层壁纸),这是留白不可见的前提
|
||||
when (page.background.type) {
|
||||
"solid" -> Box(Modifier.fillMaxSize().background(parseColor(page.background.color)))
|
||||
"gradient" -> Box(
|
||||
Modifier.fillMaxSize().background(
|
||||
Brush.verticalGradient(
|
||||
listOf(parseColor(page.background.from), parseColor(page.background.to)),
|
||||
),
|
||||
),
|
||||
)
|
||||
else -> Unit
|
||||
}
|
||||
|
||||
if (mapped == null) return@Box
|
||||
|
||||
val byId = remember(page) { page.items.associateBy { it.id } }
|
||||
|
||||
mapped.placed
|
||||
.sortedBy { byId[it.source.id]?.z ?: 1 }
|
||||
.forEach { p ->
|
||||
val def = byId[p.source.id] ?: return@forEach
|
||||
Box(
|
||||
Modifier
|
||||
.offset { IntOffset(p.left.roundToInt(), p.top.roundToInt()) }
|
||||
.size(
|
||||
with(density) { p.width.toDp() },
|
||||
with(density) { p.height.toDp() },
|
||||
),
|
||||
) {
|
||||
CanvasItemView(
|
||||
def = def,
|
||||
widgetKey = "${page.index}:${def.id}",
|
||||
placed = p,
|
||||
icons = icons,
|
||||
widgetHost = widgetHost,
|
||||
onWidgetBind = onWidgetBind,
|
||||
onClick = { onItemClick(def) },
|
||||
onLongClick = { onItemLongClick(def) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
private fun CanvasItemView(
|
||||
def: ItemDef,
|
||||
widgetKey: String,
|
||||
placed: PlacedItem,
|
||||
icons: IconLoader,
|
||||
widgetHost: WidgetHostProvider?,
|
||||
onWidgetBind: (String, String) -> Unit,
|
||||
onClick: () -> Unit,
|
||||
onLongClick: () -> Unit,
|
||||
) {
|
||||
when (def.type) {
|
||||
"app_icon" -> AppIconView(
|
||||
pkg = def.payload.pkg.orEmpty(),
|
||||
label = def.payload.label.orEmpty(),
|
||||
sizePx = (placed.width * 0.78f).roundToInt(),
|
||||
labelPx = placed.width * 0.19f,
|
||||
icons = icons,
|
||||
onClick = onClick,
|
||||
onLongClick = onLongClick,
|
||||
)
|
||||
|
||||
"shortcut" -> ShortcutView(
|
||||
label = def.payload.label.orEmpty(),
|
||||
sizePx = (placed.width * 0.78f).roundToInt(),
|
||||
labelPx = placed.width * 0.19f,
|
||||
onClick = onClick,
|
||||
onLongClick = onLongClick,
|
||||
)
|
||||
|
||||
"dock_bg" -> Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.clip(RoundedCornerShape(((def.payload.radius ?: 56) * placed.width / def.w).dp))
|
||||
.background(Color.White.copy(alpha = 0.11f)),
|
||||
)
|
||||
|
||||
"widget" -> {
|
||||
val provider = def.payload.provider.orEmpty()
|
||||
val density = LocalDensity.current.density
|
||||
val hostView = widgetHost?.obtain(
|
||||
widgetKey, provider,
|
||||
(placed.width / density).roundToInt().coerceAtLeast(1),
|
||||
(placed.height / density).roundToInt().coerceAtLeast(1),
|
||||
)
|
||||
if (hostView != null) {
|
||||
androidx.compose.runtime.key(hostView) {
|
||||
AndroidView(
|
||||
factory = {
|
||||
(hostView.parent as? ViewGroup)?.removeView(hostView)
|
||||
hostView
|
||||
},
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
}
|
||||
} else {
|
||||
// 宿主不可用时的占位,别让用户看到一片透明(会误以为桌面坏了)
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(Color.White.copy(alpha = 0.09f))
|
||||
.clickable { onWidgetBind(widgetKey, provider) },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
text = (def.payload.label ?: "组件") + " · 点击绑定",
|
||||
color = Color.White.copy(alpha = 0.45f),
|
||||
fontSize = 12.sp,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
else -> Unit // 未知类型:协议校验会 WARN,渲染端直接跳过
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
private fun AppIconView(
|
||||
pkg: String,
|
||||
label: String,
|
||||
sizePx: Int,
|
||||
labelPx: Float,
|
||||
icons: IconLoader,
|
||||
onClick: () -> Unit,
|
||||
onLongClick: () -> Unit,
|
||||
) {
|
||||
val density = LocalDensity.current
|
||||
// key 里带上 sizePx:尺寸变了要重新取,否则会拿旧分辨率的图去拉伸
|
||||
val bmp by produceState<Bitmap?>(initialValue = null, pkg, sizePx) {
|
||||
value = icons.load(pkg, sizePx)
|
||||
}
|
||||
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = Modifier.combinedClickable(
|
||||
onClick = onClick,
|
||||
onLongClick = onLongClick,
|
||||
),
|
||||
) {
|
||||
val side = with(density) { sizePx.toDp() }
|
||||
val shape = RoundedCornerShape(side * 0.24f)
|
||||
if (bmp != null) {
|
||||
Image(
|
||||
bitmap = bmp!!.asImageBitmap(),
|
||||
contentDescription = label,
|
||||
modifier = Modifier.size(side).clip(shape),
|
||||
)
|
||||
} else {
|
||||
// 首字母兜底:包名还没解析出来时也不留白块
|
||||
Box(
|
||||
Modifier
|
||||
.size(side)
|
||||
.clip(shape)
|
||||
.background(
|
||||
Brush.linearGradient(listOf(Color(0xFF5B8CFF), Color(0xFF3B5FD0))),
|
||||
),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
text = label.take(1).ifBlank { "?" },
|
||||
color = Color.White,
|
||||
fontSize = with(density) { (sizePx * 0.42f).toSp() },
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (label.isNotBlank()) {
|
||||
Text(
|
||||
text = label,
|
||||
color = Color.White.copy(alpha = 0.88f),
|
||||
fontSize = with(density) { labelPx.coerceIn(9f, 44f).toSp() },
|
||||
maxLines = 1,
|
||||
softWrap = false,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.padding(top = 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
private fun ShortcutView(
|
||||
label: String,
|
||||
sizePx: Int,
|
||||
labelPx: Float,
|
||||
onClick: () -> Unit,
|
||||
onLongClick: () -> Unit,
|
||||
) {
|
||||
val density = LocalDensity.current
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = Modifier.combinedClickable(
|
||||
onClick = onClick,
|
||||
onLongClick = onLongClick,
|
||||
),
|
||||
) {
|
||||
val side = with(density) { sizePx.toDp() }
|
||||
Box(
|
||||
Modifier
|
||||
.size(side)
|
||||
.clip(RoundedCornerShape(side * 0.24f))
|
||||
.background(
|
||||
Brush.linearGradient(listOf(Color(0xFF7A8CA8), Color(0xFF4A5A72))),
|
||||
),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
text = label.take(1).ifBlank { "?" },
|
||||
color = Color.White,
|
||||
fontSize = with(density) { (sizePx * 0.42f).toSp() },
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
}
|
||||
Text(
|
||||
text = label,
|
||||
color = Color.White.copy(alpha = 0.88f),
|
||||
fontSize = with(density) { labelPx.coerceIn(9f, 44f).toSp() },
|
||||
maxLines = 1,
|
||||
softWrap = false,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PageIndicator(count: Int, current: Int, modifier: Modifier = Modifier) {
|
||||
Row(modifier, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
repeat(count) { i ->
|
||||
Box(
|
||||
Modifier
|
||||
.size(if (i == current) 7.dp else 5.dp)
|
||||
.clip(CircleShape)
|
||||
.background(
|
||||
if (i == current) Color.White.copy(alpha = 0.9f)
|
||||
else Color.White.copy(alpha = 0.35f),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** #RRGGBB / #AARRGGBB,解析失败返回透明(不崩,最坏情况是没有背景色) */
|
||||
private fun parseColor(hex: String?): Color = runCatching {
|
||||
val s = hex?.trim()?.removePrefix("#") ?: return@runCatching Color.Transparent
|
||||
val v = when (s.length) {
|
||||
6 -> 0xFF000000L or s.toLong(16)
|
||||
8 -> s.toLong(16)
|
||||
else -> return@runCatching Color.Transparent
|
||||
}
|
||||
Color(v)
|
||||
}.getOrDefault(Color.Transparent)
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.ttstd.compose.launcher.ui.theme
|
||||
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
/**
|
||||
* 桌面固定深色主题。
|
||||
*
|
||||
* 不跟随系统浅色:桌面背景是壁纸,浅色主题会让图标文字在亮壁纸上直接看不清。
|
||||
* 系统栏颜色也不在这里设 —— 由 Activity 的 enableEdgeToEdge 负责。
|
||||
*/
|
||||
private val Scheme = darkColorScheme(
|
||||
primary = Color(0xFF7FA6FF),
|
||||
onPrimary = Color(0xFF0B0F16),
|
||||
background = Color(0xFF0B0F16),
|
||||
onBackground = Color(0xFFE8EDF7),
|
||||
surface = Color(0xFF141A24),
|
||||
onSurface = Color(0xFFE8EDF7),
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun VibeLauncherTheme(content: @Composable () -> Unit) {
|
||||
MaterialTheme(colorScheme = Scheme, content = content)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<path
|
||||
android:fillColor="@color/icon_bg"
|
||||
android:pathData="M0,0h108v108h-108z" />
|
||||
<path
|
||||
android:fillColor="@color/icon_fg"
|
||||
android:pathData="M28,30h13l13,33l13,-33h13l-20,50h-12z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!-- 窗口背景 = 壁纸主色。冷启动 T0 阶段先显示这个色,
|
||||
比默认白色好得多(白闪一下是 Launcher 最容易被投诉的手感问题) -->
|
||||
<color name="window_bg">#0B0F16</color>
|
||||
<color name="icon_bg">#1B2434</color>
|
||||
<color name="icon_fg">#4C7DFF</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">Vibe Launcher</string>
|
||||
<string name="default_layout_missing">内置布局缺失</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!-- 用平台主题,不引 AppCompat / Material Components:
|
||||
桌面只需要一个无 ActionBar 的窗口,Compose 负责全部 UI -->
|
||||
<style name="Theme.VibeLauncher" parent="android:Theme.Material.NoActionBar">
|
||||
<item name="android:windowBackground">@color/window_bg</item>
|
||||
<item name="android:colorBackground">@color/window_bg</item>
|
||||
<item name="android:statusBarColor">@android:color/transparent</item>
|
||||
<item name="android:navigationBarColor">@android:color/transparent</item>
|
||||
<item name="android:windowLightStatusBar">false</item>
|
||||
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
|
||||
<item name="android:windowAnimationStyle">@null</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,237 @@
|
||||
package com.ttstd.compose.launcher.core
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.max
|
||||
|
||||
/**
|
||||
* 设计稿映射的单测(JUnit)。
|
||||
*
|
||||
* 覆盖 50 条断言:行带识别、三种映射策略、极端比例、状态栏修正、
|
||||
* 协议校验、空输入健壮性、双向居中不变式,以及六设备全量自检报告。
|
||||
*
|
||||
* 全部是纯 Kotlin,不需要真机、不需要 Android SDK:
|
||||
* ./gradlew :app:testDebugUnitTest
|
||||
*/
|
||||
class CanvasMapperTest {
|
||||
|
||||
private var pass = 0
|
||||
private var fail = 0
|
||||
|
||||
private fun expect(name: String, cond: Boolean, detail: String = "") {
|
||||
if (cond) { pass++; println(" ✓ $name") }
|
||||
else { fail++; println(" ✗ $name $detail") }
|
||||
}
|
||||
|
||||
private fun near(a: Float, b: Float, tol: Float = 0.75f) = abs(a - b) <= tol
|
||||
|
||||
/** 与网页编辑器 canvas.html 的 demo 布局完全一致 */
|
||||
private fun demoItems(): List<CanvasItem> {
|
||||
val pad = 108f; val colW = 216f; val icon = 132f; val ih = 168f
|
||||
fun colX(c: Int) = pad + c * colW + (colW - icon) / 2f
|
||||
val out = ArrayList<CanvasItem>()
|
||||
out += CanvasItem("w_clock", "widget", pad, 196f, 864f, 320f)
|
||||
val apps = listOf("微信", "相机", "相册", "设置", "浏览器", "音乐", "地图", "日历")
|
||||
apps.forEachIndexed { i, _ ->
|
||||
val c = i % 4; val r = i / 4
|
||||
out += CanvasItem("i$i", "app_icon", colX(c), 604f + r * 224f, icon, ih)
|
||||
}
|
||||
out += CanvasItem("w_weather", "widget", pad, 1076f, 420f, 300f)
|
||||
out += CanvasItem("w_music", "widget", 552f, 1076f, 420f, 300f)
|
||||
listOf("扫一扫", "支付", "钱包", "更多").forEachIndexed { i, _ ->
|
||||
out += CanvasItem("s$i", "shortcut", colX(i), 1650f, icon, ih)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
fun allInvariants() {
|
||||
|
||||
val canvas = DesignCanvas(1080, 1920, 132, 72)
|
||||
val items = demoItems()
|
||||
|
||||
println("══ 1. 行带识别(弹性模式的前提)══")
|
||||
run {
|
||||
val bands = CanvasMapper.rowBands(items)
|
||||
expect("行带数量 = 5", bands.size == 5, "实际 ${bands.size}")
|
||||
expect("首带从 196 开始", near(bands[0].top, 196f))
|
||||
expect("末带到 1818 结束", near(bands.last().bottom, 1818f))
|
||||
}
|
||||
|
||||
println("\n══ 2. CONTAIN:完整显示、零变形、留白位置正确 ══")
|
||||
run {
|
||||
val m = CanvasMapper.map(canvas, FitConfig(FitMode.CONTAIN, 0.5f), items, 1080f, 2160f)
|
||||
expect("scale = 1.0", near(m.scaleX, 1f, 0.001f), "实际 ${m.scaleX}")
|
||||
expect("零变形", abs(m.verticalDistortion) < 0.0001f)
|
||||
expect("横向无留白(贴合)", near(m.offsetX, 0f, 0.01f))
|
||||
expect("上下各留 120", near(m.offsetY, 120f), "实际 ${m.offsetY}")
|
||||
expect("总留白 240", near(m.visualGapPx, 240f))
|
||||
val last = m.placed.maxBy { it.top }.let { it.top + it.height }
|
||||
expect("内容底部 1818+120=1938", near(last, 1938f), "实际 $last")
|
||||
expect("内容未溢出屏幕", last <= 2160f)
|
||||
}
|
||||
|
||||
println("\n══ 3. ELASTIC:零留白、零变形、间隙按比例放大 ══")
|
||||
run {
|
||||
val m = CanvasMapper.map(canvas, FitConfig(FitMode.ELASTIC), items, 1080f, 2160f)
|
||||
expect("scale = 1.0", near(m.scaleX, 1f, 0.001f))
|
||||
expect("零变形", abs(m.verticalDistortion) < 0.0001f)
|
||||
expect("整体无整块留白", near(m.visualGapPx, 0f, 0.01f))
|
||||
// 空白总量 796,多出 240 → k = 1036/796 ≈ 1.3015
|
||||
expect("间隙放大系数 ≈ 1.3015", near(m.gapScale, 1.3015f, 0.002f), "实际 ${m.gapScale}")
|
||||
val last = m.placed.maxBy { it.top }.let { it.top + it.height }
|
||||
// 1818 + (前 4 段空白 694) × 0.3015 ≈ 2027.2,底部余 102×1.3015 ≈ 132.8
|
||||
expect("末行底部 ≈ 2027", near(last, 2027.2f, 1.5f), "实际 $last")
|
||||
expect("底部余量与设计稿保持同比例", near(2160f - last, 132.8f, 1.5f), "实际 ${2160f - last}")
|
||||
expect("所有元素不溢出", m.placed.all { it.top + it.height <= 2160f + 0.5f })
|
||||
}
|
||||
|
||||
println("\n══ 4. STRETCH:铺满但有变形(用于暴露代价)══")
|
||||
run {
|
||||
val m = CanvasMapper.map(canvas, FitConfig(FitMode.STRETCH), items, 1080f, 2160f)
|
||||
expect("纵向变形 +12.5%", near(m.verticalDistortion * 100f, 12.5f, 0.1f),
|
||||
"实际 ${m.verticalDistortion * 100}%")
|
||||
expect("无留白", near(m.visualGapPx, 0f))
|
||||
expect("画布底边精确映射到 2160", near(m.contentHeight, 2160f, 0.5f), "实际 ${m.contentHeight}")
|
||||
// 设计稿底部原有 102px 空白,拉伸后按 1.125 倍变成 114.75,因此末行落在 2045
|
||||
val last = m.placed.maxBy { it.top }.let { it.top + it.height }
|
||||
expect("末行底部 = 1818×1.125 = 2045", near(last, 2045.25f, 0.6f), "实际 $last")
|
||||
}
|
||||
|
||||
println("\n══ 5. 19.5:9 与 21:9 的极端情况 ══")
|
||||
run {
|
||||
val m1 = CanvasMapper.map(canvas, FitConfig(FitMode.CONTAIN, 0.5f), items, 1080f, 2340f)
|
||||
expect("19.5:9 上下各留 210", near(m1.offsetY, 210f), "实际 ${m1.offsetY}")
|
||||
|
||||
val m2 = CanvasMapper.map(canvas, FitConfig(FitMode.ELASTIC), items, 1080f, 2520f)
|
||||
val last = m2.placed.maxBy { it.top }.let { it.top + it.height }
|
||||
expect("21:9 弹性后不溢出", last <= 2520.5f, "实际 $last")
|
||||
expect("21:9 弹性后仍零变形", abs(m2.verticalDistortion) < 0.0001f)
|
||||
}
|
||||
|
||||
println("\n══ 6. 平板 4:3:弹性必须自动退回等比,否则纵向溢出 ══")
|
||||
run {
|
||||
val m = CanvasMapper.map(canvas, FitConfig(FitMode.ELASTIC), items, 1600f, 2560f)
|
||||
expect("自动退回 CONTAIN", m.effectiveMode == FitMode.CONTAIN, "实际 ${m.effectiveMode}")
|
||||
expect("按高度贴合 s=1.333", near(m.scaleX, 1.3333f, 0.002f), "实际 ${m.scaleX}")
|
||||
expect("左右各留 80", near(m.offsetX, 80f, 0.5f), "实际 ${m.offsetX}")
|
||||
val last = m.placed.maxBy { it.top }.let { it.top + it.height }
|
||||
expect("内容不溢出", last <= 2560.5f, "实际 $last")
|
||||
}
|
||||
|
||||
println("\n══ 7. 状态栏修正:内容不得压到真机状态栏 ══")
|
||||
run {
|
||||
// 1440 屏状态栏 176px,设计稿 safeTop 132 只放大到 132(scale=1.0),差 44px
|
||||
val m = CanvasMapper.map(canvas, FitConfig(FitMode.CONTAIN, 0.5f), items, 1080f, 2160f)
|
||||
val fixed = m.avoidSystemInsets(2160f, 176f)
|
||||
expect("内容顶部被推到 176", near(fixed.offsetY, 176f), "实际 ${fixed.offsetY}")
|
||||
// 首个元素 y=196,加上 176 的顶部偏移 = 372
|
||||
expect("顶部元素不再压状态栏", near(fixed.placed.minOf { it.top }, 372f, 1f),
|
||||
"实际 ${fixed.placed.minOf { it.top }}")
|
||||
expect("未额外溢出", fixed.placed.maxOf { it.top + it.height } <= 2160.5f)
|
||||
|
||||
val noNeed = m.avoidSystemInsets(2160f, 96f)
|
||||
expect("状态栏更矮时不动", near(noNeed.offsetY, 120f), "实际 ${noNeed.offsetY}")
|
||||
}
|
||||
|
||||
println("\n══ 8. 协议校验:越界与安全区告警 ══")
|
||||
run {
|
||||
val bad = demoItems().toMutableList()
|
||||
bad += CanvasItem("oob", "app_icon", 1000f, 300f, 200f, 168f) // 右侧越界
|
||||
bad += CanvasItem("neg", "app_icon", -10f, 100f, 132f, 168f) // 负坐标 + 进安全区
|
||||
val issues = CanvasValidator.validate(canvas, bad, statusBarPx = 176, navBarPx = 96)
|
||||
expect("检出右侧越界", issues.any { it.itemId == "oob" && it.level == CanvasValidator.Issue.Level.ERROR })
|
||||
expect("检出负坐标", issues.any { it.itemId == "neg" && it.level == CanvasValidator.Issue.Level.ERROR })
|
||||
expect("检出进入安全区", issues.any { it.itemId == "neg" && it.level == CanvasValidator.Issue.Level.WARN })
|
||||
expect("检出 safeTop 小于真机状态栏", issues.any { it.message.contains("safeTop") })
|
||||
|
||||
// demo 布局本身不应有 ERROR
|
||||
val okIssues = CanvasValidator.validate(canvas, demoItems(), 120, 96)
|
||||
expect("示例布局无 ERROR", okIssues.none { it.level == CanvasValidator.Issue.Level.ERROR },
|
||||
okIssues.filter { it.level == CanvasValidator.Issue.Level.ERROR }.toString())
|
||||
}
|
||||
|
||||
println("\n══ 9. 空列表 / 零尺寸的健壮性 ══")
|
||||
run {
|
||||
val m = CanvasMapper.map(canvas, FitConfig(FitMode.ELASTIC), emptyList(), 1080f, 2160f)
|
||||
expect("空列表不崩且返回默认映射", m.placed.isEmpty() && near(m.scaleX, 1f, 0.001f))
|
||||
val z = CanvasMapper.map(canvas, FitConfig(FitMode.CONTAIN), items, 0f, 0f)
|
||||
expect("零尺寸不崩", z.placed.isEmpty())
|
||||
}
|
||||
|
||||
println("\n══ 10. 双向居中不变式:宽了居左右、高了居上下 ══")
|
||||
run {
|
||||
// 更高(21:9):上下留白,左右必须为 0
|
||||
val tall = CanvasMapper.map(canvas, FitConfig(FitMode.CONTAIN, 0.5f), items, 1080f, 2520f)
|
||||
val cwT = canvas.designWidth * tall.scaleX
|
||||
val chT = canvas.designHeight * tall.scaleY
|
||||
expect("21:9 左右无留白", near((1080f - cwT) / 2f, 0f, 0.01f))
|
||||
expect("21:9 上下各 300", near(tall.offsetY, 300f), "实际 ${tall.offsetY}")
|
||||
expect("21:9 上下对称", near(tall.offsetY, 2520f - chT - tall.offsetY, 0.01f))
|
||||
|
||||
// 更宽(16:10):左右留白,上下必须为 0
|
||||
val wide = CanvasMapper.map(canvas, FitConfig(FitMode.CONTAIN, 0.5f), items, 1440f, 2304f)
|
||||
val cwW = canvas.designWidth * wide.scaleX
|
||||
val chW = canvas.designHeight * wide.scaleY
|
||||
expect("16:10 缩放 1.2", near(wide.scaleX, 1.2f, 0.001f), "实际 ${wide.scaleX}")
|
||||
expect("16:10 上下无留白", near(2304f - chW, 0f, 0.01f))
|
||||
expect("16:10 左右各 72", near(wide.offsetX, 72f, 0.5f), "实际 ${wide.offsetX}")
|
||||
expect("16:10 左右对称", near(wide.offsetX, 1440f - cwW - wide.offsetX, 0.01f))
|
||||
|
||||
// 非 1080 宽设备:1440×3120 应放大 1.333,纵向留 560
|
||||
val k2 = CanvasMapper.map(canvas, FitConfig(FitMode.CONTAIN, 0.5f), items, 1440f, 3120f)
|
||||
expect("2K 缩放 1.333", near(k2.scaleX, 1.3333f, 0.002f), "实际 ${k2.scaleX}")
|
||||
expect("2K 纵向留 560", near(3120f - canvas.designHeight * k2.scaleY, 560f, 0.5f))
|
||||
|
||||
// 不变式:等比缩放下永远只在一个方向留白,不会两边同时留
|
||||
val all = listOf(1080f to 1920f, 1080f to 2340f, 1080f to 2520f, 1600f to 2560f, 1440f to 2304f)
|
||||
var bothSides = 0
|
||||
for ((w, h) in all) {
|
||||
val m = CanvasMapper.map(canvas, FitConfig(FitMode.CONTAIN, 0.5f), items, w, h)
|
||||
val gx = (w - canvas.designWidth * m.scaleX) / 2f
|
||||
val gy = (h - canvas.designHeight * m.scaleY) / 2f
|
||||
if (gx > 0.5f && gy > 0.5f) bothSides++
|
||||
}
|
||||
expect("不会同时出现横纵留白", bothSides == 0, "出现 $bothSides 台")
|
||||
}
|
||||
|
||||
println("\n══ 11. 六设备全量自检报告 ══")
|
||||
println(FitSelfCheckLite.report(canvas, items))
|
||||
|
||||
|
||||
println("通过 $pass 项,失败 $fail 项")
|
||||
assertEquals("有 $fail 项断言失败,详见 stdout", 0, fail)
|
||||
}
|
||||
}
|
||||
|
||||
/** 不依赖 Compose 的报告器(DesignCanvasRenderer 里那份要 Compose 环境) */
|
||||
object FitSelfCheckLite {
|
||||
fun report(canvas: DesignCanvas, items: List<CanvasItem>): String {
|
||||
val devices = listOf(
|
||||
"16:9" to (1080 to 1920),
|
||||
"16:8" to (1080 to 2160),
|
||||
"19.5:9" to (1080 to 2340),
|
||||
"20:9" to (1080 to 2400),
|
||||
"21:9" to (1080 to 2520),
|
||||
"平板4:3" to (1600 to 2560),
|
||||
)
|
||||
val sb = StringBuilder()
|
||||
for (mode in FitMode.entries) {
|
||||
sb.appendLine(" [$mode]")
|
||||
for ((name, wh) in devices) {
|
||||
val (w, h) = wh
|
||||
val m = CanvasMapper.map(canvas, FitConfig(mode), items, w.toFloat(), h.toFloat())
|
||||
val bottom = m.placed.maxOfOrNull { it.top + it.height } ?: 0f
|
||||
sb.appendLine(
|
||||
" %-8s %4dx%-5d s=%.3f 留白=%4.0f 变形=%+5.1f%% 底部=%4.0f/%-5d %s".format(
|
||||
name, w, h, m.scaleX, m.visualGapPx, m.verticalDistortion * 100,
|
||||
bottom, h, if (bottom > h + 0.5f) "溢出!" else "OK",
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
return sb.toString()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package com.ttstd.compose.launcher.core
|
||||
|
||||
import java.io.File
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.boolean
|
||||
import kotlinx.serialization.json.jsonArray
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* 协议层单测:坏包必须被拦住,好包必须能读写往返。
|
||||
*
|
||||
* 这些断言对应的是真机上最贵的一类 bug —— 一个 JSON 字段写错,
|
||||
* 桌面就变成"一片空白",而日志里什么都没有。
|
||||
*/
|
||||
class LayoutValidatorTest {
|
||||
|
||||
@Test
|
||||
fun sharedLayoutCases() {
|
||||
val fixtures = File("../../docs/layout-cases.json").readText()
|
||||
for (entry in Json.parseToJsonElement(fixtures).jsonArray) {
|
||||
val fixture = entry.jsonObject
|
||||
val result = LayoutCodec.parse(fixture.getValue("layout").toString())
|
||||
assertEquals(
|
||||
fixture.getValue("name").jsonPrimitive.content,
|
||||
fixture.getValue("accepted").jsonPrimitive.boolean,
|
||||
result is LayoutCodec.ParseResult.Ok,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun page(vararg items: ItemDef) = PageDef(0, BackgroundDef("wallpaper"), items.toList())
|
||||
|
||||
private fun layout(vararg pages: PageDef) = LauncherLayout(
|
||||
canvas = CanvasDef(1080, 1920, 132, 72),
|
||||
fit = FitDef("contain", 0.5f),
|
||||
pages = pages.toList(),
|
||||
)
|
||||
|
||||
private fun item(
|
||||
id: String,
|
||||
x: Float = 100f,
|
||||
y: Float = 300f,
|
||||
w: Float = 200f,
|
||||
h: Float = 200f,
|
||||
type: String = "app_icon",
|
||||
pkg: String? = "com.demo.app",
|
||||
provider: String? = null,
|
||||
) = ItemDef(
|
||||
id = id, type = type, x = x, y = y, w = w, h = h,
|
||||
payload = PayloadDef(label = "L", pkg = pkg, provider = provider),
|
||||
)
|
||||
|
||||
private fun errors(l: LauncherLayout) =
|
||||
LayoutValidator.validate(l).filter { it.level == LayoutValidator.Level.ERROR }
|
||||
|
||||
private fun warns(l: LauncherLayout) =
|
||||
LayoutValidator.validate(l).filter { it.level == LayoutValidator.Level.WARN }
|
||||
|
||||
@Test
|
||||
fun goodLayoutHasNoError() {
|
||||
val l = layout(page(item("a"), item("b", x = 400f)))
|
||||
assertEquals(errors(l).toString(), 0, errors(l).size)
|
||||
assertTrue(LayoutValidator.isRenderable(l))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun duplicateIdIsError() {
|
||||
val l = layout(page(item("a"), item("a", x = 500f)))
|
||||
assertTrue(errors(l).any { it.message.contains("id 重复") })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun appIconWithoutPackageIsError() {
|
||||
val l = layout(page(item("a", pkg = null)))
|
||||
assertTrue(errors(l).any { it.message.contains("package") })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun widgetProviderWithoutSlashIsError() {
|
||||
val l = layout(page(item("w", type = "widget", pkg = null, provider = "com.x.ClockWidget")))
|
||||
assertTrue(errors(l).any { it.message.contains("provider") })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun outOfCanvasIsError() {
|
||||
// x + w = 1100 > 1080
|
||||
val l = layout(page(item("a", x = 900f, w = 200f)))
|
||||
assertTrue(errors(l).any { it.message.contains("右侧超出画布") })
|
||||
val l2 = layout(page(item("b", y = 1800f, h = 200f)))
|
||||
assertTrue(errors(l2).any { it.message.contains("底部超出画布") })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun negativeCoordinateIsError() {
|
||||
val l = layout(page(item("a", x = -1f)))
|
||||
assertTrue(errors(l).any { it.message.contains("坐标为负") })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun safeAreaIsWarnNotError() {
|
||||
val l = layout(page(item("a", y = 60f))) // safeTop = 132
|
||||
assertTrue(warns(l).any { it.message.contains("顶部进入安全区") })
|
||||
assertEquals(0, errors(l).size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unknownTypeIsWarn() {
|
||||
val l = layout(page(item("x", type = "sticker", pkg = null)))
|
||||
assertTrue(warns(l).any { it.message.contains("未知类型") })
|
||||
assertEquals(0, errors(l).size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun overlapIsWarnNotError() {
|
||||
val l = layout(page(item("a"), item("b", x = 150f, y = 350f)))
|
||||
assertTrue(warns(l).any { it.message.contains("重叠") })
|
||||
assertEquals(0, errors(l).size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun emptyPagesIsRejected() {
|
||||
val r = LayoutCodec.parse("""{"schemaVersion":3,"pages":[]}""")
|
||||
assertTrue(r is LayoutCodec.ParseResult.Bad)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unsupportedSchemaIsRejected() {
|
||||
val original = layout(page(item("a"))).copy(schemaVersion = 2)
|
||||
assertTrue(LayoutCodec.parse(LayoutCodec.encode(original)) is LayoutCodec.ParseResult.Bad)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun brokenJsonIsRejectedNotThrown() {
|
||||
val r = LayoutCodec.parse("{ this is not json ")
|
||||
assertTrue(r is LayoutCodec.ParseResult.Bad)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun encodeThenParseRoundTrip() {
|
||||
val original = layout(page(item("a"), item("b", x = 400f)))
|
||||
val text = LayoutCodec.encode(original)
|
||||
val parsed = LayoutCodec.parse(text)
|
||||
assertTrue("解析失败: ${(parsed as? LayoutCodec.ParseResult.Bad)?.reason}",
|
||||
parsed is LayoutCodec.ParseResult.Ok)
|
||||
val back = (parsed as LayoutCodec.ParseResult.Ok).layout
|
||||
assertEquals(3, back.schemaVersion)
|
||||
assertEquals(original.pages[0].items.size, back.pages[0].items.size)
|
||||
assertEquals(original.pages[0].items[1].x, back.pages[0].items[1].x, 0.01f)
|
||||
assertEquals("com.demo.app", back.pages[0].items[0].payload.pkg)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unknownFieldIsIgnored() {
|
||||
// 新版编辑器加了字段,旧版 Launcher 必须还能读 —— 否则一次发版就得强制升级
|
||||
val text = """
|
||||
{"schemaVersion":3,"revision":9,"futureField":{"a":1},
|
||||
"canvas":{"designWidth":1080,"designHeight":1920,"safeTop":132,"safeBottom":72,
|
||||
"anotherNew":true},
|
||||
"fit":{"mode":"contain","anchorY":0.5},
|
||||
"pages":[{"index":0,"items":[
|
||||
{"id":"a","type":"app_icon","x":100,"y":300,"w":200,"h":200,"glow":0.6,
|
||||
"payload":{"label":"微信","package":"com.tencent.mm"}}]}]}
|
||||
""".trimIndent()
|
||||
val r = LayoutCodec.parse(text)
|
||||
assertTrue(r is LayoutCodec.ParseResult.Ok)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unknownFitModeFallsBackToContain() {
|
||||
val l = LauncherLayout(fit = FitDef("weird_mode", 0.5f))
|
||||
assertEquals(FitMode.CONTAIN, l.fit.toFitConfig().mode)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anchorIsClamped() {
|
||||
val l = LauncherLayout(fit = FitDef("contain", 3.5f))
|
||||
assertEquals(1f, l.fit.toFitConfig().anchorY, 0.0001f)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user