Add image buttons and exclusive launcher actions

This commit is contained in:
tongtong committed 2026-11-27 21:31:23 +08:00
1 parent 8d604a5807
commit 74c725e8d7
23 files changed
+868 -104

No files matched your search

+5 -1
View File
@@ -64,6 +64,8 @@ $env:LAUNCHER_DEVICE_TOKEN = '<设备令牌>'
画布的「小组件目录」与「布局发布」共用浏览器登录状态。读取目录后可切换「第三方小组件」和「系统小组件」,并按组件名称、应用名称、组件类名或应用包名搜索并添加到当前页,再调整尺寸和位置。添加到画布后按正常流程发布,设备首次使用组件仍需进行 Android 授权。
编辑器的「默认图标样式」支持应用原图、跟随系统、圆形和圆角方形。应用图标可单独覆盖默认值或上传图片。「图片按钮」可独立显示上传的图片。包名与 Intent 都留空时只显示图片;同时设置时优先使用 Intent。图片支持 PNG、JPEG 和由浏览器转换为 PNG 的 WebP,上传数据最多 512 KiB,宽高最多 1024 像素。服务器在发布前检查图片是否存在,Android 会先下载并缓存再应用布局。
## HTTP 接口
管理后台使用账号密码登录,HttpOnly、SameSite=Strict Cookie 保持登录 30 天,关闭浏览器和重启服务后仍可使用。退出会清除本浏览器 Cookie;修改密码会使已有登录失效。生产部署在 `vibe-launcher-auth` Secret 增加 `ADMIN_USERNAME`(默认 admin)、`ADMIN_PASSWORD`(至少 12 位),通过 HTTPS 使用,`COOKIE_SECURE` 保持默认 true。未配置密码时不启用网页登录。可选 `ADMIN_TOKEN` 兼容原有脚本。
@@ -75,6 +77,8 @@ $env:LAUNCHER_DEVICE_TOKEN = '<设备令牌>'
| `GET /healthz` | 服务健康状态 |
| `GET /api/layout` | 下发 v3 布局。设备可传 `If-None-Match`,版本内容相同时返回 304 |
| `GET /api/layout/events` | 设备 SSE 事件流。收到 `layout-changed` 后使用原有布局下发接口同步 |
| `POST /api/admin/images` | 登录后上传 PNG 或 JPEG 原始字节,返回图片 ID |
| `GET /api/images/{id}` | 管理员或设备读取图片,返回原始字节 |
| `GET /api/admin/layout` | 获取线上布局及其 `ETag` |
| `GET /api/admin/widget-providers` | 读取系统与第三方 AppWidget Provider 目录 |
| `PUT /api/admin/widget-providers` | 幂等导入目录。每项可用组件字符串,或包含 `component`、`label`、`appLabel` 和可选 `category` 的对象(`system` 或 `third-party`) |
@@ -99,7 +103,7 @@ $env:LAUNCHER_DEVICE_TOKEN = '<设备令牌>'
| --- | --- |
| 服务器 | `175.178.213.60`,Debian 12,k3s 单节点,SSH 密钥登录 |
| 命名空间 / 工作负载 | `vibe-launcher` / `deploy/vibe-launcher-backend`,单副本 `Recreate` |
| 镜像 | `docker.io/library/vibe-launcher-backend:1.1.0-deploy14`,`imagePullPolicy: IfNotPresent` |
| 镜像 | `docker.io/library/vibe-launcher-backend:1.1.0-deploy17`,`imagePullPolicy: IfNotPresent` |
| 端口 | 容器 8080,Service NodePort **30830**(30800 是 youlai-boot,30810 是 tts-server,30820 是 compose-remote-server) |
| 公网入口 | `https://api.ttstd.com/launcher/`(灰云直连源站,不走 Cloudflare);nginx 剥掉 `/launcher/` 前缀后反代 `127.0.0.1:30830` |
| 数据 | 宿主机 `/opt/vibe-launcher/data/layouts.sqlite` 挂到容器 `/data`,Pod 重建不丢版本历史 |
@@ -48,14 +48,6 @@ class LauncherViewModel(app: Application) : AndroidViewModel(app) {
private val _degraded = MutableStateFlow<String?>(null)
val degraded: StateFlow<String?> = _degraded.asStateFlow()
val statusBarPx: Float by lazy {
systemDimen("status_bar_height", fallbackDp = 24f)
}
val navBarPx: Float by lazy {
systemDimen("navigation_bar_height", fallbackDp = 16f)
}
init {
// 壁纸与布局并行:壁纸解码比 JSON 解析慢得多,串行会让首帧多等 100ms+
viewModelScope.launch {
@@ -78,15 +70,9 @@ class LauncherViewModel(app: Application) : AndroidViewModel(app) {
fun onItemClick(def: ItemDef) {
val ctx = getApplication<Application>()
val opened = when (def.type) {
"app_icon" -> AppLaunch.launchPackage(ctx, def.payload.pkg.orEmpty())
"shortcut" -> {
val target = def.payload.intent?.takeIf { it.isNotBlank() }
?: def.payload.pkg.orEmpty()
AppLaunch.launchUriOrAction(ctx, target)
}
else -> return
}
if (def.type !in setOf("app_icon", "shortcut", "image")) return
if (def.type == "image" && !def.payload.hasLaunchTarget()) return
val opened = AppLaunch.launch(ctx, def.payload, appIcon = def.type == "app_icon")
if (!opened) Toast.makeText(ctx, "找不到应用或无法启动", Toast.LENGTH_SHORT).show()
}
@@ -116,17 +102,7 @@ class LauncherViewModel(app: Application) : AndroidViewModel(app) {
page.items.filter { it.type == "app_icon" }.forEach { item ->
val pkg = item.payload.pkg ?: return@forEach
val px = (item.w * s * 0.78f).toInt().coerceIn(24, 384)
icons.load(pkg, px)
}
}
private fun systemDimen(name: String, fallbackDp: Float): Float {
val res = getApplication<Application>().resources
val id = res.getIdentifier(name, "dimen", "android")
return if (id > 0) {
res.getDimensionPixelSize(id).toFloat()
} else {
fallbackDp * res.displayMetrics.density
if (item.payload.iconStyle != "image") icons.load(pkg, px, item.payload.iconStyle ?: layout.iconStyle)
}
}
@@ -1,6 +1,7 @@
package com.ttstd.compose.launcher
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.SystemClock
import android.util.Log
@@ -11,10 +12,14 @@ import androidx.activity.ComponentActivity
import androidx.activity.OnBackPressedCallback
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.SystemBarStyle
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
@@ -25,6 +30,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle
@@ -77,7 +83,11 @@ class MainActivity : ComponentActivity() {
val t0 = SystemClock.uptimeMillis()
// 状态栏/导航条透明,让壁纸铺满整屏 —— 留白不可见的前提
enableEdgeToEdge()
enableEdgeToEdge(
statusBarStyle = SystemBarStyle.dark(android.graphics.Color.TRANSPARENT),
navigationBarStyle = SystemBarStyle.dark(android.graphics.Color.TRANSPARENT),
)
if (Build.VERSION.SDK_INT >= 29) window.isNavigationBarContrastEnforced = false
// 桌面按返回键什么都不该发生(默认会退出到上一个应用,体验上像"桌面崩了")
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
@@ -91,17 +101,22 @@ class MainActivity : ComponentActivity() {
val wallpaper by vm.wallpaper.collectAsState()
val degraded by vm.degraded.collectAsState()
val density = LocalDensity.current
val statusBar = WindowInsets.statusBars.getTop(density).toFloat()
val navigationBar = WindowInsets.navigationBars.getBottom(density).toFloat()
Box(Modifier.fillMaxSize()) {
LauncherCanvas(
layout = layout,
icons = vm.icons,
statusBarPx = vm.statusBarPx,
bottomInsetPx = vm.navBarPx,
statusBarPx = statusBar,
bottomInsetPx = navigationBar,
wallpaper = wallpaper,
widgetHost = widgets,
onWidgetBind = { key, provider ->
try {
widgets.requestBind(key, provider, { bindWidget.launch(it) }, ::configureWidget)
if (!widgets.requestBind(key, provider, { bindWidget.launch(it) }, ::configureWidget)) {
Toast.makeText(this@MainActivity, "此设备找不到该微件", Toast.LENGTH_SHORT).show()
}
} catch (error: RuntimeException) {
Toast.makeText(this@MainActivity, "无法打开小组件授权", Toast.LENGTH_SHORT).show()
}
@@ -1,5 +1,6 @@
package com.ttstd.compose.launcher.core
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
@@ -19,30 +20,67 @@ object AppLaunch {
private const val TAG = "AppLaunch"
fun launchPackage(context: Context, pkg: String): Boolean {
if (pkg.isBlank()) return false
val intent = context.packageManager.getLaunchIntentForPackage(pkg) ?: run {
Log.w(TAG, "no launch intent for $pkg")
return false
}
intent.addFlags(
Intent.FLAG_ACTIVITY_NEW_TASK or
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED,
private val settingsActions = mapOf(
"ACTION_SETTINGS" to Settings.ACTION_SETTINGS,
"ACTION_WIFI_SETTINGS" to Settings.ACTION_WIFI_SETTINGS,
"ACTION_BLUETOOTH_SETTINGS" to Settings.ACTION_BLUETOOTH_SETTINGS,
"ACTION_WIRELESS_SETTINGS" to Settings.ACTION_WIRELESS_SETTINGS,
"ACTION_AIRPLANE_MODE_SETTINGS" to Settings.ACTION_AIRPLANE_MODE_SETTINGS,
"ACTION_DISPLAY_SETTINGS" to Settings.ACTION_DISPLAY_SETTINGS,
"ACTION_SOUND_SETTINGS" to Settings.ACTION_SOUND_SETTINGS,
"ACTION_LOCATION_SOURCE_SETTINGS" to Settings.ACTION_LOCATION_SOURCE_SETTINGS,
"ACTION_APPLICATION_SETTINGS" to Settings.ACTION_APPLICATION_SETTINGS,
"ACTION_DATE_SETTINGS" to Settings.ACTION_DATE_SETTINGS,
"ACTION_ACCESSIBILITY_SETTINGS" to Settings.ACTION_ACCESSIBILITY_SETTINGS,
)
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)
fun launch(context: Context, payload: PayloadDef, appIcon: Boolean): Boolean {
val pkg = payload.pkg.orEmpty().trim()
val cls = payload.className.orEmpty().trim()
val action = payload.settingsAction.orEmpty()
val raw = payload.intent.orEmpty()
val intent = when (payload.launchMode(appIcon)) {
"settings" -> Intent(settingsActions[action] ?: return false)
"component" -> {
val component = ComponentName.unflattenFromString(payload.componentName.orEmpty().trim())
?: return false
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
return start(context, intent)
Intent(Intent.ACTION_MAIN).setComponent(component)
}
"application" -> {
if (pkg.isEmpty()) return false
if (cls.isEmpty()) {
context.packageManager.getLaunchIntentForPackage(pkg)
?.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)
} else {
val target = when {
cls.startsWith(".") -> pkg + cls
'.' !in cls -> "$pkg.$cls"
else -> cls
}
Intent(Intent.ACTION_MAIN).setComponent(ComponentName(pkg, target))
}
}
"intent" -> runCatching {
if (raw.contains("://")) Intent.parseUri(raw, Intent.URI_INTENT_SCHEME)
else context.packageManager.getLaunchIntentForPackage(raw)
}.getOrNull()
else -> null
} ?: return false
for (extra in payload.extras) {
val key = extra.key.trim()
if (key.isEmpty()) return false
val value = extra.value.trim()
when (extra.type) {
"string" -> intent.putExtra(key, extra.value)
"boolean" -> intent.putExtra(key, value.toBooleanStrictOrNull() ?: return false)
"int" -> intent.putExtra(key, value.toIntOrNull() ?: return false)
"long" -> intent.putExtra(key, value.toLongOrNull() ?: return false)
"double" -> intent.putExtra(key, value.toDoubleOrNull()?.takeIf { it.isFinite() } ?: return false)
else -> return false
}
}
return start(context, intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
private fun start(context: Context, intent: Intent): Boolean {
@@ -6,6 +6,10 @@ import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProviderInfo
import android.content.ComponentName
import android.content.Context
import android.util.AttributeSet
import android.widget.FrameLayout
import android.widget.TextView
import android.view.Gravity
import android.content.Intent
import androidx.compose.runtime.mutableIntStateOf
import android.os.Build
@@ -19,7 +23,10 @@ class AppWidgetHostController(
hostId: Int = loadOrCreateHostId(context),
) : WidgetHostProvider {
private val host = AppWidgetHost(context, hostId)
private val host = object : AppWidgetHost(context, hostId) {
override fun onCreateView(context: Context, appWidgetId: Int, info: AppWidgetProviderInfo): AppWidgetHostView =
CompatibleWidgetView(context)
}
private val manager = AppWidgetManager.getInstance(context)
private val bindings = context.getSharedPreferences("widget_bindings", Context.MODE_PRIVATE)
@@ -51,19 +58,21 @@ class AppWidgetHostController(
}
}
fun requestBind(key: String, provider: String, launch: (Intent) -> Unit, configure: (Int) -> Unit) {
val info = resolveProvider(provider) ?: return
if (pending != null || boundId(key, info) != null) return
fun requestBind(key: String, provider: String, launch: (Intent) -> Unit, configure: (Int) -> Unit): Boolean {
val info = resolveProvider(provider) ?: return false
if (pending != null || boundId(key, info) != null) return true
val id = host.allocateAppWidgetId()
pending = PendingBinding(key, provider, id)
try {
if (manager.bindAppWidgetIdIfAllowed(id, info.provider)) {
completeAuthorization(true, configure)
return
return true
}
launch(Intent(AppWidgetManager.ACTION_APPWIDGET_BIND)
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id)
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.provider))
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.provider)
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER_PROFILE, info.profile))
return true
} catch (error: RuntimeException) {
finishBinding(false)
throw error
@@ -173,6 +182,33 @@ class AppWidgetHostController(
return manager.installedProviders.firstOrNull { it.provider == cn }
}
private class CompatibleWidgetView(context: Context) : AppWidgetHostView(context) {
override fun generateLayoutParams(attrs: AttributeSet): FrameLayout.LayoutParams =
try {
super.generateLayoutParams(attrs)
} catch (_: UnsupportedOperationException) {
// Some providers omit a root size in RemoteViews. Use the host's assigned bounds.
val dimensions = context.obtainStyledAttributes(attrs, intArrayOf(
android.R.attr.layout_width, android.R.attr.layout_height,
))
try {
FrameLayout.LayoutParams(
dimensions.getLayoutDimension(0, LayoutParams.MATCH_PARENT),
dimensions.getLayoutDimension(1, LayoutParams.MATCH_PARENT),
Gravity.CENTER,
)
} finally {
dimensions.recycle()
}
}
override fun getErrorView(): View = TextView(context).apply {
text = "微件暂时无法显示"
setTextColor(android.graphics.Color.WHITE)
gravity = Gravity.CENTER
}
}
companion object {
private const val PREF = "widget_host"
private const val KEY_HOST_ID = "host_id"
@@ -3,8 +3,12 @@ package com.ttstd.compose.launcher.core
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Path
import android.graphics.RectF
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.AdaptiveIconDrawable
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.util.LruCache
import kotlinx.coroutines.Dispatchers
@@ -21,11 +25,11 @@ import kotlinx.coroutines.withContext
* ===========================================================================*/
class IconLoader(private val context: Context) {
// 内存上限按 1/8 可用内存给,最多 256 张
// 图标和图片共享按 KiB 计量的缓存。
private val cache = object : LruCache<String, Bitmap>(
(Runtime.getRuntime().maxMemory() / 8 / 1024).toInt().coerceIn(32, 256)
(Runtime.getRuntime().maxMemory() / 8 / 1024).toInt().coerceIn(4096, 32768)
) {
override fun sizeOf(key: String, value: Bitmap): Int = 1
override fun sizeOf(key: String, value: Bitmap): Int = (value.byteCount / 1024).coerceAtLeast(1)
}
private val pm: PackageManager get() = context.packageManager
@@ -34,14 +38,14 @@ class IconLoader(private val context: Context) {
* @param sizePx 目标边长的**像素**值,由 CanvasMapper 算出的 item 宽度决定,
* 不要在调用处写死 dp —— 这是不同分辨率下图标大小一致的唯一办法。
*/
suspend fun load(pkg: String, sizePx: Int): Bitmap? = withContext(Dispatchers.IO) {
suspend fun load(pkg: String, sizePx: Int, style: String = "system"): Bitmap? = withContext(Dispatchers.IO) {
val px = sizePx.coerceIn(24, 512)
val key = "$pkg@$px"
val key = "$pkg@$px:$style"
cache.get(key)?.let { return@withContext it }
val bmp = runCatching {
val drawable = pm.getApplicationIcon(pkg)
drawable.toBitmap(px)
drawable.toBitmap(px, style)
}.getOrNull()
if (bmp != null) cache.put(key, bmp)
@@ -55,17 +59,51 @@ class IconLoader(private val context: Context) {
fun clear() = cache.evictAll()
private fun Drawable.toBitmap(size: Int): Bitmap {
if (this is BitmapDrawable && bitmap != null) {
val src = bitmap
if (src.width == size && src.height == size) return src
return Bitmap.createScaledBitmap(src, size, size, true)
suspend fun loadImage(id: String): Bitmap? = withContext(Dispatchers.IO) {
if (!LayoutImages.validId(id)) return@withContext null
val key = "image:$id"
cache.get(key) ?: BitmapFactory.decodeFile(LayoutImages.file(context, id).path)?.also { cache.put(key, it) }
}
// 自适应图标要按目标尺寸重绘,直接 draw 到同一张画布上
private fun Drawable.toBitmap(size: Int, style: String): Bitmap {
val out = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
val canvas = Canvas(out)
setBounds(0, 0, size, size)
draw(canvas)
val side = size.toFloat()
val adaptive = this as? AdaptiveIconDrawable
if (style == "original" || style == "system" && adaptive != null) {
drawFitted(canvas, size, 0)
return out
}
val mask = Path()
when (style) {
"circle" -> mask.addCircle(side / 2, side / 2, side / 2, Path.Direction.CW)
"rounded" -> mask.addRoundRect(RectF(0f, 0f, side, side), side * .24f, side * .24f, Path.Direction.CW)
else -> {
val shape = AdaptiveIconDrawable(ColorDrawable(0), ColorDrawable(0))
shape.setBounds(0, 0, size, size)
mask.set(shape.iconMask)
}
}
canvas.clipPath(mask)
if (adaptive != null) {
adaptive.setBounds(0, 0, size, size)
adaptive.background?.draw(canvas)
adaptive.foreground?.draw(canvas)
} else {
canvas.drawColor(0xffe7ecf4.toInt())
drawFitted(canvas, size, (size * .16f).toInt())
}
return out
}
private fun Drawable.drawFitted(canvas: Canvas, size: Int, padding: Int) {
val usable = size - 2 * padding
val ratio = intrinsicWidth.coerceAtLeast(1).toFloat() / intrinsicHeight.coerceAtLeast(1)
val width = if (ratio >= 1f) usable else (usable * ratio).toInt().coerceAtLeast(1)
val height = if (ratio <= 1f) usable else (usable / ratio).toInt().coerceAtLeast(1)
val left = (size - width) / 2
val top = (size - height) / 2
setBounds(left, top, left + width, top + height)
draw(canvas)
}
}
@@ -0,0 +1,16 @@
package com.ttstd.compose.launcher.core
import android.content.Context
import java.io.File
internal object LayoutImages {
private val idPattern = Regex("[a-f0-9]{64}")
const val MAX_BYTES = 512 * 1024
fun validId(id: String?) = id != null && idPattern.matches(id)
fun file(context: Context, id: String): File {
require(validId(id))
return File(File(context.filesDir, "layout-images"), id)
}
}
@@ -22,6 +22,7 @@ data class LauncherLayout(
val canvas: CanvasDef = CanvasDef(),
val fit: FitDef = FitDef(),
val pages: List<PageDef> = emptyList(),
val iconStyle: String = "system",
)
@Serializable
@@ -87,7 +88,29 @@ data class PayloadDef(
val provider: String? = null,
val intent: String? = null,
val radius: Int? = null,
)
val imageId: String? = null,
val iconStyle: String? = null,
val className: String? = null,
val settingsAction: String? = null,
val launchMode: String? = null,
val componentName: String? = null,
val extras: List<IntentExtra> = emptyList(),
) {
fun launchMode(appIcon: Boolean = false): String = launchMode ?: when {
appIcon -> "application"
!settingsAction.isNullOrBlank() -> "settings"
!componentName.isNullOrBlank() -> "component"
!className.isNullOrBlank() -> "application"
!intent.isNullOrBlank() -> "intent"
!pkg.isNullOrBlank() -> "application"
else -> "none"
}
fun hasLaunchTarget() = launchMode() != "none"
}
@Serializable
data class IntentExtra(val key: String, val type: String, val value: String)
/* =============================================================================
* 解析:宽容但不放纵
@@ -175,10 +198,15 @@ object LayoutValidator {
"widget" -> if (!(it.payload.provider ?: "").contains('/')) {
out += Issue(Level.ERROR, who, "provider 需形如 com.x/.Widget")
}
"shortcut", "dock_bg" -> Unit
"image", "shortcut", "dock_bg" -> Unit
else -> out += Issue(Level.WARN, who, "未知类型 ${it.type},将被跳过")
}
val imageId = it.payload.imageId
if ((imageId != null || it.type == "image" || it.payload.iconStyle == "image") &&
!LayoutImages.validId(imageId)
) out += Issue(Level.ERROR, who, "图片资源 ID 无效")
if (it.y < c.safeTop) out += Issue(Level.WARN, who, "顶部进入安全区")
if (it.y + it.h > c.designHeight - c.safeBottom) {
out += Issue(Level.WARN, who, "底部进入安全区")
@@ -25,7 +25,7 @@ import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
class RemoteLayoutSync(context: Context, private val repo: LayoutRepository) {
class RemoteLayoutSync(private val context: Context, private val repo: LayoutRepository) {
data class Connection(val server: String, val token: String)
private val prefs = context.getSharedPreferences("layout_sync", Context.MODE_PRIVATE)
@@ -150,6 +150,10 @@ class RemoteLayoutSync(context: Context, private val repo: LayoutRepository) {
output.toByteArray().decodeToString(throwOnInvalidSequence = true)
}
currentCoroutineContext().ensureActive()
val parsed = LayoutCodec.parse(payload)
if (parsed !is LayoutCodec.ParseResult.Ok) throw IOException("布局验证失败")
val imageIds = parsed.layout.pages.flatMap { page -> page.items.mapNotNull { it.payload.imageId } }.toSet()
for (id in imageIds) downloadImage(config, id)
repo.save(payload).getOrThrow()
etag = connection.getHeaderField("ETag")
repo.layout.value?.revision
@@ -163,6 +167,49 @@ class RemoteLayoutSync(context: Context, private val repo: LayoutRepository) {
}
}
private suspend fun downloadImage(config: Connection, id: String) {
val target = LayoutImages.file(context, id)
if (target.isFile) return
currentCoroutineContext().ensureActive()
val url = endpoint(config.server).resolve("./images/$id").toURL()
val request = url.openConnection() as HttpURLConnection
try {
request.instanceFollowRedirects = false
request.connectTimeout = 5_000
request.readTimeout = 5_000
request.setRequestProperty("Authorization", "Bearer " + config.token)
if (request.responseCode != 200) throw IOException("图片资源下载失败")
val bytes = request.inputStream.use { input ->
val output = ByteArrayOutputStream()
val buffer = ByteArray(8192)
val deadline = SystemClock.elapsedRealtime() + 15_000
while (true) {
currentCoroutineContext().ensureActive()
if (SystemClock.elapsedRealtime() > deadline) throw IOException("图片下载超时")
val count = input.read(buffer)
if (count < 0) break
if (output.size() + count > LayoutImages.MAX_BYTES) throw IOException("图片超过大小限制")
output.write(buffer, 0, count)
}
output.toByteArray()
}
val digest = java.security.MessageDigest.getInstance("SHA-256").digest(bytes)
if (digest.joinToString("") { "%02x".format(it) } != id) throw IOException("图片校验失败")
target.parentFile?.mkdirs()
val file = android.util.AtomicFile(target)
val stream = file.startWrite()
try {
stream.write(bytes)
file.finishWrite(stream)
} catch (error: Exception) {
file.failWrite(stream)
throw error
}
} finally {
request.disconnect()
}
}
private fun endpoint(address: String): URI {
val base = runCatching { URI(address) }.getOrNull()
val scheme = base?.scheme?.lowercase()
@@ -136,6 +136,7 @@ fun LauncherCanvas(
beyondViewportPageCount = 1, // 预组合相邻页,翻页不白屏
) { pageIndex ->
CanvasPage(
iconStyle = layout.iconStyle,
page = pages[pageIndex],
canvas = layout.canvas,
fit = layout.fit.toFitConfig(),
@@ -157,7 +158,7 @@ fun LauncherCanvas(
current = pagerState.currentPage,
modifier = Modifier
.align(Alignment.BottomCenter)
.padding(bottom = 18.dp),
.padding(bottom = with(LocalDensity.current) { bottomInsetPx.toDp() } + 18.dp),
)
}
}
@@ -165,6 +166,7 @@ fun LauncherCanvas(
@Composable
private fun CanvasPage(
iconStyle: String,
page: PageDef,
canvas: CanvasDef,
fit: FitConfig,
@@ -221,6 +223,7 @@ private fun CanvasPage(
) {
CanvasItemView(
def = def,
iconStyle = iconStyle,
widgetKey = widgetBindingKey(page.index, def.id),
placed = p,
icons = icons,
@@ -238,6 +241,7 @@ private fun CanvasPage(
@Composable
private fun CanvasItemView(
def: ItemDef,
iconStyle: String,
widgetKey: String,
placed: PlacedItem,
icons: IconLoader,
@@ -249,6 +253,8 @@ private fun CanvasItemView(
when (def.type) {
"app_icon" -> AppIconView(
pkg = def.payload.pkg.orEmpty(),
style = def.payload.iconStyle ?: iconStyle,
imageId = def.payload.imageId,
label = def.payload.label.orEmpty(),
sizePx = (placed.width * 0.78f).roundToInt(),
labelPx = placed.width * 0.19f,
@@ -265,6 +271,23 @@ private fun CanvasItemView(
onLongClick = onLongClick,
)
"image" -> {
val bitmap by produceState<Bitmap?>(null, def.payload.imageId) {
value = def.payload.imageId?.let { icons.loadImage(it) }
}
val image = bitmap
if (image != null) {
val interactive = def.payload.hasLaunchTarget()
Image(
bitmap = image.asImageBitmap(),
contentDescription = def.payload.label,
contentScale = ContentScale.Fit,
modifier = if (interactive) Modifier.fillMaxSize().clickable(onClick = onClick)
else Modifier.fillMaxSize(),
)
}
}
"dock_bg" -> Box(
Modifier
.fillMaxSize()
@@ -344,6 +367,8 @@ private fun iconPressModifier(iconSize: Dp, onClick: () -> Unit, onLongClick: ()
@Composable
private fun AppIconView(
pkg: String,
style: String,
imageId: String?,
label: String,
sizePx: Int,
labelPx: Float,
@@ -353,8 +378,9 @@ private fun AppIconView(
) {
val density = LocalDensity.current
// key 里带上 sizePx:尺寸变了要重新取,否则会拿旧分辨率的图去拉伸
val bmp by produceState<Bitmap?>(initialValue = null, pkg, sizePx) {
value = icons.load(pkg, sizePx)
val bmp by produceState<Bitmap?>(initialValue = null, pkg, sizePx, style, imageId) {
value = if (style == "image") imageId?.let { icons.loadImage(it) }
else icons.load(pkg, sizePx, style)
}
val side = with(density) { sizePx.toDp() }
@@ -363,12 +389,17 @@ private fun AppIconView(
contentAlignment = Alignment.Center,
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
val shape = RoundedCornerShape(side * 0.24f)
val shape = when (style) {
"circle" -> CircleShape
"original", "image" -> androidx.compose.ui.graphics.RectangleShape
else -> RoundedCornerShape(side * 0.24f)
}
if (bmp != null) {
Image(
bitmap = bmp!!.asImageBitmap(),
contentDescription = label,
modifier = Modifier.size(side).clip(shape),
contentScale = ContentScale.Fit,
modifier = Modifier.size(side),
)
} else {
// 首字母兜底:包名还没解析出来时也不留白块
+1 -1
View File
@@ -26,7 +26,7 @@ spec:
spec:
containers:
- name: server
image: docker.io/library/vibe-launcher-backend:1.1.0-deploy14
image: docker.io/library/vibe-launcher-backend:1.1.0-deploy17
imagePullPolicy: IfNotPresent
ports:
- name: http
@@ -166,6 +166,45 @@ class LayoutController {
return serve(store.byRevision(revision));
}
@PostMapping("/api/admin/images")
Map<String, String> uploadImage(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException {
policy.requireAdmin(request, response);
byte[] bytes = request.getInputStream().readNBytes(512 * 1024 + 1);
if (bytes.length > 512 * 1024) throw new ApiError(413, "图片不能超过 512 KiB");
String type;
try (var stream = new javax.imageio.stream.MemoryCacheImageInputStream(new java.io.ByteArrayInputStream(bytes))) {
var readers = javax.imageio.ImageIO.getImageReaders(stream);
if (!readers.hasNext()) throw new ApiError(415, "仅支持 PNG 和 JPEG");
var reader = readers.next();
try {
type = switch (reader.getFormatName().toLowerCase(java.util.Locale.ROOT)) {
case "png" -> "image/png";
case "jpeg" -> "image/jpeg";
default -> throw new ApiError(415, "仅支持 PNG 和 JPEG");
};
reader.setInput(stream);
if (reader.getWidth(0) > 1024 || reader.getHeight(0) > 1024) {
throw new ApiError(422, "图片宽高不能超过 1024 像素");
}
reader.read(0);
} finally {
reader.dispose();
}
} catch (IOException error) {
throw new ApiError(400, "图片文件无法解码");
}
return Map.of("id", store.saveImage(bytes, type));
}
@GetMapping("/api/images/{id:[a-f0-9]{64}}")
ResponseEntity<byte[]> image(@PathVariable String id, HttpServletRequest request, HttpServletResponse response)
throws SQLException {
policy.requireImageAccess(request, response);
var image = store.image(id);
return ResponseEntity.ok().contentType(MediaType.parseMediaType(image.mediaType())).body(image.bytes());
}
@PutMapping("/api/admin/layout")
ResponseEntity<byte[]> publish(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
policy.requireAdmin(request, response);
@@ -25,6 +25,8 @@ class LayoutStore {
private static final String LATEST = "SELECT revision, layout FROM releases ORDER BY revision DESC LIMIT 1";
private static final String BY_REVISION = "SELECT revision, layout FROM releases WHERE revision = ?";
record ImageAsset(String mediaType, byte[] bytes) {}
record Release(int revision, String layout) {
String etag() {
return "\"" + java.util.HexFormat.of().formatHex(RequestPolicy.sha256(layout)) + "\"";
@@ -69,6 +71,11 @@ class LayoutStore {
component TEXT PRIMARY KEY
) STRICT
""");
statement.execute("""
CREATE TABLE IF NOT EXISTS image_assets (
id TEXT PRIMARY KEY, media_type TEXT NOT NULL, bytes BLOB NOT NULL
) STRICT
""");
for (var column : List.of("label", "app_label", "category")) {
boolean exists;
try (var check = connection.prepareStatement(
@@ -141,6 +148,32 @@ class LayoutStore {
}
}
String saveImage(byte[] bytes, String mediaType) throws SQLException {
String id;
try {
id = java.util.HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes));
} catch (java.security.NoSuchAlgorithmException impossible) {
throw new IllegalStateException(impossible);
}
try (var db = connect(); var insert = db.prepareStatement("INSERT OR IGNORE INTO image_assets VALUES (?, ?, ?)")) {
insert.setString(1, id);
insert.setString(2, mediaType);
insert.setBytes(3, bytes);
insert.executeUpdate();
}
return id;
}
ImageAsset image(String id) throws SQLException {
try (var db = connect(); var query = db.prepareStatement("SELECT media_type, bytes FROM image_assets WHERE id = ?")) {
query.setString(1, id);
try (var rows = query.executeQuery()) {
if (!rows.next()) throw new ApiError(404, "图片资源不存在");
return new ImageAsset(rows.getString(1), rows.getBytes(2));
}
}
}
int latestRevision() throws SQLException {
try (var connection = connect(); var statement = connection.createStatement();
var rows = statement.executeQuery("SELECT MAX(revision) FROM releases")) {
@@ -209,6 +242,21 @@ class LayoutStore {
throw new ApiError(422, "历史版本布局校验失败,无法回滚", issues.stream().limit(100).toList());
}
}
var imageIds = new java.util.HashSet<String>();
for (var page : layout.path("pages")) {
for (var item : page.path("items")) {
var id = item.path("payload").path("imageId").stringValue("");
if (!id.isEmpty()) imageIds.add(id);
}
}
try (var image = connection.prepareStatement("SELECT 1 FROM image_assets WHERE id = ?")) {
for (var id : imageIds) {
image.setString(1, id);
try (var rows = image.executeQuery()) {
if (!rows.next()) throw new ApiError(422, "布局引用了未上传的图片");
}
}
}
int revision = current.revision() + 1;
String json = mapper.writeValueAsString(layout.put("schemaVersion", 3).put("revision", revision));
if (json.getBytes(StandardCharsets.UTF_8).length > MAX_BYTES) throw new ApiError(413, "布局超过 1 MiB");
@@ -14,7 +14,7 @@ class LayoutValidator {
record Issue(String level, String path, String message) {}
private record Rect(String path, float x, float y, float right, float bottom) {}
private static final Set<String> TYPES = Set.of("app_icon", "widget", "shortcut", "dock_bg");
private static final Set<String> TYPES = Set.of("app_icon", "widget", "shortcut", "dock_bg", "image");
private static final Set<String> FIT_MODES = Set.of("contain", "elastic", "stretch");
private static final Set<String> BACKGROUNDS = Set.of("wallpaper", "solid", "gradient");
private static final Pattern HEX_COLOR = Pattern.compile("#[0-9A-Fa-f]{6}");
@@ -23,6 +23,18 @@ class LayoutValidator {
private static final int MAX_ID_LENGTH = 64;
private static final int MAX_LABEL_LENGTH = 100;
private static final Set<String> ICON_STYLES = Set.of("original", "system", "circle", "rounded");
private static final Set<String> SETTINGS_ACTIONS = Set.of(
"ACTION_SETTINGS", "ACTION_WIFI_SETTINGS", "ACTION_BLUETOOTH_SETTINGS", "ACTION_WIRELESS_SETTINGS",
"ACTION_AIRPLANE_MODE_SETTINGS", "ACTION_DISPLAY_SETTINGS", "ACTION_SOUND_SETTINGS",
"ACTION_LOCATION_SOURCE_SETTINGS", "ACTION_APPLICATION_SETTINGS", "ACTION_DATE_SETTINGS",
"ACTION_ACCESSIBILITY_SETTINGS");
private static final Pattern CLASS_NAME = Pattern.compile("\\.?[A-Za-z_$][\\w$]*(\\.[A-Za-z_$][\\w$]*)*");
private static final Pattern DECIMAL = Pattern.compile("[-+]?(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:[eE][-+]?[0-9]+)?");
private static final Set<String> LAUNCH_MODES = Set.of("none", "settings", "application", "intent", "component");
private static final Pattern PACKAGE_NAME = Pattern.compile("[A-Za-z_$][\\w$]*(\\.[A-Za-z_$][\\w$]*)*");
private static final Pattern IMAGE_ID = Pattern.compile("[a-f0-9]{64}");
List<Issue> validate(JsonNode layout) {
List<Issue> issues = new ArrayList<>();
if (!layout.isObject()) {
@@ -36,6 +48,9 @@ class LayoutValidator {
error(issues, "revision", "版本号必须是整数");
}
if (!optional(layout, "iconStyle", n -> ICON_STYLES.contains(n.stringValue("")))) {
error(issues, "iconStyle", "未知的默认图标样式");
}
JsonNode canvas = layout.path("canvas");
JsonNode fit = layout.path("fit");
if (!optional(layout, "canvas", n -> n.isObject() &&
@@ -172,11 +187,46 @@ class LayoutValidator {
private void validatePayload(List<Issue> issues, JsonNode item, String path, String type) {
JsonNode payload = item.path("payload");
if (!optional(item, "payload", n -> n.isObject()
&& optionalFields(n, LayoutValidator::nullableText, "label", "package", "provider", "intent")
&& optionalFields(n, LayoutValidator::nullableText, "label", "package", "provider", "intent", "className", "settingsAction", "launchMode", "componentName")
&& optional(n, "radius", value -> value.isNull() || integer(value)))) {
error(issues, path + ".payload", "内容字段格式错误");
return;
}
String style = payload.path("iconStyle").stringValue("");
if (!optional(payload, "iconStyle", n -> ICON_STYLES.contains(n.stringValue("")) || "image".equals(n.stringValue("")))) {
error(issues, path + ".payload.iconStyle", "未知的图标样式");
}
if (!optional(payload, "imageId", n -> IMAGE_ID.matcher(n.stringValue("")).matches())
|| ((type.equals("image") || style.equals("image")) && !payload.hasNonNull("imageId"))) {
error(issues, path + ".payload.imageId", "请上传有效的图片");
}
String mode = payload.path("launchMode").stringValue("");
if (payload.has("launchMode") && !LAUNCH_MODES.contains(mode)) {
error(issues, path + ".payload.launchMode", "未知的点击动作类型");
}
String cls = payload.path("className").stringValue("").strip();
boolean packageMissing = payload.path("package").stringValue("").isBlank();
if ((mode.equals("application") || mode.isEmpty() && !cls.isEmpty())
&& (packageMissing || !cls.isEmpty() && !CLASS_NAME.matcher(cls).matches())) {
error(issues, path + ".payload.className", "Activity 类名格式无效,或缺少应用包名");
}
String setting = payload.path("settingsAction").stringValue("");
if ((mode.equals("settings") || mode.isEmpty() && !setting.isEmpty()) && !SETTINGS_ACTIONS.contains(setting)) {
error(issues, path + ".payload.settingsAction", "请选择有效的系统设置动作");
}
String component = payload.path("componentName").stringValue("").strip();
if (mode.equals("component") || mode.isEmpty() && !component.isEmpty()) {
String[] parts = component.split("/", -1);
if (parts.length != 2 || !PACKAGE_NAME.matcher(parts[0]).matches() || !CLASS_NAME.matcher(parts[1]).matches()) {
error(issues, path + ".payload.componentName", "ComponentName 应为包名/类名");
}
}
if (mode.equals("intent") && payload.path("intent").stringValue("").isBlank()) {
error(issues, path + ".payload.intent", "请填写快捷方式 Intent");
}
if (!optional(payload, "extras", LayoutValidator::validExtras)) {
error(issues, path + ".payload.extras", "Intent 参数键重复、为空或值与类型不符");
}
if (type.equals("app_icon") && payload.path("package").stringValue("").isBlank()) {
error(issues, path + ".payload.package", "应用图标需要包名");
}
@@ -196,6 +246,34 @@ class LayoutValidator {
}
}
private static boolean validExtras(JsonNode extras) {
if (!extras.isArray() || extras.size() > 32) return false;
var keys = new java.util.HashSet<String>();
for (var extra : extras) {
var key = extra.path("key").stringValue("").strip();
var value = extra.path("value").stringValue(null);
if (key.isEmpty() || key.length() > 128 || !keys.add(key) || value == null || value.length() > 2048) {
return false;
}
try {
String trimmed = value.strip();
switch (extra.path("type").stringValue("")) {
case "string" -> { }
case "boolean" -> { if (!trimmed.equals("true") && !trimmed.equals("false")) return false; }
case "int" -> Integer.parseInt(trimmed);
case "long" -> Long.parseLong(trimmed);
case "double" -> {
if (!DECIMAL.matcher(trimmed).matches() || !Double.isFinite(Double.parseDouble(trimmed))) return false;
}
default -> { return false; }
}
} catch (NumberFormatException invalid) {
return false;
}
}
return true;
}
private static boolean validCoordinates(JsonNode item) {
JsonNode x = item.path("x"), y = item.path("y"), w = item.path("w"), h = item.path("h");
return finiteFloat(x) && finiteFloat(y) && finiteFloat(w) && finiteFloat(h)
@@ -52,6 +52,12 @@ class RequestPolicy extends OncePerRequestFilter {
require(request, response, device);
}
void requireImageAccess(HttpServletRequest request, HttpServletResponse response) {
String header = request.getHeader("Authorization");
if (header != null && MessageDigest.isEqual(sha256(header), device)) return;
requireAdmin(request, response);
}
private void require(HttpServletRequest request, HttpServletResponse response, byte[] expected) {
String header = request.getHeader("Authorization");
if (header == null || !MessageDigest.isEqual(sha256(header), expected)) {
@@ -34,6 +34,41 @@ class LayoutApiTest {
@TempDir Path dir;
@Test
void imageUploadCanBePublishedAndFetchedByDevice() throws Exception {
Path database = dir.resolve("images.sqlite");
MockMvc mvc = mvc(database);
var pixels = new java.awt.image.BufferedImage(2, 2, java.awt.image.BufferedImage.TYPE_INT_ARGB);
var output = new java.io.ByteArrayOutputStream();
javax.imageio.ImageIO.write(pixels, "png", output);
byte[] png = output.toByteArray();
mvc.perform(post("/api/admin/images").header("Authorization", DEVICE).content(png))
.andExpect(status().isUnauthorized());
var response = mvc.perform(post("/api/admin/images").header("Authorization", ADMIN)
.contentType("image/png").content(png)).andExpect(status().isOk()).andReturn().getResponse();
String id = mapper.readTree(response.getContentAsString()).path("id").stringValue();
mvc.perform(get("/api/images/" + id)).andExpect(status().isUnauthorized());
mvc(database).perform(get("/api/images/" + id).header("Authorization", DEVICE))
.andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith("image/png"))
.andExpect(content().bytes(png));
var current = mvc.perform(get(ADMIN_LAYOUT).header("Authorization", ADMIN))
.andReturn().getResponse();
String tag = current.getHeader("ETag");
var body = """
{"iconStyle":"system","pages":[{"items":[
{"id":"picture","type":"image","x":12,"y":150,"w":100,"h":100,
"payload":{"imageId":"%s","package":"org.example.app"}}
]}]}
""";
mvc.perform(put(ADMIN_LAYOUT).header("Authorization", ADMIN).header("If-Match", tag)
.contentType(MediaType.APPLICATION_JSON).content(body.formatted("0".repeat(64))))
.andExpect(status().is(422));
mvc.perform(put(ADMIN_LAYOUT).header("Authorization", ADMIN).header("If-Match", tag)
.contentType(MediaType.APPLICATION_JSON).content(body.formatted(id)))
.andExpect(status().isOk());
}
@Test
void layoutEventStreamRequiresDeviceToken() throws Exception {
MockMvc mvc = mvc(dir.resolve("events.sqlite"));
@@ -13,6 +13,28 @@ class LayoutValidatorTest {
private final LayoutValidator validator = new LayoutValidator();
private final JsonMapper mapper = JsonMapper.builder().build();
@Test
void validatesSettingsActionsAndTypedExtras() throws Exception {
var json = """
{"pages":[{"items":[{"id":"wifi","type":"image","x":0,"y":200,"w":100,"h":100,
"payload":{"imageId":"%s","settingsAction":"ACTION_WIFI_SETTINGS",
"extras":[{"key":"example","type":"long","value":"9223372036854775807"}]}}]}]}
""".formatted("a".repeat(64));
var reader = tools.jackson.databind.json.JsonMapper.builder().build();
var validator = new LayoutValidator();
assertTrue(validator.validate(reader.readTree(json)).stream().noneMatch(i -> i.level().equals("error")));
assertTrue(validator.validate(reader.readTree(json.replace("9223372036854775807", "9223372036854775808")))
.stream().anyMatch(i -> i.path().endsWith(".extras")));
assertTrue(validator.validate(reader.readTree(json.replace("ACTION_WIFI_SETTINGS", "ACTION_CALL")))
.stream().anyMatch(i -> i.path().endsWith(".settingsAction")));
var component = json.replace("\"settingsAction\":\"ACTION_WIFI_SETTINGS\"", """
"launchMode":"component","componentName":"com.example.app/.MainActivity"
""".strip());
assertTrue(validator.validate(reader.readTree(component)).stream().noneMatch(i -> i.level().equals("error")));
assertTrue(validator.validate(reader.readTree(component.replace("/.MainActivity", "")))
.stream().anyMatch(i -> i.path().endsWith(".componentName")));
}
@Test
void builtInLayoutHasNoErrors() throws Exception {
try (var input = new ClassPathResource("launcher/default_layout.json").getInputStream()) {
+14
View File
@@ -213,3 +213,17 @@ height = h * s
3. `type` 枚举扩展同理:旧端告警跳过,不会崩
**为什么必须"先校验后落盘"**:桌面是用户唯一入口,一个坏包会让整个手机没法用。四级兜底(主文件 → last_good → assets → 内存空布局)就是为了保证"无论如何能启动"。
## 图标样式与图片元素
布局根对象可选字段 `iconStyle` 支持 `original`、`system`、`circle`、`rounded`,缺省时跟随系统。应用图标的 `payload.iconStyle` 可覆盖此设置,并额外支持 `image`。使用上传图片时,在 `payload.imageId` 记录服务器返回的图片 ID。
`type: "image"` 元素使用 `payload.imageId` 引用图片,按原比例居中显示。可选的 `payload.intent` 或 `payload.package` 指定点击动作,`intent` 优先;两者都缺省时不响应点击。图片 ID 为文件内容的十六进制 SHA-256。支持此功能的 Android 客户端在应用新布局前下载缺失图片,离线时使用本地缓存。
### Activity 与系统设置动作
应用图标可在 `payload.className` 填写相对类名(如 `.MainActivity`)或完整类名,配合 `payload.package` 组成显式 ComponentName。类名留空时打开应用默认入口。图片可使用同一组字段,也可用 `payload.settingsAction` 选择公开的 Android Settings 动作,例如 `ACTION_SETTINGS` 或 `ACTION_WIFI_SETTINGS`。`payload.launchMode` 单选 `none`、`settings`、`application`、`intent` 或 `component`。选择 `component` 时通过 `payload.componentName` 填写扁平组件名,例如 `com.example.app/.MainActivity`。选择 `settings`、`application` 或 `intent` 时分别读取设置动作、包名与可选类名,或 Intent URI。缺少 `launchMode` 的旧布局仍使用原有目标推断顺序。
`payload.extras` 为独立键值列表,条目格式为 `{"key":"example","type":"int","value":"42"}`。类型支持 `string`、`boolean`、`int`、`long` 和 `double`。值以文本保存以保留 64 位整数精度,Android 在启动时以声明类型调用 `putExtra`。接收方是否消费某个键由该 Activity 决定。
+163 -12
View File
@@ -11,8 +11,8 @@ import ReleaseDialog from "./ReleaseDialog.vue";
import LayoutSurface from "./LayoutSurface.vue";
import DevicePreview from "./DevicePreview.vue";
import {
alignmentGuide, arrangeIconRow, builtInLayout, clamp, copyLayout, isIcon, normalizeLayout, resizedIconBounds, templates, validate,
type Layout, type LayoutItem, type Payload, type Template,
alignmentGuide, arrangeIconRow, builtInLayout, clamp, copyLayout, extraTypes, iconStyles, isIcon, itemLaunchMode, launchModes, normalizeLayout, resizedIconBounds, settingsActions, templates, validate,
type LaunchMode, type Layout, type LayoutItem, type Template,
} from "./layout";
const draftKey = "vibe-launcher-draft-v3";
@@ -198,11 +198,80 @@ const backgrounds = [
{ value: "solid", label: "纯色" },
{ value: "gradient", label: "渐变" },
];
const payloadFields: { key: keyof Pick<Payload, "label" | "package" | "provider" | "intent">; label: string; type?: string }[] = [
{ key: "label", label: "显示名称" }, { key: "package", label: "应用包名", type: "app_icon" },
{ key: "provider", label: "组件 Provider", type: "widget" }, { key: "intent", label: "快捷方式 Intent", type: "shortcut" },
];
const visiblePayload = computed(() => payloadFields.filter(field => !field.type || field.type === selected.value?.type));
const activeLaunchMode = computed(() => selected.value ? itemLaunchMode(selected.value) : "none");
const supportsLaunchMode = computed(() => selected.value &&
["app_icon", "image", "shortcut"].includes(selected.value.type));
function selectLaunchMode(item: LayoutItem, mode: LaunchMode) {
if (itemLaunchMode(item) === mode) return;
remember();
item.payload.launchMode = mode;
if (mode !== "settings") delete item.payload.settingsAction;
if (mode !== "intent") delete item.payload.intent;
if (mode !== "component") delete item.payload.componentName;
if (mode !== "application") {
delete item.payload.className;
if (item.type !== "app_icon") delete item.payload.package;
}
}
function addIntentExtra(item: LayoutItem) {
const extras = item.payload.extras ?? [];
if (extras.length >= 32) return;
updateValue(item.payload, "extras", [...extras, { key: "", type: "string", value: "" }]);
}
const uploadingImage = ref(false);
async function uploadItemImage(event: Event, item: LayoutItem) {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
input.value = "";
if (!file || uploadingImage.value) return;
uploadingImage.value = true;
try {
let upload: Blob = file;
if (file.type === "image/webp") {
const bitmap = await createImageBitmap(file);
try {
if (bitmap.width > 1024 || bitmap.height > 1024) throw new Error("图片宽高不能超过 1024 像素");
const surface = document.createElement("canvas");
surface.width = bitmap.width;
surface.height = bitmap.height;
surface.getContext("2d")!.drawImage(bitmap, 0, 0);
upload = await new Promise<Blob>((resolve, reject) => surface.toBlob(
blob => blob ? resolve(blob) : reject(new Error("无法转换 WebP 图片")), "image/png",
));
} finally {
bitmap.close();
}
}
if (upload.size > 512 * 1024) throw new Error("图片不能超过 512 KiB");
const response = await fetch(new URL("./api/admin/images", location.href), {
method: "POST", body: upload, credentials: "same-origin", redirect: "error",
headers: { "X-Launcher-Request": "1" }, signal: AbortSignal.timeout(10000),
});
const result = await response.json();
if (!response.ok) throw new Error(result.message || "图片上传失败");
if (!layout.value.pages.some(entry => entry.items.includes(item))) return;
remember();
item.payload.imageId = result.id;
if (item.type === "app_icon") item.payload.iconStyle = "image";
ElMessage.success("已上传图片");
} catch (error) {
ElMessage.error(error instanceof Error ? error.message : "图片上传失败");
} finally {
uploadingImage.value = false;
}
}
function setItemIconStyle(item: LayoutItem, style: string) {
if (item.payload.iconStyle === style || (style === "default" && !item.payload.iconStyle)) return;
remember();
if (style === "default") delete item.payload.iconStyle;
else item.payload.iconStyle = style;
}
const fields = ["x", "y", "w", "h", "z"] as const;
function remember() {
@@ -508,7 +577,7 @@ onUnmounted(() => {
<section>
<h2>添加内容</h2>
<div class="templates">
<ElButton v-for="template in templates" :key="template.label" :disabled="page.items.length >= 80"
<ElButton v-for="template in templates.filter(entry => hosted || entry.type !== 'image')" :key="template.label" :disabled="page.items.length >= 80"
@click="addItem(template)">{{ template.label }}</ElButton>
<ElButton v-if="hosted" :disabled="page.items.length >= 80"
@click="widgetCatalog = true; if (loggedIn && !widgetProviders.length) readWidgetProviders()">
@@ -517,7 +586,13 @@ onUnmounted(() => {
</div>
</section>
<section>
<h2>图标大小</h2>
<h2>图标样式与大小</h2>
<label>默认图标样式
<ElSelect :model-value="layout.iconStyle ?? 'system'" aria-label="默认图标样式"
@change="updateValue(layout, 'iconStyle', $event)">
<ElOption v-for="style in iconStyles" :key="style.value" v-bind="style" />
</ElSelect>
</label>
<ElCheckbox v-model="iconSize.enabled">统一图标大小</ElCheckbox>
<label>宽度 <ElInputNumber :model-value="effectiveIconSize.w" :min="1" :max="canvas.designWidth"
:precision="0" aria-label="统一图标宽度" @change="value => { if (value !== undefined) iconSize.width = value; }" /></label>
@@ -604,10 +679,86 @@ onUnmounted(() => {
<ElInputNumber :model-value="selected[field]" :precision="field === 'x' ? undefined : 0" :aria-label="field"
@change="updateValue(selected!, field, $event)" />
</label>
<label v-for="field in visiblePayload" :key="field.key">{{ field.label }}
<input class="property-input" :value="selected.payload[field.key] ?? ''"
@change="updateValue(selected!.payload, field.key, ($event.target as HTMLInputElement).value)">
<label v-if="selected.type === 'app_icon'">图标样式
<ElSelect :model-value="selected.payload.iconStyle ?? 'default'" aria-label="图标样式"
@change="setItemIconStyle(selected!, $event)">
<ElOption label="使用默认样式" value="default" />
<ElOption v-for="style in iconStyles" :key="style.value" v-bind="style" />
<ElOption label="上传图片" value="image" />
</ElSelect>
</label>
<label v-if="hosted && (selected.type === 'image' || selected.type === 'app_icon' && selected.payload.iconStyle === 'image')">
上传图片
<input type="file" accept="image/png,image/jpeg,image/webp" :disabled="!loggedIn || uploadingImage"
@change="uploadItemImage($event, selected!)">
<small v-if="!loggedIn">请先登录后上传图片。</small>
</label>
<label>显示名称
<input class="property-input" :value="selected.payload.label ?? ''"
@change="updateValue(selected!.payload, 'label', ($event.target as HTMLInputElement).value)">
</label>
<label v-if="selected.type === 'widget'">组件 Provider
<input class="property-input" :value="selected.payload.provider ?? ''"
@change="updateValue(selected!.payload, 'provider', ($event.target as HTMLInputElement).value)">
</label>
<label v-if="supportsLaunchMode">点击动作
<ElSelect :model-value="activeLaunchMode" aria-label="点击动作" @change="selectLaunchMode(selected!, $event)">
<ElOption v-for="mode in launchModes.filter(mode => mode.value !== 'none' || selected!.type !== 'app_icon')"
:key="mode.value" v-bind="mode" />
</ElSelect>
</label>
<label v-if="supportsLaunchMode && activeLaunchMode === 'settings'">系统设置动作
<ElSelect :model-value="selected.payload.settingsAction" aria-label="系统设置动作"
@change="updateValue(selected!.payload, 'settingsAction', $event)">
<ElOption v-for="action in settingsActions" :key="action.value"
:label="action.label + ' · ' + action.value" :value="action.value" />
</ElSelect>
</label>
<template v-if="supportsLaunchMode && activeLaunchMode === 'application'">
<label>应用包名
<input class="property-input" :value="selected.payload.package ?? ''"
@change="updateValue(selected!.payload, 'package', ($event.target as HTMLInputElement).value)">
</label>
<label>Activity 类名
<input class="property-input" :value="selected.payload.className ?? ''" placeholder="留空打开应用默认页"
@change="updateValue(selected!.payload, 'className', ($event.target as HTMLInputElement).value)">
</label>
</template>
<label v-if="supportsLaunchMode && activeLaunchMode === 'intent'">快捷方式 Intent
<input class="property-input" :value="selected.payload.intent ?? ''"
@change="updateValue(selected!.payload, 'intent', ($event.target as HTMLInputElement).value)">
</label>
<label v-if="supportsLaunchMode && activeLaunchMode === 'component'">ComponentName
<input class="property-input" :value="selected.payload.componentName ?? ''" placeholder="com.example.app/.MainActivity"
@change="updateValue(selected!.payload, 'componentName', ($event.target as HTMLInputElement).value)">
</label>
<label v-if="selected.type === 'app_icon' && activeLaunchMode !== 'application'">图标来源包名
<input class="property-input" :value="selected.payload.package ?? ''"
@change="updateValue(selected!.payload, 'package', ($event.target as HTMLInputElement).value)">
</label>
<section v-if="supportsLaunchMode && activeLaunchMode !== 'none'" class="intent-extras">
<h2>Intent 附加参数</h2>
<div v-for="(extra, index) in selected.payload.extras" :key="index" class="intent-extra">
<ElInput :model-value="extra.key" placeholder="键名" aria-label="参数键名"
@change="updateValue(extra, 'key', $event)" />
<ElSelect :model-value="extra.type" aria-label="参数类型" @change="updateValue(extra, 'type', $event)">
<ElOption v-for="type in extraTypes" :key="type" :label="type" :value="type" />
</ElSelect>
<ElSelect v-if="extra.type === 'boolean'" :model-value="extra.value" aria-label="参数值"
@change="updateValue(extra, 'value', $event)">
<ElOption label="true" value="true" />
<ElOption label="false" value="false" />
</ElSelect>
<ElInput v-else :model-value="extra.value" placeholder="参数值" aria-label="参数值"
@change="updateValue(extra, 'value', $event)" />
<ElButton @click="updateValue(selected!.payload, 'extras', selected!.payload.extras?.filter((_, i) => i !== index))">
删除参数
</ElButton>
</div>
<ElButton :disabled="(selected.payload.extras?.length ?? 0) >= 32" @click="addIntentExtra(selected!)">
添加参数
</ElButton>
</section>
<div class="json-actions">
<ElButton :disabled="selected.w > canvas.designWidth" @click="centerHorizontally">水平居中</ElButton>
<ElButton @click="changeLayer(selected!, true)">置顶</ElButton>
+8 -4
View File
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { computed } from "vue";
import {
backgroundStyle, clamp, deviceMapper, devices, iconColor, sortedItems,
backgroundStyle, clamp, deviceMapper, devices, iconColor, imageUrl, validImageId, sortedItems,
type Layout, type LayoutItem, type Page,
} from "./layout";
@@ -38,7 +38,7 @@ const whitespace = computed(() => {
};
});
const items = computed(() => sortedItems(props.page));
const known = new Set(["app_icon", "widget", "shortcut", "dock_bg"]);
const known = new Set(["app_icon", "widget", "shortcut", "dock_bg", "image"]);
const visible = computed(() => props.editable ? items.value : items.value.filter(item => known.has(item.type)));
const percent = (n: number, total: number) => (n / total * 100) + "%";
function itemStyle(item: LayoutItem) {
@@ -69,8 +69,12 @@ function title(item: LayoutItem) {
:class="[item.type, { selected: item.id === selectedId, 'row-selected': selectedRow?.includes(item.id) }]" :style="itemStyle(item)"
:title="title(item)" :tabindex="editable ? 0 : undefined"
@pointerdown="editable && emit('startDrag', $event, item, false)">
<template v-if="item.type === 'app_icon' || item.type === 'shortcut'">
<span class="icon-art">{{ (item.payload.label || title(item)).slice(0, 1).toUpperCase() }}</span>
<img v-if="item.type === 'image' && validImageId(item.payload.imageId)" class="canvas-image"
:src="imageUrl(item.payload.imageId)" :alt="title(item)" draggable="false">
<template v-else-if="item.type === 'app_icon' || item.type === 'shortcut'">
<img v-if="item.payload.iconStyle === 'image' && validImageId(item.payload.imageId)"
class="icon-art uploaded-icon" :src="imageUrl(item.payload.imageId)" alt="" draggable="false">
<span v-else class="icon-art" :class="'icon-' + (item.payload.iconStyle ?? layout.iconStyle ?? 'system')">{{ (item.payload.label || title(item)).slice(0, 1).toUpperCase() }}</span>
<span class="icon-label">{{ title(item) }}</span>
</template>
<span v-else-if="item.type !== 'dock_bg'" class="widget-label">{{ title(item) }}</span>
+110 -1
View File
@@ -1,11 +1,48 @@
import defaultLayout from "../../android/app/src/main/assets/default_layout.json" with { type: "json" };
export interface IntentExtra {
key: string;
type: string;
value: string;
}
export const settingsActions = [
{ value: "ACTION_SETTINGS", label: "系统设置" },
{ value: "ACTION_WIFI_SETTINGS", label: "Wi-Fi 设置" },
{ value: "ACTION_BLUETOOTH_SETTINGS", label: "蓝牙设置" },
{ value: "ACTION_WIRELESS_SETTINGS", label: "无线和网络设置" },
{ value: "ACTION_AIRPLANE_MODE_SETTINGS", label: "飞行模式设置" },
{ value: "ACTION_DISPLAY_SETTINGS", label: "显示设置" },
{ value: "ACTION_SOUND_SETTINGS", label: "声音设置" },
{ value: "ACTION_LOCATION_SOURCE_SETTINGS", label: "位置设置" },
{ value: "ACTION_APPLICATION_SETTINGS", label: "应用设置" },
{ value: "ACTION_DATE_SETTINGS", label: "日期和时间设置" },
{ value: "ACTION_ACCESSIBILITY_SETTINGS", label: "无障碍设置" },
];
export const launchModes = [
{ value: "none", label: "无动作" },
{ value: "settings", label: "系统设置动作" },
{ value: "application", label: "应用包名 / Activity 类名" },
{ value: "intent", label: "快捷方式 Intent" },
{ value: "component", label: "ComponentName" },
] as const;
export type LaunchMode = typeof launchModes[number]["value"];
export const extraTypes = ["string", "boolean", "int", "long", "double"];
export interface Payload {
label?: string | null;
package?: string | null;
provider?: string | null;
intent?: string | null;
radius?: number | null;
imageId?: string;
className?: string;
settingsAction?: string;
launchMode?: LaunchMode;
componentName?: string;
extras?: IntentExtra[];
iconStyle?: string;
}
export interface LayoutItem {
id: string;
@@ -17,6 +54,16 @@ export interface LayoutItem {
z: number;
payload: Payload;
}
export function itemLaunchMode(item: LayoutItem): LaunchMode {
const payload = item.payload;
return payload.launchMode ?? (item.type === "app_icon" ? "application"
: payload.settingsAction ? "settings"
: payload.componentName ? "component"
: payload.className ? "application"
: payload.intent ? "intent"
: payload.package ? "application" : "none");
}
export interface Background {
type: string;
color?: string;
@@ -27,6 +74,7 @@ export interface Page { index: number; background: Background; items: LayoutItem
export interface Layout {
schemaVersion: 3;
revision: number;
iconStyle?: string;
canvas: { designWidth: number; designHeight: number; safeTop: number; safeBottom: number };
fit: { mode: string; anchorY: number };
pages: Page[];
@@ -34,6 +82,15 @@ export interface Layout {
export interface Issue { level: "error" | "warning"; path: string; message: string }
export type Template = Pick<LayoutItem, "type" | "w" | "h" | "payload"> & { label: string };
export const iconStyles = [
{ value: "original", label: "应用原图" },
{ value: "system", label: "跟随系统" },
{ value: "circle", label: "圆形" },
{ value: "rounded", label: "圆角方形" },
];
export const validImageId = (id: unknown): id is string => typeof id === "string" && /^[a-f0-9]{64}$/.test(id);
export const imageUrl = (id: string) => new URL("./api/images/" + id, location.href).href;
export const templates: Template[] = [
{ type: "app_icon", label: "应用图标", w: 132, h: 168, payload: { package: "com.tencent.mm", label: "微信" } },
{ type: "app_icon", label: "相机", w: 132, h: 168, payload: { package: "com.android.camera2", label: "相机" } },
@@ -41,6 +98,7 @@ export const templates: Template[] = [
{ type: "widget", label: "搜索组件", w: 420, h: 300, payload: { provider: "com.android.quicksearchbox/com.android.quicksearchbox.SearchWidgetProvider", label: "搜索" } },
{ type: "widget", label: "音乐组件", w: 420, h: 300, payload: { provider: "com.tencent.qqmusic/com.tencent.qqmusiccommon.WidgetProviderSmall", label: "音乐" } },
{ type: "shortcut", label: "快捷方式", w: 132, h: 168, payload: { intent: "weixin://scanqrcode", label: "扫一扫" } },
{ type: "image", label: "图片按钮", w: 300, h: 200, payload: { label: "图片" } },
{ type: "dock_bg", label: "Dock 底板", w: 936, h: 200, payload: { radius: 56 } },
];
@@ -73,6 +131,7 @@ export function normalizeLayout(raw: unknown): Layout {
|| canvas.designHeight > 8192 || typeof fit.mode !== "string" || !finite(fit.anchorY)) {
throw new Error("画布尺寸或映射参数无效");
}
if (raw.iconStyle !== undefined && !iconStyles.some(style => style.value === raw.iconStyle)) throw new Error("未知的默认图标样式");
if (raw.revision !== undefined && !int(raw.revision)) throw new Error("版本号必须是整数");
if (!Array.isArray(raw.pages) || !raw.pages.length || raw.pages.length > 20) throw new Error("布局必须包含 1–20 页");
const pages = raw.pages.map((page, index) => {
@@ -94,9 +153,15 @@ export function normalizeLayout(raw: unknown): Layout {
throw new Error("元素 ID、类型、尺寸或层级格式无效");
}
const payload = item.payload === undefined ? {} : item.payload;
if (!object(payload) || ["label", "package", "provider", "intent"].some(
if (!object(payload) || ["label", "package", "provider", "intent", "imageId", "iconStyle", "className", "settingsAction", "componentName", "launchMode"].some(
key => payload[key] != null && typeof payload[key] !== "string",
) || payload.radius != null && !int(payload.radius)) throw new Error("元素内容格式无效");
if (payload.launchMode !== undefined && !launchModes.some(mode => mode.value === payload.launchMode)) {
throw new Error("未知的点击动作类型");
}
if (payload.extras !== undefined && (!Array.isArray(payload.extras) || payload.extras.length > 32 ||
payload.extras.some(extra => !object(extra) || typeof extra.key !== "string" ||
typeof extra.type !== "string" || typeof extra.value !== "string"))) throw new Error("Intent 参数格式无效");
return { ...item, id: item.id, type: item.type, x: item.x, y: item.y, w: item.w, h: item.h,
z: item.z ?? 1, payload };
}),
@@ -138,6 +203,36 @@ export function validate(layout: Layout): Issue[] {
item.x + item.w > designWidth + 0.5 || item.y + item.h > designHeight + 0.5) {
add("error", path, "尺寸无效或元素超出画布");
}
if (item.payload.imageId !== undefined && !validImageId(item.payload.imageId) ||
(item.type === "image" || item.payload.iconStyle === "image") && !validImageId(item.payload.imageId)) {
add("error", path, "请上传有效的图片");
}
if (item.payload.iconStyle !== undefined && item.payload.iconStyle !== "image" &&
!iconStyles.some(style => style.value === item.payload.iconStyle)) add("error", path, "未知的图标样式");
const mode = itemLaunchMode(item);
const cls = item.payload.className?.trim();
if (mode === "application" && (cls || item.payload.launchMode === "application") &&
(!item.payload.package?.trim() || cls && !/^\.?[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)*$/.test(cls))) {
add("error", path, "Activity 类名格式无效,或缺少应用包名");
}
if (mode === "settings" && !settingsActions.some(action => action.value === item.payload.settingsAction)) {
add("error", path, "请选择系统设置动作");
}
if (mode === "component" && !/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*\/\.?[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/
.test(item.payload.componentName?.trim() ?? "")) {
add("error", path, "ComponentName 应为包名/类名");
}
if (item.payload.launchMode === "intent" && !item.payload.intent?.trim()) {
add("error", path, "请填写快捷方式 Intent");
}
const keys = new Set<string>();
for (const extra of item.payload.extras ?? []) {
const key = extra.key.trim();
if (!key || key.length > 128 || extra.value.length > 2048 || keys.has(key) || !validExtra(extra)) {
add("error", path, "Intent 参数键重复、为空或值与类型不符");
}
keys.add(key);
}
if (item.type === "app_icon" && !item.payload.package?.trim()) add("error", path, "应用图标需要包名");
if (item.type === "widget" && !item.payload.provider?.includes("/")) add("error", path, "组件需填写包名/类名");
if (item.type === "shortcut" && !item.payload.intent?.trim()) add("warning", path, "快捷方式缺少 Intent");
@@ -163,6 +258,20 @@ interface DeviceMapping {
gapScale?: number;
}
function validExtra(extra: IntentExtra): boolean {
const value = extra.value.trim();
switch (extra.type) {
case "string": return true;
case "boolean": return value === "true" || value === "false";
case "int": return /^[-+]?\d+$/.test(value) && int(Number(value));
case "long":
if (!/^[-+]?\d+$/.test(value)) return false;
return BigInt(value) >= -9223372036854775808n && BigInt(value) <= 9223372036854775807n;
case "double": return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[-+]?\d+)?$/i.test(value) && Number.isFinite(Number(value));
default: return false;
}
}
export function deviceMapper(canvas: Layout["canvas"], fit: Layout["fit"], items: LayoutItem[],
dev: Pick<typeof devices[number], "w" | "h">): DeviceMapping {
const sx = dev.w / canvas.designWidth;
+8
View File
@@ -146,3 +146,11 @@ pre { color: #a7ccea; font-size: 11px; max-width: 100%; overflow: auto; }
.preview-swatch { width: 14px; height: 10px; border: 1px solid #f4bb66; border-radius: 2px; }
.preview-legend, .whitespace-examples p { font-size: 12px; color: #b7c5d7; }
.whitespace-examples { display: grid; gap: 9px; margin-top: 16px; padding-top: 12px; border-top: 1px solid #2a3547; }
.canvas-image { width: 100%; height: 100%; object-fit: contain; pointer-events: none; }
.icon-art.uploaded-icon { object-fit: contain; border-radius: 0; background: none; }
.icon-art.icon-circle { border-radius: 50%; }
.icon-art.icon-original { border-radius: 0; }
.intent-extras { display: grid; gap: 8px; }
.intent-extra { display: grid; grid-template-columns: minmax(0, 1fr) 80px; gap: 6px; }
+22 -1
View File
@@ -1,7 +1,7 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { runInNewContext } from "node:vm";
import { alignmentGuide, arrangeIconRow, builtInLayout, deviceMapper, normalizeLayout, resizedIconBounds, validate } from "./src/layout.ts";
import { alignmentGuide, arrangeIconRow, builtInLayout, deviceMapper, itemLaunchMode, normalizeLayout, resizedIconBounds, validate } from "./src/layout.ts";
const fixtures = JSON.parse(readFileSync(new URL("../docs/layout-cases.json", import.meta.url), "utf8"));
const offline = readFileSync(new URL("./canvas.html", import.meta.url), "utf8");
@@ -83,3 +83,24 @@ assert.deepEqual(resizedIconBounds(icon, icon.w + 16, icon.h + 20, canvas),
assert.deepEqual(resizedIconBounds({ ...icon, x: 0, y: 0 }, 200, 220, canvas),
{ x: 0, y: 0, w: 200, h: 220 });
console.log("Icon resize centering and canvas bounds passed");
const settingsButton = normalizeLayout({ pages: [{ items: [{
id: "wifi", type: "image", x: 0, y: 200, w: 100, h: 100,
payload: { imageId: "a".repeat(64), settingsAction: "ACTION_WIFI_SETTINGS",
extras: [{ key: "example", type: "long", value: "9223372036854775807" }] },
}] }] });
assert.equal(validate(settingsButton).filter(issue => issue.level === "error").length, 0);
settingsButton.pages[0].items[0].payload.extras[0].value = "9223372036854775808";
assert.ok(validate(settingsButton).some(issue => issue.level === "error" && issue.message.includes("Intent")));
console.log("Settings actions and typed extras passed");
const picture = settingsButton.pages[0].items[0];
picture.payload.extras = [];
assert.equal(itemLaunchMode(picture), "settings");
picture.payload.launchMode = "component";
picture.payload.componentName = "com.example.app/.MainActivity";
assert.equal(itemLaunchMode(picture), "component");
assert.ok(!validate(settingsButton).some(issue => issue.level === "error"));
picture.payload.componentName = "com.example.app";
assert.ok(validate(settingsButton).some(issue => issue.message.includes("ComponentName")));
console.log("Exclusive action mode and ComponentName validation passed");