commit 12a8c24441582f55dcf04756d2f391a7638c4085 Author: TongTongStudio Date: Thu Nov 26 02:34:19 2026 +0800 Initialize Compose Launcher source and deployment diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8c1d0c9 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/android/.kotlin/ diff --git a/INTEGRATION.md b/INTEGRATION.md new file mode 100644 index 0000000..b73b025 --- /dev/null +++ b/INTEGRATION.md @@ -0,0 +1,104 @@ +# Vibe Launcher 三端联调 + +项目使用同一份 v3 设计稿布局。网页负责编辑和预览,后端以版本发布,Android 桌面在本地验证后应用。后台共用一套线上布局,发布或回滚会影响所有连接到该服务的设备。 + +## 启动后台和后端 + +安装 Node.js 24、pnpm 10.34.5、JDK 17 或更高版本,以及 Maven 3.6.3 或更高版本。管理后台使用 Vue 3、TypeScript、Vite 和 Element Plus。先构建前端,再将构建资源和 Android 默认布局打进 Spring Boot JAR。 + +```powershell +pnpm --dir frontend install --frozen-lockfile +if ($LASTEXITCODE -ne 0) { throw "前端依赖安装失败" } +pnpm --dir frontend build +if ($LASTEXITCODE -ne 0) { throw "前端构建失败" } +mvn -f .\backend\pom.xml clean package +if ($LASTEXITCODE -ne 0) { throw "后端构建失败" } +$env:ADMIN_TOKEN = [Convert]::ToHexString([Security.Cryptography.RandomNumberGenerator]::GetBytes(32)) +$env:DEVICE_TOKEN = [Convert]::ToHexString([Security.Cryptography.RandomNumberGenerator]::GetBytes(32)) +Write-Host "管理员令牌 $env:ADMIN_TOKEN" +Write-Host "设备令牌 $env:DEVICE_TOKEN" +java -jar .\backend\target\vibe-launcher-backend.jar +``` + +后端会在同一地址提供内置布局编辑器和管理 API。打开 [管理后台](http://127.0.0.1:8080/)。点击「布局发布」,填写管理员令牌,再点「读取线上布局」。保存的首个版本来自 Android 内置布局。返回画布编辑,预览效果后重新打开「布局发布」,点击「发布当前画布」。导入本地布局也可以用同一流程发布。 + +开发时可运行 `pnpm --dir frontend dev`,打开 Vite 给出的地址,管理 API 默认代理到本机 8080。使用其他本地端口时,在启动 Vite 前设置 `LAUNCHER_API_TARGET`。需要直接双击打开离线编辑器时可使用 `frontend/canvas.html`。 + +版本历史支持「载入编辑」和「回滚」。回滚会以选定历史布局生成新版本,版本号继续递增。两个管理员基于同一版本同时提交时,先提交者生效。另一方看到冲突提示后,可先导出本地编辑,再读取新版进行合并。 + +默认数据库位于 `backend/data/layouts.sqlite`。可用 `LAYOUT_DB` 指定持久化路径,用 `HOST`、`PORT` 配置监听地址。正式环境在 HTTPS 反向代理后运行服务,并复用固定令牌。发布历史以 SQLite 数据库为准。已有 Node.js 版数据库时,先停止旧服务,再让 Spring Boot 的 `LAYOUT_DB` 指向原数据库的绝对路径,或在项目根目录沿用默认路径。保留原有令牌即可让已配置的 Android 端继续访问。部署时可单独复制 JAR,并通过 `LAYOUT_DB` 指向服务器上的持久化目录。 + +## 连接 Android + +需要 JDK 17、Android SDK 37,以及能下载 Gradle 8.13 和工程依赖的网络。从项目根目录执行: + +```powershell +.\android\gradlew.bat -p .\android :app:assembleDebug :app:testDebugUnitTest +adb install -r .\android\app\build\outputs\apk\debug\app-debug.apk +``` + +应用包名为 `com.ttstd.compose.launcher`。从旧包名升级时,Android 会将其安装为独立应用。请重新选择默认桌面,配置布局同步,并授权需要的小组件。 + +也可以在编译期把服务地址和设备令牌写进 APK,新安装后无需手填即可自动同步: + +```powershell +$env:LAUNCHER_SYNC_SERVER = 'https://api.ttstd.com/launcher' +$env:LAUNCHER_DEVICE_TOKEN = '<设备令牌>' +.\android\gradlew.bat -p .\android :app:assembleDebug +``` + +内置值只在新安装(没有本机连接设置)时生效;用户手动保存过的配置优先,清空两项并保存仍可关闭同步。 + +同步设置页的「测试第三方小组件」是 Debug 排障入口:枚举设备上已安装的 AppWidget Provider,点「绑定」拉起系统授权弹窗,授权成功后在页面内预览真实组件并回显绑定状态。普通 Launcher 页面仍按布局里的 `widget` 元素渲染,点击桌面上的组件占位块可发起系统授权。同一 provider 可以绑定到多个实例,已绑定实例会随应用重启恢复。 + +用系统应用列表打开「布局同步」,或在 Vibe Launcher 的桌面空白处长按。填写服务根地址和设备令牌,点「保存并同步」,然后回到桌面。测试时可以调整任意一个现有图标的位置,发布后确认手机的位置和版本号都更新。桌面处于前台时每分钟查询一次,回到桌面时立即查询。清空两项连接设置并保存可以关闭同步,已应用的布局仍可离线使用。 + +| 环境 | Android 中填写的服务根地址 | +| --- | --- | +| Android Studio 模拟器,Debug 构建 | `http://10.0.2.2:8080` | +| 同一局域网真机,Debug 构建 | `http://电脑的局域网 IP:8080`。启动后端前将 `HOST` 设为 `0.0.0.0` | +| 正式构建 | `https://你的服务域名` | + +手机断网、令牌无效或新布局校验失败时,继续显示本地布局。冷启动依次读取主布局、上次有效布局和内置布局,如果三个来源都不可用则显示内存兜底桌面。 + +## HTTP 接口 + +管理接口使用 `Authorization: Bearer `。设备接口使用 `Authorization: Bearer `。 + +| 方法和路径 | 用途 | +| --- | --- | +| `GET /healthz` | 服务健康状态 | +| `GET /api/layout` | 下发 v3 布局。设备可传 `If-None-Match`,版本内容相同时返回 304 | +| `GET /api/admin/layout` | 获取线上布局及其 `ETag` | +| `PUT /api/admin/layout` | 发布布局 JSON。通过 `If-Match` 传入当前线上 `ETag` | +| `GET /api/admin/history?before=整数` | 按版本倒序读取历史,每次最多 50 条。首次查询省略 `before` | +| `GET /api/admin/history/{revision}` | 获取某一版本的布局 | +| `POST /api/admin/rollback` | 提交 `{"revision": 1}` 并带当前线上 `If-Match`,生成回滚版本 | + +所有错误响应统一为 JSON:`{"message": "错误说明"}`,校验失败时附带 `issues` 数组(字段位置与原因)。鉴权失败返回 401,参数错误返回 400,接口或版本不存在返回 404,方法不支持返回 405,布局请求超过 1 MiB 返回 413,校验失败返回 422,未提供发布前置版本返回 428,线上版本发生并发变化返回 412,服务内部错误返回 500。 + +校验覆盖协议 v3 的必填字段、画布尺寸(320–8192)、页数与单页元素上限、元素坐标与重叠、背景颜色格式、映射模式与留白位置、页序一致性等。ERROR 拒绝发布并返回校验详情。WARN 不阻挡发布,编辑器会在发布确认时展示画布警告。回滚会在生成新版本前重新校验历史布局,避免旧数据污染线上版本。 + +服务端回归测试可从项目根目录运行 `mvn -f .\backend\pom.xml test`,覆盖鉴权、校验、条件下载、发布冲突、回滚、历史分页、错误响应和数据库重开后的持久化。 + +`LayoutApiTest` 检查 Spring Boot 返回 Vue 页面及其 JS、CSS 资源。`UniformityTest` 核验 Android 内置默认布局和服务端协议限制,包括基准尺寸 1080×1920、顶部安全区 132、底部安全区 72、最多 20 页及每页最多 80 个元素。 + +## 生产部署 + +沿用 `TTSTDElderly` 的 Spring Boot 部署方式:开发机构建 JAR → 上传服务器 → 用 `eclipse-temurin:17-jre-jammy` 构建镜像并导入 k3s containerd → `kubectl apply` → nginx 反代。部署文件在 `backend/deploy/`(`Dockerfile`、`deploy.yaml`、`nginx-launcher.conf`、`verify.sh`)。 + +| 项 | 值 | +| --- | --- | +| 服务器 | `175.178.213.60`,Debian 12,k3s 单节点,SSH 密钥登录 | +| 命名空间 / 工作负载 | `vibe-launcher` / `deploy/vibe-launcher-backend`,单副本 `Recreate` | +| 镜像 | `docker.io/library/vibe-launcher-backend:1.1.0-deploy3`,`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 重建不丢版本历史 | +| 令牌 | 服务器 `/opt/vibe-launcher/auth.env`(root,`600`)生成 Secret `vibe-launcher-auth`,令牌不入库 | + +Android「布局同步」的服务根地址填写 `https://api.ttstd.com/launcher`,管理后台打开 `https://api.ttstd.com/launcher/` 并填入管理员令牌。编辑器会从当前访问路径推导 API 前缀,因此本地根目录访问与线上子路径访问都可用。 + +升级流程:本地执行 `pnpm --dir frontend build` 和 `mvn -f backend/pom.xml clean package`,再上传新 JAR 到 `/opt/vibe-launcher/target/vibe-launcher-backend.jar`,用**新 tag** 构建并导入镜像,修改 `deploy.yaml` 的 image,执行 `kubectl apply`,最后运行 `kubectl -n vibe-launcher rollout status deploy/vibe-launcher-backend --timeout=180s`。同 tag 重建需额外执行 `rollout restart`。回滚用上一版 tag 执行 `kubectl -n vibe-launcher set image deploy/vibe-launcher-backend server=docker.io/library/vibe-launcher-backend:<旧 tag>` 并重启。nginx 站点配置备份放在 `/etc/nginx/backups/`(备份文件不要留在 `sites-enabled/`,否则会被 `include *` 加载并造成 server_name 冲突)。 + +上线验证可在服务器执行 `/opt/vibe-launcher/verify.sh`,覆盖 healthz、设备下发、管理接口 ETag、428/422 错误响应与版本历史。 diff --git a/README.md b/README.md new file mode 100644 index 0000000..2416d38 --- /dev/null +++ b/README.md @@ -0,0 +1,34 @@ +# Vibe Coding Compose Launcher + +在 Android Studio 中打开 `android/` 即可导入 Launcher 工程。三端联调说明位于项目根目录。 + +| 路径 | 内容 | +| --- | --- | +| [android/](android/) | Android Compose Launcher | +| [frontend/](frontend/) | Vue 3 + TypeScript + Vite + Element Plus 管理后台和离线布局编辑器 | +| [backend/](backend/) | Spring Boot 后端、SQLite 布局发布和版本历史 | +| [docs/](docs/) | 布局协议、画布映射和历史设计文档 | +| [INTEGRATION.md](INTEGRATION.md) | 启动后台、构建 APK 和设备联调 | + +## 前端开发 + +使用 Node.js 24 和 pnpm 10.34.5。在项目根目录执行以下命令: + +```powershell +pnpm --dir frontend install --frozen-lockfile +pnpm --dir frontend dev +``` + +生产构建使用 `pnpm --dir frontend build`,产物输出到 `frontend/dist/`。 + +## Android 构建 + +Gradle Wrapper 使用 8.13,AGP 使用 8.13.2,Kotlin 和 Compose 编译器插件使用 2.4.21。使用 JDK 17 运行 Gradle,应用编译目标为 Java 8,编译和目标 SDK 为 37,最低支持 API 26。 + +在项目根目录执行: + +```powershell +.\android\gradlew.bat -p .\android :app:assembleDebug :app:testDebugUnitTest +``` + +调试 APK 输出到 `android/app/build/outputs/apk/debug/app-debug.apk`。后台和后端的启动方式见 [INTEGRATION.md](INTEGRATION.md)。 diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..8714b26 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,13 @@ +*.iml +.gradle/ +local.properties +.idea/ +.DS_Store +build/ +captures/ +.externalNativeBuild/ +.cxx/ +*.apk +*.aab +*.keystore +!debug.keystore diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..206205a --- /dev/null +++ b/android/app/build.gradle.kts @@ -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") +} diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro new file mode 100644 index 0000000..2f1354b --- /dev/null +++ b/android/app/proguard-rules.pro @@ -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 { *; } diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..36f3d2c --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,4 @@ + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..eef50f9 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/assets/default_layout.json b/android/app/src/main/assets/default_layout.json new file mode 100644 index 0000000..9d2edca --- /dev/null +++ b/android/app/src/main/assets/default_layout.json @@ -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" + } + } + ] + } + ] +} \ No newline at end of file diff --git a/android/app/src/main/java/com/ttstd/compose/launcher/LauncherApp.kt b/android/app/src/main/java/com/ttstd/compose/launcher/LauncherApp.kt new file mode 100644 index 0000000..006a351 --- /dev/null +++ b/android/app/src/main/java/com/ttstd/compose/launcher/LauncherApp.kt @@ -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) + } +} diff --git a/android/app/src/main/java/com/ttstd/compose/launcher/LauncherViewModel.kt b/android/app/src/main/java/com/ttstd/compose/launcher/LauncherViewModel.kt new file mode 100644 index 0000000..292607b --- /dev/null +++ b/android/app/src/main/java/com/ttstd/compose/launcher/LauncherViewModel.kt @@ -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 = _layout.asStateFlow() + + private val _wallpaper = MutableStateFlow(null) + val wallpaper: StateFlow = _wallpaper.asStateFlow() + + /** 非 null 表示发生了降级(主布局坏了 / 用了内置默认),仅 debug 下展示 */ + private val _degraded = MutableStateFlow(null) + val degraded: StateFlow = _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().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() + 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().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().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())), + ) + } +} diff --git a/android/app/src/main/java/com/ttstd/compose/launcher/MainActivity.kt b/android/app/src/main/java/com/ttstd/compose/launcher/MainActivity.kt new file mode 100644 index 0000000..c3dde34 --- /dev/null +++ b/android/app/src/main/java/com/ttstd/compose/launcher/MainActivity.kt @@ -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) + } +} diff --git a/android/app/src/main/java/com/ttstd/compose/launcher/SyncSettingsActivity.kt b/android/app/src/main/java/com/ttstd/compose/launcher/SyncSettingsActivity.kt new file mode 100644 index 0000000..d39f5f9 --- /dev/null +++ b/android/app/src/main/java/com/ttstd/compose/launcher/SyncSettingsActivity.kt @@ -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("返回桌面") } + } + } + } + } + } +} diff --git a/android/app/src/main/java/com/ttstd/compose/launcher/WidgetTestActivity.kt b/android/app/src/main/java/com/ttstd/compose/launcher/WidgetTestActivity.kt new file mode 100644 index 0000000..6882d72 --- /dev/null +++ b/android/app/src/main/java/com/ttstd/compose/launcher/WidgetTestActivity.kt @@ -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(null) + private var pendingProvider: AppWidgetProviderInfo? = null + private var pendingSize: Pair = 0 to 0 + private lateinit var controller: TestHost + private lateinit var bindLauncher: ActivityResultLauncher + + 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 = + 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) } + } +} diff --git a/android/app/src/main/java/com/ttstd/compose/launcher/core/AppLaunch.kt b/android/app/src/main/java/com/ttstd/compose/launcher/core/AppLaunch.kt new file mode 100644 index 0000000..038a3fa --- /dev/null +++ b/android/app/src/main/java/com/ttstd/compose/launcher/core/AppLaunch.kt @@ -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) } + } +} diff --git a/android/app/src/main/java/com/ttstd/compose/launcher/core/AppWidgetHostController.kt b/android/app/src/main/java/com/ttstd/compose/launcher/core/AppWidgetHostController.kt new file mode 100644 index 0000000..fd8957f --- /dev/null +++ b/android/app/src/main/java/com/ttstd/compose/launcher/core/AppWidgetHostController.kt @@ -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() + private val sizes = HashMap>() + + 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 + } + } +} diff --git a/android/app/src/main/java/com/ttstd/compose/launcher/core/CanvasMapper.kt b/android/app/src/main/java/com/ttstd/compose/launcher/core/CanvasMapper.kt new file mode 100644 index 0000000..1d0015d --- /dev/null +++ b/android/app/src/main/java/com/ttstd/compose/launcher/core/CanvasMapper.kt @@ -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, + /** 视觉上剩余的整块留白(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): List { + if (items.isEmpty()) return emptyList() + val sorted = items.map { it.y to it.y + it.h }.sortedBy { it.first } + val out = ArrayList(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, + 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>(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, statusBarPx: Int, navBarPx: Int): List { + val out = ArrayList() + val w = canvas.designWidth + val h = canvas.designHeight + + val ids = HashSet() + 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) }, + ) +} diff --git a/android/app/src/main/java/com/ttstd/compose/launcher/core/IconLoader.kt b/android/app/src/main/java/com/ttstd/compose/launcher/core/IconLoader.kt new file mode 100644 index 0000000..e6d7705 --- /dev/null +++ b/android/app/src/main/java/com/ttstd/compose/launcher/core/IconLoader.kt @@ -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( + (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, 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 + } +} diff --git a/android/app/src/main/java/com/ttstd/compose/launcher/core/LayoutModels.kt b/android/app/src/main/java/com/ttstd/compose/launcher/core/LayoutModels.kt new file mode 100644 index 0000000..0cc72d3 --- /dev/null +++ b/android/app/src/main/java/com/ttstd/compose/launcher/core/LayoutModels.kt @@ -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 = 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 = 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(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 { + val out = ArrayList() + 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(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 } +} diff --git a/android/app/src/main/java/com/ttstd/compose/launcher/core/LayoutRepository.kt b/android/app/src/main/java/com/ttstd/compose/launcher/core/LayoutRepository.kt new file mode 100644 index 0000000..0e665d6 --- /dev/null +++ b/android/app/src/main/java/com/ttstd/compose/launcher/core/LayoutRepository.kt @@ -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(null) + val layout: StateFlow = _layout.asStateFlow() + + private val _degraded = MutableStateFlow(null) + val degraded: StateFlow = _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 = 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() + } + } +} diff --git a/android/app/src/main/java/com/ttstd/compose/launcher/core/RemoteLayoutSync.kt b/android/app/src/main/java/com/ttstd/compose/launcher/core/RemoteLayoutSync.kt new file mode 100644 index 0000000..e5ba00d --- /dev/null +++ b/android/app/src/main/java/com/ttstd/compose/launcher/core/RemoteLayoutSync.kt @@ -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 + } +} diff --git a/android/app/src/main/java/com/ttstd/compose/launcher/core/WallpaperLoader.kt b/android/app/src/main/java/com/ttstd/compose/launcher/core/WallpaperLoader.kt new file mode 100644 index 0000000..1c4cb9d --- /dev/null +++ b/android/app/src/main/java/com/ttstd/compose/launcher/core/WallpaperLoader.kt @@ -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() + } +} diff --git a/android/app/src/main/java/com/ttstd/compose/launcher/core/WidgetHostProvider.kt b/android/app/src/main/java/com/ttstd/compose/launcher/core/WidgetHostProvider.kt new file mode 100644 index 0000000..8899f1c --- /dev/null +++ b/android/app/src/main/java/com/ttstd/compose/launcher/core/WidgetHostProvider.kt @@ -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? +} diff --git a/android/app/src/main/java/com/ttstd/compose/launcher/ui/LauncherCanvas.kt b/android/app/src/main/java/com/ttstd/compose/launcher/ui/LauncherCanvas.kt new file mode 100644 index 0000000..a935be2 --- /dev/null +++ b/android/app/src/main/java/com/ttstd/compose/launcher/ui/LauncherCanvas.kt @@ -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(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) diff --git a/android/app/src/main/java/com/ttstd/compose/launcher/ui/theme/Theme.kt b/android/app/src/main/java/com/ttstd/compose/launcher/ui/theme/Theme.kt new file mode 100644 index 0000000..75cdc19 --- /dev/null +++ b/android/app/src/main/java/com/ttstd/compose/launcher/ui/theme/Theme.kt @@ -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) +} diff --git a/android/app/src/main/res/drawable/ic_launcher.xml b/android/app/src/main/res/drawable/ic_launcher.xml new file mode 100644 index 0000000..7524913 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_launcher.xml @@ -0,0 +1,12 @@ + + + + diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..d99d1d0 --- /dev/null +++ b/android/app/src/main/res/values/colors.xml @@ -0,0 +1,8 @@ + + + + #0B0F16 + #1B2434 + #4C7DFF + diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..d5fdcfc --- /dev/null +++ b/android/app/src/main/res/values/strings.xml @@ -0,0 +1,5 @@ + + + Vibe Launcher + 内置布局缺失 + diff --git a/android/app/src/main/res/values/themes.xml b/android/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..6da9212 --- /dev/null +++ b/android/app/src/main/res/values/themes.xml @@ -0,0 +1,14 @@ + + + + + diff --git a/android/app/src/test/java/com/ttstd/compose/launcher/core/CanvasMapperTest.kt b/android/app/src/test/java/com/ttstd/compose/launcher/core/CanvasMapperTest.kt new file mode 100644 index 0000000..63e28e3 --- /dev/null +++ b/android/app/src/test/java/com/ttstd/compose/launcher/core/CanvasMapperTest.kt @@ -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 { + 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() + 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): 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() + } +} diff --git a/android/app/src/test/java/com/ttstd/compose/launcher/core/LayoutValidatorTest.kt b/android/app/src/test/java/com/ttstd/compose/launcher/core/LayoutValidatorTest.kt new file mode 100644 index 0000000..77f6b1a --- /dev/null +++ b/android/app/src/test/java/com/ttstd/compose/launcher/core/LayoutValidatorTest.kt @@ -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) + } +} diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..7b8cda6 --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,8 @@ +// 顶层构建脚本:只声明插件版本,不引入依赖 +plugins { + id("com.android.application") version "8.13.2" apply false + id("org.jetbrains.kotlin.android") version "2.4.21" apply false + // Kotlin 2.0 起 Compose 编译器是独立插件,不再用 composeOptions 指定版本 + id("org.jetbrains.kotlin.plugin.compose") version "2.4.21" apply false + id("org.jetbrains.kotlin.plugin.serialization") version "2.4.21" apply false +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..167b26c --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,12 @@ +org.gradle.jvmargs=-Xmx4096m -XX:MaxMetaspaceSize=512m -Dfile.encoding=UTF-8 +org.gradle.parallel=true +org.gradle.caching=true +org.gradle.configuration-cache=false + +android.useAndroidX=true +android.nonTransitiveRClass=true +android.enableJetifier=true +android.suppressUnsupportedCompileSdk=37.0 +kotlin.suppressGradlePluginWarnings=DeprecatedGradleVersionWarning + +kotlin.code.style=official diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..f6b961f Binary files /dev/null and b/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..c09bdf5 --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sat Oct 11 20:25:09 CST 2025 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-all.zip diff --git a/android/gradlew b/android/gradlew new file mode 100755 index 0000000..cccdd3d --- /dev/null +++ b/android/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/android/gradlew.bat b/android/gradlew.bat new file mode 100644 index 0000000..f955316 --- /dev/null +++ b/android/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..3a7b247 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,24 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + maven("https://maven.aliyun.com/repository/google") + maven("https://maven.aliyun.com/repository/gradle-plugin") + maven("https://maven.aliyun.com/repository/central") + } +} + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + maven("https://maven.aliyun.com/repository/google") + maven("https://maven.aliyun.com/repository/central") + maven("https://maven.aliyun.com/repository/public") + } +} + +rootProject.name = "VibeCodingComposeLauncher" +include(":app") diff --git a/backend/.gitignore b/backend/.gitignore new file mode 100644 index 0000000..d3902b5 --- /dev/null +++ b/backend/.gitignore @@ -0,0 +1,2 @@ +/data/ +/target/ diff --git a/backend/deploy/Dockerfile b/backend/deploy/Dockerfile new file mode 100644 index 0000000..71e8ace --- /dev/null +++ b/backend/deploy/Dockerfile @@ -0,0 +1,12 @@ +FROM eclipse-temurin:17-jre-jammy + +WORKDIR /app + +ENV TZ=Asia/Shanghai \ + JAVA_TOOL_OPTIONS="-Xms64m -Xmx192m -XX:MaxMetaspaceSize=128m -XX:+UseSerialGC -XX:+ExitOnOutOfMemoryError -Djava.security.egd=file:/dev/./urandom" + +COPY target/vibe-launcher-backend.jar /app/app.jar + +EXPOSE 8080 + +ENTRYPOINT ["java", "-jar", "/app/app.jar"] diff --git a/backend/deploy/deploy.yaml b/backend/deploy/deploy.yaml new file mode 100644 index 0000000..41dbd65 --- /dev/null +++ b/backend/deploy/deploy.yaml @@ -0,0 +1,95 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: vibe-launcher + labels: + name: vibe-launcher +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: vibe-launcher-backend + namespace: vibe-launcher + labels: + app: vibe-launcher-backend +spec: + replicas: 1 + strategy: + type: Recreate + selector: + matchLabels: + app: vibe-launcher-backend + template: + metadata: + labels: + app: vibe-launcher-backend + spec: + containers: + - name: server + image: docker.io/library/vibe-launcher-backend:1.1.0-deploy3 + imagePullPolicy: IfNotPresent + ports: + - name: http + containerPort: 8080 + protocol: TCP + env: + - name: TZ + value: Asia/Shanghai + - name: HOST + value: 0.0.0.0 + - name: PORT + value: "8080" + - name: LAYOUT_DB + value: /data/layouts.sqlite + envFrom: + - secretRef: + name: vibe-launcher-auth + volumeMounts: + - name: data + mountPath: /data + resources: + requests: + cpu: 100m + memory: 192Mi + limits: + cpu: 750m + memory: 384Mi + readinessProbe: + httpGet: + path: /healthz + port: http + initialDelaySeconds: 15 + periodSeconds: 10 + timeoutSeconds: 5 + failureThreshold: 6 + livenessProbe: + httpGet: + path: /healthz + port: http + initialDelaySeconds: 60 + periodSeconds: 20 + timeoutSeconds: 5 + failureThreshold: 5 + volumes: + - name: data + hostPath: + path: /opt/vibe-launcher/data + type: DirectoryOrCreate +--- +apiVersion: v1 +kind: Service +metadata: + name: vibe-launcher-backend + namespace: vibe-launcher + labels: + app: vibe-launcher-backend +spec: + type: NodePort + selector: + app: vibe-launcher-backend + ports: + - name: http + port: 8080 + targetPort: http + nodePort: 30830 + protocol: TCP diff --git a/backend/deploy/nginx-launcher.conf b/backend/deploy/nginx-launcher.conf new file mode 100644 index 0000000..fe39a7e --- /dev/null +++ b/backend/deploy/nginx-launcher.conf @@ -0,0 +1,22 @@ +# Vibe Launcher 后端(k3s vibe-launcher/vibe-launcher-backend, NodePort 30830) +# 挂载点:https://api.ttstd.com/launcher/(灰云直连源站,不走 Cloudflare) +# 用法:放到 /etc/nginx/snippets/launcher-path.conf,在 api.ttstd.com 的 443 server 块内 include +# 以 /launcher/ 前缀反代,proxy_pass 末尾斜杠会剥掉前缀,后端仍收到 /api/... 与 / +location = /launcher { + return 301 /launcher/; +} + +location ^~ /launcher/ { + client_max_body_size 2m; + proxy_pass http://127.0.0.1:30830/; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_connect_timeout 10s; + proxy_read_timeout 30s; + proxy_send_timeout 30s; + proxy_buffering off; + add_header Cache-Control "no-store" always; +} diff --git a/backend/deploy/verify.sh b/backend/deploy/verify.sh new file mode 100755 index 0000000..e13f724 --- /dev/null +++ b/backend/deploy/verify.sh @@ -0,0 +1,36 @@ +#!/bin/bash +set -euo pipefail + +BASE=${BASE:-https://api.ttstd.com/launcher} +AUTH_FILE=${AUTH_FILE:-/opt/vibe-launcher/auth.env} +. "$AUTH_FILE" + +echo "== healthz ==" +curl -fsS "$BASE/healthz"; echo + +echo "== device layout ==" +curl -fsS -H "Authorization: Bearer $DEVICE_TOKEN" -D /tmp/launcher-device.headers \ + -o /tmp/launcher-device.json "$BASE/api/layout" +grep -i '^X-Layout-Revision:' /tmp/launcher-device.headers + +echo "== admin layout ==" +curl -fsS -H "Authorization: Bearer $ADMIN_TOKEN" -D /tmp/launcher-admin.headers \ + -o /tmp/launcher-admin.json "$BASE/api/admin/layout" +TAG=$(sed -n 's/^[Ee][Tt][Aa][Gg]: //p' /tmp/launcher-admin.headers | tr -d '\r') +echo "ETag=$TAG" + +echo "== missing If-Match ==" +curl -sS -o /tmp/launcher-428.json -w '%{http_code}\n' -X PUT \ + -H "Authorization: Bearer $ADMIN_TOKEN" -H 'Content-Type: application/json' \ + --data @/tmp/launcher-admin.json "$BASE/api/admin/layout" +cat /tmp/launcher-428.json; echo + +echo "== invalid layout ==" +curl -sS -o /tmp/launcher-422.json -w '%{http_code}\n' -X PUT \ + -H "Authorization: Bearer $ADMIN_TOKEN" -H "If-Match: $TAG" \ + -H 'Content-Type: application/json' \ + --data '{"schemaVersion":2,"pages":[]}' "$BASE/api/admin/layout" +head -c 200 /tmp/launcher-422.json; echo + +echo "== history ==" +curl -fsS -H "Authorization: Bearer $ADMIN_TOKEN" "$BASE/api/admin/history"; echo diff --git a/backend/pom.xml b/backend/pom.xml new file mode 100644 index 0000000..38a2f2b --- /dev/null +++ b/backend/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 4.1.2 + + + com.ttstd + vibe-launcher-backend + 1.1.0 + + 17 + 3.41.2.2 + + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.xerial + sqlite-jdbc + ${sqlite-jdbc.version} + + + org.springframework.boot + spring-boot-starter-test + test + + + + vibe-launcher-backend + + src/main/resources + + ../frontend/dist + launcher/web + + + ../android/app/src/main/assets + default_layout.json + launcher + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/backend/src/main/java/com/ttstd/launcher/ApiError.java b/backend/src/main/java/com/ttstd/launcher/ApiError.java new file mode 100644 index 0000000..aa321b6 --- /dev/null +++ b/backend/src/main/java/com/ttstd/launcher/ApiError.java @@ -0,0 +1,24 @@ +package com.ttstd.launcher; + +import java.util.List; +import java.util.Map; + +class ApiError extends RuntimeException { + final int status; + private final List issues; + + ApiError(int status, String message) { + this(status, message, List.of()); + } + + ApiError(int status, String message, List issues) { + super(message); + this.status = status; + this.issues = issues; + } + + Map body() { + return issues.isEmpty() ? Map.of("message", getMessage()) + : Map.of("message", getMessage(), "issues", issues); + } +} diff --git a/backend/src/main/java/com/ttstd/launcher/ApiExceptionHandler.java b/backend/src/main/java/com/ttstd/launcher/ApiExceptionHandler.java new file mode 100644 index 0000000..00acc7d --- /dev/null +++ b/backend/src/main/java/com/ttstd/launcher/ApiExceptionHandler.java @@ -0,0 +1,53 @@ +package com.ttstd.launcher; + +import jakarta.servlet.http.HttpServletRequest; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.MissingServletRequestParameterException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; +import org.springframework.web.servlet.NoHandlerFoundException; +import org.springframework.web.servlet.resource.NoResourceFoundException; + +@RestControllerAdvice +class ApiExceptionHandler { + private static final Logger log = LoggerFactory.getLogger(ApiExceptionHandler.class); + private static final MediaType JSON = new MediaType("application", "json", StandardCharsets.UTF_8); + + @ExceptionHandler(ApiError.class) + ResponseEntity> apiError(ApiError error) { + return ResponseEntity.status(error.status).contentType(JSON).body(error.body()); + } + + @ExceptionHandler({NoHandlerFoundException.class, NoResourceFoundException.class}) + ResponseEntity> notFound() { + return ResponseEntity.status(404).contentType(JSON).body(Map.of("message", "接口不存在")); + } + + @ExceptionHandler(HttpRequestMethodNotSupportedException.class) + ResponseEntity> methodNotAllowed(HttpRequestMethodNotSupportedException error) { + var response = ResponseEntity.status(405).contentType(JSON); + if (error.getSupportedHttpMethods() != null) { + response = response.header("Allow", String.join(", ", + error.getSupportedHttpMethods().stream().map(method -> method.name()).toList())); + } + return response.body(Map.of("message", "不支持的请求方法")); + } + + @ExceptionHandler({MissingServletRequestParameterException.class, MethodArgumentTypeMismatchException.class}) + ResponseEntity> badRequest() { + return ResponseEntity.status(400).contentType(JSON).body(Map.of("message", "请求参数错误")); + } + + @ExceptionHandler(Exception.class) + ResponseEntity> internal(Exception error, HttpServletRequest request) { + log.error("处理 {} {} 失败", request.getMethod(), request.getRequestURI(), error); + return ResponseEntity.status(500).contentType(JSON).body(Map.of("message", "服务内部错误")); + } +} diff --git a/backend/src/main/java/com/ttstd/launcher/LauncherApplication.java b/backend/src/main/java/com/ttstd/launcher/LauncherApplication.java new file mode 100644 index 0000000..0b303c0 --- /dev/null +++ b/backend/src/main/java/com/ttstd/launcher/LauncherApplication.java @@ -0,0 +1,11 @@ +package com.ttstd.launcher; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class LauncherApplication { + public static void main(String[] args) { + SpringApplication.run(LauncherApplication.class, args); + } +} diff --git a/backend/src/main/java/com/ttstd/launcher/LayoutController.java b/backend/src/main/java/com/ttstd/launcher/LayoutController.java new file mode 100644 index 0000000..492bf5b --- /dev/null +++ b/backend/src/main/java/com/ttstd/launcher/LayoutController.java @@ -0,0 +1,165 @@ +package com.ttstd.launcher; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.Map; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.http.CacheControl; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import tools.jackson.core.JacksonException; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.node.ObjectNode; + +@RestController +class LayoutController { + private static final long MAX_SAFE_INTEGER = 9_007_199_254_740_991L; + private static final MediaType JSON = new MediaType("application", "json", StandardCharsets.UTF_8); + private static final String EDITOR_CSP = "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; " + + "img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'"; + + private final LayoutStore store; + private final RequestPolicy policy; + private final LayoutValidator validator; + private final ObjectMapper mapper; + private final Resource editor = new ClassPathResource("launcher/web/index.html"); + + LayoutController(LayoutStore store, RequestPolicy policy, LayoutValidator validator, ObjectMapper mapper) { + this.store = store; + this.policy = policy; + this.validator = validator; + this.mapper = mapper; + } + + @GetMapping({"/", "/index.html", "/canvas.html"}) + ResponseEntity editor() { + return ResponseEntity.ok() + .contentType(new MediaType("text", "html", StandardCharsets.UTF_8)) + .cacheControl(CacheControl.noCache()) + .header("Content-Security-Policy", EDITOR_CSP) + .body(editor); + } + + @GetMapping("/assets/{name:[a-zA-Z0-9_-]+\\.(?:js|css)}") + ResponseEntity editorAsset(@PathVariable String name) { + var asset = new ClassPathResource("launcher/web/assets/" + name); + if (!asset.exists()) throw new ApiError(404, "编辑器资源不存在"); + var type = new MediaType("text", name.endsWith(".js") ? "javascript" : "css", StandardCharsets.UTF_8); + return ResponseEntity.ok().contentType(type).body(asset); + } + + @GetMapping("/healthz") + Map health() { + return Map.of("status", "ok"); + } + + @GetMapping("/api/layout") + ResponseEntity deviceLayout(HttpServletRequest request, HttpServletResponse response) throws SQLException { + policy.requireDevice(request, response); + var release = store.latest(); + if (release.etag().equals(request.getHeader("If-None-Match"))) { + return releaseHeaders(304, release).build(); + } + return serve(release); + } + + @GetMapping("/api/admin/layout") + ResponseEntity adminLayout(HttpServletRequest request, HttpServletResponse response) throws SQLException { + policy.requireAdmin(request, response); + return serve(store.latest()); + } + + @GetMapping("/api/admin/history") + LayoutStore.History history(@RequestParam(defaultValue = "2147483648") String before, + HttpServletRequest request, HttpServletResponse response) throws SQLException { + policy.requireAdmin(request, response); + long revision; + try { + revision = Long.parseLong(before); + } catch (NumberFormatException error) { + throw new ApiError(400, "无效的分页参数"); + } + if (revision < 1 || revision > MAX_SAFE_INTEGER) throw new ApiError(400, "无效的分页参数"); + return store.history(revision); + } + + @GetMapping("/api/admin/history/{revision:[1-9][0-9]{0,9}}") + ResponseEntity historyEntry(@PathVariable long revision, HttpServletRequest request, + HttpServletResponse response) throws SQLException { + policy.requireAdmin(request, response); + return serve(store.byRevision(revision)); + } + + @PutMapping("/api/admin/layout") + ResponseEntity publish(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException { + policy.requireAdmin(request, response); + String tag = requireTag(request); + JsonNode json = readJson(request); + var issues = validator.validate(json); + if (issues.stream().anyMatch(issue -> issue.level().equals("error"))) { + throw new ApiError(422, "布局校验失败", issues.stream().limit(100).toList()); + } + return serve(store.publish(tag, (ObjectNode) json, null)); + } + + @PostMapping("/api/admin/rollback") + ResponseEntity rollback(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException { + policy.requireAdmin(request, response); + String tag = requireTag(request); + JsonNode revision = readJson(request).path("revision"); + if (!revision.isNumber() || !revision.canConvertToExactIntegral() || !revision.canConvertToLong() + || revision.longValue() < 1 || revision.longValue() > MAX_SAFE_INTEGER) { + throw new ApiError(400, "无效的回滚版本号"); + } + return serve(store.publish(tag, null, revision.longValue())); + } + + private static String requireTag(HttpServletRequest request) { + String tag = request.getHeader(HttpHeaders.IF_MATCH); + if (tag == null || tag.isEmpty()) throw new ApiError(428, "发布前请先读取线上版本"); + return tag; + } + + private JsonNode readJson(HttpServletRequest request) throws IOException { + String type = request.getContentType(); + if (type == null || !type.split(";", 2)[0].trim().equalsIgnoreCase("application/json")) { + throw new ApiError(415, "请求必须使用 application/json"); + } + if (request.getContentLengthLong() > LayoutStore.MAX_BYTES) throw new ApiError(413, "布局超过 1 MiB"); + byte[] bytes = request.getInputStream().readNBytes(LayoutStore.MAX_BYTES + 1); + if (bytes.length > LayoutStore.MAX_BYTES) throw new ApiError(413, "布局超过 1 MiB"); + try { + String text = StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString(); + if (text.startsWith("\uFEFF")) text = text.substring(1); + JsonNode node = mapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS).readTree(text); + if (node == null || node.isMissingNode()) throw new ApiError(400, "无效的 UTF-8 JSON"); + return node; + } catch (CharacterCodingException | JacksonException error) { + throw new ApiError(400, "无效的 UTF-8 JSON"); + } + } + + private static ResponseEntity.BodyBuilder releaseHeaders(int status, LayoutStore.Release release) { + return ResponseEntity.status(status).eTag(release.etag()) + .header("X-Layout-Revision", Integer.toString(release.revision())); + } + + private static ResponseEntity serve(LayoutStore.Release release) { + return releaseHeaders(200, release).contentType(JSON).body(release.layout().getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/backend/src/main/java/com/ttstd/launcher/LayoutStore.java b/backend/src/main/java/com/ttstd/launcher/LayoutStore.java new file mode 100644 index 0000000..33c4327 --- /dev/null +++ b/backend/src/main/java/com/ttstd/launcher/LayoutStore.java @@ -0,0 +1,181 @@ +package com.ttstd.launcher; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.ClassPathResource; +import org.springframework.stereotype.Repository; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.node.ObjectNode; + +@Repository +class LayoutStore { + static final int MAX_BYTES = 1024 * 1024; + private static final int PAGE_SIZE = 50; + 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 Release(int revision, String layout) { + String etag() { + return "\"" + java.util.HexFormat.of().formatHex(RequestPolicy.sha256(layout)) + "\""; + } + } + record HistoryEntry(int revision, String publishedAt, Integer restoredFrom) {} + record History(List revisions, Integer nextBefore) {} + + private final String address; + private final ObjectMapper mapper; + private final LayoutValidator validator; + + LayoutStore(@Value("${launcher.database}") String database, ObjectMapper mapper, LayoutValidator validator) + throws IOException, SQLException { + this.mapper = mapper; + this.validator = validator; + Path path = Path.of(database).toAbsolutePath().normalize(); + Files.createDirectories(path.getParent()); + address = "jdbc:sqlite:" + path; + + ObjectNode initial; + try (var stream = new ClassPathResource("launcher/default_layout.json").getInputStream()) { + var node = mapper.readTree(stream); + if (!node.isObject() || validator.validate(node).stream().anyMatch(i -> i.level().equals("error"))) { + throw new IllegalStateException("内置布局未通过校验"); + } + initial = (ObjectNode) node; + } + try (var connection = connect(); var statement = connection.createStatement()) { + statement.execute("PRAGMA journal_mode = WAL"); + statement.execute(""" + CREATE TABLE IF NOT EXISTS releases ( + revision INTEGER PRIMARY KEY CHECK (revision BETWEEN 1 AND 2147483647), + layout TEXT NOT NULL, + publishedAt TEXT NOT NULL, + restoredFrom INTEGER REFERENCES releases(revision) + ) STRICT + """); + try (var seed = connection.prepareStatement(""" + INSERT OR IGNORE INTO releases (revision, layout, publishedAt, restoredFrom) + VALUES (1, ?, ?, NULL) + """)) { + seed.setString(1, mapper.writeValueAsString(initial.put("revision", 1))); + seed.setString(2, Instant.now().toString()); + seed.executeUpdate(); + } + } + } + + private Connection connect() throws SQLException { + var connection = DriverManager.getConnection(address); + try (var statement = connection.createStatement()) { + statement.execute("PRAGMA busy_timeout = 5000"); + statement.execute("PRAGMA synchronous = FULL"); + statement.execute("PRAGMA foreign_keys = ON"); + return connection; + } catch (SQLException e) { + connection.close(); + throw e; + } + } + + Release latest() throws SQLException { + try (var connection = connect(); var statement = connection.createStatement(); + var rows = statement.executeQuery(LATEST)) { + if (!rows.next()) throw new IllegalStateException("布局版本库为空"); + return release(rows); + } + } + + Release byRevision(long revision) throws SQLException { + try (var connection = connect()) { + return byRevision(connection, revision); + } + } + + private Release byRevision(Connection connection, long revision) throws SQLException { + try (var statement = connection.prepareStatement(BY_REVISION)) { + statement.setLong(1, revision); + try (var rows = statement.executeQuery()) { + if (!rows.next()) throw new ApiError(404, "该版本不存在"); + return release(rows); + } + } + } + + History history(long before) throws SQLException { + List result = new ArrayList<>(); + try (var connection = connect(); var statement = connection.prepareStatement(""" + SELECT revision, publishedAt, restoredFrom FROM releases + WHERE revision < ? ORDER BY revision DESC LIMIT 51 + """)) { + statement.setLong(1, before); + try (var rows = statement.executeQuery()) { + while (rows.next()) { + if (result.size() == PAGE_SIZE) return new History(result, result.get(PAGE_SIZE - 1).revision()); + int restoredFrom = rows.getInt("restoredFrom"); + Integer previous = rows.wasNull() ? null : restoredFrom; + result.add(new HistoryEntry(rows.getInt("revision"), rows.getString("publishedAt"), previous)); + } + } + } + return new History(result, null); + } + + Release publish(String expected, ObjectNode layout, Long restoredFrom) throws SQLException { + try (var connection = connect(); var tx = connection.createStatement()) { + tx.execute("BEGIN IMMEDIATE"); + try { + Release current; + try (var rows = tx.executeQuery(LATEST)) { + if (!rows.next()) throw new IllegalStateException("布局版本库为空"); + current = release(rows); + } + if (!current.etag().equals(expected)) throw new ApiError(412, "线上版本已变化,请重新读取后再发布"); + if (current.revision() == Integer.MAX_VALUE) throw new ApiError(409, "布局版本号已达上限"); + if (restoredFrom != null) { + layout = (ObjectNode) mapper.readTree(byRevision(connection, restoredFrom).layout()); + var issues = validator.validate(layout); + if (issues.stream().anyMatch(issue -> issue.level().equals("error"))) { + throw new ApiError(422, "历史版本布局校验失败,无法回滚", issues.stream().limit(100).toList()); + } + } + 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"); + + try (var insert = connection.prepareStatement(""" + INSERT INTO releases (revision, layout, publishedAt, restoredFrom) VALUES (?, ?, ?, ?) + """)) { + insert.setInt(1, revision); + insert.setString(2, json); + insert.setString(3, Instant.now().toString()); + if (restoredFrom == null) insert.setNull(4, Types.INTEGER); + else insert.setLong(4, restoredFrom); + insert.executeUpdate(); + } + tx.execute("COMMIT"); + return new Release(revision, json); + } catch (SQLException | RuntimeException error) { + try { + tx.execute("ROLLBACK"); + } catch (SQLException rollbackError) { + error.addSuppressed(rollbackError); + } + throw error; + } + } + } + + private static Release release(ResultSet rows) throws SQLException { + return new Release(rows.getInt("revision"), rows.getString("layout")); + } +} diff --git a/backend/src/main/java/com/ttstd/launcher/LayoutValidator.java b/backend/src/main/java/com/ttstd/launcher/LayoutValidator.java new file mode 100644 index 0000000..ccf1d1a --- /dev/null +++ b/backend/src/main/java/com/ttstd/launcher/LayoutValidator.java @@ -0,0 +1,236 @@ +package com.ttstd.launcher; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Predicate; +import java.util.regex.Pattern; +import org.springframework.stereotype.Component; +import tools.jackson.databind.JsonNode; + +@Component +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 TYPES = Set.of("app_icon", "widget", "shortcut", "dock_bg"); + private static final Set FIT_MODES = Set.of("contain", "elastic", "stretch"); + private static final Set BACKGROUNDS = Set.of("wallpaper", "solid", "gradient"); + private static final Pattern HEX_COLOR = Pattern.compile("#[0-9A-Fa-f]{6}"); + private static final Pattern SCHEME = Pattern.compile("[A-Za-z][A-Za-z0-9+.-]*://.*"); + private static final int MAX_CANVAS = 8192; + private static final int MAX_ID_LENGTH = 64; + private static final int MAX_LABEL_LENGTH = 100; + + List validate(JsonNode layout) { + List issues = new ArrayList<>(); + if (!layout.isObject()) { + error(issues, "$", "布局必须是 JSON 对象"); + return issues; + } + if (!optional(layout, "schemaVersion", n -> integer(n) && n.intValue() == 3)) { + error(issues, "schemaVersion", "仅支持协议 v3"); + } + if (!optional(layout, "revision", LayoutValidator::integer)) { + error(issues, "revision", "版本号必须是整数"); + } + + JsonNode canvas = layout.path("canvas"); + JsonNode fit = layout.path("fit"); + if (!optional(layout, "canvas", n -> n.isObject() && + optionalFields(n, LayoutValidator::integer, "designWidth", "designHeight", "safeTop", "safeBottom"))) { + error(issues, "canvas", "画布字段必须是整数"); + return issues; + } + if (!optional(layout, "fit", n -> n.isObject() && optional(n, "mode", JsonNode::isTextual) + && optional(n, "anchorY", LayoutValidator::finiteFloat))) { + error(issues, "fit", "映射模式或留白位置格式错误"); + } + int width = canvas.path("designWidth").asInt(1080); + int height = canvas.path("designHeight").asInt(1920); + int safeTop = canvas.path("safeTop").asInt(132); + int safeBottom = canvas.path("safeBottom").asInt(72); + if (width < 320 || height < 480) error(issues, "canvas", "画布最小尺寸为 320 × 480"); + if (width > MAX_CANVAS || height > MAX_CANVAS) error(issues, "canvas", "画布尺寸不能超过 " + MAX_CANVAS); + if (safeTop < 0 || safeBottom < 0) error(issues, "canvas", "安全区不能为负数"); + if (safeTop + safeBottom >= height) warn(issues, "canvas", "安全区总和高过画布,内容可能没有可用区域"); + if (safeTop < 118) warn(issues, "canvas.safeTop", "safeTop 偏小,1440 屏状态栏约 176px"); + if (safeBottom < 40) warn(issues, "canvas.safeBottom", "safeBottom 偏小,可能被手势条压住"); + + String mode = fit.path("mode").stringValue(""); + if (!mode.isEmpty() && !FIT_MODES.contains(mode)) warn(issues, "fit.mode", "未知映射模式,端上按 contain 处理"); + JsonNode anchor = fit.get("anchorY"); + if (anchor != null && finiteFloat(anchor) && (anchor.doubleValue() < 0 || anchor.doubleValue() > 1)) { + warn(issues, "fit.anchorY", "留白位置需在 0–1 之间,端上会截断"); + } + + JsonNode pages = layout.path("pages"); + if (!pages.isArray() || pages.isEmpty() || pages.size() > 20) { + error(issues, "pages", "布局必须包含 1–20 页"); + return issues; + } + Set indexes = new HashSet<>(); + for (int i = 0; i < pages.size(); i++) { + JsonNode page = pages.get(i); + if (page.isObject()) { + JsonNode index = page.get("index"); + if (index != null && integer(index)) { + if (!indexes.add(index.intValue())) { + warn(issues, "pages[" + i + "].index", "页序重复,端上按数组顺序显示"); + } else if (index.intValue() != i) { + warn(issues, "pages[" + i + "].index", "页序与数组顺序不一致,端上按数组顺序显示"); + } + } + } + validatePage(issues, page, "pages[" + i + "]", width, height, safeTop, safeBottom); + } + return issues; + } + + private void validatePage(List issues, JsonNode page, String path, int width, int height, int safeTop, int safeBottom) { + if (!page.isObject()) { + error(issues, path, "页面必须是对象"); + return; + } + if (!optional(page, "index", LayoutValidator::integer)) error(issues, path + ".index", "页序必须是整数"); + if (!optional(page, "background", n -> n.isObject() && optional(n, "type", JsonNode::isTextual) + && optionalFields(n, LayoutValidator::nullableText, "color", "from", "to"))) { + error(issues, path + ".background", "页面背景字段格式错误"); + } + JsonNode background = page.get("background"); + if (background != null && background.isObject()) { + String backgroundType = background.path("type").stringValue("wallpaper"); + if (!BACKGROUNDS.contains(backgroundType)) { + warn(issues, path + ".background.type", "未知背景类型,端上按壁纸处理"); + } + if (backgroundType.equals("solid") && background.path("color").stringValue("").isBlank()) { + warn(issues, path + ".background.color", "纯色背景缺少 color"); + } + if (backgroundType.equals("gradient") && (background.path("from").stringValue("").isBlank() + || background.path("to").stringValue("").isBlank())) { + warn(issues, path + ".background", "渐变背景需要 from 和 to"); + } + for (String name : List.of("color", "from", "to")) { + String color = background.path(name).stringValue(""); + if (!color.isEmpty() && !HEX_COLOR.matcher(color).matches()) { + warn(issues, path + ".background." + name, "颜色需为 #RRGGBB 格式"); + } + } + } + + JsonNode items = page.path("items"); + if (items.isMissingNode()) return; + if (!items.isArray() || items.size() > 80) { + error(issues, path + ".items", "每页最多 80 个元素"); + return; + } + Set ids = new HashSet<>(); + List rectangles = new ArrayList<>(); + for (int i = 0; i < items.size(); i++) { + JsonNode item = items.get(i); + String at = path + ".items[" + i + "]"; + if (!item.isObject()) { + error(issues, at, "元素必须是对象"); + continue; + } + String id = item.path("id").stringValue(""); + if (id.isBlank() || !ids.add(id)) error(issues, at + ".id", "ID 为空或重复"); + if (id.length() > MAX_ID_LENGTH) warn(issues, at + ".id", "ID 过长,建议不超过 " + MAX_ID_LENGTH + " 字符"); + JsonNode typeNode = item.path("type"); + String type = typeNode.stringValue(""); + if (!typeNode.isTextual()) error(issues, at + ".type", "元素类型必须是字符串"); + else if (!TYPES.contains(type)) warn(issues, at + ".type", "未知类型,手机会跳过此元素"); + if (!optional(item, "z", LayoutValidator::integer)) error(issues, at + ".z", "层级必须是整数"); + + if (validCoordinates(item)) { + float x = item.get("x").floatValue(); + float y = item.get("y").floatValue(); + float right = x + item.get("w").floatValue(); + float bottom = y + item.get("h").floatValue(); + if (right > width + 0.5f || bottom > height + 0.5f) error(issues, at, "元素超出画布"); + if (y < safeTop || bottom > (long) height - safeBottom) warn(issues, at, "元素进入安全区"); + if (!type.equals("dock_bg")) rectangles.add(new Rect(at, x, y, right, bottom)); + } else { + error(issues, at, "坐标必须非负且尺寸必须为正数"); + } + validatePayload(issues, item, at, type); + } + + for (int i = 0; i < rectangles.size(); i++) { + Rect a = rectangles.get(i); + for (int j = i + 1; j < rectangles.size(); j++) { + Rect b = rectangles.get(j); + if (a.x < b.right && a.right > b.x && a.y < b.bottom && a.bottom > b.y) { + warn(issues, a.path, "元素与同页其他元素重叠"); + break; + } + } + } + } + + private void validatePayload(List 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") + && optional(n, "radius", value -> value.isNull() || integer(value)))) { + error(issues, path + ".payload", "内容字段格式错误"); + return; + } + if (type.equals("app_icon") && payload.path("package").stringValue("").isBlank()) { + error(issues, path + ".payload.package", "应用图标需要包名"); + } + if (type.equals("widget") && !payload.path("provider").stringValue("").contains("/")) { + error(issues, path + ".payload.provider", "组件需填写包名/类名"); + } + if (payload.path("label").stringValue("").length() > MAX_LABEL_LENGTH) { + warn(issues, path + ".payload.label", "显示名过长,可能被截断"); + } + JsonNode radius = payload.get("radius"); + if (radius != null && integer(radius) && radius.intValue() < 0) { + warn(issues, path + ".payload.radius", "圆角不能为负数"); + } + String intent = payload.path("intent").stringValue(""); + if (!intent.isEmpty() && !SCHEME.matcher(intent).matches()) { + warn(issues, path + ".payload.intent", "快捷方式 intent 应使用 scheme:// 形式"); + } + } + + 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) + && x.doubleValue() >= 0 && y.doubleValue() >= 0 && w.floatValue() > 0 && h.floatValue() > 0; + } + + private static boolean optionalFields(JsonNode node, Predicate check, String... names) { + for (String name : names) { + if (!optional(node, name, check)) return false; + } + return true; + } + + private static boolean optional(JsonNode node, String name, Predicate check) { + JsonNode value = node.get(name); + return value == null || check.test(value); + } + + private static boolean integer(JsonNode n) { + return n.isNumber() && n.canConvertToExactIntegral() && n.canConvertToInt(); + } + + private static boolean finiteFloat(JsonNode n) { + return n.isNumber() && Float.isFinite(n.floatValue()); + } + + private static boolean nullableText(JsonNode n) { + return n.isNull() || n.isTextual(); + } + + private static void error(List issues, String path, String message) { + issues.add(new Issue("error", path, message)); + } + + private static void warn(List issues, String path, String message) { + issues.add(new Issue("warning", path, message)); + } +} diff --git a/backend/src/main/java/com/ttstd/launcher/RequestPolicy.java b/backend/src/main/java/com/ttstd/launcher/RequestPolicy.java new file mode 100644 index 0000000..527defa --- /dev/null +++ b/backend/src/main/java/com/ttstd/launcher/RequestPolicy.java @@ -0,0 +1,64 @@ +package com.ttstd.launcher; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +@Component +class RequestPolicy extends OncePerRequestFilter { + private final byte[] admin; + private final byte[] device; + + RequestPolicy(@Value("${launcher.admin-token}") String adminToken, + @Value("${launcher.device-token}") String deviceToken) { + if (!adminToken.matches("[!-~]{24,256}") || !deviceToken.matches("[!-~]{24,256}") + || adminToken.equals(deviceToken)) { + throw new IllegalArgumentException("请配置两组不同的 ADMIN_TOKEN 和 DEVICE_TOKEN,各使用 24–256 位可打印 ASCII 字符"); + } + this.admin = sha256("Bearer " + adminToken); + this.device = sha256("Bearer " + deviceToken); + } + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + response.setHeader("Cache-Control", "no-store"); + response.setHeader("X-Content-Type-Options", "nosniff"); + response.setHeader("Referrer-Policy", "no-referrer"); + + // Match the decoded paths using Spring MVC itself, then authorize each mapped API handler. + chain.doFilter(request, response); + } + + void requireAdmin(HttpServletRequest request, HttpServletResponse response) { + require(request, response, admin); + } + + void requireDevice(HttpServletRequest request, HttpServletResponse response) { + require(request, response, device); + } + + private void require(HttpServletRequest request, HttpServletResponse response, byte[] expected) { + String header = request.getHeader("Authorization"); + if (header == null || !MessageDigest.isEqual(sha256(header), expected)) { + response.setHeader("WWW-Authenticate", "Bearer"); + throw new ApiError(401, "访问令牌无效"); + } + } + + static byte[] sha256(String text) { + try { + return MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8)); + } catch (NoSuchAlgorithmException error) { + throw new IllegalStateException(error); + } + } +} diff --git a/backend/src/main/resources/application.properties b/backend/src/main/resources/application.properties new file mode 100644 index 0000000..7991cf0 --- /dev/null +++ b/backend/src/main/resources/application.properties @@ -0,0 +1,9 @@ +spring.application.name=vibe-launcher +server.address=${HOST:127.0.0.1} +server.port=${PORT:8080} +server.tomcat.connection-timeout=10s +spring.web.resources.add-mappings=false +spring.mvc.throw-exception-if-no-handler-found=true +launcher.admin-token=${ADMIN_TOKEN:} +launcher.device-token=${DEVICE_TOKEN:} +launcher.database=${LAYOUT_DB:backend/data/layouts.sqlite} diff --git a/backend/src/test/java/com/ttstd/launcher/LauncherApplicationTest.java b/backend/src/test/java/com/ttstd/launcher/LauncherApplicationTest.java new file mode 100644 index 0000000..c70f15c --- /dev/null +++ b/backend/src/test/java/com/ttstd/launcher/LauncherApplicationTest.java @@ -0,0 +1,24 @@ +package com.ttstd.launcher; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.nio.file.Path; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.builder.SpringApplicationBuilder; + +class LauncherApplicationTest { + @TempDir Path temp; + + @Test + void startsAndSeedsNewDatabase() throws Exception { + try (var context = new SpringApplicationBuilder(LauncherApplication.class) + .web(WebApplicationType.NONE) + .run("--launcher.admin-token=test-launcher-admin-token-24", + "--launcher.device-token=test-launcher-device-token-24", + "--launcher.database=" + temp.resolve("new.sqlite"))) { + assertEquals(1, context.getBean(LayoutStore.class).latest().revision()); + } + } +} diff --git a/backend/src/test/java/com/ttstd/launcher/LayoutApiTest.java b/backend/src/test/java/com/ttstd/launcher/LayoutApiTest.java new file mode 100644 index 0000000..cb3ce32 --- /dev/null +++ b/backend/src/test/java/com/ttstd/launcher/LayoutApiTest.java @@ -0,0 +1,239 @@ +package com.ttstd.launcher; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.sql.DriverManager; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.Executors; +import java.util.regex.Pattern; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ObjectNode; + +class LayoutApiTest { + private static final String ADMIN = "Bearer test-launcher-admin-token-24"; + private static final String DEVICE = "Bearer test-launcher-device-token-24"; + private static final String ADMIN_LAYOUT = "/api/admin/layout"; + private final JsonMapper mapper = JsonMapper.builder().build(); + + @TempDir Path dir; + + @Test + void migratedDatabaseRetainsLayoutsAndSupportsPublishRollbackAndRestart() throws Exception { + Path database = dir.resolve("layouts.sqlite"); + String legacyLayout; + try (var input = new ClassPathResource("launcher/default_layout.json").getInputStream()) { + legacyLayout = new String(input.readAllBytes(), StandardCharsets.UTF_8); + } + try (var connection = DriverManager.getConnection("jdbc:sqlite:" + database); + var statement = connection.createStatement()) { + statement.execute(""" + CREATE TABLE releases ( + revision INTEGER PRIMARY KEY CHECK (revision BETWEEN 1 AND 2147483647), + layout TEXT NOT NULL, + publishedAt TEXT NOT NULL, + restoredFrom INTEGER REFERENCES releases(revision) + ) STRICT + """); + try (var insert = connection.prepareStatement("INSERT INTO releases VALUES (1, ?, '2026-01-01T00:00:00.000Z', NULL)")) { + insert.setString(1, legacyLayout); + insert.executeUpdate(); + } + } + + MockMvc mvc = mvc(database); + var editor = mvc.perform(get("/")).andExpect(status().isOk()).andReturn().getResponse(); + assertTrue(editor.getHeader("Content-Security-Policy").contains("script-src 'self'")); + String html = editor.getContentAsString(StandardCharsets.UTF_8); + assertEquals(html, mvc.perform(get("/canvas.html")).andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)); + var js = Pattern.compile("src=\"\\./(assets/[^\"]+\\.js)\"").matcher(html); + assertTrue(js.find()); + mvc.perform(get("/" + js.group(1))).andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith("text/javascript")); + var css = Pattern.compile("href=\"\\./(assets/[^\"]+\\.css)\"").matcher(html); + assertTrue(css.find()); + mvc.perform(get("/" + css.group(1))).andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith("text/css")); + mvc.perform(get("/assets/invalid.js")).andExpect(status().isNotFound()); + mvc.perform(get("/healthz")).andExpect(status().isOk()); + mvc.perform(get("/api/layout")).andExpect(status().isUnauthorized()) + .andExpect(header().string("WWW-Authenticate", "Bearer")); + mvc.perform(get("/api/admin/history").header("Authorization", DEVICE)).andExpect(status().isUnauthorized()); + + var original = mvc.perform(get("/api/layout").header("Authorization", DEVICE)) + .andExpect(status().isOk()).andExpect(header().string("X-Layout-Revision", "1")) + .andReturn().getResponse(); + assertEquals(legacyLayout, original.getContentAsString(StandardCharsets.UTF_8)); + String tag = original.getHeader("ETag"); + assertEquals(new LayoutStore.Release(1, legacyLayout).etag(), tag); + mvc.perform(get("/api/layout").header("Authorization", DEVICE).header("If-None-Match", tag)) + .andExpect(status().isNotModified()).andExpect(header().string("ETag", tag)); + + mvc.perform(put(ADMIN_LAYOUT).header("Authorization", ADMIN).contentType(MediaType.APPLICATION_JSON) + .content(legacyLayout)).andExpect(status().isPreconditionRequired()); + mvc.perform(put(ADMIN_LAYOUT).header("Authorization", ADMIN).header("If-Match", tag) + .contentType(MediaType.APPLICATION_JSON).content("{} {}")).andExpect(status().isBadRequest()); + mvc.perform(put(ADMIN_LAYOUT).header("Authorization", ADMIN).header("If-Match", tag) + .contentType(MediaType.APPLICATION_JSON).content(new byte[LayoutStore.MAX_BYTES + 1])) + .andExpect(status().is(413)); + var invalid = mvc.perform(put(ADMIN_LAYOUT).header("Authorization", ADMIN).header("If-Match", tag) + .contentType(MediaType.APPLICATION_JSON).content("{\"schemaVersion\":2,\"pages\":[]}")) + .andExpect(status().is(422)).andReturn().getResponse(); + assertTrue(mapper.readTree(invalid.getContentAsByteArray()).path("issues").size() >= 2); + + var changed = (ObjectNode) mapper.readTree(legacyLayout); + changed.put("futureField", "同步验证"); + String body = mapper.writeValueAsString(changed); + Callable publish = () -> mvc.perform(put(ADMIN_LAYOUT).header("Authorization", ADMIN) + .header("If-Match", tag).contentType(MediaType.APPLICATION_JSON).content(body)) + .andReturn().getResponse().getStatus(); + var executor = Executors.newFixedThreadPool(2); + try { + var outcomes = executor.invokeAll(List.of(publish, publish)); + assertEquals(List.of(200, 412), List.of(outcomes.get(0).get(), outcomes.get(1).get()).stream().sorted().toList()); + } finally { + executor.shutdownNow(); + } + + var posted = mvc.perform(get("/api/admin/history/2").header("Authorization", ADMIN)) + .andExpect(status().isOk()).andReturn().getResponse(); + assertEquals("同步验证", mapper.readTree(posted.getContentAsByteArray()).path("futureField").stringValue()); + assertNotNull(posted.getHeader("ETag")); + mvc.perform(post("/api/admin/rollback").header("Authorization", ADMIN) + .header("If-Match", posted.getHeader("ETag")).contentType(MediaType.APPLICATION_JSON) + .content("{\"revision\":1}")) + .andExpect(status().isOk()).andExpect(header().string("X-Layout-Revision", "3")); + + MockMvc restarted = mvc(database); + var history = restarted.perform(get("/api/admin/history").header("Authorization", ADMIN)) + .andExpect(status().isOk()).andReturn().getResponse(); + var revisions = mapper.readTree(history.getContentAsByteArray()).path("revisions"); + assertEquals(3, revisions.size()); + assertEquals(1, revisions.get(0).path("restoredFrom").intValue()); + var latest = restarted.perform(get("/api/layout").header("Authorization", DEVICE)) + .andExpect(status().isOk()).andReturn().getResponse(); + assertEquals(((ObjectNode) mapper.readTree(legacyLayout)).put("revision", 3), + mapper.readTree(latest.getContentAsByteArray())); + } + + @Test + void errorsAreReturnedAsJson() throws Exception { + MockMvc mvc = mvc(dir.resolve("errors.sqlite")); + var unauthorized = mvc.perform(get(ADMIN_LAYOUT)).andExpect(status().isUnauthorized()) + .andReturn().getResponse(); + assertEquals("访问令牌无效", message(unauthorized.getContentAsByteArray())); + + var wrongMethod = mvc.perform(post("/healthz")).andExpect(status().isMethodNotAllowed()) + .andReturn().getResponse(); + assertEquals("不支持的请求方法", message(wrongMethod.getContentAsByteArray())); + + var badPage = mvc.perform(get("/api/admin/history").header("Authorization", ADMIN).param("before", "abc")) + .andExpect(status().isBadRequest()).andReturn().getResponse(); + assertEquals("无效的分页参数", message(badPage.getContentAsByteArray())); + + var tag = mvc.perform(get(ADMIN_LAYOUT).header("Authorization", ADMIN)) + .andExpect(status().isOk()).andReturn().getResponse().getHeader("ETag"); + var badRevision = mvc.perform(post("/api/admin/rollback").header("Authorization", ADMIN) + .header("If-Match", tag).contentType(MediaType.APPLICATION_JSON).content("{\"revision\":0}")) + .andExpect(status().isBadRequest()).andReturn().getResponse(); + assertEquals("无效的回滚版本号", message(badRevision.getContentAsByteArray())); + + var missing = mvc.perform(get("/api/admin/history/999").header("Authorization", ADMIN)) + .andExpect(status().isNotFound()).andReturn().getResponse(); + assertEquals("该版本不存在", message(missing.getContentAsByteArray())); + } + + @Test + void historyIsPagedWithNextBefore() throws Exception { + Path database = dir.resolve("paged.sqlite"); + var store = new LayoutStore(database.toString(), mapper, new LayoutValidator()); + String layout = store.latest().layout(); + try (var connection = DriverManager.getConnection("jdbc:sqlite:" + database); + var insert = connection.prepareStatement(""" + INSERT INTO releases (revision, layout, publishedAt, restoredFrom) VALUES (?, ?, ?, NULL) + """)) { + for (int revision = 2; revision <= 101; revision++) { + insert.setInt(1, revision); + insert.setString(2, layout); + insert.setString(3, "2026-01-01T00:00:00Z"); + insert.executeUpdate(); + } + } + MockMvc mvc = mvc(database); + var first = mapper.readTree(mvc.perform(get("/api/admin/history").header("Authorization", ADMIN)) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray()); + assertEquals(50, first.path("revisions").size()); + assertEquals(101, first.path("revisions").get(0).path("revision").intValue()); + assertEquals(52, first.path("nextBefore").intValue()); + + var second = mapper.readTree(mvc.perform(get("/api/admin/history").header("Authorization", ADMIN) + .param("before", "52")).andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray()); + assertEquals(50, second.path("revisions").size()); + assertEquals(2, second.path("nextBefore").intValue()); + + var last = mapper.readTree(mvc.perform(get("/api/admin/history").header("Authorization", ADMIN) + .param("before", "2")).andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray()); + assertEquals(1, last.path("revisions").size()); + assertTrue(last.path("nextBefore").isNull()); + } + + @Test + void rejectsOversizedCanvasAndInvalidRollbackSource() throws Exception { + Path database = dir.resolve("guarded.sqlite"); + MockMvc mvc = mvc(database); + var tag = mvc.perform(get(ADMIN_LAYOUT).header("Authorization", ADMIN)) + .andExpect(status().isOk()).andReturn().getResponse().getHeader("ETag"); + + var layout = (ObjectNode) mapper.readTree(new ClassPathResource("launcher/default_layout.json").getInputStream()); + ((ObjectNode) layout.get("canvas")).put("designWidth", 9000); + var invalid = mvc.perform(put(ADMIN_LAYOUT).header("Authorization", ADMIN).header("If-Match", tag) + .contentType(MediaType.APPLICATION_JSON).content(mapper.writeValueAsString(layout))) + .andExpect(status().is(422)).andReturn().getResponse(); + assertTrue(mapper.readTree(invalid.getContentAsByteArray()).path("issues").toString().contains("canvas")); + + try (var connection = DriverManager.getConnection("jdbc:sqlite:" + database); + var statement = connection.createStatement()) { + statement.executeUpdate(""" + INSERT INTO releases (revision, layout, publishedAt, restoredFrom) + VALUES (2, '{"schemaVersion":2,"pages":[]}', '2026-01-01T00:00:00Z', NULL) + """); + } + var latestTag = mvc.perform(get(ADMIN_LAYOUT).header("Authorization", ADMIN)) + .andExpect(status().isOk()).andReturn().getResponse().getHeader("ETag"); + var rollback = mvc.perform(post("/api/admin/rollback").header("Authorization", ADMIN) + .header("If-Match", latestTag).contentType(MediaType.APPLICATION_JSON) + .content("{\"revision\":2}")) + .andExpect(status().is(422)).andReturn().getResponse(); + assertEquals("历史版本布局校验失败,无法回滚", message(rollback.getContentAsByteArray())); + } + + private String message(byte[] body) throws Exception { + return mapper.readTree(body).path("message").stringValue(); + } + + private MockMvc mvc(Path database) throws Exception { + var validator = new LayoutValidator(); + var store = new LayoutStore(database.toString(), mapper, validator); + var policy = new RequestPolicy(ADMIN.substring(7), DEVICE.substring(7)); + return MockMvcBuilders.standaloneSetup(new LayoutController(store, policy, validator, mapper)) + .setControllerAdvice(new ApiExceptionHandler()) + .addFilters(policy).build(); + } +} diff --git a/backend/src/test/java/com/ttstd/launcher/LayoutValidatorTest.java b/backend/src/test/java/com/ttstd/launcher/LayoutValidatorTest.java new file mode 100644 index 0000000..52e6622 --- /dev/null +++ b/backend/src/test/java/com/ttstd/launcher/LayoutValidatorTest.java @@ -0,0 +1,115 @@ +package com.ttstd.launcher; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.springframework.core.io.ClassPathResource; +import tools.jackson.databind.json.JsonMapper; + +class LayoutValidatorTest { + private final LayoutValidator validator = new LayoutValidator(); + private final JsonMapper mapper = JsonMapper.builder().build(); + + @Test + void builtInLayoutHasNoErrors() throws Exception { + try (var input = new ClassPathResource("launcher/default_layout.json").getInputStream()) { + var layout = mapper.readTree(new String(input.readAllBytes(), StandardCharsets.UTF_8)); + assertTrue(validator.validate(layout).stream().noneMatch(issue -> issue.level().equals("error"))); + } + } + + @Test + void rejectsBrokenProtocolFields() throws Exception { + var issues = issues(""" + { + "schemaVersion": 2, + "canvas": {"designWidth": 100, "designHeight": 100, "safeTop": -1, "safeBottom": 0}, + "fit": {"mode": "contain", "anchorY": 0.5}, + "pages": [{ + "index": 0, + "background": {"type": "wallpaper"}, + "items": [ + {"id": "", "type": "app_icon", "x": -1, "y": 0, "w": 0, "h": 10, "z": 1, + "payload": {"package": ""}}, + {"id": "", "type": "widget", "x": 10, "y": 10, "w": 10, "h": 10, "z": 1, + "payload": {"provider": "nocomponent"}} + ] + }] + } + """); + assertTrue(hasError(issues, "schemaVersion")); + assertTrue(hasError(issues, "canvas")); + assertTrue(hasError(issues, "pages[0].items[0].id")); + assertTrue(hasError(issues, "pages[0].items[0].payload.package")); + assertTrue(hasError(issues, "pages[0].items[1].payload.provider")); + } + + @Test + void rejectsOversizedCanvasAndEmptyPages() throws Exception { + var issues = issues(""" + {"schemaVersion":3,"canvas":{"designWidth":9000,"designHeight":9000},"pages":[]} + """); + assertTrue(hasError(issues, "canvas")); + assertTrue(hasError(issues, "pages")); + } + + @Test + void warnsOnProtocolEdgeCases() throws Exception { + var issues = issues(""" + { + "schemaVersion": 3, + "canvas": {"designWidth": 1080, "designHeight": 1920, "safeTop": 132, "safeBottom": 72}, + "fit": {"mode": "unknown", "anchorY": 1.4}, + "pages": [ + {"index": 1, "background": {"type": "image", "color": "white"}, + "items": [{"id": "%s", "type": "mystery", "x": 0, "y": 0, "w": 10, "h": 10, "z": 1, + "payload": {"label": "%s", "radius": -1, "intent": "bad"}}]}, + {"index": 1, "background": {"type": "gradient", "from": "#ffffff"}, "items": []} + ] + } + """.formatted("x".repeat(65), "标题".repeat(60))); + assertTrue(issues.stream().noneMatch(issue -> issue.level().equals("error"))); + for (String path : List.of("fit.mode", "fit.anchorY", "pages[0].index", "pages[1].index", + "pages[0].background.type", "pages[0].background.color", "pages[1].background", + "pages[0].items[0].id", "pages[0].items[0].type", "pages[0].items[0].payload.label", + "pages[0].items[0].payload.radius", "pages[0].items[0].payload.intent")) { + assertTrue(issues.stream().anyMatch(issue -> issue.level().equals("warning") && issue.path().equals(path)), + "缺少告警:" + path); + } + } + + @Test + void warnsOnSmallSafeAreasLikeTheEditor() throws Exception { + var issues = issues(""" + {"schemaVersion":3, + "canvas":{"designWidth":1080,"designHeight":1920,"safeTop":100,"safeBottom":20}, + "pages":[{"index":0,"background":{"type":"wallpaper"},"items":[]}]} + """); + assertTrue(issues.stream().anyMatch(issue -> issue.level().equals("warning") + && issue.path().equals("canvas.safeTop"))); + assertTrue(issues.stream().anyMatch(issue -> issue.level().equals("warning") + && issue.path().equals("canvas.safeBottom"))); + assertTrue(issues.stream().noneMatch(issue -> issue.level().equals("error"))); + } + + @Test + void acceptsUnknownTopLevelFields() throws Exception { + var issues = issues(""" + {"schemaVersion":3,"futureField":{"a":1}, + "canvas":{"designWidth":1080,"designHeight":1920}, + "pages":[{"index":0,"background":{"type":"wallpaper"},"items":[]}]} + """); + assertEquals(List.of(), issues.stream().filter(issue -> issue.level().equals("error")).toList()); + } + + private List issues(String json) throws Exception { + return validator.validate(mapper.readTree(json)); + } + + private static boolean hasError(List issues, String path) { + return issues.stream().anyMatch(issue -> issue.level().equals("error") && issue.path().equals(path)); + } +} diff --git a/backend/src/test/java/com/ttstd/launcher/UniformityTest.java b/backend/src/test/java/com/ttstd/launcher/UniformityTest.java new file mode 100644 index 0000000..c59cce1 --- /dev/null +++ b/backend/src/test/java/com/ttstd/launcher/UniformityTest.java @@ -0,0 +1,79 @@ +package com.ttstd.launcher; + +import static java.util.stream.Collectors.joining; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.List; +import java.util.stream.IntStream; +import org.junit.jupiter.api.Test; +import org.springframework.core.io.ClassPathResource; +import tools.jackson.databind.json.JsonMapper; + +class UniformityTest { + private final LayoutValidator validator = new LayoutValidator(); + private final JsonMapper mapper = JsonMapper.builder().build(); + + @Test + void sharedLayoutCases() throws Exception { + var fixtures = Path.of("..", "docs", "layout-cases.json"); + for (var fixture : mapper.readTree(fixtures.toFile())) { + assertEquals(fixture.path("accepted").booleanValue(), + errors(validator.validate(fixture.path("layout"))).isEmpty(), + fixture.path("name").stringValue()); + } + } + + @Test + void builtInLayoutMatchesProtocolBaseline() throws Exception { + var layout = mapper.readTree(read("launcher/default_layout.json")); + assertTrue(errors(validator.validate(layout)).isEmpty()); + assertEquals(3, layout.path("schemaVersion").intValue()); + assertEquals(1080, layout.path("canvas").path("designWidth").intValue()); + assertEquals(1920, layout.path("canvas").path("designHeight").intValue()); + assertEquals(132, layout.path("canvas").path("safeTop").intValue()); + assertEquals(72, layout.path("canvas").path("safeBottom").intValue()); + } + + @Test + void protocolLimitsMatchEditorAndAndroid() throws Exception { + String page = "{\"index\":%d,\"background\":{\"type\":\"wallpaper\"},\"items\":[]}"; + String pages20 = IntStream.range(0, 20).mapToObj(i -> page.formatted(i)).collect(joining(",")); + String pages21 = IntStream.range(0, 21).mapToObj(i -> page.formatted(i)).collect(joining(",")); + assertTrue(errors(validator.validate(mapper.readTree(layout(320, 480, "[" + pages20 + "]")))).isEmpty()); + assertTrue(errors(validator.validate(mapper.readTree(layout(320, 480, "[" + pages21 + "]")))) + .stream().anyMatch(issue -> issue.path().equals("pages"))); + + assertTrue(errors(validator.validate(mapper.readTree(layout(319, 480, "[" + + page.formatted(0) + "]")))).stream().anyMatch(issue -> issue.path().equals("canvas"))); + assertTrue(errors(validator.validate(mapper.readTree(layout(8193, 1920, "[" + + page.formatted(0) + "]")))).stream().anyMatch(issue -> issue.path().equals("canvas"))); + + String item = "{\"id\":\"i%d\",\"type\":\"app_icon\",\"x\":0,\"y\":0,\"w\":10,\"h\":10,\"z\":1," + + "\"payload\":{\"package\":\"com.demo.app\"}}"; + String items80 = IntStream.range(0, 80).mapToObj(i -> item.formatted(i)).collect(joining(",")); + String page80 = "{\"index\":0,\"background\":{\"type\":\"wallpaper\"},\"items\":[" + items80 + "]}"; + assertTrue(errors(validator.validate(mapper.readTree(layout(1080, 1920, "[" + page80 + "]")))).isEmpty()); + String items81 = items80 + "," + item.formatted(80); + String page81 = "{\"index\":0,\"background\":{\"type\":\"wallpaper\"},\"items\":[" + items81 + "]}"; + assertTrue(errors(validator.validate(mapper.readTree(layout(1080, 1920, "[" + page81 + "]")))) + .stream().anyMatch(issue -> issue.path().equals("pages[0].items"))); + } + + private static String layout(int width, int height, String pages) { + return "{\"schemaVersion\":3,\"canvas\":{\"designWidth\":" + width + + ",\"designHeight\":" + height + "},\"pages\":" + pages + "}"; + } + + private static List errors(List issues) { + return issues.stream().filter(issue -> issue.level().equals("error")).toList(); + } + + private static String read(String resource) throws Exception { + try (var input = new ClassPathResource(resource).getInputStream()) { + return new String(input.readAllBytes(), StandardCharsets.UTF_8); + } + } +} diff --git a/docs/COMPOSE-BETTER.md b/docs/COMPOSE-BETTER.md new file mode 100644 index 0000000..ccc8d79 --- /dev/null +++ b/docs/COMPOSE-BETTER.md @@ -0,0 +1,191 @@ +# Compose 自研 Launcher:更优解(对比 + 落地取舍) + +> 上一版给的是「能跑」,这一版回答「哪里还能更好、哪些看着更好其实是坑」。 +> 结论:**Compose 自研路线上,最优组合是「固定网格 + 绝对定位 + Long 位图碰撞 + 页级 HorizontalPager」, +> 而不是社区最流行的 Reorderable / compose-dnd 那一套 Lazy 方案。** 理由在下面逐条展开。 + +--- + +## 一、先给结论表 + +| 层 | 常见做法 | 更优解 | 为什么 | +|---|---|---|---| +| 排布容器 | `LazyVerticalGrid` + `animateItem` | **固定网格 + `Box` 绝对定位** | 桌面一页 ≤ 42 格,不需要虚拟化;Lazy 的复用回收会中断拖拽手势,span 静态改不了 | +| 拖拽库 | Reorderable / compose-dnd | **手写 `detectDragGesturesAfterLongPress`** | 这两个库的契约是「列表换序」,桌面要的是「跨格落位 + 挤压」 | +| 翻页 | `LazyRow` 手写分页 或 每页一个 `Column` 自管滚动 | **`HorizontalPager` + `beyondViewportPageCount = 1`** | 只预载邻页,翻页跟手;拖拽时 `userScrollEnabled=false` 天然避免手势打架 | +| 碰撞检测 | `items.any { overlaps() }` | **`Long` 位图(一格一 bit)** | 5×6=30 位、6×7=42 位,单 `Long` 够;判断 O(1),无临时对象分配 | +| 状态模型 | 可变 `mutableListOf` | **`@Immutable` + 不可变 `List`,编辑走纯函数** | 搭配 `@Stable` 控制器,重组可跳过;纯函数可 JVM 单测、可与 Web 端共用 | +| 拖动过程渲染 | 每个 item 存 offset 的 `mutableStateOf` | **单一全局 offset + `graphicsLayer`** | 拖动帧只改 layer 平移,不进入 draw 之外的重组,稳定 120Hz | +| 归位动画 | `animateItem()` | **每格 `animateDpAsState`(弹簧)** | 对标 `CellLayout.reorderAnimator`,只有真正移动的格子动 | +| 数据源 | 每次启动查 `LauncherApps` | **Room 缓存 + `LauncherApps.Callback` 增量** | 冷启动首帧不依赖全量 PackageManager 查询 | +| widget | `AppWidgetHost.createView` 立即绑定 | **可见页才绑定,页面滑走 `deleteView` 保留 id** | 内存与 provider 进程唤醒成本都降一个量级 | + +--- + +## 二、为什么不用 Reorderable / compose-dnd(社区最热,但不合桌面语义) + +`Reorderable`(1.4k★,被 Lawnchair、Neo Launcher 等在用)和 `compose-dnd`(554★)能力都很强,但它们解决的是**「一维/二维格子里等大元素的顺序重排」**: + +1. **span 是静态的**:`LazyVerticalGrid` 的 `GridItemSpan` 在组合时就定死,2×2 widget 拖动后换位置要重建整页的 span 映射,会闪一下。桌面必须支持任意跨格,这是硬伤。 +2. **复用回收**:Lazy 容器在 item 离开视口时回收节点。长按拖动中把它拖到视口边缘触发自动滚动,item 被回收后手势直接断。桌面图标本来就少,虚拟化毫无收益,却引入这个风险。 +3. **没有「挤压 / 上浮」语义**:库只报告 `from → to`,怎么处理空洞、怎么保持阅读顺序全要自己写。既然逻辑要自己写,容器就不该被 Lazy 绑死。 +4. **对比 `compose-dnd` 的自由摆放**:它支持「Drop anywhere + snap to grid」,看着更像桌面,但它是像素模型 + 吸附,跨 DPI 与协议层(格子索引)语义不匹配,等于每次都要做一次反算。 + +**结论**:这类库适合「应用抽屉」「设置项排序」「图片排序」,不适合**桌面工作区**。桌面工作区应当是 `GridLayout` 语义(Launcher3 的 `CellLayout`),不是 `RecyclerView` 语义。 + +--- + +## 三、三个真正决定手感与性能的细节 + +### 1) 压缩算法:从 O(n²) 逐格扫描到位图 + 列序不变式 + +原始写法(也是我第一版的写法): + +```kotlin +while (y > 0 && placed.none { p -> overlaps(it, p, y - 1) }) y-- +``` + +两个问题: +- `overlaps` 每次创建临时对象 + 线性扫全部已落位元素,n=30 时约 2.4 µs/次; +- **语义 bug**:单纯「能上就上」会让下方的 1×1 图标从 2×2 widget 右侧的空隙挤上去,视觉上像布局被打乱。 + +更优解: + +```kotlin +// 1. 碰撞用 Long 位图:一格一个 bit,canPlace 只需一次与运算 +fun canPlace(x: Int, y: Int, w: Int, h: Int): Boolean { + var m = 0L + for (yy in y until y + h) for (xx in x until x + w) m = m or bit(xx, yy) + return (occupied and m) == 0L +} + +// 2. 上浮时保持列内顺序:左侧有人停在目标行或更低,就不许越过 +while (y > 0 && occ.canPlace(it.x, y - 1, it.w, it.h) && + (0 until it.x).none { cx -> lastRow[cx] >= y - 1 }) y-- +``` + +实测(JVM,5×6 网格,24 个元素含跨格 widget): + +| 实现 | 耗时 | 说明 | +|---|---|---| +| 逐格 `overlaps` 扫描 | 2.413 µs/次 | 有临时对象,语义有错位 | +| Long 位图 + 列序不变式 | **1.407 µs/次**(1.7×) | 零分配,语义正确 | +| `move` 全流程(换位+压缩+不可变复制) | **1.467 µs/次** | 占 16.6ms 帧预算的 0.0088% | +| 满页 30 格 compact | 1.040 µs/次 | 最坏情况仍然是常数级 | + +也就是说:**手感瓶颈根本不在算法,在重组与图片解码**。别把时间花在微优化算法上,先把 `@Immutable` 和图标缓存做对。 + +### 2) 拖动帧不能触发重组 + +```kotlin +// ✗ 每个 item 都持有 offset state → 每次 move 触发全页重组 +var offset by remember { mutableStateOf(Offset.Zero) } + +// ✓ 全局只有一个 offset,拖动帧只走 graphicsLayer +.graphicsLayer { + if (isDragging) { + translationX = dragOffset.x + translationY = dragOffset.y + scaleX = 1.06f; scaleY = 1.06f + } +} +``` + +`graphicsLayer` 的 lambda 版本在 draw 阶段的独立层里执行,**不进入测量/布局/重组**三阶段。这是 120Hz 屏上「跟手」与「拖影」的分水岭。 + +### 3) 落位后不要立刻压缩 + +如果你拖到第 5 行空白处,松手后立刻 `compact`,图标会被吸回第 1 行 —— 用户会觉得「没拖成功」。Launcher3 的语义是:**`findVacantCell` 找到就用,只有换位/删除才做 reorder**。这条我在 `LayoutEngine.move()` 和网页 `editor` 里都改成了同一个语义(第一版是错的)。 + +--- + +## 四、冷启动:Launcher 是开机第一屏,这份顺序不能错 + +``` +T0 Application.onCreate 只做:Room 引用 + 读本地缓存 JSON(几 KB)+ 异步预热前 40 个图标 +T1 setContent 用**上一版缓存**立即 compose(首帧目标 < 300ms),不等网络、不等 LauncherApps 全量查询 +T2 IO 线程 拉远端 revision → 校验 → 写暂存 → 合法才热替换(无感) +T3 空闲 预热邻页、绑定可见页 widget;滑走的页 deleteView 但保留 appWidgetId +``` + +对应实现见 `LauncherActivity.kt`(含 `onPreDraw` 里的首帧耗时埋点,先把数字量出来再谈优化)。 + +反向案例:启动时同步 `packageManager.queryIntentActivities` 全量查询 + 逐个 `drawable` 解码,这是很多第三方桌面冷启动 1.5s 白屏的根因。 + +--- + +## 五、Compose 做 Launcher 的已知边界(必须提前接受) + +| 问题 | 现实情况 | 处置 | +|---|---|---| +| 图标数量大时冻结列表 | Compose 非 Lazy 容器在 100+ 元素时组合成本上升;桌面单页 ≤ 42,可控 | 单页上限硬约束,别做「无限画布」 | +| 内存占用 | Compose 运行时比 View 体系多约 2–5MB 常驻 | Launcher 是常驻进程,可接受;但要 `baseline profile` | +| 系统级能力 | 长按菜单、widget 拖放、`DragLayer` 跨进程拖拽,Compose 没有现成等价物 | 长按菜单用 `DropdownMenu` 自绘;跨窗口拖拽仍需 `View.startDragAndDrop` 桥接 | +| 手写 Launcher3 的动画细节 | 图标「拉出弹簧」「文件夹张开」等 | 独立 `Animatable` 池,别用隐式动画堆叠 | +| 桌面替换(设默认 Launcher) | `ACTION_SET_HOME` 需要 `RoleManager` | Android 10+ 用 `RoleManager.createRequestRoleIntent(ROLE_HOME)` | +| 系统签名要求 | 预装桌面需 `sharedUserId`/`HOME` intent-filter | 第三方桌面只声明 `CATEGORY_HOME`;预装需系统签名 | + +> 补一条参考事实:Lawnchair 至今**核心 Workspace 仍是 View 体系**,Compose 只用在设置页、弹层、搜索结果(官方开发者文档明确写了「新增 Workspace 的 bug 仍用 View 修」)。这不是说 Compose 不行,而是说明**工作区的虚拟化与回收语义,View 体系更成熟**。我们选择 Compose 自研时,要清楚这一点,并把工作区限定在「固定格、无虚拟化」的范围内,方向就对了。 + +--- + +## 六、最终架构(可落地) + +``` +┌───────────────────────────────────────────────┐ +│ Web 编辑器 (editor/index.html) │ +│ grid-layout-plus / React-Grid-Layout 亦可 │ +└──────────────────┬────────────────────────────┘ + │ 布局协议 JSON(格子索引,schemaVersion=2) +┌──────────────────▼────────────────────────────┐ +│ :shared(纯 Kotlin,无 Android 依赖,可单测) │ +│ LayoutEngine:findFreeSlot / compact / move │ +│ GridOccupancy:Long 位图碰撞 │ +└──────────────────┬────────────────────────────┘ +┌──────────────────▼────────────────────────────┐ +│ Launcher(Compose) │ +│ LauncherViewModel ── 缓存优先,事件驱动更新 │ +│ WorkspacePager ── 固定网格 + 绝对定位 │ +│ WorkspaceController── 撤销栈 + 不可变提交 │ +│ LauncherItemFactory── 图标 / widget / 文件夹 │ +│ WidgetHostController── 可见才绑定,滑走释放视图 │ +└───────────────────────────────────────────────┘ +``` + +--- + +## 七、验证结果(可复现) + +纯逻辑层用 JVM 单测跑通,不依赖 Android 运行时: + +``` +1) 空位查找 2) 满页返回 null 3) 拖到元素上交换 4) 压缩上浮 +5) 压缩不挤压占用 6) 拖到空白处保持原位 7) 越界夹取 +8) widget 尺寸变更迁位 9) 跨页移动 10) 与网页示例布局对拍 +结果:14 通过 / 0 失败 +``` + +性能:`compact` 1.7× 提速,`move` 全流程 1.467 µs(帧预算占用 0.0088%)。 + +复现方式(任意机器装了 kotlinc): + +```bash +kotlinc launcher-kt/LayoutEngine.kt test/EngineTest.kt -include-runtime -d test.jar && java -jar test.jar +``` + +--- + +## 八、文件清单 + +| 文件 | 说明 | +|---|---| +| `launcher-kt/LayoutEngine.kt` | **核心**:Long 位图碰撞 + 列序不变式压缩 + 纯函数编辑,可单测 | +| `launcher-kt/ComposeWorkspace.kt` | 固定网格 + `HorizontalPager` + `graphicsLayer` 拖拽,含方案对比注释 | +| `launcher-kt/LauncherActivity.kt` | 冷启动分层、ViewModel、协议→UI 模型转换、首帧耗时埋点 | +| `launcher-kt/GridWorkspace.kt` | View 体系版网格画布(作为对照组/降级方案保留) | +| `launcher-kt/LayoutProtocol.kt` | 协议数据类 + 校验器 + `GridMetrics` | +| `launcher-kt/LayoutRepository.kt` | 三级兜底加载、Launcher3 导入、Widget 绑定 | +| `launcher-kt/LauncherItemFactory.kt` | 图标加载、`AppWidgetHost` 宿主与尺寸下发 | +| `launcher-kt/LayoutSync.kt` | 下发通道、协议迁移、撤销栈 | +| `editor/index.html` | 网页拖拽编辑器,布局规则已与 Android 端对齐 | +| `test/EngineTest.kt` | 14 项单测(与网页端规则对拍) | diff --git a/docs/DESIGN-CANVAS.md b/docs/DESIGN-CANVAS.md new file mode 100644 index 0000000..3fa05e1 --- /dev/null +++ b/docs/DESIGN-CANVAS.md @@ -0,0 +1,223 @@ +# 设计稿画布 · 不同设备显示同一效果 + +> 你提出的做法本身是对的:**画布按目标设备的比例缩放、居中、不裁切**。 +> 但它有一个必须先讲清的物理事实,以及一个能让它"好看"的关键技巧。 + +--- + +## 一、公式只有三行 + +不管屏幕比画布**更宽**还是**更高**,都套同一个公式——取两个方向缩放比例里**更严格**的那个: + +```kotlin +val s = min(screenW / designW, screenH / designH) // 关键:取 min,不取 max +val cw = designW * s +val ch = designH * s +val ox = (screenW - cw) / 2f // 水平居中 +val oy = (screenH - ch) / 2f // 垂直居中 +``` + +`min` 保证"内容完整装得下",两边分别减去后除以 2 保证"居中"。这一个式子同时覆盖两种情形,不需要 if 分支: + +| 屏幕相对画布 | `min` 选中哪个 | 结果 | +|---|---|---| +| **更高**(19.5:9、21:9) | 按宽度缩放 | 左右贴合,上下留白 | +| **更宽**(16:10、平板 4:3) | 按高度缩放 | 上下贴合,左右留白 | + +还有一个容易忽略的性质:**等比缩放只会在一个方向留白,不会两边同时留**。因为 `min` 只会让一个约束恰好取等号,另一个必然有余量。验证页里六台设备全部符合这条(已写进单测)。 + +## 二、先看数字:留白为什么一定在上下 + +竖屏语境下,画布 1080×1920(16:9),手机 1080×2160(16:8)。 +**手机比画布更细长**,所以"完整显示"必然是按宽度贴齐、纵向多出空间。 + +| 设备 | 屏比例 | scale | 横向 | 纵向留白(共) | 需要压缩多少 | +|---|---|---|---|---|---| +| 1080×1920 | 0.5625 | 1.000 | 贴合 | **0** | 0% | +| 1080×2160(16:8) | 0.5000 | 1.000 | 贴合 | **240px** | 12.5% | +| 1080×2340(19.5:9) | 0.4615 | 1.000 | 贴合 | **420px** | 21.9% | +| 1080×2400(20:9) | 0.4500 | 1.000 | 贴合 | **480px** | 25.0% | +| 1080×2520(21:9) | 0.4286 | 1.000 | 贴合 | **600px** | 31.3% | +| 1600×2560(平板) | 0.6250 | 1.333 | 左右各 80px | 0 | 0% | + +三个结论: + +1. **横向永远贴合**,因为画布宽度就等于屏幕宽度,`scale` 恒为 1.0。这一条很重要——图标列的左右边距在所有手机上完全一致。 +2. **留白全在纵向**,且随屏幕变长而变大。19.5:9(当代主流)就有 **420px**,肉眼一眼能看出"桌面挤在中间"。 +3. **平板反向**:4:3 屏比画布更宽扁,等比缩放后是左右各 80px 留白,纵向反而贴合。 + +也就是说:`contain` 数学上完美,视觉上在长屏手机上会翻车。这是必须解决的问题。 + +--- + +## 三、三种做法,实测量化 + +验证页 `frontend/canvas.html` 用同一份数据同时渲染四台设备,可实时切换: + +| 策略 | 留白 | 变形 | 元素位置偏差 | 评价 | +|---|---|---|---|---| +| **等比居中** `contain` | 240~600px | **0%** | 0 | **你要的,已设为默认** | +| 弹性行距 `elastic` | **0** | **0%** | ≤ 3.5% | 可选优化:留白转行距 | +| 纵向铺满 `stretch` | **0** | **+12.5%~+31.3%** | 0 | 图标变竖长,不建议 | + +### 默认:等比居中(contain) + +`scale = min(...)`、`offset = (屏幕 − 内容) / 2`,元素尺寸与相对位置在所有设备上完全一致,代价是留白。 + +留白怎么处理,按"能不能看见"排序: + +1. **壁纸铺满整屏 + 画布背景透明**(默认做法)—— 留白区露出的是壁纸,用户感知不到"空了一块",只会觉得图标离顶栏近一点。这条最有效,且零成本。 +2. **把留白做成功能区** —— 顶部留白放搜索栏/日期,底部留白放 Dock。设计稿里只画"图标区",系统组件吃掉多余空间。这要求设计稿不画 Dock。 +3. **允许少量裁切** —— 比如上下各裁 3%,420px 留白能吃掉 140px。但要保证边缘 6% 内不放内容。 + +### 可选:弹性行距(elastic) + +不缩放元素、不裁切、不留黑边,而是**把多出来的空间按原空白比例放大到各行之间**。 + +``` +设计稿:空白总量 796px,屏幕多出 240px + → 空白放大系数 k = (796+240)/796 = 1.3015 + → 每段空白 × 1.3015,元素尺寸一律不变 +``` + +为什么是"按比例"而不是"平均分":设计稿里大间隙变大、小间隙变小,**疏密节奏被完整保留**;平均分会让原本紧凑的两行被拉开、原本宽松的地方没变化,节奏就散了。 + +实测(1080×2160): + +| 指标 | 值 | +|---|---| +| 缩放 | 1.000 | +| 变形 | **0.000%** | +| 整块留白 | **0** | +| 间隙放大 | ×1.3015 | +| 末行落点 | 2027(设计稿 1818 → +209) | +| 底部余量 | 133px(= 设计稿 102px × 1.3015,比例不变) | + +21:9 上 k 会到 1.75——间距拉开 75%,这是唯一需要留意的场景:间距过大会显得松散。所以在 20:9 以上的长屏,建议给 `k` 设上限(如 `k ≤ 1.5`),超出部分退回 `contain` 的少量留白,两者各让一步。 + +### 为什么默认不选 elastic + +它确实消除了留白,但改动了元素间距——你明确要的是"缩放到合适位置居中",那就先保真。elastic 留作"如果真机上留白太难看"的后手,切换只需要改一个枚举值,协议不用动。 + +### 为什么不推荐 stretch + +`16:8` 只差 12.5%,图标从 1:1 变成 1:1.125,肉眼勉强能忍。 +但 `19.5:9` 就是 21.9%,圆形图标变成明显的竖椭圆,`21:9` 直接 31.3%,一眼假。 + +> 经验阈值:**纵向拉伸 ≤ 6% 可以用 stretch,超过就用 elastic**。 +> 16:9 → 16:8 已经超过阈值。 + +--- + +## 四、四个必须处理的工程细节 + +### 1)不要用整体 `Modifier.scale()` + +`scale` 只影响绘制与命中测试,**布局约束仍是原始尺寸**。想真正缩放,外层得先 `requiredSize(1080.dp, 1920.dp)` 把画布撑开,再整体缩放——但这样文字是"栅格化后放大",0.45 倍下明显发虚。 + +正解是逐元素乘系数: + +```kotlin +Box(Modifier + .offset { IntOffset(p.left.roundToInt(), p.top.roundToInt()) } // 直接吃像素 + .size(with(density) { p.width.toDp() }, with(density) { p.height.toDp() }) +) +``` + +`offset` 用 lambda 版本 + px,避免 `dp` 四舍五入的累积误差(48 个元素能看出不齐)。 + +### 2)壁纸铺满整屏,画布背景透明 + +**这是让留白彻底消失的关键,比任何算法都重要。** + +画布背景透明 → 用户在纵向多出的区域看到的不是黑边,而是壁纸本身。他只会觉得"图标离顶栏近一点",不会觉得"这里空了一块"。 + +反过来,如果画布自带背景色(哪怕和壁纸同色),一旦两端有 1px 差值就会露出接缝,一眼假。 + +### 3)状态栏高度不参与缩放——最高频的真机翻车点 + +设计稿 `safeTop = 132` 是"设计时的假设"。真机状态栏:1080 屏约 132px、1440 屏约 176px、720 屏约 88px。它跟画布缩放**不同比**。 + +所以 `contain` 算完 anchor 后必须做一次下限修正: + +```kotlin +val minOffset = statusBarPx.coerceAtMost(totalGap) +if (offsetY < minOffset) → 内容整体下移 (minOffset - offsetY) +``` + +否则在 1440 屏上 `safeTop=132 × 1.0 = 132 < 176`,时钟组件会被状态栏压掉 44px。`CanvasMapper.avoidSystemInsets()` 就是这个。 + +### 4)`anchorY` 别只给 0.5 + +上下均分在数学上最"公平",但产品上往往不合适: + +| anchorY | 效果 | 适合 | +|---|---|---| +| 0(贴顶) | 内容贴状态栏,留白全在 Dock 上方 | 留白 < 10% 时观感最好 | +| 0.5(均分) | 上下各一半 | 留白 > 20% 时更平衡 | +| 1(贴底) | 留白全在顶部 | 少见,顶部会显得很空 | + +建议:留白 < 10% 用 `0`,否则 `0.5`。 + +--- + +## 五、一个比策略更重要的选择:画布基准别用 16:9 + +`elastic` 只能"消化"差异,消不掉的部分还是要还给留白。而差异大小取决于**画布比例离主流机型有多远**: + +| 画布基准 | 19.5:9 手机上 | 21:9 手机上 | 16:9 画板/投屏 | +|---|---|---|---| +| 1080×1920(16:9) | k = 1.53,间距放大 53% | k = 1.75 | 完美 | +| 1080×2340(19.5:9) | **k = 1.00,零调整** | k = 1.14 | 左右留白 97px | +| 1080×2400(20:9) | k = 1.05 | k = 1.09 | 左右留白 108px | + +**建议用 19.5:9 或 20:9 做画布基准。** 理由: + +- 当代手机 99% 落在 19.5:9 ~ 21:9,用主力比例做基准,绝大多数设备是 `k ≈ 1.0`,也就是"什么都不用调,天然一致" +- 只有落到 16:9 的设备(折叠屏内屏、平板横屏、投屏)才会出现左右留白,而这些场景本来就该单独出一版设计稿 +- 你现在用 16:9,等于让最常见的那批用户在承担最大的间距调整 + +编辑器里直接把「基准尺寸」切到 `1080 × 2340` 就能看到差别:右下角四台设备的「间隙」读数会全部落到 ×1.0 附近。 + +--- + +## 六、和之前那套网格方案的关系 + +不冲突,是**两个阶段**: + +| | 网格模式(`editor/index.html`) | 设计稿画布(`frontend/canvas.html`) | +|---|---|---| +| 用途 | 编辑期做规整排布 | 编辑期做自由排布、渲染期唯一真源 | +| 坐标 | 格子索引 `x/y/w/h` | 设计稿像素 `x/y/w/h` | +| 渲染端 | 需要 DeviceProfile 换算、会随设备漂移 | 一次乘系数,所有设备一致 | +| 适合 | 用户自己排桌面 | **你现在的形态:网页排、手机只看** | + +你这个产品形态(手机端只显示、不能拖)用**画布模式**是对的:网格在编辑期只是辅助,渲染期不该存在。`LayoutEngine.kt`(压缩、换位、碰撞)在新方案里**完全不需要**——没有拖拽,就没有碰撞。 + +--- + +## 七、落地清单 + +已交付: + +| 文件 | 内容 | +|---|---| +| `frontend/canvas.html` | 设计稿编辑器 + **六设备**实时矩阵(含 2K 与 16:10),三策略可切换,导出 schemaVersion 3 | +| `launcher-kt/canvas/CanvasMapper.kt` | 映射核心(纯 Kotlin,无 Android 依赖)+ 协议校验 + 状态栏修正 | +| `launcher-kt/canvas/DesignCanvasRenderer.kt` | Compose 渲染器,壁纸层 + 逐元素定位 + 三处踩坑注释 | +| `test/CanvasTest.kt` | **49 项单测**,含双向居中不变式与六设备全量自检 | + +两端数值已对拍一致(`k=1.3015`、末行 2027.2、平板自动回退 contain、无溢出)。 + +`contain` 的三条不变式已写成断言: +- 高屏(21:9)左右留白必须为 0、上下对称 +- 宽屏(16:10)上下留白必须为 0、左右对称 +- 任何比例下不会同时出现横纵留白 + +### 一个视觉细节:`anchorY` 别固定 0.5 + +几何居中是"上下边距相等",但桌面的**视觉重心偏上**——状态栏占了顶部一条,用户的眼睛会把那条算进"上边距"。所以在 19.5:9 这种 420px 留白的设备上,纯 0.5 会显得桌面略微下沉。 + +经验值:`anchorY = 0.42 ~ 0.45`,内容上移 8% 的留白量(420px → 上移约 34px),看起来才是"正的"。 + +这个值可以随设备比例给:留白 < 10% 时直接用 0.5,留白 > 20% 时用 0.42。需要我把它做成自动的吗? diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md new file mode 100644 index 0000000..47e4df4 --- /dev/null +++ b/docs/PROTOCOL.md @@ -0,0 +1,215 @@ +# 布局协议 v3(launcher_layout.json) + +> 一句话:**坐标是设计稿像素,不是 dp、不是格子、不是百分比。** +> 端上只做一次等比换算,因此同一份文件在所有分辨率上得到同一张画面。 + +--- + +## 1. 完整示例 + +```jsonc +{ + "schemaVersion": 3, + "revision": 12, + "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.tencent.mm", "label": "微信" } + }, + { + "id": "s0", + "type": "shortcut", + "x": 150, "y": 1650, "w": 132, "h": 168, + "z": 2, + "payload": { "label": "扫一扫", "intent": "alipays://platformapi/startapp?appId=20000067" } + } + ] + } + ] +} +``` + +--- + +## 2. 顶层字段 + +| 字段 | 类型 | 默认 | 说明 | +|---|---|---|---| +| `schemaVersion` | int | 3 | 协议版本。当前端只认 3,未来不兼容变更才 +1 | +| `revision` | int | 1 | 内容版本号,端上可用于"是否需要重新落盘"的判断与埋点 | +| `canvas` | object | — | 设计稿基准,与设备无关 | +| `fit` | object | — | 比例不合时的处理策略 | +| `pages` | array | `[]` | 至少 1 页;超过 20 页判 ERROR | + +### canvas + +| 字段 | 类型 | 说明 | +|---|---|---| +| `designWidth` / `designHeight` | int | 设计稿分辨率。**一旦发布不要再改**,否则已存布局会整体偏移 | +| `safeTop` | int | 内容顶部安全区(设计稿坐标系)。状态栏高度的"设计假设",端上还会按真机状态栏做一次下限修正 | +| `safeBottom` | int | 底部安全区,避让手势条 / Dock | + +选 `1080×1920` 还是 `1080×2340`: + +| 基准 | 19.5:9 手机的间距调整 | 21:9 手机 | +|---|---|---| +| 1080×1920(16:9) | 需放大 53% | 75% | +| **1080×2340(19.5:9)** | **×1.00 零调整** | 14% | + +当代手机 99% 落在 19.5:9 ~ 21:9,用 16:9 做基准等于让最常见的用户承担最大调整。**建议 2340**(编辑器左上「画布基准」可切换)。 + +### fit + +| 字段 | 取值 | 说明 | +|---|---|---| +| `mode` | `contain` / `elastic` / `stretch` | 未知值一律按 `contain` 处理(绝不让脏数据决定渲染) | +| `anchorY` | 0 ~ 1 | 仅 contain 生效:0 贴顶、0.5 居中、1 贴底。端上会 clamp | + +| 模式 | 留白 | 变形 | 一致性 | 适用 | +|---|---|---|---|---| +| `contain` | 有(单方向) | 无 | 100% | **默认**:等比居中,不裁不拉 | +| `elastic` | 无 | 无 | ≈99% | 留白按原空白比例转成行间距,间距会变松 | +| `stretch` | 无 | 有 | 几何 100% / 观感差 | 只在屏幕比例差 5% 以内时考虑 | + +--- + +## 3. 页面与元素 + +### pages[] + +| 字段 | 类型 | 说明 | +|---|---|---| +| `index` | int | 页序,从 0 开始 | +| `background.type` | `wallpaper` / `solid` / `gradient` | `wallpaper` = 画布透明,露出最底层壁纸,**留白不可见的关键** | +| `background.color` | `#RRGGBB` | `solid` 时生效 | +| `background.from` / `.to` | `#RRGGBB` | `gradient` 时生效(垂直渐变) | +| `items` | array | 单页上限 80 个 | + +### items[] + +| 字段 | 类型 | 说明 | +|---|---|---| +| `id` | string | 页内唯一,重复判 ERROR | +| `type` | string | `app_icon` / `widget` / `shortcut` / `dock_bg`;其他值告警后跳过该项 | +| `x` / `y` | number | 左上角,设计稿像素,不可为负 | +| `w` / `h` | number | 尺寸,必须 > 0;`x+w ≤ designWidth`、`y+h ≤ designHeight` | +| `z` | int | 同页叠放顺序,小的在下 | +| `payload` | object | 见下表 | + +### payload + +| 字段 | 用于 | 必填 | 说明 | +|---|---|---|---| +| `label` | 全部 | 否 | 显示名。缺省时图标位显示首字母 / `?` | +| `package` | `app_icon` | **是** | 应用包名。缺失即 ERROR("白图标"的根因) | +| `provider` | `widget` | **是** | `包名/类名`,必须含 `/`。缺 `/` 即 ERROR | +| `intent` | `shortcut` | 否 | `scheme://...` 形式;为空时回退把 `package` 当包名启动 | +| `radius` | `dock_bg` | 否 | 圆角(设计稿像素,默认 56) | + +--- + +## 4. 换算规则(端上唯一入口) + +```kotlin +val s = min(screenW / designW, screenH / designH) +val ox = (screenW - designW * s) / 2f +val oy = (screenH - designH * s) / 2f + +// 每个元素 +left = ox + x * s +top = oy + y * s +width = w * s +height = h * s +``` + +推论(可直接写成测试断言): + +1. 屏幕更高 → 上下留白、左右贴合;屏幕更宽 → 左右留白、上下贴合 +2. 等比缩放下**不会**同时出现横纵留白 +3. 元素宽高比在任何设备上恒定(除 `stretch`) +4. 图标字号、间距、留白节奏全部同比,观感一致 + +特例(`avoidSystemInsets`):`contain` 模式下若 `oy` 小于真机状态栏高度,则整体下移到状态栏下方。原因见 README「已知边界 2」。 + +--- + +## 5. 编辑器 ↔ 端上字段对照 + +| 编辑器 UI | 协议字段 | 备注 | +|---|---|---| +| 画布基准 | `canvas.designWidth/Height` | 切换会重排现有元素坐标吗?不会,坐标是绝对值,只改变"画布边界" | +| 安全区 | `canvas.safeTop/safeBottom` | 只影响校验提示与端上下限修正 | +| 映射策略 | `fit.mode` | 三个按钮对应 contain/elastic/stretch | +| 留白位置 | `fit.anchorY` | 仅 contain 可见 | +| X / Y / W / H | `items[].x/y/w/h` | 导出时四舍五入为整数 | +| 层级 | `items[].z` | 右键可置顶/置底 | +| 包名 | `payload.package` | 应用图标必填 | +| Provider | `payload.provider` | 小组件必填,格式 `包名/类名` | +| 圆角 | `payload.radius` | dock 背景用 | + +--- + +## 6. 校验规则(与端上 `LayoutValidator` 逐条对齐) + +**ERROR —— 拒绝解析、拒绝落盘** + +- `id` 为空或页内重复 +- `w ≤ 0` 或 `h ≤ 0` +- `x < 0` 或 `y < 0` +- `x + w > designWidth` / `y + h > designHeight` +- `app_icon` 缺 `payload.package` +- `widget` 的 `provider` 不含 `/` +- 画布尺寸异常(< 320×480)、页数 > 20、单页元素 > 80 +- `pages` 为空 + +**WARN —— 提示但照常渲染** + +- 元素进入 `safeTop` / `safeBottom` 区域 +- 两元素重叠(自由画布允许有意叠放) +- 未知 `type` +- `safeTop` 小于真机状态栏高度的 90% + +--- + +## 7. 下发与兼容 + +``` +编辑器 / 服务端 ──JSON──▶ LayoutRepository.save(text) + │ ① LayoutCodec.parse(含 Validator) + │ ② 有 ERROR → 返回 Result.failure,不落盘 + │ ③ 通过 → 旧文件备份为 last_good,原子写主文件 + ▼ + LauncherViewModel.layout(StateFlow) +``` + +**演进约定** + +1. 加字段永远安全:`Json { ignoreUnknownKeys = true }`,旧端会忽略新字段(有用例覆盖) +2. 删字段 / 改语义 → `schemaVersion +1`,端上拒绝解析未知大版本并走兜底 +3. `type` 枚举扩展同理:旧端告警跳过,不会崩 + +**为什么必须"先校验后落盘"**:桌面是用户唯一入口,一个坏包会让整个手机没法用。四级兜底(主文件 → last_good → assets → 内存空布局)就是为了保证"无论如何能启动"。 diff --git a/docs/README-工程说明.md b/docs/README-工程说明.md new file mode 100644 index 0000000..48e2e15 --- /dev/null +++ b/docs/README-工程说明.md @@ -0,0 +1,234 @@ +# VibeCodingComposeLauncher + +Compose 自研 Launcher 工程初版。 + +桌面的**唯一数据源是一份设计稿 JSON**(设计稿坐标系 1080×1920),手机上只按比例等比缩放并居中,**不重排、不断点、不裁切、不拉伸**。所以同一份布局在 16:9、16:8、19.5:9、21:9、2K、平板 4:3 上看到的是同一张画面,差异只体现在留白多寡。 + +配套一个零依赖的网页编辑器(`frontend/canvas.html`),在浏览器里排版 → 导出 JSON → 推到设备即可。 + +--- + +## 一、三分钟跑起来 + +**环境**:JDK 17+、Android Studio(支持 AGP 8.13)、Gradle 8.13(wrapper 会自动下载) + +```bash +# 在项目根目录进入 Android 工程,再编译并安装 +cd android +./gradlew :app:assembleDebug +adb install -r app/build/outputs/apk/debug/app-debug.apk + +# 2. 设为默认桌面:按 Home 键 → 选择 Vibe Launcher +# 也可以在命令行直接设(部分机型需要 MIUI/EMUI 里额外允许"默认桌面") +adb shell cmd package set-home-activity com.ttstd.compose.launcher/.MainActivity + +# 3. 纯逻辑单测(不需要真机、不需要模拟器,1 秒跑完) +./gradlew :app:testDebugUnitTest +``` + +**Android Studio**:直接打开项目根目录下的 `android/`,不要用 "Import project"。首次同步会拉 Gradle 8.13 与依赖;依赖源和镜像在 `android/settings.gradle.kts` 中配置。 + +**换一份布局**: + +```bash +# 1. 浏览器打开 frontend/canvas.html(或 python3 -m http.server 8080 后访问) +# 2. 排版 → 右侧 JSON 页 → 导出 launcher_layout.json +# 3. 推到设备(debug 包可直接 adb push,见下) +adb push launcher_layout.json /data/local/tmp/ +adb shell run-as com.ttstd.compose.launcher cp /data/local/tmp/launcher_layout.json files/launcher_layout.json +adb shell am force-stop com.ttstd.compose.launcher +``` + +线上环境这一步换成"服务端下发 → `LayoutRepository.save(json)`",坏包会被拦在落盘之前。 + +--- + +## 二、目录结构 + +``` +android/ +├── settings.gradle.kts / build.gradle.kts / gradle.properties +├── gradle/wrapper/gradle-wrapper.properties # Gradle 8.13 +└── app/ + ├── build.gradle.kts # AGP 8.13.2 / Kotlin 2.4.21 / Compose BOM 2024.09 + ├── src/main/ + ├── AndroidManifest.xml # HOME + DEFAULT + LAUNCHER + ├── assets/default_layout.json # 内置默认布局(已校验 0 越界 0 重叠) + ├── res/ # 主题、窗口背景色、矢量图标 + └── java/com/vibe/launcher/ + ├── LauncherApp.kt # 进程级依赖容器(repo/icons/widgetHost) + ├── MainActivity.kt # 入口 + 冷启动分层 + 首帧埋点 + ├── LauncherViewModel.kt # 状态 + 壁纸 + 图标预取 + 点击分发 + ├── core/ + │ ├── CanvasMapper.kt # ★ 映射核心:纯 Kotlin,可 JVM 单测 + │ ├── LayoutModels.kt # ★ 协议 v3 + Codec + Validator + │ ├── LayoutRepository.kt # 三级兜底 + 原子写 + │ ├── IconLoader.kt # LruCache 按「包名@像素」缓存 + │ ├── AppWidgetHostController.kt # 第三方 widget 宿主 + │ ├── AppLaunch.kt # 启动应用 / 快捷方式 / 应用详情 + │ ├── WallpaperLoader.kt # 壁纸取样并降采样 + │ └── WidgetHostProvider.kt # 解耦接口 + └── ui/ + ├── LauncherCanvas.kt # ★ Compose 渲染:壁纸 + Pager + 逐元素定位 + └── theme/Theme.kt + └── src/test/java/com/vibe/launcher/core/ + ├── CanvasMapperTest.kt # 49 条映射断言 + └── LayoutValidatorTest.kt # 15 项协议用例 +``` + +--- + +## 三、数据流 + +``` +网页编辑器(设计稿坐标 1080×1920) + │ 导出 launcher_layout.json + ▼ +LayoutRepository ──① 主文件 ② last_good ③ assets 默认──▶ LauncherLayout + │ + ▼ +CanvasMapper.map(画布, 策略, 元素, 真实宽高) ← 唯一的换算入口 + │ 每个元素的 left/top/width/height(设备像素) + ▼ +LauncherCanvas:壁纸铺满整屏 → HorizontalPager → 逐元素 offset{IntOffset(px)} +``` + +设备端**没有**格子、没有吸附、没有拖拽、没有碰撞检测——那些只存在于编辑期。这是"只显示不编辑"带来的最大简化。 + +--- + +## 四、映射公式(只有三行) + +```kotlin +val s = min(screenW / designW, screenH / designH) // 取 min:保证装得下 +val ox = (screenW - designW * s) / 2f // 水平居中 +val oy = (screenH - designH * s) / 2f // 垂直居中 +``` + +一个式子覆盖两种情形,不需要 `if`: + +| 屏幕相对画布 | `min` 选中 | 结果 | +|---|---|---| +| **更高**(16:8、19.5:9、21:9) | 按宽度缩放 | 左右贴合、上下留白 | +| **更宽**(16:10、平板 4:3) | 按高度缩放 | 上下贴合、左右留白 | + +等比缩放**只会在一个方向留白**,不会两边同时留——因为 `min` 只让一个约束取等号。这条写进了单测,六台设备全部通过。 + +六设备实测(画布 1080×1920): + +| 设备 | 缩放 | 留白方向 | 留白量 | 首排位置 | +|---|---|---|---|---| +| 1080×1920 | 1.000 | 无 | 0 | y=0 | +| 1080×2160(16:8) | 1.000 | 上下 | 各 120 | y=120 | +| 1080×2340(19.5:9) | 1.000 | 上下 | 各 210 | y=210 | +| 1440×3120(2K 20:9) | 1.333 | 上下 | 各 280 | y=280 | +| 1440×2304(16:10) | 1.200 | **左右** | 各 72 | y=0 | +| 1600×2560(平板 4:3) | 1.333 | **左右** | 各 80 | y=0 | + +> 2K 那台是特意留的:它证明公式在**非 1080 宽**的屏幕上同样成立(缩放 1.333,而不是误用 1.0)。 + +**留白为什么不可见**:壁纸铺满整屏,画布背景透明。用户在留白区看到的是壁纸本身,只会觉得"图标离顶栏近一点",不会觉得"空了一块"。画布一旦自带背景色,两端差 1px 就露接缝。 + +--- + +## 五、协议(schemaVersion 3) + +```jsonc +{ + "schemaVersion": 3, + "revision": 12, + "canvas": { "designWidth": 1080, "designHeight": 1920, "safeTop": 132, "safeBottom": 72 }, + "fit": { "mode": "contain", "anchorY": 0.5 }, + "pages": [{ + "index": 0, + "background": { "type": "wallpaper" }, + "items": [ + { "id": "i0", "type": "app_icon", "x": 150, "y": 604, "w": 132, "h": 168, "z": 2, + "payload": { "package": "com.tencent.mm", "label": "微信" } }, + { "id": "w_clock", "type": "widget", "x": 108, "y": 196, "w": 864, "h": 320, "z": 1, + "payload": { "provider": "com.android.deskclock/.ClockWidget", "label": "时钟" } } + ] + }] +} +``` + +| 字段 | 说明 | +|---|---| +| `x/y/w/h` | **设计稿像素**,相对 1080×1920。不是 dp、不是格子索引、不是百分比 | +| `type` | `app_icon` / `widget` / `shortcut` / `dock_bg`;未知类型告警后跳过(不影响整页) | +| `z` | 同页叠放顺序,小的在下 | +| `payload.package` | `app_icon` 必填,缺了就是"白图标" | +| `payload.provider` | `widget` 必填,格式 `包名/类名`,必须含 `/` | +| `fit.mode` | `contain`(默认)/ `elastic` / `stretch`,未知值一律按 `contain` | +| `fit.anchorY` | 仅 contain 生效:0 贴顶、0.5 居中、1 贴底 | + +完整字段与编辑器联动见 `docs/PROTOCOL.md`。 + +**校验分两级**(`LayoutValidator`): + +- **ERROR**:id 重复/为空、尺寸非正、坐标越界、`app_icon` 缺 package、`widget` 的 provider 不含 `/` → 拒绝解析,仓库拒绝落盘 +- **WARN**:进入安全区、元素重叠、未知类型 → 只提示,照常渲染(自由画布允许有意叠放) + +--- + +## 六、已经实现的行为 + +| 能力 | 实现要点 | +|---|---| +| 多页翻页 | `HorizontalPager` + `beyondViewportPageCount = 1`,翻页不白屏 | +| 点击图标启动 | `getLaunchIntentForPackage` + `FLAG_ACTIVITY_NEW_TASK`;包名错/被卸载只打日志不崩 | +| 长按图标 | 跳系统"应用信息"页(否则用户装了就卸不掉) | +| 返回键 | 桌面吞掉,不会退出到上一个应用 | +| 第三方小组件 | `AppWidgetHost` + `updateAppWidgetOptions` 每次尺寸变化重发 | +| 壁纸 | 整屏 `ContentScale.Crop`,取不到就退化为渐变 | +| 布局降级 | 主文件 → last_good → assets → 内存空布局,四级;坏文件改名留证 | +| 冷启动 | T0 窗口背景色 → T1 空布局首帧 → T2 真实布局 → T3 图标替换 | +| 图标缓存 | `LruCache`,key = `包名@目标像素`,尺寸变了才重新解码 | +| 降级可见 | debug 包左上角显示降级原因(release 不显示) | + +--- + +## 七、验证结果 + +**单测(`./gradlew :app:testDebugUnitTest`)** + +| 套件 | 内容 | 结果 | +|---|---|---| +| `CanvasMapperTest` | 行带识别、三策略、极端比例、状态栏修正、双向居中不变式、六设备自检 | **49 条断言全过** | +| `LayoutValidatorTest` | 坏 id / 缺 package / provider 格式 / 越界 / 安全区 / 未知字段兼容 / 编解码往返 | **15 项全过** | + +这两套都是纯 Kotlin,我在 JVM 上实际编译并跑过(`kotlinc` + JUnitCore),不是"看起来应该能过"。 + +**内置布局**:`assets/default_layout.json` 用真实 `LayoutCodec.parse` 解析通过,`LayoutValidator` 零 ERROR 零 WARN;六种分辨率映射后全部无溢出、无越界。 + +**网页编辑器**:拖拽、缩放、属性改值、撤销重做、多页增删、校验、导出下载、切画布尺寸、导入 JSON 全部实测通过,无 JS 报错;导出的 JSON 与 `LayoutModels.kt` 结构逐字段对齐。 + +--- + +## 八、已知边界(真机上线前必须处理) + +1. **`BIND_APPWIDGET` 是 signature|privileged 权限。** 系统签名/预装没问题;商店分发的普通安装只能显示自家 Glance 组件,第三方 widget 绑不上(`bindAppWidgetIdIfAllowed` 返回 false,我们会退回占位块而不是空白)。 +2. **状态栏高度不参与缩放。** 1080 屏约 132px、1440 屏约 176px,与画布缩放不同比,所以 `CanvasMapper.avoidSystemInsets()` 会做一次下限修正,保证内容不压到状态栏。全面屏手势条同理(`bottomInsetPx`)。 +3. **字体缩放(`fontScale`)** 目前按像素换算字号,系统开到 1.3× 时中文标题可能被 `maxLines=1` 截断。要彻底解决得改成"按格宽决定行数",属于下一版。 +4. **横屏/折叠屏展开** 会走"左右留白"分支,画面不破但两侧空得比较明显。建议后续给平板单独出一份 4:3 设计稿,协议不用改(`canvas.designWidth/Height` 换一组即可)。 +5. **没有应用抽屉 / 全局搜索 / 图标包 / 卸载拖拽。** 当前形态是"模板化桌面",这些是产品功能,不是渲染问题。 + +--- + +## 九、常被问到的四个坑 + +| 现象 | 原因 | 处理 | +|---|---|---| +| 桌面一片黑 | 布局解析失败且没走兜底 | `LayoutRepository` 已四级兜底;debug 包左上角会显示降级原因 | +| 图标是灰白方块 | `payload.package` 写错或应用未安装 | 校验期就报 ERROR;渲染期首字母兜底 + 日志 | +| widget 一片空白 | 没下发尺寸 / 没权限 / provider 名少写 `/` | `updateAppWidgetOptions` 每次重发;provider 必须 `包名/类名` | +| 换了布局没生效 | 主文件被旧副本覆盖,或没重启桌面 | 看 `files/last_good_layout.json` 与 `broken_layout.json` 是否存在 | + +--- + +## 十、下一步可以做什么 + +1. **Glance 小组件**:自家组件不走 `AppWidgetHost`,直接 Compose 渲染,性能和一致性都更好 +2. **`LauncherApps` + 自适应图标**:拿到与系统一致的裁切和角标,图标缓存会自动跟随应用安装/卸载增量更新 +3. **应用抽屉**:`LauncherApps.getActivityList()` + 字母索引,与桌面共用 IconLoader +4. **字体缩放适配**:`BoxWithConstraints` 拿格宽决定字号与行数,大字体模式优先减行不改字号 diff --git a/docs/archive/ANDROID-INTEGRATION-网格版.md b/docs/archive/ANDROID-INTEGRATION-网格版.md new file mode 100644 index 0000000..d0bc13c --- /dev/null +++ b/docs/archive/ANDROID-INTEGRATION-网格版.md @@ -0,0 +1,183 @@ +# Android 端接入说明 + +> 网页端产出 `launcher_layout.json`(schemaVersion 3),Android 端按「设计稿坐标 → 等比居中」渲染。 +> 手机端只读,不带任何拖拽逻辑。 + +--- + +## 一、文件清单 + +| 文件 | 职责 | 依赖 | +|---|---|---| +| `CanvasMapper.kt` | **映射核心**:`contain` / `elastic` / `stretch` 三种策略 + 安全区修正 | 纯 Kotlin,零 Android 依赖,可放 `:shared` 模块 | +| `LayoutSpec.kt` | 协议数据类 + JSON 解析 + 校验(与网页端规则逐条对齐) | kotlinx-serialization | +| `LayoutRepository.kt` | 三级兜底加载、原子写入、坏包隔离 | coroutines | +| `IconLoader.kt` | 图标加载 + LruCache + 后台解码 | — | +| `DesignCanvasRenderer.kt` | Compose 渲染:壁纸层 + Pager + 逐元素像素定位 | Compose | +| `AppWidgetHostController.kt` | AppWidget 绑定与尺寸下发 | — | +| `LauncherActivity.kt` | 冷启动分层、首帧埋点、ViewModel | activity-compose | +| `assets/default_layout.json` | 首启内置布局(已校验无越界无重叠) | — | + +旧的 `GridWorkspace.kt`、`LayoutEngine.kt` 是**网格编辑版**的实现,本方案不再需要(没有拖拽就没有碰撞与压缩)。留着只作对照。 + +--- + +## 二、依赖 + +`build.gradle.kts`(module): + +```kotlin +plugins { + id("org.jetbrains.kotlin.plugin.serialization") version "2.0.21" +} + +dependencies { + implementation("androidx.core:core-ktx:1.13.1") + implementation("androidx.activity:activity-compose:1.9.3") + implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.7") + implementation(platform("androidx.compose:compose-bom:2024.10.01")) + implementation("androidx.compose.ui:ui") + implementation("androidx.compose.foundation:foundation") // HorizontalPager 在 foundation 里 + implementation("androidx.compose.material3:material3") + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0") +} +``` + +> `HorizontalPager` 在 `androidx.compose.foundation.pager`,从 Compose 1.4 起已稳定,不需要额外库。 + +--- + +## 三、Manifest + +```xml + + + + + + + + +``` + +主题里给窗口一个深色背景,避免首帧白闪: + +```xml + +``` + +`windowLayoutInDisplayCutoutMode=shortEdges` 必须有,否则刘海屏上壁纸铺不满、内容被压到刘海下方。 + +--- + +## 四、接入五步 + +**1. 把 `launcher_layout.json` 放进 `app/src/main/assets/default_layout.json`** + +**2. 启动时加载** + +```kotlin +val repo = LayoutRepository(context) +val layout = repo.load() // suspend,内部已做三级兜底 +``` + +**3. 渲染** + +```kotlin +LauncherCanvas( + layout = layout, + icons = IconLoader(context), + statusBarPx = statusBarHeightPx(), + widgetHost = AppWidgetHostController(context), +) +``` + +`statusBarPx` 一定要传真实值。渲染端会用它做 `avoidSystemInsets`,否则在 1440 屏上 `safeTop=132` 会被状态栏压掉 44px。 + +**4. 热更新布局** + +```kotlin +lifecycleScope.launch { + repo.save(jsonFromServer).onFailure { Log.w("Layout", "坏包已拒绝:${it.message}") } +} +``` + +`save()` 会先解析校验,坏包直接返回失败、不落盘。落盘前把当前可用版本备份成 `last_good_layout.json`。 + +**5. 多页翻页**已内置在 `HorizontalPager` 里,`beyondViewportPageCount = 1` 预组合相邻页,翻页不白屏。 + +--- + +## 五、四个必须知道的边界 + +### 1)AppWidget 需要系统权限 + +`BIND_APPWIDGET` 是 `signature|privileged` 级。普通 App 只能在用户点「添加小组件」时走系统授权弹窗: + +```kotlin +val intent = Intent(AppWidgetManager.ACTION_APPWIDGET_BIND).apply { + putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id) + putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.provider) +} +startActivityForResult(intent, REQ_BIND) +``` + +系统签名 Launcher 直接有权限,不需要这步。**如果你们是预装系统应用,这条不构成障碍;如果是应用商店分发,第三方 widget 基本加不进来。** + +### 2)widget 必须下发尺寸 + +`updateAppWidgetOptions` 不给的后果是 widget 内部按 0 尺寸排版,表现为「组件一片空白」。代码里每次尺寸变化都会重发一次,别优化掉。 + +### 3)`hostId` 必须持久化 + +每次启动换 `hostId`,系统认为你放弃了旧实例,用户已加的 widget 全被回收。代码里用 SharedPreferences 存。 + +### 4)跨设备一致性有物理上限 + +设计稿 16:9 放到 19.5:9 上,等比居中后上下各留 210px。这个留白**无法消除**——消除它只有两条路:裁切(切掉内容)或拉伸(图标变形)。当前实现选了第三条:**留白交给壁纸**(画布背景透明),用户感知不到。 + +如果某些设备上留白确实太难看,把协议里的 `fit.mode` 改成 `elastic`,留白会转成行间距,代价是元素间距变化 5%~50%。 + +--- + +## 六、验证 + +`CanvasMapper` 是纯 Kotlin,可以在 JVM 上直接跑,不需要真机: + +```bash +kotlinc launcher-kt/canvas/CanvasMapper.kt test/CanvasTest.kt -include-runtime -d t.jar +java -cp t.jar CanvasTestKt +``` + +当前 **49 项断言全过**,覆盖: + +- 三种策略在 16:9 / 16:8 / 19.5:9 / 20:9 / 21:9 / 16:10 / 平板 4:3 上的缩放、留白、变形 +- 双向居中不变式:高屏左右留白必须为 0 且上下对称、宽屏上下留白必须为 0 且左右对称 +- 等比缩放下**不会同时出现横纵留白** +- 平板 4:3 上 `elastic` 自动退回 `contain`(否则纵向溢出) +- 状态栏修正:内容不得压到真机状态栏 +- 协议校验:越界、负坐标、重复 id、缺 package / provider、进安全区 +- 空列表、零尺寸不崩 + +真机验收清单: + +| 项 | 期望 | +|---|---| +| 首帧 | < 300ms 看到壁纸 + 布局轮廓 | +| 图标 | 加载完成后替换首字母占位,无闪烁跳动 | +| 19.5:9 | 上下各留 210px,壁纸铺满,看不出"空了一块" | +| 平板 4:3 | 左右各留 80px,内容完整不裁切 | +| 翻页 | 相邻页预组合,无白屏 | +| 坏包 | 推送非法 JSON → 桌面不变,logcat 有拒绝原因 | +| widget | 绑定后内容正常,不空白、不重叠 | diff --git a/docs/archive/README-网格版方案.md b/docs/archive/README-网格版方案.md new file mode 100644 index 0000000..2cff46f --- /dev/null +++ b/docs/archive/README-网格版方案.md @@ -0,0 +1,146 @@ +# Android 桌面设计器 · 设计稿坐标方案 + +> 网页端自由排版 → 导出一份 `launcher_layout.json` → Android 端**等比缩放 + 居中**渲染。 +> 手机端只读,不可拖拽。目标是**同一份设计在任何分辨率上看起来是同一张画面**,不裁切、不变形。 + +--- + +## 快速开始 + +**网页端**(零依赖单文件,直接双击打开) + +``` +editor/canvas.html +``` + +- 左侧添加元素、调画布、切映射策略 +- 中间拖拽排版,坐标即设计稿像素 +- 右侧四栏:六设备实时预览 / 属性 / 校验 / JSON +- 「导出」得到 `launcher_layout.json` + +**Android 端**(把 JSON 放进 assets,接三个类) + +```kotlin +val layout = LayoutRepository(context).load() // 三级兜底 +LauncherCanvas(layout, IconLoader(context), statusBarPx, widgetHost = widgets) +``` + +细节见 [`ANDROID-INTEGRATION.md`](ANDROID-INTEGRATION.md)。 + +--- + +## 核心只有三行 + +不管屏幕比画布**更宽**还是**更高**,都套同一个公式——取两个方向里更严格的那个: + +```kotlin +val s = min(screenW / designW, screenH / designH) +val ox = (screenW - designW * s) / 2f +val oy = (screenH - designH * s) / 2f +``` + +`min` 保证完整装下,减半保证居中。一个式子同时覆盖两种情形: + +| 屏幕相对画布 | 结果 | +|---|---| +| **更高**(16:8、19.5:9、21:9) | 左右贴合,上下留白 | +| **更宽**(16:10、平板 4:3) | 上下贴合,左右留白 | + +等比缩放**只会在一个方向留白**,不会两边同时留——因为 `min` 只会让一个约束取等号。 + +--- + +## 六台设备实测(画布 1080×1920) + +| 设备 | 缩放 | 留白方向 | 留白量 | 变形 | +|---|---|---|---|---| +| 1080×1920 | 1.000 | 无 | 0 | 0% | +| 1080×2160(16:8) | 1.000 | 上下 | 各 120 | 0% | +| 1080×2340(19.5:9) | 1.000 | 上下 | 各 210 | 0% | +| 1440×3120(2K 20:9) | 1.333 | 上下 | 各 280 | 0% | +| 1440×2304(16:10) | 1.200 | 左右 | 各 72 | 0% | +| 1600×2560(平板 4:3) | 1.333 | 左右 | 各 80 | 0% | + +留白怎么办:**壁纸铺满整屏 + 画布背景透明**。用户看到的边缘其实是壁纸,感知不到"空了一块"。这条比任何算法都有效。 + +--- + +## 目录 + +| 路径 | 内容 | +|---|---| +| `editor/canvas.html` | **网页编辑器(当前方案)**:设计稿坐标 + 六设备矩阵 + 校验 + 导入导出 | +| `launcher-kt/canvas/` | **Android 端(当前方案)**:映射、协议、仓库、图标、渲染、widget 宿主、Activity | +| `launcher-kt/canvas/assets/default_layout.json` | 首启内置布局(已校验无越界无重叠) | +| `test/CanvasTest.kt` | 映射单测,**49 项全过**,含六设备全量自检 | +| `DESIGN-CANVAS.md` | **为什么这么做**:留白几何、三策略实测、四个工程坑、画布基准怎么选 | +| `ANDROID-INTEGRATION.md` | **怎么接**:依赖、Manifest、五步接入、四大边界、验收清单 | +| `editor/index.html` | 网格编辑器(旧方案,保留对照:格子索引 → DeviceProfile 换算) | +| `launcher-kt/*.kt`(根目录) | 网格版 Android 实现(`GridWorkspace` / `LayoutEngine`),新方案不需要 | +| `COMPOSE-BETTER.md` | Compose 生态选型对比(LazyGrid / Reorderable 为什么不适合工作区) | + +--- + +## 验证 + +**映射逻辑**(纯 Kotlin,无需真机) + +```bash +kotlinc launcher-kt/canvas/CanvasMapper.kt test/CanvasTest.kt -include-runtime -d t.jar +java -cp t.jar CanvasTestKt +``` + +覆盖 49 项:三种策略在七种比例上的缩放/留白/变形、双向居中不变式、平板自动回退、状态栏修正、协议校验、空数据健壮性。 + +**网页端**:`editor/canvas.html` 右侧「设备预览」同时渲染六台,切换策略实时看到留白与变形。 + +--- + +## 协议(schemaVersion 3) + +```jsonc +{ + "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": "i0", "type": "app_icon", "x": 150, "y": 604, "w": 132, "h": 168, "z": 2, + "payload": { "package": "com.tencent.mm", "label": "微信" } } + ] + }] +} +``` + +三条铁律: + +1. **坐标是设计稿像素**,不是 dp、不是格子索引、不是百分比 +2. **不携带样式**(颜色/字号/圆角由 Launcher 主题决定),只携带内容与位置 +3. **版本号进协议,解析失败必须能降级**——坏包永远不能进桌面 + +`fit.mode` 三选一: + +| mode | 留白 | 变形 | 用途 | +|---|---|---|---| +| `contain` | 有 | 0% | **默认**,保真 | +| `elastic` | 0 | 0% | 留白转行间距,间距变化 5%~50% | +| `stretch` | 0 | +12.5%~+31.3% | 铺满但图标变竖长,不建议 | + +--- + +## 高频坑位 + +| 坑 | 后果 | 处理 | +|---|---|---| +| 用整体 `Modifier.scale()` 缩放 | 文字发虚、布局约束错误 | 逐元素 `offset{}` + `size()`,直接吃像素 | +| `offset(x.dp)` 而非 px | 数十个元素累积误差,看得出不齐 | 用 lambda 版 `offset { IntOffset(px) }` | +| 画布自带背景色 | 与壁纸差 1px 就露接缝 | 背景透明,壁纸铺整屏 | +| `safeTop` 按设计稿算完就用 | 1440 屏状态栏 176px 压掉内容 | `avoidSystemInsets()` 做下限修正 | +| 图标尺寸写死 dp | 小屏占格 40%、大屏占 30% | `iconSize = item.w × s × 0.78` | +| widget 不调 `updateAppWidgetOptions` | 组件一片空白 | 每次尺寸变化都重发 | +| `hostId` 每次启动重算 | 用户已加的 widget 全被回收 | SharedPreferences 持久化 | +| 直接按 provider 建 hostView | 拿不到实例,空白 | `allocateAppWidgetId` → `bindAppWidgetIdIfAllowed` | +| 协议里下发 `appWidgetId` | 换设备全失效 | 由 Launcher 绑定时分配 | diff --git a/docs/layout-cases.json b/docs/layout-cases.json new file mode 100644 index 0000000..54577e7 --- /dev/null +++ b/docs/layout-cases.json @@ -0,0 +1,58 @@ +[ + { + "name": "defaults", + "accepted": true, + "layout": { + "pages": [ + {} + ] + } + }, + { + "name": "unknown-fit", + "accepted": true, + "layout": { + "fit": { + "mode": "future" + }, + "pages": [ + {} + ] + } + }, + { + "name": "negative-x", + "accepted": false, + "layout": { + "pages": [ + { + "items": [ + { + "id": "a", + "type": "app_icon", + "x": -1, + "y": 300, + "w": 100, + "h": 100, + "payload": { + "package": "com.example.app" + } + } + ] + } + ] + } + }, + { + "name": "oversized-canvas", + "accepted": false, + "layout": { + "canvas": { + "designWidth": 8193 + }, + "pages": [ + {} + ] + } + } +] diff --git a/frontend/.gitignore b/frontend/.gitignore new file mode 100644 index 0000000..b0a5c34 --- /dev/null +++ b/frontend/.gitignore @@ -0,0 +1,2 @@ +/node_modules/ +/dist/ diff --git a/frontend/canvas.html b/frontend/canvas.html new file mode 100644 index 0000000..a6e312b --- /dev/null +++ b/frontend/canvas.html @@ -0,0 +1,1417 @@ + + + + + +桌面设计稿编辑器 · 设计坐标 → 多设备等比居中 + + + + + + + +
+
+
桌面设计稿坐标即设计稿像素 · 手机端只读渲染
+ + + + + + + + + + +
+ +
+
+
+ 设计稿 1080 × 1920 + | + 蓝色虚线 = 安全区 · 双击空白新增图标 +
+
+
+
safeTop
+
safeBottom
+
+
+
+ +
页面
+
+ + + + +

布局发布

+ + +
+ + + +
+ +
    + +
    + +
    + + + + + diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 0000000..b65a557 --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,12 @@ + + + + + + Vibe Launcher · 桌面布局 + + +
    + + + diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 0000000..ce9be63 --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,28 @@ +{ + "name": "vibe-launcher-frontend", + "private": true, + "version": "1.1.0", + "type": "module", + "packageManager": "pnpm@10.34.5", + "engines": { + "node": "^24.0.0", + "pnpm": "10.34.5" + }, + "scripts": { + "dev": "vite", + "build": "vue-tsc --noEmit && vite build", + "preview": "vite preview", + "type-check": "vue-tsc --noEmit" + }, + "dependencies": { + "element-plus": "2.14.7", + "vue": "3.5.44" + }, + "devDependencies": { + "@types/node": "24.19.2", + "@vitejs/plugin-vue": "6.0.10", + "typescript": "6.0.3", + "vite": "8.2.4", + "vue-tsc": "3.3.11" + } +} diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml new file mode 100644 index 0000000..c36c6ea --- /dev/null +++ b/frontend/pnpm-lock.yaml @@ -0,0 +1,886 @@ +lockfileVersion: "9.0" +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false +importers: + .: + dependencies: + element-plus: + specifier: 2.14.7 + version: 2.14.7(vue@3.5.44(typescript@6.0.3)) + vue: + specifier: 3.5.44 + version: 3.5.44(typescript@6.0.3) + devDependencies: + "@types/node": + specifier: 24.19.2 + version: 24.19.2 + "@vitejs/plugin-vue": + specifier: 6.0.10 + version: 6.0.10(vite@8.2.4(@types/node@24.19.2))(vue@3.5.44(typescript@6.0.3)) + typescript: + specifier: 6.0.3 + version: 6.0.3 + vite: + specifier: 8.2.4 + version: 8.2.4(@types/node@24.19.2) + vue-tsc: + specifier: 3.3.11 + version: 3.3.11(typescript@6.0.3) +packages: + "@babel/helper-string-parser@7.29.11": + resolution: + integrity: sha512-snZbO7MEDOof+hvNa97EjEY7qD7h2kwvQr5AJC3ZhQudKW5dnej6k3kP9NQV88hJwaS8vDqRLFo9rivLEhle2g== + engines: + node: ">=6.9.0" + "@babel/helper-validator-identifier@7.29.7": + resolution: + integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg== + engines: + node: ">=6.9.0" + "@babel/parser@7.29.12": + resolution: + integrity: sha512-WJ7JBp/Q4+z/ImydtI7jS6NVco5++632ExBemSX+Ysb+G1lCwQ5BVo3SY+jGGOcZXI4ZccbZSUSJLNBW6eEpJg== + engines: + node: ">=6.0.0" + hasBin: true + "@babel/types@7.29.11": + resolution: + integrity: sha512-WCsemW40Cpc6gouC1SrY6PBaZ+oLRlEVY9XBvZBI7il/HyUrb2nJ505wE1MHEFyDZNnrWDEuy4jL50WVHfTTSQ== + engines: + node: ">=6.9.0" + "@ctrl/tinycolor@4.2.2": + resolution: + integrity: sha512-9rQHijqB2Rq6qOEC/xHaA6aPlsKGi5kmCQW50O1asn9g63XFeD5NmBwysriistW5Xx0JPafyD/TA7yk2S3pXGQ== + engines: + node: ">=14" + "@element-plus/icons-vue@2.3.2": + resolution: + integrity: sha512-OzIuTaIfC8QXEPmJvB4Y4kw34rSXdCJzxcD1kFStBvr8bK6X1zQAYDo0CNMjojnfTqRQCJ0I7prlErcoRiET2A== + peerDependencies: + vue: ^3.2.0 + "@floating-ui/core@1.8.0": + resolution: + integrity: sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ== + "@floating-ui/dom@1.8.0": + resolution: + integrity: sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg== + "@floating-ui/utils@0.2.12": + resolution: + integrity: sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww== + "@jridgewell/sourcemap-codec@1.6.0": + resolution: + integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw== + "@oxc-project/types@0.156.0": + resolution: + integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw== + "@rolldown/binding-android-arm-eabi@1.2.16": + resolution: + integrity: sha512-ia3DwAs0OsMGS7+IConptSiyk9pEXkOx/AbJ2n/lAGxH3QkWQus1t8d7gnAT38FCU2sQu8lUbeR6AiZFv4JxaA== + engines: + node: ^20.19.0 || >=22.12.0 + cpu: + - arm + os: + - android + "@rolldown/binding-android-arm64@1.2.16": + resolution: + integrity: sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg== + engines: + node: ^20.19.0 || >=22.12.0 + cpu: + - arm64 + os: + - android + "@rolldown/binding-darwin-arm64@1.2.16": + resolution: + integrity: sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ== + engines: + node: ^20.19.0 || >=22.12.0 + cpu: + - arm64 + os: + - darwin + "@rolldown/binding-darwin-x64@1.2.16": + resolution: + integrity: sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ== + engines: + node: ^20.19.0 || >=22.12.0 + cpu: + - x64 + os: + - darwin + "@rolldown/binding-freebsd-x64@1.2.16": + resolution: + integrity: sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q== + engines: + node: ^20.19.0 || >=22.12.0 + cpu: + - x64 + os: + - freebsd + "@rolldown/binding-linux-arm-gnueabihf@1.2.16": + resolution: + integrity: sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA== + engines: + node: ^20.19.0 || >=22.12.0 + cpu: + - arm + os: + - linux + "@rolldown/binding-linux-arm64-gnu@1.2.16": + resolution: + integrity: sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w== + engines: + node: ^20.19.0 || >=22.12.0 + cpu: + - arm64 + os: + - linux + libc: + - glibc + "@rolldown/binding-linux-arm64-musl@1.2.16": + resolution: + integrity: sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg== + engines: + node: ^20.19.0 || >=22.12.0 + cpu: + - arm64 + os: + - linux + libc: + - musl + "@rolldown/binding-linux-ppc64-gnu@1.2.16": + resolution: + integrity: sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA== + engines: + node: ^20.19.0 || >=22.12.0 + cpu: + - ppc64 + os: + - linux + libc: + - glibc + "@rolldown/binding-linux-s390x-gnu@1.2.16": + resolution: + integrity: sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg== + engines: + node: ^20.19.0 || >=22.12.0 + cpu: + - s390x + os: + - linux + libc: + - glibc + "@rolldown/binding-linux-x64-gnu@1.2.16": + resolution: + integrity: sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w== + engines: + node: ^20.19.0 || >=22.12.0 + cpu: + - x64 + os: + - linux + libc: + - glibc + "@rolldown/binding-linux-x64-musl@1.2.16": + resolution: + integrity: sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA== + engines: + node: ^20.19.0 || >=22.12.0 + cpu: + - x64 + os: + - linux + libc: + - musl + "@rolldown/binding-openharmony-arm64@1.2.16": + resolution: + integrity: sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ== + engines: + node: ^20.19.0 || >=22.12.0 + cpu: + - arm64 + os: + - openharmony + "@rolldown/binding-win32-arm64-msvc@1.2.16": + resolution: + integrity: sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw== + engines: + node: ^20.19.0 || >=22.12.0 + cpu: + - arm64 + os: + - win32 + "@rolldown/binding-win32-x64-msvc@1.2.16": + resolution: + integrity: sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw== + engines: + node: ^20.19.0 || >=22.12.0 + cpu: + - x64 + os: + - win32 + "@rolldown/pluginutils@1.0.1": + resolution: + integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw== + "@sxzz/popperjs-es@2.11.8": + resolution: + integrity: sha512-wOwESXvvED3S8xBmcPWHs2dUuzrE4XiZeFu7e1hROIJkm02a49N120pmOXxY33sBb6hArItm5W5tcg1cBtV+HQ== + "@types/lodash-es@4.17.12": + resolution: + integrity: sha512-0NgftHUcV4v34VhXm8QBSftKVXtbkBG3ViCjs6+eJ5a6y6Mi/jiFGPc1sC7QK+9BFhWrURE3EOggmWaSxL9OzQ== + "@types/lodash@4.17.27": + resolution: + integrity: sha512-VenMRv/eKNrspX9v3H4dbmjsrnCOYdYBG3kxXKk3dG6X+urBGcj2Prww3xw1U5K4FV/mE4h5GbWd0szEKf+9ew== + "@types/node@24.19.2": + resolution: + integrity: sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ== + "@types/web-bluetooth@0.0.21": + resolution: + integrity: sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA== + "@vitejs/plugin-vue@6.0.10": + resolution: + integrity: sha512-b80aUQh3n+qEzzZm5oQp3rT2QImeCx58K6eFl/RkJ3d65KW0kTuv5lNsLRVAjbW9YRUpo/wzmvzMgV34bTAItA== + engines: + node: ^20.19.0 || >=22.12.0 + peerDependencies: + vite: ~8.2.4 + vue: ^3.2.25 || ^3.6.0-rc.10 + "@volar/language-core@2.4.28": + resolution: + integrity: sha512-w4qhIJ8ZSitgLAkVay6AbcnC7gP3glYM3fYwKV3srj8m494E3xtrCv6E+bWviiK/8hs6e6t1ij1s2Endql7vzQ== + "@volar/source-map@2.4.28": + resolution: + integrity: sha512-yX2BDBqJkRXfKw8my8VarTyjv48QwxdJtvRgUpNE5erCsgEUdI2DsLbpa+rOQVAJYshY99szEcRDmyHbF10ggQ== + "@volar/typescript@2.4.28": + resolution: + integrity: sha512-Ja6yvWrbis2QtN4ClAKreeUZPVYMARDYZl9LMEv1iQ1QdepB6wn0jTRxA9MftYmYa4DQ4k/DaSZpFPUfxl8giw== + "@vue/compiler-core@3.5.44": + resolution: + integrity: sha512-k34nCytbK8PQ1gR2mGROYOw6Pnv/mumqIdrZ3x2tbyXZDWm7ViKGLTfdB+DRrWqEQsLgGJvn0WN9jBif5zCTLQ== + "@vue/compiler-dom@3.5.44": + resolution: + integrity: sha512-W5AoBFWdw1lQAKiHowkfgFKFab82oSRT6sGsPfw/q1GRjsy/ZJFLHGhJyBRIFN9APLTUduDH9U2JAiPOIyKuYg== + "@vue/compiler-sfc@3.5.44": + resolution: + integrity: sha512-dzHmQ4jXTpdr5FjIQUeykVakN/uzqFbUo9/C5ikBFg3a3PeM6uRxeczx1ZbXBML0/zJstEh3ygYipzR5Z7b2Pw== + "@vue/compiler-ssr@3.5.44": + resolution: + integrity: sha512-xr5gb1JVHlfXJwSlRz1FeP6uxoazdzHuMTVLE7up+4Vrqxk219CvxLPxD9NXBt47yvZW7+p4DXfyp4O1fkByIA== + "@vue/language-core@3.3.11": + resolution: + integrity: sha512-QJmpliwAVpC/OxubIByPAhNzsQPRc8/gxlN2qnVzVfIMjMDz/9RnXRFoetjz5yEgXVXyp4LqhXq3V53PjmNzFw== + "@vue/reactivity@3.5.44": + resolution: + integrity: sha512-u+QJdKeBBEADkPdevsL+6E12QlYVfBD8Zcw5qjDQKtamI6l14KyqazJMobhCKelhWN5zpyKUiEDoTyHE93cqWw== + "@vue/runtime-core@3.5.44": + resolution: + integrity: sha512-uEa/ndwjhrrhnOfb2p+sZy6zeoamJOISqaLSJGk/8R6nABT1ZldpzcJoPzKj+zHVomVBPcmQYyC2r4LtvDV6CQ== + "@vue/runtime-dom@3.5.44": + resolution: + integrity: sha512-3fc4ARcXVhVBaJ3ujWiNZJARD6pkyRcwG+ZYhMzjKtKUp7MAY0HLwr7r3Smep3Li6ZaWT6ewdmx8XqdaD5oNZg== + "@vue/server-renderer@3.5.44": + resolution: + integrity: sha512-R4S1UoH4h5Frrauv8Z5XE5TxV9oBiUSgWIC4TyVK1FK+RocRnOLwFA5Xcmo2011RlgJp+AbZCnw6afrhlgRuUQ== + "@vue/shared@3.5.44": + resolution: + integrity: sha512-H82XLH0DjmSOdbEwO15x3QTo1f5PWEtv237eLpYKc0mqLu+B8hnq16lFWmuBmNurkeiG3wr+oM1FhOll/YVFRg== + "@vueuse/core@15.0.0": + resolution: + integrity: sha512-Zv67h5mrk7YHDJsRObx+DXaCBz6RKBUpxqLesJ+3xZNPG6yuQs7ja7kg3veFrrouYLWAqydQ7CwGEbLVxB43Ng== + engines: + node: ">=22" + peerDependencies: + vue: ^3.5.0 + "@vueuse/metadata@15.0.0": + resolution: + integrity: sha512-sfWE5LADAKJ0KnjtGliMdSN8Ij/L7uP6rXIZlgPloAI4zvvefbw6H5Lt7KJA6RqQOYgVqWF5Guj50HHMIzygBg== + engines: + node: ">=22" + "@vueuse/shared@15.0.0": + resolution: + integrity: sha512-vbNXhGrbV53xPOMSyOzMHQRvhMgZf7oNDw2RChUetVxwTIEkInQ1joZ9JbT0G3z2n2AJNjvmCWeM9ySYrnvogA== + engines: + node: ">=22" + peerDependencies: + vue: ^3.5.0 + alien-signals@3.2.1: + resolution: + integrity: sha512-I8FjmltrfnDFoZedi5CG8DghVYNhzb/Ijluz7tCSJH0xpd0484Kowhbb1XDYOxfJpU1p5wnM2X54dA+IfGyD1g== + async-validator@4.2.5: + resolution: + integrity: sha512-7HhHjtERjqlNbZtqNqy2rckN/SpOOlmDliet+lP7k+eKZEjPk3DgyeU9lIXLdeLz0uBbbVp+9Qdow9wJWgwwfg== + csstype@3.2.3: + resolution: + integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ== + dayjs@1.11.23: + resolution: + integrity: sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ== + detect-libc@2.1.2: + resolution: + integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ== + engines: + node: ">=8" + element-plus@2.14.7: + resolution: + integrity: sha512-lrG7pZyCS+mpCNVpzxxyu5r35+T6V0hzkAeIwn7HA6to772XSTHKuYCZG51OfzlqaxGbNegLxs650zAF1j43gA== + peerDependencies: + vue: ^3.3.7 + entities@7.0.1: + resolution: + integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA== + engines: + node: ">=0.12" + estree-walker@2.0.2: + resolution: + integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w== + fdir@6.5.0: + resolution: + integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg== + engines: + node: ">=12.0.0" + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + fsevents@2.3.3: + resolution: + integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw== + engines: + node: ^8.16.0 || ^10.6.0 || >=11.0.0 + os: + - darwin + lightningcss-android-arm64@1.33.0: + resolution: + integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg== + engines: + node: ">= 12.0.0" + cpu: + - arm64 + os: + - android + lightningcss-darwin-arm64@1.33.0: + resolution: + integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg== + engines: + node: ">= 12.0.0" + cpu: + - arm64 + os: + - darwin + lightningcss-darwin-x64@1.33.0: + resolution: + integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ== + engines: + node: ">= 12.0.0" + cpu: + - x64 + os: + - darwin + lightningcss-freebsd-x64@1.33.0: + resolution: + integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg== + engines: + node: ">= 12.0.0" + cpu: + - x64 + os: + - freebsd + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: + integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ== + engines: + node: ">= 12.0.0" + cpu: + - arm + os: + - linux + lightningcss-linux-arm64-gnu@1.33.0: + resolution: + integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg== + engines: + node: ">= 12.0.0" + cpu: + - arm64 + os: + - linux + libc: + - glibc + lightningcss-linux-arm64-musl@1.33.0: + resolution: + integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ== + engines: + node: ">= 12.0.0" + cpu: + - arm64 + os: + - linux + libc: + - musl + lightningcss-linux-x64-gnu@1.33.0: + resolution: + integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg== + engines: + node: ">= 12.0.0" + cpu: + - x64 + os: + - linux + libc: + - glibc + lightningcss-linux-x64-musl@1.33.0: + resolution: + integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw== + engines: + node: ">= 12.0.0" + cpu: + - x64 + os: + - linux + libc: + - musl + lightningcss-win32-arm64-msvc@1.33.0: + resolution: + integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA== + engines: + node: ">= 12.0.0" + cpu: + - arm64 + os: + - win32 + lightningcss-win32-x64-msvc@1.33.0: + resolution: + integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA== + engines: + node: ">= 12.0.0" + cpu: + - x64 + os: + - win32 + lightningcss@1.33.0: + resolution: + integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA== + engines: + node: ">= 12.0.0" + lodash-es@4.18.1: + resolution: + integrity: sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A== + lodash-unified@1.0.3: + resolution: + integrity: sha512-WK9qSozxXOD7ZJQlpSqOT+om2ZfcT4yO+03FuzAHD0wF6S0l0090LRPDx3vhTTLZ8cFKpBn+IOcVXK6qOcIlfQ== + peerDependencies: + "@types/lodash-es": "*" + lodash: "*" + lodash-es: "*" + lodash@4.18.1: + resolution: + integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q== + magic-string@0.30.21: + resolution: + integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ== + memoize-one@6.0.0: + resolution: + integrity: sha512-rkpe71W0N0c0Xz6QD0eJETuWAJGnJ9afsl1srmwPrI+yBCkge5EycXXbYRyvL29zZVUWQCY7InPRCv3GDXuZNw== + muggle-string@0.4.1: + resolution: + integrity: sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ== + nanoid@3.3.20: + resolution: + integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ== + engines: + node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1 + hasBin: true + normalize-wheel-es@1.2.0: + resolution: + integrity: sha512-Wj7+EJQ8mSuXr2iWfnujrimU35R2W4FAErEyTmJoJ7ucwTn2hOUSsRehMb5RSYkxXGTM7Y9QpvPmp++w5ftoJw== + path-browserify@1.0.1: + resolution: + integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g== + picocolors@1.1.1: + resolution: + integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA== + picomatch@4.0.7: + resolution: + integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA== + engines: + node: ">=12" + postcss@8.5.32: + resolution: + integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g== + engines: + node: ^10 || ^12 || >=14 + rolldown@1.2.16: + resolution: + integrity: sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw== + engines: + node: ^20.19.0 || >=22.12.0 + hasBin: true + source-map-js@1.2.2: + resolution: + integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw== + engines: + node: ">=0.10.0" + tinyglobby@0.2.17: + resolution: + integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g== + engines: + node: ">=12.0.0" + typescript@6.0.3: + resolution: + integrity: sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw== + engines: + node: ">=14.17" + hasBin: true + undici-types@7.24.6: + resolution: + integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg== + vite@8.2.4: + resolution: + integrity: sha512-lfauXnrf2x0p+UoA+wXh0dgFWnUjCyG6Js95KBkgaCwUU9k0DAHI4W6Q0WCx+h+5g+Alce1y4Zi2QjjK0UvGBw== + engines: + node: ^20.19.0 || >=22.12.0 + hasBin: true + peerDependencies: + "@types/node": ^20.19.0 || >=22.12.0 + "@vitejs/devtools": ^0.4.0 || ^0.5.0 + esbuild: ^0.27.0 || ^0.28.0 + jiti: ">=1.21.0" + less: ^4.0.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: ">=0.54.8" + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + "@types/node": + optional: true + "@vitejs/devtools": + optional: true + esbuild: + optional: true + jiti: + optional: true + less: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + vscode-uri@3.2.0: + resolution: + integrity: sha512-m2gXo3bn0G1kT9InzMf07fTbqMbGtyckj3bH5ktLO+1Ssv+yiATZ4dhwaQv9UZWxJh6E9IFGnQyjgWVDWVBDrg== + vue-component-type-helpers@3.3.14: + resolution: + integrity: sha512-Pq3+OnbCiPCHk0R7KSZrx+j/XXaUn2kSQ1epxq60w8CPbByLjC1EJgV51n4WY851sTXUVzsNMuitywdkdVyKjA== + vue-tsc@3.3.11: + resolution: + integrity: sha512-gOb0B9rtU2+f1dszwPqSH5kAieIF9ReeLhD3kSRNHv5WZZUQz/JdVXW0RTdqhNTMlQkqKzrTTviqKr/4FYZraQ== + hasBin: true + peerDependencies: + typescript: ">=5.0.0" + vue@3.5.44: + resolution: + integrity: sha512-dvvmaOCG7lAMkJTPqPwWeGMsPS6DIsFsfZDUgBp9V6mHf9b3+/wyVwYR4Es+WV6uJC0FKRxp81Obcq0ZwUcGFQ== + peerDependencies: + typescript: "*" + peerDependenciesMeta: + typescript: + optional: true +snapshots: + "@babel/helper-string-parser@7.29.11": {} + "@babel/helper-validator-identifier@7.29.7": {} + "@babel/parser@7.29.12": + dependencies: + "@babel/types": 7.29.11 + "@babel/types@7.29.11": + dependencies: + "@babel/helper-string-parser": 7.29.11 + "@babel/helper-validator-identifier": 7.29.7 + "@ctrl/tinycolor@4.2.2": {} + "@element-plus/icons-vue@2.3.2(vue@3.5.44(typescript@6.0.3))": + dependencies: + vue: 3.5.44(typescript@6.0.3) + "@floating-ui/core@1.8.0": + dependencies: + "@floating-ui/utils": 0.2.12 + "@floating-ui/dom@1.8.0": + dependencies: + "@floating-ui/core": 1.8.0 + "@floating-ui/utils": 0.2.12 + "@floating-ui/utils@0.2.12": {} + "@jridgewell/sourcemap-codec@1.6.0": {} + "@oxc-project/types@0.156.0": {} + "@rolldown/binding-android-arm-eabi@1.2.16": + optional: true + "@rolldown/binding-android-arm64@1.2.16": + optional: true + "@rolldown/binding-darwin-arm64@1.2.16": + optional: true + "@rolldown/binding-darwin-x64@1.2.16": + optional: true + "@rolldown/binding-freebsd-x64@1.2.16": + optional: true + "@rolldown/binding-linux-arm-gnueabihf@1.2.16": + optional: true + "@rolldown/binding-linux-arm64-gnu@1.2.16": + optional: true + "@rolldown/binding-linux-arm64-musl@1.2.16": + optional: true + "@rolldown/binding-linux-ppc64-gnu@1.2.16": + optional: true + "@rolldown/binding-linux-s390x-gnu@1.2.16": + optional: true + "@rolldown/binding-linux-x64-gnu@1.2.16": + optional: true + "@rolldown/binding-linux-x64-musl@1.2.16": + optional: true + "@rolldown/binding-openharmony-arm64@1.2.16": + optional: true + "@rolldown/binding-win32-arm64-msvc@1.2.16": + optional: true + "@rolldown/binding-win32-x64-msvc@1.2.16": + optional: true + "@rolldown/pluginutils@1.0.1": {} + "@sxzz/popperjs-es@2.11.8": {} + "@types/lodash-es@4.17.12": + dependencies: + "@types/lodash": 4.17.27 + "@types/lodash@4.17.27": {} + "@types/node@24.19.2": + dependencies: + undici-types: 7.24.6 + "@types/web-bluetooth@0.0.21": {} + "@vitejs/plugin-vue@6.0.10(vite@8.2.4(@types/node@24.19.2))(vue@3.5.44(typescript@6.0.3))": + dependencies: + "@rolldown/pluginutils": 1.0.1 + vite: 8.2.4(@types/node@24.19.2) + vue: 3.5.44(typescript@6.0.3) + "@volar/language-core@2.4.28": + dependencies: + "@volar/source-map": 2.4.28 + "@volar/source-map@2.4.28": {} + "@volar/typescript@2.4.28": + dependencies: + "@volar/language-core": 2.4.28 + path-browserify: 1.0.1 + vscode-uri: 3.2.0 + "@vue/compiler-core@3.5.44": + dependencies: + "@babel/parser": 7.29.12 + "@vue/shared": 3.5.44 + entities: 7.0.1 + estree-walker: 2.0.2 + source-map-js: 1.2.2 + "@vue/compiler-dom@3.5.44": + dependencies: + "@vue/compiler-core": 3.5.44 + "@vue/shared": 3.5.44 + "@vue/compiler-sfc@3.5.44": + dependencies: + "@babel/parser": 7.29.12 + "@vue/compiler-core": 3.5.44 + "@vue/compiler-dom": 3.5.44 + "@vue/compiler-ssr": 3.5.44 + "@vue/shared": 3.5.44 + estree-walker: 2.0.2 + magic-string: 0.30.21 + postcss: 8.5.32 + source-map-js: 1.2.2 + "@vue/compiler-ssr@3.5.44": + dependencies: + "@vue/compiler-dom": 3.5.44 + "@vue/shared": 3.5.44 + "@vue/language-core@3.3.11": + dependencies: + "@volar/language-core": 2.4.28 + "@vue/compiler-dom": 3.5.44 + "@vue/shared": 3.5.44 + alien-signals: 3.2.1 + muggle-string: 0.4.1 + path-browserify: 1.0.1 + picomatch: 4.0.7 + "@vue/reactivity@3.5.44": + dependencies: + "@vue/shared": 3.5.44 + "@vue/runtime-core@3.5.44": + dependencies: + "@vue/reactivity": 3.5.44 + "@vue/shared": 3.5.44 + "@vue/runtime-dom@3.5.44": + dependencies: + "@vue/reactivity": 3.5.44 + "@vue/runtime-core": 3.5.44 + "@vue/shared": 3.5.44 + csstype: 3.2.3 + "@vue/server-renderer@3.5.44": + dependencies: + "@vue/compiler-ssr": 3.5.44 + "@vue/runtime-dom": 3.5.44 + "@vue/shared": 3.5.44 + "@vue/shared@3.5.44": {} + "@vueuse/core@15.0.0(vue@3.5.44(typescript@6.0.3))": + dependencies: + "@types/web-bluetooth": 0.0.21 + "@vueuse/metadata": 15.0.0 + "@vueuse/shared": 15.0.0(vue@3.5.44(typescript@6.0.3)) + vue: 3.5.44(typescript@6.0.3) + "@vueuse/metadata@15.0.0": {} + "@vueuse/shared@15.0.0(vue@3.5.44(typescript@6.0.3))": + dependencies: + vue: 3.5.44(typescript@6.0.3) + alien-signals@3.2.1: {} + async-validator@4.2.5: {} + csstype@3.2.3: {} + dayjs@1.11.23: {} + detect-libc@2.1.2: {} + element-plus@2.14.7(vue@3.5.44(typescript@6.0.3)): + dependencies: + "@ctrl/tinycolor": 4.2.2 + "@element-plus/icons-vue": 2.3.2(vue@3.5.44(typescript@6.0.3)) + "@floating-ui/dom": 1.8.0 + "@popperjs/core": "@sxzz/popperjs-es@2.11.8" + "@types/lodash": 4.17.27 + "@types/lodash-es": 4.17.12 + "@vueuse/core": 15.0.0(vue@3.5.44(typescript@6.0.3)) + async-validator: 4.2.5 + dayjs: 1.11.23 + lodash: 4.18.1 + lodash-es: 4.18.1 + lodash-unified: 1.0.3(@types/lodash-es@4.17.12)(lodash-es@4.18.1)(lodash@4.18.1) + memoize-one: 6.0.0 + normalize-wheel-es: 1.2.0 + vue: 3.5.44(typescript@6.0.3) + vue-component-type-helpers: 3.3.14 + entities@7.0.1: {} + estree-walker@2.0.2: {} + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + fsevents@2.3.3: + optional: true + lightningcss-android-arm64@1.33.0: + optional: true + lightningcss-darwin-arm64@1.33.0: + optional: true + lightningcss-darwin-x64@1.33.0: + optional: true + lightningcss-freebsd-x64@1.33.0: + optional: true + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + lightningcss-linux-arm64-musl@1.33.0: + optional: true + lightningcss-linux-x64-gnu@1.33.0: + optional: true + lightningcss-linux-x64-musl@1.33.0: + optional: true + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + lightningcss-win32-x64-msvc@1.33.0: + optional: true + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + lodash-es@4.18.1: {} + lodash-unified@1.0.3(@types/lodash-es@4.17.12)(lodash-es@4.18.1)(lodash@4.18.1): + dependencies: + "@types/lodash-es": 4.17.12 + lodash: 4.18.1 + lodash-es: 4.18.1 + lodash@4.18.1: {} + magic-string@0.30.21: + dependencies: + "@jridgewell/sourcemap-codec": 1.6.0 + memoize-one@6.0.0: {} + muggle-string@0.4.1: {} + nanoid@3.3.20: {} + normalize-wheel-es@1.2.0: {} + path-browserify@1.0.1: {} + picocolors@1.1.1: {} + picomatch@4.0.7: {} + postcss@8.5.32: + dependencies: + nanoid: 3.3.20 + picocolors: 1.1.1 + source-map-js: 1.2.2 + rolldown@1.2.16: + dependencies: + "@oxc-project/types": 0.156.0 + "@rolldown/pluginutils": 1.0.1 + optionalDependencies: + "@rolldown/binding-android-arm-eabi": 1.2.16 + "@rolldown/binding-android-arm64": 1.2.16 + "@rolldown/binding-darwin-arm64": 1.2.16 + "@rolldown/binding-darwin-x64": 1.2.16 + "@rolldown/binding-freebsd-x64": 1.2.16 + "@rolldown/binding-linux-arm-gnueabihf": 1.2.16 + "@rolldown/binding-linux-arm64-gnu": 1.2.16 + "@rolldown/binding-linux-arm64-musl": 1.2.16 + "@rolldown/binding-linux-ppc64-gnu": 1.2.16 + "@rolldown/binding-linux-s390x-gnu": 1.2.16 + "@rolldown/binding-linux-x64-gnu": 1.2.16 + "@rolldown/binding-linux-x64-musl": 1.2.16 + "@rolldown/binding-openharmony-arm64": 1.2.16 + "@rolldown/binding-win32-arm64-msvc": 1.2.16 + "@rolldown/binding-win32-x64-msvc": 1.2.16 + source-map-js@1.2.2: {} + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + typescript@6.0.3: {} + undici-types@7.24.6: {} + vite@8.2.4(@types/node@24.19.2): + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.32 + rolldown: 1.2.16 + tinyglobby: 0.2.17 + optionalDependencies: + "@types/node": 24.19.2 + fsevents: 2.3.3 + vscode-uri@3.2.0: {} + vue-component-type-helpers@3.3.14: {} + vue-tsc@3.3.11(typescript@6.0.3): + dependencies: + "@volar/typescript": 2.4.28 + "@vue/language-core": 3.3.11 + typescript: 6.0.3 + vue@3.5.44(typescript@6.0.3): + dependencies: + "@vue/compiler-dom": 3.5.44 + "@vue/compiler-sfc": 3.5.44 + "@vue/runtime-dom": 3.5.44 + "@vue/server-renderer": 3.5.44 + "@vue/shared": 3.5.44 + optionalDependencies: + typescript: 6.0.3 diff --git a/frontend/src/App.vue b/frontend/src/App.vue new file mode 100644 index 0000000..425177c --- /dev/null +++ b/frontend/src/App.vue @@ -0,0 +1,432 @@ + + + diff --git a/frontend/src/LayoutSurface.vue b/frontend/src/LayoutSurface.vue new file mode 100644 index 0000000..40ac947 --- /dev/null +++ b/frontend/src/LayoutSurface.vue @@ -0,0 +1,67 @@ + + + diff --git a/frontend/src/ReleaseDialog.vue b/frontend/src/ReleaseDialog.vue new file mode 100644 index 0000000..97344bb --- /dev/null +++ b/frontend/src/ReleaseDialog.vue @@ -0,0 +1,173 @@ + + + diff --git a/frontend/src/layout.ts b/frontend/src/layout.ts new file mode 100644 index 0000000..58a0c77 --- /dev/null +++ b/frontend/src/layout.ts @@ -0,0 +1,203 @@ +import defaultLayout from "../../android/app/src/main/assets/default_layout.json" with { type: "json" }; + +export interface Payload { + label?: string | null; + package?: string | null; + provider?: string | null; + intent?: string | null; + radius?: number | null; +} +export interface LayoutItem { + id: string; + type: string; + x: number; + y: number; + w: number; + h: number; + z: number; + payload: Payload; +} +export interface Background { + type: string; + color?: string; + from?: string; + to?: string; +} +export interface Page { index: number; background: Background; items: LayoutItem[] } +export interface Layout { + schemaVersion: 3; + revision: number; + canvas: { designWidth: number; designHeight: number; safeTop: number; safeBottom: number }; + fit: { mode: string; anchorY: number }; + pages: Page[]; +} +export interface Issue { level: "error" | "warning"; path: string; message: string } +export type Template = Pick & { label: string }; + +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.camera", label: "相机" } }, + { type: "widget", label: "时钟组件", w: 864, h: 320, payload: { provider: "com.android.deskclock/.ClockWidget", label: "时钟" } }, + { type: "widget", label: "天气组件", w: 420, h: 300, payload: { provider: "com.android.weather/.WeatherWidget", label: "天气" } }, + { type: "widget", label: "音乐组件", w: 420, h: 300, payload: { provider: "com.spotify/.MusicWidget", label: "音乐" } }, + { type: "shortcut", label: "快捷方式", w: 132, h: 168, payload: { intent: "weixin://scanqrcode", label: "扫一扫" } }, + { type: "dock_bg", label: "Dock 底板", w: 936, h: 200, payload: { radius: 56 } }, +]; + +export const devices = [ + { name: "16:9", w: 1080, h: 1920 }, + { name: "16:8", w: 1080, h: 2160 }, + { name: "19.5:9", w: 1080, h: 2340 }, + { name: "2K 20:9", w: 1440, h: 3120 }, + { name: "16:10", w: 1440, h: 2304 }, + { name: "平板 4:3", w: 1600, h: 2560 }, +]; + +const canvasDefaults = { designWidth: 1080, designHeight: 1920, safeTop: 132, safeBottom: 72 }; +const fitDefaults = { mode: "contain", anchorY: 0.5 }; +const object = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); +const finite = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value); +const int = (value: unknown): value is number => finite(value) && Number.isInteger(value) + && value >= -2147483648 && value <= 2147483647; + +export function normalizeLayout(raw: unknown): Layout { + if (!object(raw) || (raw.schemaVersion !== undefined && raw.schemaVersion !== 3)) throw new Error("仅支持 v3 布局"); + if (raw.canvas !== undefined && !object(raw.canvas) || raw.fit !== undefined && !object(raw.fit)) { + throw new Error("画布或映射字段格式不正确"); + } + const canvas = { ...canvasDefaults, ...raw.canvas }; + const fit = { ...fitDefaults, ...raw.fit }; + if (!Object.keys(canvasDefaults).every(key => int(canvas[key as keyof typeof canvasDefaults])) + || canvas.designWidth < 320 || canvas.designHeight < 480 || canvas.designWidth > 8192 + || canvas.designHeight > 8192 || typeof fit.mode !== "string" || !finite(fit.anchorY)) { + 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) => { + if (!object(page) || page.items !== undefined && (!Array.isArray(page.items) || page.items.length > 80)) { + throw new Error("第 " + (index + 1) + " 页的元素格式有误或超过 80 项"); + } + if (page.background !== undefined && (!object(page.background) || + page.background.type !== undefined && typeof page.background.type !== "string" || + ["color", "from", "to"].some(key => object(page.background) && page.background[key] != null && typeof page.background[key] !== "string"))) { + throw new Error("页面背景格式无效"); + } + const items = (page.items ?? []) as unknown[]; + return { + ...page, index, background: { type: "wallpaper", ...page.background } as Background, + items: items.map(item => { + if (!object(item) || typeof item.id !== "string" || typeof item.type !== "string" || + !finite(item.x) || !finite(item.y) || !finite(item.w) || !finite(item.h) || + item.z !== undefined && !int(item.z)) { + throw new Error("元素 ID、类型、尺寸或层级格式无效"); + } + const payload = item.payload === undefined ? {} : item.payload; + if (!object(payload) || ["label", "package", "provider", "intent"].some( + key => payload[key] != null && typeof payload[key] !== "string", + ) || payload.radius != null && !int(payload.radius)) throw new Error("元素内容格式无效"); + 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 }; + }), + }; + }); + return { ...raw, schemaVersion: 3, revision: raw.revision ?? 1, canvas, fit, pages }; +} + +export const builtInLayout = () => normalizeLayout(structuredClone(defaultLayout)); +export const copyLayout = (layout: Layout): Layout => JSON.parse(JSON.stringify(layout)); +export const sortedItems = (page: Page) => [...page.items].sort((a, b) => a.z - b.z); +export const clamp = (n: number, min: number, max: number) => Math.max(min, Math.min(max, n)); + +const color = (value: string | undefined) => + typeof value === "string" && /^#(?:[\da-f]{6}|[\da-f]{3})$/i.test(value) ? value : "#151a22"; +export function backgroundStyle(bg: Background) { + if (bg.type === "solid") return color(bg.color); + if (bg.type === "gradient") return "linear-gradient(" + color(bg.from) + "," + color(bg.to) + ")"; + return undefined; +} + +export function validate(layout: Layout): Issue[] { + const issues: Issue[] = []; + const { designWidth, designHeight, safeTop, safeBottom } = layout.canvas; + const add = (level: Issue["level"], path: string, message: string) => issues.push({ level, path, message }); + if (safeTop < 0 || safeBottom < 0) add("error", "画布", "安全区不能为负数"); + if (safeTop + safeBottom >= designHeight) add("warning", "画布", "安全区总和达到画布高度"); + if (safeTop < 118) add("warning", "顶部安全区", "顶部安全区偏小,内容可能被状态栏遮挡"); + if (safeBottom < 40) add("warning", "底部安全区", "底部安全区偏小,内容可能被手势条遮挡"); + if (!["contain", "elastic", "stretch"].includes(layout.fit.mode)) add("warning", "映射策略", "手机会按等比居中处理"); + if (layout.fit.anchorY < 0 || layout.fit.anchorY > 1) add("warning", "留白位置", "应在 0–1 之间"); + layout.pages.forEach((page, index) => { + const ids = new Set(); + page.items.forEach((item, i) => { + const path = "第 " + (index + 1) + " 页 · " + (item.payload.label || item.id || (i + 1)); + if (!item.id.trim() || ids.has(item.id)) add("error", path, "ID 为空或重复"); + ids.add(item.id); + if (item.x < 0 || item.y < 0 || item.w <= 0 || item.h <= 0 || + item.x + item.w > designWidth + 0.5 || item.y + item.h > designHeight + 0.5) { + add("error", path, "尺寸无效或元素超出画布"); + } + 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"); + if (!templates.some(template => template.type === item.type)) add("warning", path, "手机会跳过未知类型"); + if (item.y < safeTop || item.y + item.h > designHeight - safeBottom) add("warning", path, "元素进入安全区"); + if (item.type !== "dock_bg" && page.items.slice(i + 1).some(other => other.type !== "dock_bg" && + item.x < other.x + other.w && item.x + item.w > other.x && + item.y < other.y + other.h && item.y + item.h > other.y)) { + add("warning", path, "元素与同页其他元素重叠"); + } + }); + }); + return issues; +} + +export function deviceMapper(canvas: Layout["canvas"], fit: Layout["fit"], items: LayoutItem[], dev: typeof devices[number]) { + const sx = dev.w / canvas.designWidth; + const sy = dev.h / canvas.designHeight; + const mode = fit.mode.toLowerCase(); + if (mode === "stretch") return { sx, sy, x: (x: number) => x * sx, y: (y: number) => y * sy }; + const extra = dev.h - canvas.designHeight * sx; + if (mode === "elastic" && extra > 0.5) { + const bands: [number, number][] = []; + const spans = items.map(item => [item.y, item.y + item.h] as const).sort((a, b) => a[0] - b[0]); + for (const [top, bottom] of spans) { + const last = bands.at(-1); + if (last && top < last[1] - 0.5) last[1] = Math.max(last[1], bottom); + else bands.push([top, bottom]); + } + let previous = 0; + let cumulative = 0; + const gaps = bands.map(([top, bottom]) => { + cumulative += Math.max(0, top - previous); + previous = bottom; + return [top, cumulative] as const; + }); + const totalBlank = cumulative + Math.max(0, canvas.designHeight - previous) || 1; + return { + sx, sy: sx, + x: (x: number) => x * sx, + y: (y: number) => { + let blank = 0; + for (const [top, offset] of gaps) { + if (y < top - 0.5) break; + blank = offset; + } + return y * sx + blank * extra / totalBlank; + }, + }; + } + const scale = Math.min(sx, sy); + const ox = (dev.w - canvas.designWidth * scale) / 2; + const oy = (dev.h - canvas.designHeight * scale) * clamp(fit.anchorY, 0, 1); + return { sx: scale, sy: scale, x: (x: number) => ox + x * scale, y: (y: number) => oy + y * scale }; +} + +export function iconColor(item: LayoutItem) { + let hue = 0; + for (const char of item.payload.package || item.payload.label || item.id) { + hue = (hue * 31 + char.charCodeAt(0)) % 360; + } + return "linear-gradient(150deg,hsl(" + hue + " 62% 56%),hsl(" + (hue + 25) + " 55% 34%))"; +} diff --git a/frontend/src/main.ts b/frontend/src/main.ts new file mode 100644 index 0000000..6c634c3 --- /dev/null +++ b/frontend/src/main.ts @@ -0,0 +1,8 @@ +import { createApp } from "vue"; +import "element-plus/theme-chalk/index.css"; +import "element-plus/theme-chalk/dark/css-vars.css"; +import "./styles.css"; +import App from "./App.vue"; + +document.documentElement.classList.add("dark"); +createApp(App).mount("#app"); diff --git a/frontend/src/styles.css b/frontend/src/styles.css new file mode 100644 index 0000000..eed82f8 --- /dev/null +++ b/frontend/src/styles.css @@ -0,0 +1,122 @@ +:root { + color-scheme: dark; + font-family: system-ui, "Microsoft YaHei UI", sans-serif; + font-size: 14px; + color: #e0e8f2; + background: #10151e; +} +*, *::before, *::after { box-sizing: border-box; } +body { margin: 0; } +#app { min-width: 320px; } +h1, h2, p, figure { margin: 0; } +h1 { font-size: 17px; white-space: nowrap; } +h2 { font-size: 13px; font-weight: 650; } +small { color: #9caec3; } +.toolbar { + display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; + gap: 12px; padding: 14px 20px; border-bottom: 1px solid #2a3547; background: #161e2a; +} +.toolbar nav, .page-bar, .templates, .json-actions, .release-actions { display: flex; flex-wrap: wrap; gap: 8px; } +.toolbar .el-button, .page-bar .el-button, .templates .el-button, .json-actions .el-button, .release-actions .el-button { + margin: 0; +} +.workspace { + display: grid; grid-template-columns: 224px minmax(0, 1fr) 348px; + height: calc(100dvh - 54px); min-height: 610px; +} +.settings, .inspector { overflow: auto; background: #151d29; } +.settings { border-right: 1px solid #2a3547; } +.settings section { display: grid; gap: 10px; padding: 16px; border-bottom: 1px solid #2a3547; } +.settings .el-checkbox { margin: 0; height: auto; } +.settings label, .item-properties label, .token-field { + display: grid; gap: 5px; font-size: 12px; color: #b7c5d7; +} +.settings label.el-checkbox { display: inline-flex; } +.settings .el-input-number, .item-properties .el-input-number { width: 100%; } +.settings input[type=color] { width: 100%; height: 28px; cursor: pointer; } +.editor { display: flex; flex-direction: column; min-width: 0; min-height: 0; } +.canvas-head { + display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; padding: 12px 16px; + color: #aebed0; border-bottom: 1px solid #2a3547; +} +.canvas-head strong { color: #e0e8f2; } +.hint { margin-left: auto; font-size: 12px; } +.stage { + flex: 1; min-height: 0; display: grid; place-items: center; overflow: hidden; + background: radial-gradient(ellipse at center, #222e42, #10151e 75%); +} +.layout-surface { + position: relative; overflow: hidden; width: 100%; container-type: inline-size; + isolation: isolate; background: linear-gradient(155deg, #263748, #141b2b 68%); + outline: 1px solid #42536b; border-radius: 5px; +} +.layout-surface.editable { touch-action: none; user-select: none; box-shadow: 0 12px 36px #050b16a6; } +.layout-surface.with-guides::before { + content: ""; position: absolute; inset: 0; pointer-events: none; + background: linear-gradient(#b3c8ea12 1px, transparent 1px), linear-gradient(90deg, #b3c8ea12 1px, transparent 1px); + background-size: 8.333% 5%; +} +.safe-zone { position: absolute; left: 0; right: 0; pointer-events: none; background: #4b9cf22a; } +.safe-zone.top { top: 0; border-bottom: 1px dashed #79b9fc; } +.safe-zone.bottom { bottom: 0; border-top: 1px dashed #79b9fc; } +.layout-item { + position: absolute; display: flex; align-items: center; justify-content: center; flex-direction: column; + min-width: 0; min-height: 0; padding: 0; color: #f4f8fb; overflow: hidden; +} +.editable .layout-item { cursor: grab; } +.layout-item.selected, .editable .layout-item:focus-visible { outline: 1px solid #7bc2ff; outline-offset: -1px; } +.layout-item.widget { background: #6f91b442; border: 1px solid #9ab6d267; border-radius: 1.6cqw; } +.layout-item.dock_bg { background: #b0bfdd30; border: 1px solid #a3b8d44a; } +.icon-art { + display: grid; place-items: center; width: 74%; max-width: 15cqw; aspect-ratio: 1; + border-radius: 26%; background: var(--icon-fill); font-size: 4cqw; font-weight: bold; +} +.icon-label, .widget-label { + font-size: 2.55cqw; max-width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; +} +.widget-label { font-size: 3.1cqw; } +.resize-handle { + position: absolute; inset: auto 0 0 auto; width: 11px; height: 11px; + background: #a2d0fa; border-radius: 3px 0 0 0; cursor: nwse-resize; opacity: 0; +} +.selected > .resize-handle, .layout-item:hover > .resize-handle, .layout-item:focus-visible > .resize-handle { opacity: 1; } +.page-bar { border-top: 1px solid #2a3547; padding: 10px 12px; background: #161e2a; } +.inspector { border-left: 1px solid #2a3547; padding: 0 12px 12px; } +.previews { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 17px 12px; } +.previews figure { display: flex; align-items: center; flex-direction: column; justify-content: flex-end; gap: 8px; } +.previews figcaption { text-align: center; font-size: 12px; } +.previews small, .release-history small { display: block; font-size: 11px; } +.item-properties { display: grid; gap: 10px; } +.property-input { + width: 100%; height: 24px; padding: 0 8px; border: 1px solid var(--el-border-color); + border-radius: 4px; color: var(--el-text-color-regular); background: var(--el-fill-color-blank); +} +.property-input:focus { outline: 1px solid var(--el-color-primary); } +.empty { color: #9caec3; padding: 10px 0; } +.issues, .release-history { list-style: none; padding: 0; margin: 8px 0; } +.issues li { display: grid; gap: 4px; margin-bottom: 8px; padding: 8px; border-left: 2px solid #d7a754; } +.issues li.error { border-color: #f17c7c; } +pre { color: #a7ccea; font-size: 11px; max-width: 100%; overflow: auto; } +.release-actions { margin: 12px 0; } +.release-status { display: block; white-space: pre-wrap; margin-bottom: 12px; } +.release-error { color: #f49797; } +.release-history { max-height: 38vh; overflow: auto; } +.release-history li { + display: flex; gap: 10px; align-items: center; justify-content: space-between; + padding: 8px 0; border-top: 1px solid #394254; +} +@media (max-width: 1120px) { + .workspace { grid-template-columns: 188px minmax(0, 1fr) 288px; } + .hint { margin-left: 0; } +} +@media (max-width: 820px) { + .workspace { height: auto; grid-template-columns: 180px minmax(0, 1fr); } + .editor { min-height: 550px; } + .inspector { grid-column: 1 / -1; } + .previews { grid-template-columns: repeat(auto-fit, minmax(85px, 120px)); } +} +@media (max-width: 540px) { + .workspace { display: flex; flex-direction: column; } + .editor { order: -1; min-height: 520px; } + .settings { display: grid; grid-template-columns: 1fr 1fr; } +} diff --git a/frontend/test-layout.mjs b/frontend/test-layout.mjs new file mode 100644 index 0000000..a89c17a --- /dev/null +++ b/frontend/test-layout.mjs @@ -0,0 +1,41 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { runInNewContext } from "node:vm"; +import { normalizeLayout, 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"); +const offlineFunction = name => { + const start = offline.indexOf("function " + name + "("); + const end = offline.indexOf("\n}", start) + 2; + assert.ok(start >= 0 && end > start, name); + return offline.slice(start, end); +}; + +for (const { name, accepted, layout } of fixtures) { + let editorAccepted; + try { + editorAccepted = !validate(normalizeLayout(layout)).some(issue => issue.level === "error"); + } catch { + editorAccepted = false; + } + assert.equal(editorAccepted, accepted, "Vue editor: " + name); + + const offlineAccepted = runInNewContext(` + let state, activePage, selectedId; + function pushHistory() {} + function syncControls() {} + function fitCanvas() {} + function render() {} + ${offlineFunction("importLayout")} + ${offlineFunction("validate")} + try { + importLayout(layout); + validate().errors === 0; + } catch { + false; + } + `, { layout }); + assert.equal(offlineAccepted, accepted, "Offline editor: " + name); +} +console.log(`${fixtures.length} shared cases passed in both editors`); diff --git a/frontend/tsconfig.json b/frontend/tsconfig.json new file mode 100644 index 0000000..097ec4b --- /dev/null +++ b/frontend/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "skipLibCheck": true, + "resolveJsonModule": true, + "lib": [ + "ES2022", + "DOM", + "DOM.Iterable" + ], + "types": [ + "vite/client", + "node" + ] + }, + "include": [ + "src/**/*.ts", + "src/**/*.vue", + "vite.config.ts" + ] +} diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts new file mode 100644 index 0000000..1345aa9 --- /dev/null +++ b/frontend/vite.config.ts @@ -0,0 +1,13 @@ +import { defineConfig, loadEnv } from "vite"; +import vue from "@vitejs/plugin-vue"; + +export default defineConfig(({ mode }) => { + const env = loadEnv(mode, process.cwd(), ""); + const proxy = { "/api": { target: env.LAUNCHER_API_TARGET || "http://127.0.0.1:8080" } }; + return { + base: "./", + plugins: [vue()], + server: { proxy }, + preview: { proxy }, + }; +});