diff --git a/.metadata b/.metadata index 61ff721..18287b2 100644 --- a/.metadata +++ b/.metadata @@ -18,6 +18,9 @@ migration: - platform: windows create_revision: 9584c6713b324636289d067944a46fd6b49df14b base_revision: 9584c6713b324636289d067944a46fd6b49df14b + - platform: android + create_revision: 9584c6713b324636289d067944a46fd6b49df14b + base_revision: 9584c6713b324636289d067944a46fd6b49df14b # User provided section diff --git a/BUILD-NOTES.md b/BUILD-NOTES.md index 1a03151..75c8089 100644 --- a/BUILD-NOTES.md +++ b/BUILD-NOTES.md @@ -97,3 +97,85 @@ flutter build windows --release (不使用 `path_provider` / `file_selector`)。应用数据目录通过 `%APPDATA%` 环境变量获取,文件打开/保存使用自研的应用内文件浏览器。 - 国内网络请使用上述 Flutter/Pub 镜像。 + +--- + +## Android 平板版构建(`dev/android-tablet` 分支) + +面向 1280×800dp(2560×1600)平板、无 license 授权的应用商店分发版。 + +### 环境 + +| 项 | 版本 / 说明 | +| --- | --- | +| JDK | 17(如 Temurin 17,`JAVA_HOME` 指向安装目录) | +| Android SDK | cmdline-tools + `platform-tools` + `platforms;android-36` + `build-tools;36.0.0`,`ANDROID_HOME`/`ANDROID_SDK_ROOT` 指向 SDK 根目录 | +| Gradle | 9.3.1(wrapper 分发已改腾讯镜像 `mirrors.cloud.tencent.com/gradle`) | +| Maven | 已配置阿里镜像(google / central / gradle-plugin / public),官方源作回退 | + +> SDK 组件也可用镜像安装,例如: +> `https://mirrors.cloud.tencent.com/AndroidSDK/commandlinetools-win-11076708_latest.zip` + +### 构建命令 + +```powershell +$env:JAVA_HOME = "D:\jdk-17.0.20.1+1" +$env:ANDROID_HOME = "D:\android-sdk" +$env:FLUTTER_STORAGE_BASE_URL = "https://storage.flutter-io.cn" +$env:PUB_HOSTED_URL = "https://pub.flutter-io.cn" +flutter pub get +flutter build apk --release # 产物:build\app\outputs\flutter-apk\app-release.apk +``` + +- 发布包归档:`release\sequence_diagram_tablet_v1.0.1_release.apk`(universal:arm64-v8a / armeabi-v7a / x86_64)。 +- 上架应用商店时建议在 `android\app\build.gradle.kts` 配置正式签名后再构建 AAB: + `flutter build appbundle --release`。 +- 应用名「时序图设计器」、包名 `cc.sincos.sequence_diagram`、launcher 图标由 + `tools\gen-android-icons.py` 生成(与桌面版「环序」标志同源)。 + +### 正式签名 + +- keystore:`android\key\release.jks`(alias=`sequence`,storepass/keypass=`sdstudio2026`,有效期 30 年); +- 签名参数由 `android\key.properties` 提供(已 gitignore;模板见仓库 `android\key\release.jks` 同目录说明): + ```properties + storePassword=sdstudio2026 + keyPassword=sdstudio2026 + keyAlias=sequence + storeFile=key/release.jks + ``` +- 缺失 `key.properties` 时自动回退 debug 签名,不影响本地调试构建; +- **换机重建**:把 `release.jks` 复制到 `android\key\` 并创建 `key.properties`,签名即可保持一致 + (否则新签名与旧包不兼容,需卸载后重装); +- **上架提醒**:正式商店上架前建议另生成**不入库**的专属 keystore 并妥善保存; + 当前入库的 `release.jks` 仅用于内部测试分发。 + +### 平台差异说明 + +- **license**:`LicenseService.init()` 在非 Windows 平台直接判定已授权,Android 版无授权限制。 +- **文件保存(安卓)**:保存工程 / 导出 SVG / PNG 写入公共目录(平板文件管理器可见), + **位置可在应用内修改**(保存/打开对话框里的「更改位置」): + - 基础目录可选 **文档 / 下载 / 图片**,子文件夹名可自定义(默认 `SequenceDiagram`); + - 设置保存在应用私有目录 `save_location.json`,跨会话生效; + - Android 10+ 通过 MediaStore 写入(无需存储权限,商店合规); + - Android 9 及以下直接写公共目录(manifest 中 `WRITE_EXTERNAL_STORAGE` 限 maxSdkVersion=28)。 + - 原生实现:`android/app/src/main/kotlin/.../MainActivity.kt`(通道 `seqstudio/docs`), + Dart 侧封装见 `lib/persistence/android_docs.dart`。 +- **导出格式(Windows 与 Android 一致)**: + - 固定画布 **1920×1080**(SVG `viewBox` 同步); + - **标题固定在左上角**、图例固定在左下角; + - 时序图内容按自身包围盒**等比缩放并居中**到内容区,不裁切、不溢出 + (`lib/export/export_fit.dart` 统一计算,PNG 渲染器与 SVG 写入器共用)。 +- **桌面(Windows)文件保存**:仍使用应用内文件浏览器,默认起始目录为桌面, + 并跨会话记忆上次使用的目录。 +- **自动保存**:安卓落于应用私有缓存目录(仅用于崩溃恢复,不对外可见)。 +- **侧栏**:触屏默认收起为贴边把手(点把手直接停靠展开);面板宽度随屏幕动态压缩, + 窄屏双侧栏停靠也不溢出。 +- **系统栏**:edge-to-edge,状态栏/导航栏区域由工具栏/状态栏底色填满(全屏无黑边), + 图标亮度随深浅主题切换;文本缩放固定 1.0,保证平板各分辨率像素级一致。 + +### 自测 + +```bash +flutter test test\tablet_layout_test.dart # 7 种分辨率无溢出回归 +flutter test --update-goldens test\tablet_screenshots_test.dart # 重新生成 demo/tablet-*.png +``` diff --git a/README.md b/README.md index 7bacf4c..02de04a 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,21 @@ node tools/demo-gen.mjs Flutter 3.29+(Desktop) · CustomPainter 自绘 · Riverpod · 不可变模型 + Command 撤销栈 · 纯 Dart 几何算法 · 自研 SVG 序列化器 · JSON(`.seq.json`)持久化 · 主题 Token 化(深浅双主题) +## Android 平板版(`dev/android-tablet` 分支) + +- **目标分辨率**:1280×800dp(2560×1600 物理),并动态兼容其它横竖屏分辨率; +- **无 license 授权**(面向应用商店分发);包名 `cc.sincos.sequence_diagram`,应用名「时序图设计器」; +- **文件保存**:工程 / SVG / PNG 保存到平板可见的公共目录(默认 `Documents/SequenceDiagram`,可在保存对话框「更改位置」中选择文档/下载/图片 + 自定义子文件夹;Android 10+ 走 MediaStore,无需权限); +- **导出格式**:固定 **1920×1080**,标题恒定左上、图例恒定左下,内容按包围盒自适应缩放居中(SVG / PNG 一致,exe 与安卓一致); +- **触控手势**:画布支持**双指捏合缩放 / 双指平移**(以捏合焦点为锚点),单指拖拽编辑不变;全屏无黑边(状态栏/导航栏区域融入界面); +- **正式签名**:release 用独立 keystore 签名(`android/key/release.jks`,见 `BUILD-NOTES.md`),更新安装无需卸载重装; +- **构建**:JDK 17 + Android SDK 36(详见 `BUILD-NOTES.md`),Gradle 与 Maven 已配置国内镜像: + ```bash + flutter build apk --release # 产物 → release/sequence_diagram_tablet_v1.0.1_release.apk + ``` +- **自测**:`test/tablet_layout_test.dart` 覆盖 1280×800、2560×1600、960×600、800×480、竖屏 800×1280、600×960 等 7 种分辨率的无溢出回归; +- **demo 图**:`demo/tablet-*.png`(由 `test/tablet_screenshots_test.dart` 生成)。 + ## 路线图 - [ ] M1 数据模型 + 单位体系 + JSON 存取 + 条形视图(渲染 / 缩放 / 平移) diff --git a/analysis_options.yaml b/analysis_options.yaml index cb1e3ab..6dd0be0 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -13,6 +13,7 @@ analyzer: exclude: - build/** - windows/** + - android/** linter: # The lint rules applied to this project can be customized in the diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..12bf523 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,16 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks + +/key.properties diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..8ed2228 --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,74 @@ +import java.io.FileInputStream +import java.util.Properties + +plugins { + id("com.android.application") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +// 正式签名配置:android/key.properties(不入库)提供密钥信息; +// 缺失时回退 debug 签名,保证无密钥环境也能构建。 +val keystoreProperties = Properties() +val keystorePropertiesFile = rootProject.file("key.properties") +if (keystorePropertiesFile.exists()) { + keystoreProperties.load(FileInputStream(keystorePropertiesFile)) +} + +android { + namespace = "cc.sincos.sequence_diagram" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "cc.sincos.sequence_diagram" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + // Uses the version code from pubspec.yaml. When using split APKs, 1000 * ABI_VERSION + // is added automatically by Flutter. (https://developer.android.com/studio/build/configure-apk-splits#configure-APK-versions) + // You can force using the value of versionCode by specifying the `-P force-version-code-ignoring-abi=true` + // flag during build. + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + signingConfigs { + create("release") { + if (keystorePropertiesFile.exists()) { + keyAlias = keystoreProperties["keyAlias"] as String + keyPassword = keystoreProperties["keyPassword"] as String + storeFile = rootProject.file(keystoreProperties["storeFile"] as String) + storePassword = keystoreProperties["storePassword"] as String + } + } + } + + buildTypes { + release { + // 有 key.properties 时使用正式签名;否则回退 debug 签名。 + signingConfig = if (keystorePropertiesFile.exists()) { + signingConfigs.getByName("release") + } else { + signingConfigs.getByName("debug") + } + } + } +} + +kotlin { + compilerOptions { + jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17 + } +} + +flutter { + source = "../.." +} diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..8e5f70c --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/cc/sincos/sequence_diagram/MainActivity.kt b/android/app/src/main/kotlin/cc/sincos/sequence_diagram/MainActivity.kt new file mode 100644 index 0000000..e692614 --- /dev/null +++ b/android/app/src/main/kotlin/cc/sincos/sequence_diagram/MainActivity.kt @@ -0,0 +1,189 @@ +package cc.sincos.sequence_diagram + +import android.content.ContentValues +import android.net.Uri +import android.os.Build +import android.os.Environment +import android.provider.MediaStore +import io.flutter.embedding.android.FlutterActivity +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.plugin.common.MethodChannel +import java.io.File + +/** + * 安卓公共文档读写通道(`seqstudio/docs`): + * 保存 / 列出 / 读取配置目录(默认 `Documents/SequenceDiagram`,可在应用内修改为 + * Download / Pictures + 自定义子文件夹)下的文件。 + * + * - API 29+(Android 10+):通过 MediaStore 写入公共目录, + * 无需存储权限,符合应用商店的分区存储(scoped storage)要求; + * - API ≤ 28:直接写入公共目录(配合 manifest 中 maxSdkVersion=28 的 + * WRITE_EXTERNAL_STORAGE 权限)。 + */ +class MainActivity : FlutterActivity() { + private val channelName = "seqstudio/docs" + + override fun configureFlutterEngine(flutterEngine: FlutterEngine) { + super.configureFlutterEngine(flutterEngine) + MethodChannel(flutterEngine.dartExecutor.binaryMessenger, channelName) + .setMethodCallHandler { call, result -> + when (call.method) { + "saveFile" -> { + val name = call.argument("name") + val data = call.argument("data") + val mime = call.argument("mime") + val base = call.argument("base") ?: "documents" + val folder = call.argument("folder") ?: "SequenceDiagram" + if (name == null || data == null) { + result.error("ARGS", "name/data required", null) + } else { + try { + result.success(saveFile(base, folder, name, data, mime)) + } catch (e: Exception) { + result.error("WRITE", e.message, null) + } + } + } + "listFiles" -> { + val base = call.argument("base") ?: "documents" + val folder = call.argument("folder") ?: "SequenceDiagram" + try { + result.success(listFiles(base, folder)) + } catch (e: Exception) { + result.error("LIST", e.message, null) + } + } + "readFile" -> { + val name = call.argument("name") + val base = call.argument("base") ?: "documents" + val folder = call.argument("folder") ?: "SequenceDiagram" + if (name == null) { + result.error("ARGS", "name required", null) + } else { + try { + result.success(readFile(base, folder, name)) + } catch (e: Exception) { + result.error("READ", e.message, null) + } + } + } + else -> result.notImplemented() + } + } + } + + /** 把 base 关键字映射为系统的公共目录常量。 */ + private fun envDir(base: String): String = when (base) { + "downloads" -> Environment.DIRECTORY_DOWNLOADS + "pictures" -> Environment.DIRECTORY_PICTURES + else -> Environment.DIRECTORY_DOCUMENTS + } + + /** MediaStore 相对路径(Q+);API ≤ 28 返回绝对路径。 */ + private fun folderPath(base: String, folder: String): String { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + return envDir(base) + "/" + folder + } + @Suppress("DEPRECATION") + val dir = File( + Environment.getExternalStoragePublicDirectory(envDir(base)), + folder, + ) + if (!dir.exists()) dir.mkdirs() + return dir.absolutePath + } + + /** 保存文件到配置的公共目录,返回用于展示的位置。 */ + private fun saveFile(base: String, folder: String, name: String, data: ByteArray, mime: String?): String { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + val resolver = contentResolver + val collection = MediaStore.Files.getContentUri("external_primary") + val values = ContentValues().apply { + put(MediaStore.Files.FileColumns.DISPLAY_NAME, name) + put(MediaStore.Files.FileColumns.MIME_TYPE, mime ?: "application/octet-stream") + put(MediaStore.Files.FileColumns.RELATIVE_PATH, folderPath(base, folder)) + put(MediaStore.Files.FileColumns.IS_PENDING, 1) + } + val uri: Uri = resolver.insert(collection, values) + ?: throw IllegalStateException("MediaStore insert failed") + resolver.openOutputStream(uri)?.use { it.write(data) } + ?: throw IllegalStateException("openOutputStream failed") + values.clear() + values.put(MediaStore.Files.FileColumns.IS_PENDING, 0) + resolver.update(uri, values, null, null) + return "${envDir(base)}/$folder/$name" + } + @Suppress("DEPRECATION") + val dir = File( + Environment.getExternalStoragePublicDirectory(envDir(base)), + folder, + ) + if (!dir.exists()) dir.mkdirs() + File(dir, name).writeBytes(data) + return "${envDir(base)}/$folder/$name" + } + + /** 列出配置目录下的文件([{name, size}],新在前)。 */ + private fun listFiles(base: String, folder: String): List> { + val out = mutableListOf>() + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + val resolver = contentResolver + val collection = MediaStore.Files.getContentUri("external_primary") + val projection = arrayOf( + MediaStore.Files.FileColumns._ID, + MediaStore.Files.FileColumns.DISPLAY_NAME, + MediaStore.Files.FileColumns.SIZE, + ) + val selection = "${MediaStore.Files.FileColumns.RELATIVE_PATH}=?" + val args = arrayOf(folderPath(base, folder) + "/") + resolver.query(collection, projection, selection, args, null)?.use { c -> + val iName = c.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DISPLAY_NAME) + val iSize = c.getColumnIndexOrThrow(MediaStore.Files.FileColumns.SIZE) + while (c.moveToNext()) { + out.add(mapOf("name" to c.getString(iName), "size" to c.getLong(iSize))) + } + } + } else { + @Suppress("DEPRECATION") + val dir = File( + Environment.getExternalStoragePublicDirectory(envDir(base)), + folder, + ) + if (dir.exists()) { + dir.listFiles()?.sortedByDescending { it.lastModified() }?.forEach { + out.add(mapOf("name" to it.name, "size" to it.length())) + } + } + } + return out + } + + /** 读取配置目录下的文件内容;不存在返回 null。 */ + private fun readFile(base: String, folder: String, name: String): ByteArray? { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + val resolver = contentResolver + val collection = MediaStore.Files.getContentUri("external_primary") + val projection = arrayOf(MediaStore.Files.FileColumns._ID) + val selection = + "${MediaStore.Files.FileColumns.RELATIVE_PATH}=? AND " + + "${MediaStore.Files.FileColumns.DISPLAY_NAME}=?" + val args = arrayOf(folderPath(base, folder) + "/", name) + resolver.query(collection, projection, selection, args, null)?.use { c -> + if (c.moveToFirst()) { + val uri = Uri.withAppendedPath(collection, c.getLong(0).toString()) + return resolver.openInputStream(uri)?.use { it.readBytes() } + } + } + return null + } + @Suppress("DEPRECATION") + val f = File( + File( + Environment.getExternalStoragePublicDirectory(envDir(base)), + folder, + ), + name, + ) + return if (f.exists()) f.readBytes() else null + } +} diff --git a/android/app/src/main/res/drawable-v21/launch_background.xml b/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..c1d8a50 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..a1cf436 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..7ff0f50 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..2635e53 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..b6a9c8d Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/profile/AndroidManifest.xml b/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..727d286 --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,28 @@ +allprojects { + repositories { + // 国内镜像优先,加快依赖下载;保持官方源作为回退。 + maven { url = uri("https://maven.aliyun.com/repository/google") } + maven { url = uri("https://maven.aliyun.com/repository/central") } + maven { url = uri("https://maven.aliyun.com/repository/public") } + google() + mavenCentral() + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..e96108c --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,6 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +# This newDsl flag was added by the Flutter template +android.newDsl=false +# This builtInKotlin flag was added by the Flutter template +android.builtInKotlin=false diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..f8deb6c --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://mirrors.cloud.tencent.com/gradle/gradle-9.3.1-all.zip diff --git a/android/key/release.jks b/android/key/release.jks new file mode 100644 index 0000000..936df1a Binary files /dev/null and b/android/key/release.jks differ diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..488d45c --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,31 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + // 国内镜像优先,加快依赖下载;保持官方源作为回退。 + maven { url = uri("https://maven.aliyun.com/repository/google") } + maven { url = uri("https://maven.aliyun.com/repository/central") } + maven { url = uri("https://maven.aliyun.com/repository/gradle-plugin") } + maven { url = uri("https://maven.aliyun.com/repository/public") } + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "9.1.0" apply false + id("org.jetbrains.kotlin.android") version "2.4.0" apply false +} + +include(":app") diff --git a/demo/tablet-bar-dark.png b/demo/tablet-bar-dark.png new file mode 100644 index 0000000..4a66854 Binary files /dev/null and b/demo/tablet-bar-dark.png differ diff --git a/demo/tablet-bar-light-panels.png b/demo/tablet-bar-light-panels.png new file mode 100644 index 0000000..b2d7c1b Binary files /dev/null and b/demo/tablet-bar-light-panels.png differ diff --git a/demo/tablet-bar-light.png b/demo/tablet-bar-light.png new file mode 100644 index 0000000..bb17a12 Binary files /dev/null and b/demo/tablet-bar-light.png differ diff --git a/demo/tablet-circular-dark.png b/demo/tablet-circular-dark.png new file mode 100644 index 0000000..3027da8 Binary files /dev/null and b/demo/tablet-circular-dark.png differ diff --git a/demo/tablet-circular-light.png b/demo/tablet-circular-light.png new file mode 100644 index 0000000..b2d7c1b Binary files /dev/null and b/demo/tablet-circular-light.png differ diff --git a/lib/export/export_fit.dart b/lib/export/export_fit.dart new file mode 100644 index 0000000..eba1005 --- /dev/null +++ b/lib/export/export_fit.dart @@ -0,0 +1,134 @@ +/// 导出适配:固定 1920×1080 画布下,把时序图内容缩放到内容区并居中, +/// 供 PNG 渲染器与 SVG 写入器共用,保证两种导出几何完全一致。 +/// +/// 约定: +/// - 画布固定 1920×1080; +/// - 标题固定在左上角(标题区 0–128px); +/// - 内容区 = (48, 128) → (1872, 1016),图例固定左下角; +/// - 内容按自身包围盒等比缩放并居中到内容区,不裁切、不溢出。 +library; + +import 'dart:math' as math; + +import 'package:flutter/material.dart' hide Action; + +import '../layout/layout.dart'; +import '../model/models.dart'; +import '../model/units.dart'; +import '../render/bar_painter.dart'; +import '../theme/tokens.dart'; + +/// 导出画布尺寸(固定,逻辑单位)。 +const Size kExportSize = Size(1920, 1080); + +/// 导出渲染像素比:按 2 倍像素渲染(3840×2160),保证高分辨率屏幕下清晰锐利。 +const double kExportPixelRatio = 2.0; + +/// 内容区(标题下方、图例上方)。 +const Rect kExportContentArea = Rect.fromLTRB(48, 128, 1872, 1016); + +/// 导出适配结果:内容变换 `scale` + `translate(tx, ty)`。 +class ExportFit { + /// 构造适配结果。 + const ExportFit(this.scale, this.tx, this.ty); + + /// 缩放系数。 + final double scale; + /// 水平平移。 + final double tx; + /// 垂直平移。 + final double ty; + + /// SVG transform 属性值。 + String get svgTransform => + 'translate(${tx.toStringAsFixed(1)} ${ty.toStringAsFixed(1)}) scale(${scale.toStringAsFixed(4)})'; +} + +/// 计算内容在 [area] 内的适配变换。 +/// +/// 先以 1920×1080 为参考画布求内容包围盒,再等比缩放并居中。 +ExportFit computeExportFit(Project project, ViewMode mode, Rect area) { + Rect bounds; + if (mode == ViewMode.bar) { + final BarLayout l = BarLayout(project, kExportSize); + final int n = l.lanes.length; + final double bottom = n == 0 ? BarLayout.topPad + BarLayout.rowVisual : l.yFor(n) + BarLayout.rowVisual + 8; + bounds = Rect.fromLTRB(12, BarPainter.phaseBandTop - 14, l.plotRight + 120, bottom); + } else { + final CircularLayout l = CircularLayout(project, kExportSize); + final double rExt = l.tickR + 100; + bounds = Rect.fromLTRB(l.center.dx - rExt, l.center.dy - rExt, l.center.dx + rExt, l.center.dy + rExt); + } + if (bounds.width <= 1 || bounds.height <= 1) { + return const ExportFit(1, 0, 0); + } + final double s = math.min(area.width / bounds.width, area.height / bounds.height).clamp(0.2, 1.6); + final double tx = area.left + (area.width - bounds.width * s) / 2 - bounds.left * s; + final double ty = area.top + (area.height - bounds.height * s) / 2 - bounds.top * s; + return ExportFit(s, tx, ty); +} + +/// 导出标题(与画布浮层一致)。 +String exportTitle(ViewMode mode) => + mode == ViewMode.bar ? '条形时序视图' : '圆周时序视图'; + +/// 导出副标题(与画布浮层一致)。 +String exportSubtitle(Project project, ViewMode mode) { + if (mode == ViewMode.bar) { + return '箭头表示动作之间关联(绿色实线 FS 严格顺序 / 琥珀虚线 SS 并行重叠)'; + } + return '同心圆环 = 动作层 · 1 圈 = 1 循环 = ${tfmt(project.cycle.durationMs, project.units)} = 360° = 100%'; +} + +/// 导出图例(左下角固定)。 +String exportLegend(Project project) => + '时序图设计器 · ${project.name} · 循环 ${tfmt(project.cycle.durationMs, project.units)} = 360°'; + +/// 导出专用令牌:始终使用浅色、**纯白背景**(印刷 / 工艺卡导向), +/// 文字、语义色与屏幕浅色主题保持一致。 +/// +/// 无论当前屏幕主题是深是浅,导出的 PNG / SVG 背景都是纯白、文字深色, +/// 避免「导出背景不是纯白」的问题。 +Tokens exportTokens(Tokens base) { + return Tokens( + brightness: Brightness.light, + bg: Colors.white, + canvas1: Colors.white, + canvas2: Colors.white, + chrome: base.chrome, + panel: Colors.white, + panel2: Colors.white, + dialog: Colors.white, + line: base.line, + line2: base.line2, + text: base.text, + text2: base.text2, + sub: base.sub, + dim: base.dim, + accent: base.accent, + accent2: base.accent2, + ok: base.ok, + warn: base.warn, + danger: base.danger, + fs: base.fs, + ss: base.ss, + crit: base.crit, + chip: Colors.white, + dial: Colors.white, + arcText: base.arcText, + onAccent: base.onAccent, + ringA: base.ringA, + ringB: base.ringB, + ringEdge: base.ringEdge, + ringLabel: base.ringLabel, + info: Colors.white, + track: base.track, + sel: base.sel, + grid: base.grid, + shadow: base.shadow, + shadowOp: 0.10, + selOutline: base.selOutline, + overlay: base.overlay, + tailOp: base.tailOp, + ); +} diff --git a/lib/export/export_renderer.dart b/lib/export/export_renderer.dart new file mode 100644 index 0000000..d5e7f3e --- /dev/null +++ b/lib/export/export_renderer.dart @@ -0,0 +1,106 @@ +/// PNG 导出渲染器:把时序图渲染为固定 1920×1080 的位图。 +/// +/// 与 SVG 导出共用同一套适配计算([computeExportFit]),保证两种格式几何一致: +/// - 背景铺满 1920×1080; +/// - 标题固定在左上角、图例固定在左下角; +/// - 内容(条形 / 圆周)按自身包围盒等比缩放并居中到内容区。 +library; + +import 'dart:typed_data'; +import 'dart:ui' as ui; + +import 'package:flutter/material.dart' hide Action; + +import '../model/models.dart'; +import '../render/bar_painter.dart'; +import '../render/circular_painter.dart'; +import '../theme/tokens.dart'; +import 'export_fit.dart'; + +/// 渲染导出 PNG 并返回字节。 +/// +/// 参数: +/// - [project]:数据源; +/// - [tokens]:配色令牌(内部转为导出专用纯白主题); +/// - [criticalActions]/[criticalDeps]:关键路径高亮(与屏幕一致)。 +/// +/// 输出:3840×2160 像素(1920×1080 逻辑画布 × 2 倍像素比), +/// 保证平板 / 2K / 4K 屏幕上查看清晰锐利。 +Future renderExportPng({ + required Project project, + required Tokens tokens, + required Set criticalActions, + required Set criticalDeps, +}) async { + // 导出专用令牌:纯白背景、浅色文字。 + final Tokens et = exportTokens(tokens); + final ui.PictureRecorder recorder = ui.PictureRecorder(); + final Canvas canvas = Canvas(recorder); + final double w = kExportSize.width; + final double h = kExportSize.height; + // 2 倍像素比:整体放大绘制,矢量内容保持锐利。 + canvas.scale(kExportPixelRatio); + + // 背景铺满(纯白)。 + canvas.drawRect(Rect.fromLTWH(0, 0, w, h), Paint()..color = et.bg); + + // 标题:固定左上角。 + final ViewMode mode = project.viewState.mode; + _text(canvas, exportTitle(mode), const Offset(48, 36), + color: et.text, size: 34, weight: FontWeight.w700); + _text(canvas, exportSubtitle(project, mode), const Offset(48, 88), + color: et.sub, size: 16, weight: FontWeight.w400); + + // 内容:适配缩放并居中到内容区。 + final ExportFit fit = computeExportFit(project, mode, kExportContentArea); + canvas.save(); + canvas.translate(fit.tx, fit.ty); + canvas.scale(fit.scale); + if (mode == ViewMode.bar) { + BarPainter( + project: project, + tokens: et, + criticalActions: criticalActions, + criticalDeps: criticalDeps, + selectedIds: const {}, + ).paint(canvas, kExportSize); + } else { + CircularPainter( + project: project, + tokens: et, + criticalActions: criticalActions, + criticalDeps: criticalDeps, + selectedIds: const {}, + ).paint(canvas, kExportSize); + } + canvas.restore(); + + // 图例:固定左下角。 + _text(canvas, exportLegend(project), Offset(48, h - 38), + color: et.sub, size: 15, weight: FontWeight.w400); + + final ui.Image image = await recorder + .endRecording() + .toImage((w * kExportPixelRatio).toInt(), (h * kExportPixelRatio).toInt()); + final ByteData? data = await image.toByteData(format: ui.ImageByteFormat.png); + return data!.buffer.asUint8List(); +} + +/// 用统一字体绘制单行文本。 +void _text(Canvas canvas, String s, Offset at, + {required Color color, required double size, required FontWeight weight}) { + final TextPainter tp = TextPainter( + text: TextSpan( + text: s, + style: TextStyle( + color: color, + fontSize: size, + fontWeight: weight, + fontFamily: 'Microsoft YaHei UI', + fontFamilyFallback: const ['Microsoft YaHei', 'Noto Sans SC', 'sans-serif'], + ), + ), + textDirection: ui.TextDirection.ltr, + )..layout(); + tp.paint(canvas, Offset(at.dx, at.dy - tp.height / 2)); +} diff --git a/lib/export/svg_writer.dart b/lib/export/svg_writer.dart index d358b3b..52d39cd 100644 --- a/lib/export/svg_writer.dart +++ b/lib/export/svg_writer.dart @@ -10,8 +10,10 @@ /// - 每个逻辑分组写成 ``(背景、标尺、动作、标签、依赖、图例), /// 动作组与依赖组额外附带 `data-*` 属性,便于下游脚本解析。 /// -/// 输出约定: -/// - 画布固定 2560×1440,通过 `viewBox` 支持无损缩放。 +/// 输出约定(与 PNG 导出一致): +/// - 画布固定 1920×1080,通过 `viewBox` 支持无损缩放; +/// - 标题固定在左上角、图例固定在左下角; +/// - 时序图内容按自身包围盒等比缩放并居中到内容区,不裁切、不溢出。 /// - 所有文本内联 [_font] 字体栈,保证跨平台字形一致。 library; @@ -22,6 +24,7 @@ import '../layout/layout.dart'; import '../model/models.dart'; import '../model/units.dart'; import '../theme/tokens.dart'; +import 'export_fit.dart'; /// SVG 文档写入器。 /// @@ -35,7 +38,10 @@ class SvgWriter { /// - [mode]:视图模式,决定生成条形还是圆形布局。 /// /// 构造时不生成任何内容;调用 [build] 才写出 SVG。 - SvgWriter({required this.project, required this.tokens, required this.mode}); + /// + /// [tokens] 会经 [exportTokens] 转为导出专用令牌(纯白背景、浅色文字)。 + SvgWriter({required this.project, required Tokens tokens, required this.mode}) + : tokens = exportTokens(tokens); /// 数据源工程。 final Project project; @@ -51,28 +57,42 @@ class SvgWriter { /// 生成完整 SVG 文档字符串。 /// + /// 输出约定(与 PNG 导出一致): + /// - 画布固定 1920×1080; + /// - 标题固定在左上角、图例固定在左下角; + /// - 时序图内容按自身包围盒等比缩放并居中到内容区,不裁切、不溢出。 + /// /// 返回:以 `` 开头、`` 结尾的字符串。 /// 副作用:会持续向内部缓冲区追加内容;重复调用不会自动清空缓冲区, /// 因此约定每次导出都新建一个 [SvgWriter] 实例。 String build() { - // 固定逻辑画布尺寸;viewBox 与 width/height 相同,缩放时几何不失真。 - final double w = 2560; - final double h = 1440; - _b.write(''); + const double w = 1920; + const double h = 1080; + _b.write(''); // 先写箭头 marker 定义,供后续依赖路径引用。 _defs(); // 背景层:铺满整张画布。 _b.write(''); _rect(0, 0, w, h, fill: _hex(tokens.bg)); _b.write(''); - // 按当前视图模式生成主体内容。 + // 标题:固定左上角。 + _b.write(''); + _text(48, 60, exportTitle(mode), color: _hex(tokens.text), size: 34, weight: '700'); + _text(48, 104, exportSubtitle(project, mode), color: _hex(tokens.sub), size: 16); + _b.write(''); + // 内容:适配缩放并居中到内容区。 + final ExportFit fit = computeExportFit(project, mode, kExportContentArea); + _b.write(''); if (mode == ViewMode.bar) { - _barView(Size(w, h)); + _barView(const Size(w, h)); } else { - _circularView(Size(w, h)); + _circularView(const Size(w, h)); } - // 图例始终绘制在最上层。 - _legend(w, h); + _b.write(''); + // 图例:固定左下角。 + _b.write(''); + _text(48, h - 36, exportLegend(project), color: _hex(tokens.sub), size: 15); + _b.write(''); _b.write(''); return _b.toString(); } @@ -253,16 +273,6 @@ class SvgWriter { } } - /// 写入图例分组,展示工程名、循环时长与 360° 的等价关系。 - /// - /// 参数 [w]/[h] 为画布宽高,用于定位到左下角。 - void _legend(double w, double h) { - _b.write(''); - _text(24, h - 28, '时序图设计器 · ${project.name} · 循环 ${tfmt(project.cycle.durationMs, project.units)} = 360°', - color: _hex(tokens.sub), size: 13); - _b.write(''); - } - /// 生成一段圆弧的 SVG `d` 路径字符串。 /// /// 参数 [c] 圆心、[r] 半径、[a0]/[a1] 起止角度(度)。 diff --git a/lib/license/license_service.dart b/lib/license/license_service.dart index 271206b..d1cee30 100644 --- a/lib/license/license_service.dart +++ b/lib/license/license_service.dart @@ -58,7 +58,14 @@ class LicenseService { Directory get licenseDir => Directory('${Directory.current.path}${Platform.pathSeparator}license'); /// 初始化:读取 MAC 并校验 `license/*.lic`。 + /// + /// Android 平板版(应用商店分发)不需要授权:非 Windows 平台直接判定为 + /// 已授权,跳过 MAC 读取与 .lic 校验。 Future init() async { + if (!Platform.isWindows) { + _info = const LicenseInfo(mac: null, valid: true); + return _info; + } final String? mac = await _readMac(); bool valid = false; String? hitPath; diff --git a/lib/main.dart b/lib/main.dart index 5f77c7e..9a76c71 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -5,6 +5,8 @@ // Storage(本地持久化),并通过 AppController 向整个 UI 层提供状态与 // 业务动作。启动后还会检查是否存在异常退出遗留的自动快照,并引导用户 // 选择恢复方式。 +import 'dart:io' show Platform; + import 'dart:ui' show AppExitResponse; import 'package:flutter/material.dart'; @@ -23,6 +25,10 @@ import 'ui/app_shell.dart'; /// 然后启动根组件 [SequenceDiagramApp]。 Future main() async { WidgetsFlutterBinding.ensureInitialized(); + // 移动端:沉浸式(edge-to-edge)显示,系统栏区域由应用工具栏/状态栏底色填充。 + if (Platform.isAndroid || Platform.isIOS) { + await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); + } await Storage.instance.init(); runApp(const SequenceDiagramApp()); } @@ -158,6 +164,27 @@ class _SequenceDiagramAppState extends State { title: '时序图设计器 · Sequence Diagram Studio', debugShowCheckedModeBanner: false, theme: buildTheme(tokens), + // 固定文本缩放;系统栏图标随主题亮度自动切换(透明系统栏, + // 状态栏 / 导航栏区域由 AppShell 的工具栏 / 状态栏底色填满)。 + builder: (BuildContext context, Widget? child) { + final bool dark = Theme.of(context).brightness == Brightness.dark; + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarColor: Colors.transparent, + statusBarIconBrightness: dark ? Brightness.light : Brightness.dark, + statusBarBrightness: dark ? Brightness.dark : Brightness.light, + systemNavigationBarColor: Colors.transparent, + systemNavigationBarIconBrightness: dark ? Brightness.light : Brightness.dark, + systemNavigationBarDividerColor: Colors.transparent, + ), + child: MediaQuery( + data: MediaQuery.of(context).copyWith( + textScaler: const TextScaler.linear(1.0), + ), + child: child ?? const SizedBox.shrink(), + ), + ); + }, home: AppShell(controller: _controller), ); }, diff --git a/lib/persistence/android_docs.dart b/lib/persistence/android_docs.dart new file mode 100644 index 0000000..0b15f9a --- /dev/null +++ b/lib/persistence/android_docs.dart @@ -0,0 +1,120 @@ +/// 安卓公共存储读写服务。 +/// +/// 通过原生通道(MainActivity 中的 `seqstudio/docs`)实现: +/// - Android 10+(API 29+)走 MediaStore,无需存储权限(应用商店合规); +/// - Android 9 及以下直接写公共目录(配合 maxSdkVersion=28 的权限声明)。 +/// +/// 保存位置可配置:基础目录(Documents / Download / Pictures)+ 子文件夹名, +/// 设置保存在应用私有目录的 `save_location.json`,跨会话生效。 +/// +/// 桌面平台不可用([isAvailable] 为 false),此时应使用应用内文件浏览器。 +library; + +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/services.dart'; + +import 'storage.dart'; + +/// 安卓公共存储读写。 +class AndroidDocs { + AndroidDocs._(); + + /// 原生通道。 + static const MethodChannel _channel = MethodChannel('seqstudio/docs'); + + /// 是否可用(仅 Android)。 + static bool get isAvailable => Platform.isAndroid; + + /// 可选的基础目录:文档 / 下载 / 图片。 + static const List baseOptions = ['documents', 'downloads', 'pictures']; + + /// 基础目录的展示名。 + static String baseLabel(String base) => switch (base) { + 'downloads' => 'Download', + 'pictures' => 'Pictures', + _ => 'Documents', + }; + + /// 当前配置(懒加载一次)。 + static Map _settings = {}; + + /// 设置文件(应用私有目录,不对外可见)。 + static File get _settingsFile => File( + '${Storage.instance.appDir.path}${Platform.pathSeparator}save_location.json'); + + /// 读取当前保存位置配置。 + static Map settings() { + if (_settings.isNotEmpty) return _settings; + try { + if (_settingsFile.existsSync()) { + final Map j = jsonDecode(_settingsFile.readAsStringSync()) as Map; + _settings = { + 'base': j['base'] as String? ?? 'documents', + 'folder': j['folder'] as String? ?? 'SequenceDiagram', + }; + } + } catch (_) {} + if (_settings.isEmpty) { + _settings = {'base': 'documents', 'folder': 'SequenceDiagram'}; + } + return _settings; + } + + /// 写入保存位置配置并立即生效。 + static Future saveSettings(String base, String folder) async { + _settings = { + 'base': baseOptions.contains(base) ? base : 'documents', + 'folder': folder.trim().isEmpty ? 'SequenceDiagram' : folder.trim(), + }; + try { + await _settingsFile.parent.create(recursive: true); + await _settingsFile.writeAsString(jsonEncode(_settings), flush: true); + } catch (_) {} + } + + /// 当前保存位置的展示描述(如 `Documents/SequenceDiagram`)。 + static String location() { + final Map s = settings(); + return '${baseLabel(s['base'] ?? 'documents')}/${s['folder'] ?? 'SequenceDiagram'}'; + } + + /// 保存文件到配置的公共目录,返回展示位置。 + static Future saveFile(String name, Uint8List data, {String? mime}) async { + final Map s = settings(); + final Object? r = await _channel.invokeMethod('saveFile', { + 'name': name, + 'data': data, + 'mime': mime, + 'base': s['base'], + 'folder': s['folder'], + }); + return r as String; + } + + /// 列出配置目录下的文件(`[{name, size}]`,新在前)。 + static Future>> listFiles() async { + final Map s = settings(); + final Object? r = await _channel.invokeMethod('listFiles', { + 'base': s['base'], + 'folder': s['folder'], + }); + final List list = (r as List?) ?? const []; + return list + .map((Object? e) => Map.from(e as Map)) + .toList(); + } + + /// 读取配置目录下的文件内容;不存在返回 null。 + static Future readFile(String name) async { + final Map s = settings(); + final Object? r = await _channel.invokeMethod('readFile', { + 'name': name, + 'base': s['base'], + 'folder': s['folder'], + }); + if (r == null) return null; + return r as Uint8List; + } +} diff --git a/lib/state/app_controller.dart b/lib/state/app_controller.dart index 202ccdd..a4268a1 100644 --- a/lib/state/app_controller.dart +++ b/lib/state/app_controller.dart @@ -288,6 +288,19 @@ class AppController extends ChangeNotifier { return true; } + /// 通过外部通道(如安卓公共 Documents)保存成功后标记为已保存。 + /// + /// [displayPath] 仅用于展示与状态栏;自动保存快照标记为干净, + /// 不写 .bak 备份(外部存储不经过 dart:io)。 + Future markSaved(String displayPath) async { + _filePath = displayPath; + _dirty = false; + _lastSavedAt = DateTime.now(); + _status = '已保存 ${_baseName(displayPath)}'; + await Storage.instance.writeAutosave(_project, projectPath: null, clean: true); + notifyListeners(); + } + /// 从完整路径中提取文件名(兼容 `\` 与 `/` 分隔符)。 static String _baseName(String p) => p.split(RegExp(r'[\\/]')).last; @@ -353,6 +366,22 @@ class AppController extends ChangeNotifier { zoomAt(factor, focal); } + /// 直接设置缩放与平移(双指捏合手势使用);缩放钳制到 [0.25, 4.0]。 + /// + /// 调用方按「捏合焦点锚定」自行计算 pan(见 CanvasView._onScaleUpdate), + /// 本方法只负责写入视图状态并通知。 + void setViewTransform({double? zoom, double? panX, double? panY}) { + final ViewState v = _project.viewState; + _project = _project.copyWith( + viewState: v.copyWith( + zoom: (zoom ?? v.zoom).clamp(0.25, 4.0), + panX: panX ?? v.panX, + panY: panY ?? v.panY, + ), + ); + notifyListeners(); + } + /// 按偏移量 [d] 平移视图。 void panBy(Offset d) { _project = _project.copyWith( diff --git a/lib/ui/app_shell.dart b/lib/ui/app_shell.dart index a19a201..713e993 100644 --- a/lib/ui/app_shell.dart +++ b/lib/ui/app_shell.dart @@ -8,17 +8,18 @@ // · 侧栏的“停靠 / 悬浮 / 收起为轨道”状态机; // · 自适应/紧凑工具栏布局(按可用宽度切换); // · 文件打开/保存/另存为与 SVG、PNG 导出流程。 +import 'dart:convert'; import 'dart:io'; import 'dart:math' as math; -import 'dart:ui' as ui; import 'package:flutter/material.dart' hide Action; -import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; +import '../export/export_renderer.dart'; import '../export/svg_writer.dart'; import '../model/models.dart'; import '../model/units.dart'; +import '../persistence/android_docs.dart'; import '../state/app_controller.dart'; import '../theme/tokens.dart'; import 'ai_dialog.dart'; @@ -43,9 +44,6 @@ class AppShell extends StatefulWidget { /// 应用外壳状态:维护左右侧栏的可见性、钉住与悬浮状态, /// 并提供文件操作、导出与快捷键处理。 class _AppShellState extends State { - /// 画布舞台的绘制边界 key,用于 PNG 导出时抓取像素。 - final GlobalKey _stageKey = GlobalKey(); - // ---- 侧栏状态机:可见(visible) × 钉住(pinned) × 悬停(hover) ---- /// 左侧栏是否可见。 bool _leftVisible = true; @@ -64,6 +62,18 @@ class _AppShellState extends State { AppController get c => widget.controller; // ---- 由上述三态派生的侧栏呈现方式 ---- + /// 左侧栏宽度:随屏幕宽度动态压缩(300 → 200),窄屏双侧栏停靠也不溢出。 + double get _leftPanelWidth { + final double w = MediaQuery.sizeOf(context).width; + return math.min(300.0, math.max(200.0, w * 0.24)); + } + + /// 右侧栏宽度:随屏幕宽度动态压缩(340 → 240),窄屏双侧栏停靠也不溢出。 + double get _rightPanelWidth { + final double w = MediaQuery.sizeOf(context).width; + return math.min(340.0, math.max(240.0, w * 0.26)); + } + /// 左侧栏是否处于停靠(固定)状态。 bool get _leftDocked => _leftVisible && _leftPinned; /// 右侧栏是否处于停靠(固定)状态。 @@ -84,6 +94,27 @@ class _AppShellState extends State { c.addListener(_onChange); } + /// 是否已完成一次按平台 / 屏幕宽度的默认布局初始化。 + bool _layoutInited = false; + + /// 首次构建时按平台与屏幕宽度设定侧栏默认状态(动态兼容不同分辨率): + /// - 触屏平台(Android / iOS):默认收起为贴边轨道,给画布让出完整宽度; + /// - 桌面窄窗口(< 1500 逻辑宽):同样默认收起,避免两侧栏挤占画布。 + @override + void didChangeDependencies() { + super.didChangeDependencies(); + if (_layoutInited) return; + _layoutInited = true; + final bool touch = Platform.isAndroid || Platform.isIOS; + final double w = MediaQuery.of(context).size.width; + if (touch || w < 1500) { + _leftVisible = false; + _rightVisible = false; + _leftPinned = false; + _rightPinned = false; + } + } + /// 取消订阅并释放资源。 @override void dispose() { @@ -117,6 +148,30 @@ class _AppShellState extends State { /// 打开项目:选择 .seq.json 文件并解码加载。 Future _open() async { + // 安卓版:从公共 Documents/SequenceDiagram 打开。 + if (AndroidDocs.isAvailable) { + final String? name = await showDialog( + context: context, + builder: (_) => const AndroidFileDialog( + saveMode: false, + defaultName: '', + suffix: '.seq.json', + ), + ); + if (name == null) return; + try { + final Uint8List? bytes = await AndroidDocs.readFile(name); + if (bytes == null) { + if (mounted) await showMessage(context, '打开失败', '未找到文件 $name'); + return; + } + c.loadProject(Project.decode(utf8.decode(bytes)), path: null); + c.setStatus('已打开 ${AndroidDocs.location()}/$name'); + } catch (e) { + if (mounted) await showMessage(context, '打开失败', '$e'); + } + return; + } final String? path = await pickFile(context, save: false, initialPath: c.filePath); if (path == null) return; try { @@ -129,16 +184,43 @@ class _AppShellState extends State { /// 保存项目:已有路径则直接保存,否则转入“另存为”。 Future _save() async { - if (c.filePath != null) { - await c.save(); + // 安卓版:始终走“另存为”(Documents 通道),避免把展示路径当真实路径写入。 + if (AndroidDocs.isAvailable || c.filePath == null) { + await _saveAs(); return; } - await _saveAs(); + await c.save(); } /// 另存为:选择目标路径后写入文件(同时生成 .bak 备份)。 Future _saveAs() async { - final String? path = await pickFile(context, save: true, initialPath: c.filePath); + // 安卓版:写入公共 Documents/SequenceDiagram(MediaStore 通道)。 + if (AndroidDocs.isAvailable) { + final String? name = await showDialog( + context: context, + builder: (_) => AndroidFileDialog( + saveMode: true, + defaultName: '${c.project.name}.seq.json', + suffix: '.seq.json', + ), + ); + if (name == null) return; + try { + final Uint8List data = Uint8List.fromList(utf8.encode(c.project.encode())); + await AndroidDocs.saveFile(name, data, mime: 'application/json'); + await c.markSaved('${AndroidDocs.location()}/$name'); + } catch (e) { + if (mounted) await showMessage(context, '保存失败', '$e'); + } + return; + } + final String? path = await pickFile( + context, + save: true, + initialPath: c.filePath, + defaultName: c.filePath == null ? '${c.project.name}.seq.json' : null, + suffix: '.seq.json', + ); if (path == null) return; try { await c.saveAs(path); @@ -154,40 +236,98 @@ class _AppShellState extends State { if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 SVG。'); return; } - final String? path = await pickFile(context, save: true, initialPath: c.filePath); + // 安卓版:写入公共 Documents/SequenceDiagram。 + if (AndroidDocs.isAvailable) { + final String? name = await showDialog( + context: context, + builder: (_) => AndroidFileDialog( + saveMode: true, + defaultName: '${c.project.name}.svg', + suffix: '.svg', + ), + ); + if (name == null) return; + try { + final String svg = SvgWriter( + project: c.project, + tokens: Tokens.of(c.brightness), + mode: c.project.viewState.mode, + ).build(); + await AndroidDocs.saveFile(name, Uint8List.fromList(utf8.encode(svg)), mime: 'image/svg+xml'); + if (mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name'); + } catch (e) { + if (mounted) await showMessage(context, '导出失败', '$e'); + } + return; + } + final String? path = await pickFile( + context, + save: true, + defaultName: '${c.project.name}.svg', + suffix: '.svg', + ); if (path == null) return; - final String svgPath = path.replaceAll(RegExp(r'\.json$'), '.svg'); try { final String svg = SvgWriter( project: c.project, tokens: Tokens.of(c.brightness), mode: c.project.viewState.mode, ).build(); - await File(svgPath).writeAsString(svg, flush: true); - if (mounted) c.setStatus('已导出 $svgPath'); + await File(path).writeAsString(svg, flush: true); + if (mounted) c.setStatus('已导出 $path'); } catch (e) { if (mounted) await showMessage(context, '导出失败', '$e'); } } - /// 导出 PNG:把画布舞台的 [RenderRepaintBoundary] 以 2 倍像素比 - /// 渲染为位图并写入文件。 + /// 导出 PNG:以固定 1920×1080 画布离屏渲染(标题固定左上、内容自适应缩放)。 Future _exportPng() async { if (!c.licensed) { if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 PNG。'); return; } - final String? path = await pickFile(context, save: true, initialPath: c.filePath); - if (path == null) return; - final String pngPath = path.replaceAll(RegExp(r'\.(json|svg)$'), '.png'); + final Uint8List bytes; try { - // 抓取画布舞台的渲染对象并转换为图像。 - final RenderRepaintBoundary boundary = - _stageKey.currentContext!.findRenderObject()! as RenderRepaintBoundary; - final ui.Image image = await boundary.toImage(pixelRatio: 2); - final ByteData? data = await image.toByteData(format: ui.ImageByteFormat.png); - await File(pngPath).writeAsBytes(data!.buffer.asUint8List(), flush: true); - if (mounted) c.setStatus('已导出 $pngPath'); + bytes = await renderExportPng( + project: c.project, + tokens: Tokens.of(c.brightness), + criticalActions: c.criticalActions, + criticalDeps: c.criticalDeps, + ); + } catch (e) { + if (mounted) await showMessage(context, '导出失败', '$e'); + return; + } + if (!mounted) return; + // 安卓版:写入配置的公共目录。 + if (AndroidDocs.isAvailable) { + final String? name = await showDialog( + context: context, + builder: (_) => AndroidFileDialog( + saveMode: true, + defaultName: '${c.project.name}.png', + suffix: '.png', + ), + ); + if (name == null) return; + try { + await AndroidDocs.saveFile(name, bytes, mime: 'image/png'); + if (mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name'); + } catch (e) { + if (mounted) await showMessage(context, '导出失败', '$e'); + } + return; + } + final String? path = await pickFile( + context, + save: true, + defaultName: '${c.project.name}.png', + suffix: '.png', + ); + if (path == null) return; + try { + await File(path).writeAsBytes(bytes, flush: true); + if (mounted) c.setStatus('已导出 $path'); } catch (e) { if (mounted) await showMessage(context, '导出失败', '$e'); } @@ -223,8 +363,13 @@ class _AppShellState extends State { backgroundColor: t.bg, body: Column( children: [ - // 顶部:自适应工具栏。 - _toolbar(t), + // 顶部:系统状态栏区域与工具栏同底色,内容在系统栏下方, + // 移动端实现真正的全屏(无黑边),桌面端 padding 为 0 无影响。 + Container( + color: t.chrome, + padding: EdgeInsets.only(top: MediaQuery.paddingOf(context).top), + child: _toolbar(t), + ), Expanded( child: Row( // 拉伸交叉轴:保证左右侧栏始终从工具栏一直贯通到底部状态栏。 @@ -236,36 +381,16 @@ class _AppShellState extends State { // 画布舞台:可绘制区域,叠加画布视图与浮层。 child: Stack( children: [ - // 导出边界:仅包含「时序图 + 标题」,不含编辑辅助浮层。 + // 底层:可交互的画布。 Positioned.fill( - child: RepaintBoundary( - key: _stageKey, - child: Stack( - children: [ - // 底层:可交互的画布。 - Positioned.fill( - child: Container(color: t.canvas2, child: CanvasView(controller: c)), - ), - // 仅标题(参与导出)。 - Positioned.fill( - child: CanvasOverlays( - controller: c, - leftInset: _leftRail ? 22 : 0, - rightInset: _rightRail ? 22 : 0, - showPanels: false, - ), - ), - ], - ), - ), + child: Container(color: t.canvas2, child: CanvasView(controller: c)), ), - // 编辑辅助浮层(图例 / 统计 / 工具 / 预览 / 浮动条):不参与导出。 + // 浮层:标题 / 图例 / 统计 / 工具 / 预览 / 浮动条。 Positioned.fill( child: CanvasOverlays( controller: c, leftInset: _leftRail ? 22 : 0, rightInset: _rightRail ? 22 : 0, - showTitle: false, ), ), // 收起状态:贴边轨道(悬停可展开为悬浮面板)。 @@ -286,8 +411,12 @@ class _AppShellState extends State { ], ), ), - // 底部:状态栏。 - _statusBar(t), + // 底部:系统导航栏区域与状态栏同底色,内容在系统栏上方。 + Container( + color: t.chrome, + padding: EdgeInsets.only(bottom: MediaQuery.paddingOf(context).bottom), + child: _statusBar(t), + ), ], ), ), @@ -733,10 +862,19 @@ class _AppShellState extends State { onTap: () => setState(() { if (left) { _leftVisible = true; - if (!_leftPinned) _leftHover = true; + if (Platform.isAndroid || Platform.isIOS) { + // 触屏平台:点把手直接停靠展开(无悬停概念)。 + _leftPinned = true; + } else if (!_leftPinned) { + _leftHover = true; + } } else { _rightVisible = true; - if (!_rightPinned) _rightHover = true; + if (Platform.isAndroid || Platform.isIOS) { + _rightPinned = true; + } else if (!_rightPinned) { + _rightHover = true; + } } }), child: Container( @@ -784,7 +922,7 @@ class _AppShellState extends State { Widget _leftPanel(Tokens t, {bool floating = false}) { final bool bar = c.project.viewState.mode == ViewMode.bar; return Container( - width: 300, + width: _leftPanelWidth, decoration: BoxDecoration( color: t.panel, border: floating ? Border.all(color: t.line2) : Border(right: BorderSide(color: t.line)), @@ -1073,15 +1211,22 @@ class _AppShellState extends State { ), ), const SizedBox(width: 6), - Column( - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - Text( - bar ? '${a0.toStringAsFixed(0)}° – ${math.min(a1, 360).toStringAsFixed(0)}°' : 'L${li + 1}', - style: TextStyle(color: t.sub, fontSize: 11), - ), - Text('${acts.length} 个动作', style: TextStyle(color: t.dim, fontSize: 10)), - ], + Flexible( + child: Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text( + bar ? '${a0.toStringAsFixed(0)}° – ${math.min(a1, 360).toStringAsFixed(0)}°' : 'L${li + 1}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.sub, fontSize: 11), + ), + Text('${acts.length} 个动作', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.dim, fontSize: 10)), + ], + ), ), const SizedBox(width: 6), InkWell( @@ -1156,18 +1301,24 @@ class _AppShellState extends State { ), ), const SizedBox(width: 6), - Column( - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - Text( - bar - ? '${a.startAngle.toStringAsFixed(0)}° – ${math.min(a.endAngle, 360).toStringAsFixed(0)}°' - : 'L${a.layer + 1}', - style: TextStyle(color: t.sub, fontSize: 10), - ), - Text(tfmt(a.durationAngle / 360 * c.project.cycle.durationMs, c.project.units), - style: TextStyle(color: t.dim, fontSize: 10)), - ], + Flexible( + child: Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text( + bar + ? '${a.startAngle.toStringAsFixed(0)}° – ${math.min(a.endAngle, 360).toStringAsFixed(0)}°' + : 'L${a.layer + 1}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.sub, fontSize: 10), + ), + Text(tfmt(a.durationAngle / 360 * c.project.cycle.durationMs, c.project.units), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.dim, fontSize: 10)), + ], + ), ), const SizedBox(width: 6), InkWell( @@ -1331,7 +1482,7 @@ class _AppShellState extends State { final Action? a = c.selected; final bool bar = c.project.viewState.mode == ViewMode.bar; return Container( - width: 340, + width: _rightPanelWidth, decoration: BoxDecoration( color: t.panel, border: floating ? Border.all(color: t.line2) : Border(left: BorderSide(color: t.line)), diff --git a/lib/ui/canvas_view.dart b/lib/ui/canvas_view.dart index 329be4d..d16cc81 100644 --- a/lib/ui/canvas_view.dart +++ b/lib/ui/canvas_view.dart @@ -76,6 +76,15 @@ class _CanvasViewState extends State { /// 目标泳道是否可放置(时间不重叠)。 bool _dropValid = true; + /// 是否处于双指捏合会话。 + bool _pinching = false; + + /// 捏合开始时的视图缩放。 + double _pinchStartZoom = 1; + + /// 捏合开始时的焦点(逻辑坐标),作为缩放锚点。 + Offset _pinchFocalLogical = Offset.zero; + /// 控制器快捷访问器。 AppController get c => widget.controller; @@ -291,8 +300,7 @@ class _CanvasViewState extends State { /// 拖拽开始:判断落点是否命中动作。 /// 条形视图下靠近动作右端 8px 视为“调整持续角”,否则为“平移相位”; /// 圆周视图下统一为“平移相位”。未命中则进入画布平移模式。 - void _onPanStart(DragStartDetails d, Size size) { - final Offset p = _toLogical(d.localPosition, size); + void _onPanStart(Offset p, Size size) { if (c.project.viewState.mode == ViewMode.bar) { final BarLayout layout = BarLayout(c.project, size); // 优先命中相位分区边界(位于图表顶部,不与动作条重叠)。 @@ -348,8 +356,8 @@ class _CanvasViewState extends State { /// 拖拽更新:未命中动作时平移画布;命中动作时根据模式与修饰键 /// 计算增量并写回控制器(调整持续角 / 改层 / 平移相位)。 - void _onPanUpdate(DragUpdateDetails d, Size size) { - final Offset p = _toLogical(d.localPosition, size); + /// [p] 为指针逻辑坐标,[screenDelta] 为指针在屏幕(未变换)空间的位移。 + void _onPanUpdate(Offset p, Offset screenDelta, Size size) { // 拖拽相位分区边界:按横坐标换算角度(结束角允许超过 360° 表示跨圈), // 并做「弱吸附」——靠近整 5°、动作端点或其它分区边界时自动贴合。 if (_zoneIndex >= 0) { @@ -362,7 +370,7 @@ class _CanvasViewState extends State { } // 未命中动作:整幅画布跟随指针平移。 if (_dragAction == null) { - c.panBy(d.delta); + c.panBy(screenDelta); return; } final bool shift = HardwareKeyboard.instance.isShiftPressed; @@ -430,7 +438,7 @@ class _CanvasViewState extends State { } /// 拖拽结束:重置拖拽会话状态。 - void _onPanEnd(DragEndDetails d) { + void _onPanEnd() { _mode = _DragMode.none; _dragAction = null; _zoneIndex = -1; @@ -438,6 +446,56 @@ class _CanvasViewState extends State { _dropLane = null; } + // ===================== 双指捏合缩放 / 平移 ===================== + + /// 进入捏合会话:记录起始缩放与逻辑焦点(作为缩放锚点)。 + void _beginPinch(Offset logicalFocal) { + _pinching = true; + _pinchStartZoom = c.project.viewState.zoom; + _pinchFocalLogical = logicalFocal; + _mode = _DragMode.none; + _dragAction = null; + _zoneIndex = -1; + _zoneGuideAngle = null; + _dropLane = null; + } + + /// 缩放手势开始:单指沿用既有拖拽逻辑,双指进入捏合。 + void _onScaleStart(ScaleStartDetails d, Size size) { + final Offset p = _toLogical(d.localFocalPoint, size); + if (d.pointerCount >= 2) { + _beginPinch(p); + } else { + _onPanStart(p, size); + } + } + + /// 缩放手势更新: + /// - 双指:以捏合焦点为锚点同时缩放与平移(焦点处内容跟随手指); + /// - 单指:沿用原拖拽逻辑(平移相位 / 改时长 / 平移画布)。 + void _onScaleUpdate(ScaleUpdateDetails d, Size size) { + final Offset p = _toLogical(d.localFocalPoint, size); + if (d.pointerCount >= 2) { + // 拖拽中途落下第二根手指:立即切换为捏合。 + if (!_pinching) _beginPinch(p); + final double z = (_pinchStartZoom * d.scale).clamp(0.25, 4.0); + // 锚点公式:screen = logical × zoom + pan → pan = screenFocal − logicalFocal × z。 + c.setViewTransform( + zoom: z, + panX: d.localFocalPoint.dx - _pinchFocalLogical.dx * z, + panY: d.localFocalPoint.dy - _pinchFocalLogical.dy * z, + ); + } else if (!_pinching) { + _onPanUpdate(p, d.focalPointDelta, size); + } + } + + /// 缩放手势结束:重置捏合与拖拽会话状态。 + void _onScaleEnd(ScaleEndDetails d) { + _pinching = false; + _onPanEnd(); + } + /// 滚轮:按住 Ctrl 时以指针方向缩放,否则按滚轮增量平移画布。 void _onScroll(PointerScrollEvent e, Size size) { if (HardwareKeyboard.instance.isControlPressed) { @@ -566,9 +624,10 @@ class _CanvasViewState extends State { behavior: HitTestBehavior.opaque, onTapDown: (TapDownDetails d) => _onTapDown(d, size), onDoubleTapDown: (TapDownDetails d) => _onDoubleTapDown(d, size), - onPanStart: (DragStartDetails d) => _onPanStart(d, size), - onPanUpdate: (DragUpdateDetails d) => _onPanUpdate(d, size), - onPanEnd: _onPanEnd, + // 单指拖拽编辑 / 双指捏合缩放平移:由缩放手势回调统一分发。 + onScaleStart: (ScaleStartDetails d) => _onScaleStart(d, size), + onScaleUpdate: (ScaleUpdateDetails d) => _onScaleUpdate(d, size), + onScaleEnd: _onScaleEnd, onSecondaryTapDown: (TapDownDetails d) => _contextMenu(d.globalPosition, size), // 裁剪到画布范围内,避免缩放/平移后内容溢出。 child: ClipRect( diff --git a/lib/ui/dialogs.dart b/lib/ui/dialogs.dart index c24edd0..913c6f6 100644 --- a/lib/ui/dialogs.dart +++ b/lib/ui/dialogs.dart @@ -14,6 +14,8 @@ import 'package:flutter/material.dart' hide Action; import '../license/license_service.dart'; import '../model/models.dart'; import '../model/units.dart'; +import '../persistence/android_docs.dart'; +import '../persistence/storage.dart'; import '../state/app_controller.dart'; import '../theme/tokens.dart'; @@ -66,15 +68,27 @@ Future showMessage(BuildContext context, String title, String message) { // ===================== 文件浏览 / 保存对话框 ===================== -/// 文件浏览对话框:用于打开或另存为 `.seq.json` 文件。 -/// [saveMode] 为 true 时进入保存流程,否则为打开流程。 +/// 文件浏览对话框:用于打开或另存为文件(工程 `.seq.json`、导出 `.svg` / `.png`)。 +/// +/// [saveMode] 为 true 时进入保存流程,否则为打开流程;[suffix] 决定文件过滤 +/// 与保存时自动补全的后缀;[defaultName] 为保存模式的默认文件名。 class FileBrowserDialog extends StatefulWidget { - const FileBrowserDialog({super.key, required this.saveMode, this.initialPath}); + const FileBrowserDialog({ + super.key, + required this.saveMode, + this.initialPath, + this.defaultName, + this.suffix = '.seq.json', + }); /// 是否为保存模式(true = 另存为,false = 打开)。 final bool saveMode; /// 初始目录或初始文件路径。 final String? initialPath; + /// 保存模式的默认文件名(如 `装配线节拍.svg`)。 + final String? defaultName; + /// 文件后缀:过滤目录列表并自动补全用户输入(如 `.svg` / `.png` / `.seq.json`)。 + final String suffix; /// 创建文件浏览对话框对应的状态对象。 @override @@ -87,39 +101,97 @@ class _FileBrowserDialogState extends State { late Directory _dir; /// 文件名输入控制器。 late TextEditingController _name; - /// 当前目录下的条目(子目录 + .json 文件)。 + /// 当前目录下的条目(子目录 + 匹配后缀的文件)。 List _entries = []; /// 读取目录失败时的错误信息。 String? _error; - /// 解析初始路径、初始化文件名,并首次刷新目录列表。 + /// 解析初始路径 / 上次目录 / 桌面,初始化文件名并刷新目录列表。 @override void initState() { super.initState(); - String start = widget.initialPath ?? ''; - if (start.isEmpty) { - start = Platform.environment['USERPROFILE'] ?? Directory.current.path; + final String base = widget.defaultName ?? + (widget.initialPath != null && widget.initialPath!.isNotEmpty + ? widget.initialPath!.split(RegExp(r'[\\/]')).last + : '节拍方案${widget.suffix}'); + _name = TextEditingController(text: base); + _bootstrap(); + } + + /// 异步确定起始目录:优先初始路径 → 上次使用的目录 → 桌面 → 用户目录。 + Future _bootstrap() async { + String start = ''; + if (widget.initialPath != null && widget.initialPath!.isNotEmpty) { + final File f = File(widget.initialPath!); + start = await f.exists() ? f.parent.path : widget.initialPath!; } - if (File(start).existsSync()) { - start = File(start).parent.path; + if (start.isEmpty || !Directory(start).existsSync()) { + start = await _readLastDir(); + } + if (start.isEmpty || !Directory(start).existsSync()) { + final Directory? desktop = _desktop(); + if (desktop != null) { + start = desktop.path; + } else { + start = Platform.environment['USERPROFILE'] ?? + (Platform.isAndroid || Platform.isIOS + ? Directory.systemTemp.path + : Directory.current.path); + } } _dir = Directory(start); if (!_dir.existsSync()) _dir = Directory.current; - final String base = widget.initialPath != null && widget.initialPath!.isNotEmpty - ? widget.initialPath!.split(RegExp(r'[\\/]')).last - : '节拍方案.seq.json'; - _name = TextEditingController(text: base); - _refresh(); + if (mounted) _refresh(); } - /// 重新读取当前目录:仅保留子目录与 .json 文件, + /// 上次使用目录的持久化文件路径(位于应用数据目录,跨会话记忆)。 + File get _lastDirFile => File( + '${Storage.instance.appDir.path}${Platform.pathSeparator}last_dir.txt'); + + /// 读取上次使用的目录;不存在或不可用时返回空串。 + Future _readLastDir() async { + try { + final File f = _lastDirFile; + if (await f.exists()) { + final String s = (await f.readAsString()).trim(); + if (s.isNotEmpty && Directory(s).existsSync()) return s; + } + } catch (_) {} + return ''; + } + + /// 记住本次使用的目录,便于下次直接定位。 + Future _writeLastDir(String path) async { + try { + final File f = _lastDirFile; + await f.parent.create(recursive: true); + await f.writeAsString(path, flush: true); + } catch (_) {} + } + + /// 规范化文件名:替换其它已知后缀并补全目标后缀。 + String _ensureSuffix(String raw) { + String n = raw.trim(); + if (n.isEmpty) return n; + const List known = ['.seq.json', '.json', '.svg', '.png']; + for (final String k in known) { + if (n.toLowerCase().endsWith(k)) { + if (k == widget.suffix) return n; + n = n.substring(0, n.length - k.length); + break; + } + } + return '$n${widget.suffix}'; + } + + /// 重新读取当前目录:仅保留子目录与匹配后缀的文件, /// 目录排在文件之前并按名称不区分大小写排序。 void _refresh() { try { final List all = _dir.listSync(); _entries = all.where((FileSystemEntity e) { if (e is Directory) return true; - return e.path.toLowerCase().endsWith('.json'); + return e.path.toLowerCase().endsWith(widget.suffix.toLowerCase()); }).toList() ..sort((FileSystemEntity a, FileSystemEntity b) { final bool ad = a is Directory; @@ -184,7 +256,7 @@ class _FileBrowserDialogState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(widget.saveMode ? '另存为 .seq.json' : '打开 .seq.json', + Text(widget.saveMode ? '保存 ${widget.suffix} 文件' : '打开 ${widget.suffix} 文件', style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: t.text)), const SizedBox(height: 10), Row( @@ -218,21 +290,22 @@ class _FileBrowserDialogState extends State { scrollDirection: Axis.horizontal, child: Row( children: [ - // 桌面快捷入口:导出 / 打开 / 保存时一键跳到桌面。 - Padding( - padding: const EdgeInsets.only(right: 6), - child: ActionChip( - avatar: Icon(Icons.desktop_windows_outlined, size: 15, color: t.accent), - label: const Text('桌面'), - onPressed: () { - final Directory? d = _desktop(); - if (d != null) { - _dir = d; - _refresh(); - } - }, + // 桌面快捷入口:仅在桌面平台显示(移动平台无“桌面”概念)。 + if (Platform.isWindows || Platform.isLinux || Platform.isMacOS) + Padding( + padding: const EdgeInsets.only(right: 6), + child: ActionChip( + avatar: Icon(Icons.desktop_windows_outlined, size: 15, color: t.accent), + label: const Text('桌面'), + onPressed: () { + final Directory? d = _desktop(); + if (d != null) { + _dir = d; + _refresh(); + } + }, + ), ), - ), ...drives.map((String d) { return Padding( padding: const EdgeInsets.only(right: 6), @@ -278,7 +351,7 @@ class _FileBrowserDialogState extends State { const Divider(), Row( children: [ - Text('文件名', style: TextStyle(color: t.sub, fontSize: 11)), + Text('文件名(${widget.suffix})', style: TextStyle(color: t.sub, fontSize: 11)), const SizedBox(width: 10), Expanded( child: TextField( @@ -288,6 +361,8 @@ class _FileBrowserDialogState extends State { isDense: true, filled: true, fillColor: t.panel2, + hintText: '名称${widget.suffix}', + hintStyle: TextStyle(color: t.dim, fontSize: 11), border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)), ), ), @@ -302,12 +377,13 @@ class _FileBrowserDialogState extends State { const SizedBox(width: 8), FilledButton( onPressed: () { - // 规范化文件名:空名忽略,缺少 .json 后缀时补全为 .seq.json。 - String name = _name.text.trim(); + // 规范化文件名:空名忽略;替换其它已知后缀并补全目标后缀。 + final String name = _ensureSuffix(_name.text); if (name.isEmpty) return; - if (!name.toLowerCase().endsWith('.json')) name = '$name.seq.json'; final String sep = Platform.pathSeparator; final String path = '${_dir.path}$sep$name'; + // 记住本次使用的目录,下次直接定位。 + _writeLastDir(_dir.path); Navigator.pop(context, path); }, child: Text(widget.saveMode ? '保存' : '打开'), @@ -322,14 +398,324 @@ class _FileBrowserDialogState extends State { } } -/// 打开文件选择对话框并返回所选路径;[save] 决定保存或打开模式。 -Future pickFile(BuildContext context, {required bool save, String? initialPath}) { +/// 打开文件选择对话框并返回所选路径。 +/// +/// [save] 决定保存或打开模式;[suffix] 决定文件过滤与自动补全的后缀 +/// (`.seq.json` / `.svg` / `.png`);[defaultName] 为保存模式的默认文件名。 +Future pickFile( + BuildContext context, { + required bool save, + String? initialPath, + String? defaultName, + String suffix = '.seq.json', +}) { return showDialog( context: context, - builder: (BuildContext ctx) => FileBrowserDialog(saveMode: save, initialPath: initialPath), + builder: (BuildContext ctx) => FileBrowserDialog( + saveMode: save, + initialPath: initialPath, + defaultName: defaultName, + suffix: suffix, + ), ); } +// ===================== 安卓公共 Documents 文件对话框 ===================== + +/// 保存位置设置:选择基础目录(文档 / 下载 / 图片)与子文件夹名。 +class SaveLocationDialog extends StatefulWidget { + const SaveLocationDialog({super.key}); + + @override + State createState() => _SaveLocationDialogState(); +} + +class _SaveLocationDialogState extends State { + late String _base; + late TextEditingController _folder; + + static String zh(String b) => switch (b) { + 'downloads' => '下载', + 'pictures' => '图片', + _ => '文档', + }; + + @override + void initState() { + super.initState(); + final Map s = AndroidDocs.settings(); + _base = s['base'] ?? 'documents'; + _folder = TextEditingController(text: s['folder'] ?? 'SequenceDiagram'); + } + + @override + void dispose() { + _folder.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final Tokens t = context.tok; + return AlertDialog( + backgroundColor: t.dialog, + title: const Text('保存位置'), + content: SizedBox( + width: 420, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('基础目录', style: TextStyle(color: t.sub, fontSize: 12)), + const SizedBox(height: 8), + Wrap( + spacing: 8, + children: AndroidDocs.baseOptions.map((String b) { + return ChoiceChip( + label: Text(zh(b)), + selected: _base == b, + onSelected: (_) => setState(() => _base = b), + ); + }).toList(), + ), + const SizedBox(height: 14), + Text('子文件夹名称', style: TextStyle(color: t.sub, fontSize: 12)), + const SizedBox(height: 8), + TextField( + controller: _folder, + style: TextStyle(color: t.text, fontSize: 12.5), + decoration: InputDecoration( + isDense: true, + filled: true, + fillColor: t.panel2, + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + const SizedBox(height: 10), + Text('保存、导出、打开都使用该目录;位于平板「文件管理」可见的公共存储。', + style: TextStyle(color: t.dim, fontSize: 11, height: 1.5)), + ], + ), + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')), + FilledButton( + onPressed: () async { + await AndroidDocs.saveSettings(_base, _folder.text); + if (context.mounted) Navigator.pop(context); + }, + child: const Text('确定'), + ), + ], + ); + } +} + +/// 安卓版文件对话框:保存到 / 打开自配置的公共目录(默认 Documents/SequenceDiagram)。 +/// +/// - 保存模式:显示当前保存位置(可点「更改位置」修改),输入文件名自动补全后缀; +/// - 打开模式:列出目录中匹配后缀的文件,点选返回文件名。 +/// 返回值为文件名;取消返回 null。 +class AndroidFileDialog extends StatefulWidget { + const AndroidFileDialog({ + super.key, + required this.saveMode, + required this.defaultName, + required this.suffix, + }); + + /// 保存(true)或打开(false)。 + final bool saveMode; + /// 保存模式的默认文件名。 + final String defaultName; + /// 文件后缀(过滤与自动补全)。 + final String suffix; + + @override + State createState() => _AndroidFileDialogState(); +} + +class _AndroidFileDialogState extends State { + late TextEditingController _name; + List> _files = >[]; + bool _loading = false; + String? _error; + + @override + void initState() { + super.initState(); + _name = TextEditingController(text: widget.defaultName); + if (!widget.saveMode) _load(); + } + + @override + void dispose() { + _name.dispose(); + super.dispose(); + } + + /// 列出配置目录中的匹配文件(新在前)。 + Future _load() async { + setState(() { + _loading = true; + _error = null; + }); + try { + final List> all = await AndroidDocs.listFiles(); + final String sfx = widget.suffix.toLowerCase(); + final List> matched = all + .where((Map f) => (f['name'] as String? ?? '').toLowerCase().endsWith(sfx)) + .toList(); + if (mounted) setState(() => _files = matched); + } catch (e) { + if (mounted) setState(() => _error = '无法读取目录:$e'); + } finally { + if (mounted) setState(() => _loading = false); + } + } + + /// 替换其它已知后缀并补全目标后缀。 + String _ensureSuffix(String raw) { + String n = raw.trim(); + if (n.isEmpty) return n; + const List known = ['.seq.json', '.json', '.svg', '.png']; + for (final String k in known) { + if (n.toLowerCase().endsWith(k)) { + if (k == widget.suffix) return n; + n = n.substring(0, n.length - k.length); + break; + } + } + return '$n${widget.suffix}'; + } + + /// 「更改位置」按钮:打开保存位置设置,返回后刷新本对话框。 + Future _changeLocation() async { + await showDialog(context: context, builder: (_) => const SaveLocationDialog()); + if (!mounted) return; + setState(() {}); + if (!widget.saveMode) _load(); + } + + /// 当前保存位置展示行。 + Widget _locationRow(Tokens t) { + return Row( + children: [ + Icon(Icons.folder_outlined, size: 15, color: t.accent), + const SizedBox(width: 6), + Expanded( + child: Text('平板存储 / ${AndroidDocs.location()} /', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.dim, fontSize: 11)), + ), + TextButton( + onPressed: _changeLocation, + style: TextButton.styleFrom( + padding: const EdgeInsets.symmetric(horizontal: 8), + minimumSize: const Size(0, 28), + ), + child: const Text('更改位置', style: TextStyle(fontSize: 12)), + ), + ], + ); + } + + @override + Widget build(BuildContext context) { + final Tokens t = context.tok; + return AlertDialog( + backgroundColor: t.dialog, + title: Text(widget.saveMode ? '保存到公共目录' : '从公共目录打开'), + content: SizedBox( + width: 460, + child: widget.saveMode + ? Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _locationRow(t), + const SizedBox(height: 10), + TextField( + controller: _name, + autofocus: true, + style: TextStyle(color: t.text, fontSize: 12.5), + decoration: InputDecoration( + isDense: true, + labelText: '文件名(${widget.suffix})', + filled: true, + fillColor: t.panel2, + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + ], + ) + : Column( + mainAxisSize: MainAxisSize.min, + children: [ + _locationRow(t), + const SizedBox(height: 6), + if (_loading) + const Padding( + padding: EdgeInsets.all(16), + child: Center(child: CircularProgressIndicator()), + ) + else if (_error != null) + Padding( + padding: const EdgeInsets.all(10), + child: Text(_error!, style: TextStyle(color: t.danger, fontSize: 11.5)), + ) + else if (_files.isEmpty) + Padding( + padding: const EdgeInsets.all(14), + child: Text('目录中暂无 ${widget.suffix} 文件', + style: TextStyle(color: t.dim, fontSize: 11.5)), + ) + else + Flexible( + child: ListView.builder( + shrinkWrap: true, + itemCount: _files.length, + itemBuilder: (BuildContext ctx, int i) { + final Map f = _files[i]; + final String name = f['name'] as String? ?? ''; + return ListTile( + dense: true, + leading: Icon(Icons.description, size: 20, color: t.sub), + title: Text(name, style: TextStyle(color: t.text, fontSize: 12)), + onTap: () => Navigator.pop(context, name), + ); + }, + ), + ), + ], + ), + ), + actions: widget.saveMode + ? [ + TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')), + FilledButton( + onPressed: () { + final String name = _ensureSuffix(_name.text); + if (name.isEmpty) return; + Navigator.pop(context, name); + }, + child: const Text('保存'), + ), + ] + : [ + TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')), + if (!_loading && _error == null) + TextButton.icon( + onPressed: _load, + icon: const Icon(Icons.refresh, size: 16), + label: const Text('刷新'), + ), + ], + ); + } +} + // ===================== 动作编辑对话框 ===================== /// 动作编辑对话框:修改选中动作的名称、驱动、工位、相位与颜色。 diff --git a/pubspec.lock b/pubspec.lock index d2970fb..18c1c36 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -260,10 +260,10 @@ packages: dependency: transitive description: name: vector_math - sha256: f36f9f3be64c6198714492bb455c11056e33e2f85d9a0b676a48301e44fdcf47 + sha256: "92b9910f66ed1057fd4da7b040ae7c74cafacf885bdc81be496928d5049b032d" url: "https://pub.flutter-io.cn" source: hosted - version: "2.4.2" + version: "2.4.3" vm_service: dependency: transitive description: diff --git a/test/export_test.dart b/test/export_test.dart new file mode 100644 index 0000000..b0f0f08 --- /dev/null +++ b/test/export_test.dart @@ -0,0 +1,53 @@ +// 导出回归测试:SVG / PNG 固定 1920×1080、标题恒定、内容自适应缩放。 +import 'dart:io'; +import 'dart:typed_data'; +import 'dart:ui' as ui; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:sequence_diagram/export/export_renderer.dart'; +import 'package:sequence_diagram/export/svg_writer.dart'; +import 'package:sequence_diagram/model/models.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; + +import 'helpers.dart'; + +void main() { + test('svg export: fixed 1920x1080 + white bg + title + fit transform + legend', () { + final Project p = demoTiming(); + final String svg = SvgWriter(project: p, tokens: Tokens.light, mode: ViewMode.bar).build(); + expect(svg, contains('width="1920" height="1080" viewBox="0 0 1920 1080"')); + expect(svg, contains('')); + expect(svg, contains('条形时序视图')); + expect(svg, contains('')); + expect(svg, contains('装配线节拍')); + // 背景纯白。 + expect(svg, contains('fill="#ffffff"')); + + final String circ = SvgWriter(project: p, tokens: Tokens.dark, mode: ViewMode.circular).build(); + expect(circ, contains('圆周时序视图')); + expect(circ, contains('width="1920" height="1080"')); + expect(circ, contains('fill="#ffffff"')); + }); + + test('png export: 3840x2160 pixels (2x) with pure white background', () async { + final Project p = demoTiming(); + final Uint8List bytes = await renderExportPng( + project: p, + tokens: Tokens.dark, + criticalActions: const {'A1', 'A2'}, + criticalDeps: const {'A1->A2'}, + ); + final ui.ImmutableBuffer buf = await ui.ImmutableBuffer.fromUint8List(bytes); + final ui.ImageDescriptor desc = await ui.ImageDescriptor.encoded(buf); + expect(desc.width, 3840); + expect(desc.height, 2160); + // 左上角像素应为纯白。 + final ui.Codec codec = await desc.instantiateCodec(); + final ui.FrameInfo frame = await codec.getNextFrame(); + final ByteData? rgba = await frame.image.toByteData(format: ui.ImageByteFormat.rawRgba); + final int first = rgba!.getUint32(0); + expect(first & 0xFFFFFF, 0xFFFFFF); + File('build/export_preview.png').writeAsBytesSync(bytes); + }); +} diff --git a/test/helpers.dart b/test/helpers.dart new file mode 100644 index 0000000..9096810 --- /dev/null +++ b/test/helpers.dart @@ -0,0 +1,59 @@ +// 测试辅助:构造演示工程与加载中文字体(用于平板布局测试与截图生成)。 +import 'dart:io'; + +import 'package:flutter/services.dart'; +import 'package:sequence_diagram/model/models.dart'; + +/// 构造一个动作较多、含依赖与相位分区的演示工程。 +Project demoTiming() { + return Project( + name: '装配线节拍', + cycle: const Cycle(durationMs: 2400), + stations: const [ + Station(id: 'ST1', name: '上料工位', order: 0, color: 0xFF4CC9F0), + Station(id: 'ST2', name: '加工工位', order: 1, color: 0xFFFFD166), + Station(id: 'ST3', name: '检测工位', order: 2, color: 0xFF34D399), + ], + actions: [ + const Action(id: 'A1', name: '上料', stationId: 'ST1', driver: '气缸 Y1', startAngle: 0, durationAngle: 45, layer: 0, color: 0xFF4CC9F0), + const Action(id: 'A2', name: '定位夹紧', stationId: 'ST1', driver: '气缸 Y2', startAngle: 50, durationAngle: 55, layer: 0, color: 0xFF7BD88F, + deps: [Dependency(fromId: 'A1', toId: 'A2', type: DepType.fs)]), + const Action(id: 'A3', name: '伺服下压', stationId: 'ST2', driver: '伺服 M1', startAngle: 90, durationAngle: 70, layer: 1, color: 0xFFFFD166, + deps: [Dependency(fromId: 'A2', toId: 'A3', type: DepType.fs)]), + const Action(id: 'A4', name: '超声焊接', stationId: 'ST2', driver: '超声 U1', startAngle: 100, durationAngle: 50, layer: 2, color: 0xFFF472B6, + deps: [Dependency(fromId: 'A3', toId: 'A4', type: DepType.ss, offsetAngle: 10)]), + const Action(id: 'A5', name: '视觉检测', stationId: 'ST3', driver: '相机 C1', startAngle: 160, durationAngle: 70, layer: 1, color: 0xFF7C5CFF, + deps: [Dependency(fromId: 'A4', toId: 'A5', type: DepType.fs)]), + const Action(id: 'A6', name: '分选下料', stationId: 'ST3', driver: '气缸 Y3', startAngle: 200, durationAngle: 70, layer: 2, color: 0xFFFF9F7C, + deps: [Dependency(fromId: 'A5', toId: 'A6', type: DepType.fs)]), + const Action(id: 'A7', name: '清洁吹气', stationId: 'ST1', driver: '电磁阀 V1', startAngle: 240, durationAngle: 80, layer: 3, color: 0xFF34D399, + deps: [Dependency(fromId: 'A6', toId: 'A7', type: DepType.fs)]), + ], + units: const UnitSettings(timeUnit: TimeUnit.s), + viewState: const ViewState(mode: ViewMode.bar), + phaseZones: const [ + PhaseZone(name: '上料相位', startAngle: 0, endAngle: 70), + PhaseZone(name: '加工相位', startAngle: 70, endAngle: 200), + PhaseZone(name: '检测相位', startAngle: 200, endAngle: 300), + PhaseZone(name: '下料相位', startAngle: 300, endAngle: 360), + ], + ); +} + +/// 从系统字体加载中文字体,使测试截图中的中文正常渲染。 +Future loadZhFonts() async { + const List candidates = [ + r'C:\Windows\Fonts\simhei.ttf', + r'C:\Windows\Fonts\msyh.ttf', + r'C:\Windows\Fonts\msyh.ttc', + r'C:\Windows\Fonts\simsun.ttc', + ]; + for (final String path in candidates) { + final File f = File(path); + if (!f.existsSync()) continue; + final ByteData bytes = ByteData.sublistView(await f.readAsBytes()); + final FontLoader loader = FontLoader('Microsoft YaHei UI')..addFont(Future.value(bytes)); + await loader.load(); + return; + } +} diff --git a/test/tablet_layout_test.dart b/test/tablet_layout_test.dart new file mode 100644 index 0000000..d443a28 --- /dev/null +++ b/test/tablet_layout_test.dart @@ -0,0 +1,79 @@ +// 平板/多分辨率布局回归测试:在多种分辨率、主题、视图模式下泵出整个外壳, +// 并展开/停靠侧栏,确保无溢出异常(RenderFlex overflow 会导致测试失败)。 +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:sequence_diagram/model/models.dart'; +import 'package:sequence_diagram/state/app_controller.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; +import 'package:sequence_diagram/ui/app_shell.dart'; + +import 'helpers.dart'; + +void main() { + const List<(String, Size, double)> cases = <(String, Size, double)>[ + ('tablet-landscape', Size(1280, 800), 1.0), + ('tablet-landscape-2x', Size(1280, 800), 2.0), // 物理 2560×1600 + ('wide-1920', Size(1920, 1080), 1.0), + ('small-960', Size(960, 600), 1.0), + ('phone-landscape-800', Size(800, 480), 1.0), + ('portrait-800x1280', Size(800, 1280), 1.0), + ('portrait-600x960', Size(600, 960), 1.0), + ]; + + for (final (String name, Size size, double dpr) in cases) { + testWidgets('layout @ $name ${size.width}x${size.height} dpr=$dpr 无溢出', (WidgetTester tester) async { + tester.view.physicalSize = size * dpr; + tester.view.devicePixelRatio = dpr; + addTearDown(tester.view.reset); + + final AppController c = AppController(project: demoTiming()); + addTearDown(c.dispose); + + await tester.pumpWidget(MaterialApp( + theme: buildTheme(Tokens.light), + home: AppShell(controller: c), + )); + await tester.pump(); + + // 条形视图:深浅主题各渲染一次。 + c.toggleTheme(); + await tester.pump(); + c.toggleTheme(); + await tester.pump(); + + // 展开左侧栏(浮层)并钉住(停靠,压缩画布宽度)。 + if (tester.any(find.byIcon(Icons.chevron_right))) { + await tester.tap(find.byIcon(Icons.chevron_right).first); + await tester.pump(); + } + if (tester.any(find.byIcon(Icons.push_pin_outlined))) { + await tester.tap(find.byIcon(Icons.push_pin_outlined).first); + await tester.pump(); + } + // 展开右侧栏(浮层)并钉住。 + if (tester.any(find.byIcon(Icons.chevron_left))) { + await tester.tap(find.byIcon(Icons.chevron_left).first); + await tester.pump(); + } + if (tester.any(find.byIcon(Icons.push_pin_outlined))) { + await tester.tap(find.byIcon(Icons.push_pin_outlined).first); + await tester.pump(); + } + + // 圆周视图 + 深色主题 + 缩放。 + c.setViewMode(ViewMode.circular); + await tester.pump(); + c.toggleTheme(); + await tester.pump(); + c.setZoom(1.4); + await tester.pump(); + + // 回到条形视图,选中一个动作(右侧栏渲染属性面板)。 + c.setViewMode(ViewMode.bar); + c.select('A3'); + await tester.pump(); + c.toggleTheme(); + await tester.pump(); + }); + } +} diff --git a/test/tablet_screenshots_test.dart b/test/tablet_screenshots_test.dart new file mode 100644 index 0000000..9ac0d79 --- /dev/null +++ b/test/tablet_screenshots_test.dart @@ -0,0 +1,67 @@ +// 平板版演示截图生成:把整个应用外壳在 1280×800(平板横屏基准)下渲染为 PNG。 +// 运行方式:flutter test --update-goldens test\tablet_screenshots_test.dart +// 输出:demo/tablet-*.png +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:sequence_diagram/model/models.dart'; +import 'package:sequence_diagram/state/app_controller.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; +import 'package:sequence_diagram/ui/app_shell.dart'; + +import 'helpers.dart'; + +void main() { + testWidgets('generate tablet demo screenshots', (WidgetTester tester) async { + await tester.runAsync(() => loadZhFonts()); + + tester.view.physicalSize = const Size(1280, 800); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + final AppController c = AppController(project: demoTiming()); + addTearDown(c.dispose); + + Widget shell(Tokens t) => RepaintBoundary( + key: const ValueKey('shot'), + child: MaterialApp( + theme: buildTheme(t), + home: AppShell(controller: c), + ), + ); + + Future shot(String path) async { + await tester.pump(); + await expectLater(find.byKey(const ValueKey('shot')), matchesGoldenFile(path)); + } + + await tester.pumpWidget(shell(Tokens.light)); + await shot('../demo/tablet-bar-light.png'); + + // 展开左右侧栏(浮层)并钉住,展示停靠布局。 + await tester.tap(find.byIcon(Icons.chevron_right).first); + await tester.pump(); + if (tester.any(find.byIcon(Icons.push_pin_outlined))) { + await tester.tap(find.byIcon(Icons.push_pin_outlined).first); + await tester.pump(); + } + await tester.tap(find.byIcon(Icons.chevron_left).first); + await tester.pump(); + if (tester.any(find.byIcon(Icons.push_pin_outlined))) { + await tester.tap(find.byIcon(Icons.push_pin_outlined).first); + await tester.pump(); + } + await shot('../demo/tablet-bar-light-panels.png'); + + // 圆周视图(浅色,含停靠侧栏)。 + c.setViewMode(ViewMode.circular); + await shot('../demo/tablet-circular-light.png'); + + // 深色主题:条形与圆周。 + c.toggleTheme(); + await tester.pumpWidget(shell(Tokens.dark)); + c.setViewMode(ViewMode.bar); + await shot('../demo/tablet-bar-dark.png'); + c.setViewMode(ViewMode.circular); + await shot('../demo/tablet-circular-dark.png'); + }); +} diff --git a/tools/gen-android-icons.py b/tools/gen-android-icons.py new file mode 100644 index 0000000..c75b339 --- /dev/null +++ b/tools/gen-android-icons.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +"""Generate Android launcher icons from the original "Cycle-Step" mark. + +Renders the same geometry as tools/gen-icon.py (gapped ring + step polyline ++ origin/terminal dots), full-bleed (no transparent inset) so the tile fills +the icon, at every Android launcher density. + +Outputs: + android/app/src/main/res/mipmap-*/ic_launcher.png +""" +import math +import os + +from PIL import Image, ImageDraw + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +RES = os.path.join(ROOT, "android", "app", "src", "main", "res") + +TILE_TOP = (24, 33, 61, 255) # #18213D +TILE_BOT = (12, 18, 38, 255) # #0C1226 +EDGE = (255, 255, 255, 38) +RING = (76, 201, 240, 255) # #4CC9F0 +STEP = (255, 209, 102, 255) # #FFD166 +ORIGIN = (255, 255, 255, 255) +END = (52, 211, 153, 255) # #34D399 + +DENSITIES = { + "mdpi": 48, + "hdpi": 72, + "xhdpi": 96, + "xxhdpi": 144, + "xxxhdpi": 192, +} + + +def lerp(a, b, t): + return tuple(round(a[i] + (b[i] - a[i]) * t) for i in range(4)) + + +def polar(cx, cy, r, deg): + t = math.radians(deg - 90) + return (cx + r * math.cos(t), cy + r * math.sin(t)) + + +def draw_ring(img, cx, cy, r_ring, ring_w, gap_deg, color, s): + outer = r_ring + ring_w / 2 + inner = r_ring - ring_w / 2 + mask = Image.new("L", (s, s), 0) + md = ImageDraw.Draw(mask) + md.ellipse([cx - outer, cy - outer, cx + outer, cy + outer], fill=255) + md.ellipse([cx - inner, cy - inner, cx + inner, cy + inner], fill=0) + a0 = polar(cx, cy, outer + 8, -90 - gap_deg / 2) + a1 = polar(cx, cy, outer + 8, -90 + gap_deg / 2) + md.polygon([(cx, cy), a0, a1], fill=0) + for deg in (-90 + gap_deg / 2, -90 - gap_deg / 2): + p = polar(cx, cy, r_ring, deg) + md.ellipse([p[0] - ring_w / 2, p[1] - ring_w / 2, + p[0] + ring_w / 2, p[1] + ring_w / 2], fill=255) + img.paste(color, (0, 0), mask) + + +def draw_steps(img, pts, width, color): + d = ImageDraw.Draw(img) + d.line(pts, fill=color, width=width, joint="curve") + for p in pts: + d.ellipse([p[0] - width / 2, p[1] - width / 2, + p[0] + width / 2, p[1] + width / 2], fill=color) + + +def build(s): + img = Image.new("RGBA", (s, s), (0, 0, 0, 0)) + body = Image.new("RGBA", (s, s), (0, 0, 0, 0)) + bd = ImageDraw.Draw(body) + for y in range(s): + bd.line([(0, y), (s, y)], fill=lerp(TILE_TOP, TILE_BOT, y / (s - 1))) + mask = Image.new("L", (s, s), 0) + ImageDraw.Draw(mask).rounded_rectangle([0, 0, s - 1, s - 1], radius=int(0.27 * s), fill=255) + img.paste(body, (0, 0), mask) + ImageDraw.Draw(img).rounded_rectangle([0, 0, s - 1, s - 1], radius=int(0.27 * s), outline=EDGE, width=max(1, s // 200)) + + cx = cy = s / 2.0 + r_ring = 0.293 * s + ring_w = (0.075 if s <= 48 else 0.062) * s + draw_ring(img, cx, cy, r_ring, ring_w, 68, RING, s) + + d = ImageDraw.Draw(img) + od = 0.045 * s + op = (cx, cy - r_ring) + d.ellipse([op[0] - od, op[1] - od, op[0] + od, op[1] + od], fill=ORIGIN) + + sw = (0.075 if s <= 48 else 0.057) * s + p1 = (cx - 0.146 * s, cy + 0.088 * s) + p2 = (cx - 0.010 * s, cy + 0.088 * s) + p3 = (cx - 0.010 * s, cy - 0.059 * s) + p4 = (cx + 0.166 * s, cy - 0.059 * s) + draw_steps(img, [p1, p2, p3, p4], int(sw), STEP) + + ed = (0.050 if s <= 48 else 0.037) * s + d.ellipse([p4[0] - ed, p4[1] - ed, p4[0] + ed, p4[1] + ed], fill=END) + return img + + +def main(): + for density, size in DENSITIES.items(): + out_dir = os.path.join(RES, "mipmap-%s" % density) + os.makedirs(out_dir, exist_ok=True) + out = os.path.join(out_dir, "ic_launcher.png") + build(size).save(out) + print("wrote", out) + + +if __name__ == "__main__": + main()