diff --git a/.github/workflows/flutter_mobile.yml b/.github/workflows/flutter_mobile.yml index f9aa0294..d744345a 100644 --- a/.github/workflows/flutter_mobile.yml +++ b/.github/workflows/flutter_mobile.yml @@ -76,28 +76,3 @@ jobs: with: name: android-release path: app/build/app/outputs/flutter-apk/app-release.apk - ios: - needs: markdown-update - if: ${{ !cancelled() && needs.markdown-update.outputs.skip != 'true' }} - runs-on: macos-15 - steps: - - uses: actions/checkout@v4 - - uses: subosito/flutter-action@v2 - with: - flutter-version: "3.47.5" - cache: true - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: "1.94.1" - targets: aarch64-apple-ios,aarch64-apple-ios-sim,x86_64-apple-ios - - run: flutter pub get && flutter build ios --simulator --debug - working-directory: app - - name: iOS 模拟器离线集成测试 - working-directory: app - run: | - DEVICE=$(xcrun simctl list devices available -j | python3 -c 'import json,sys; print(next(d["udid"] for devices in json.load(sys.stdin)["devices"].values() for d in devices if d["name"].startswith("iPhone")))') - xcrun simctl boot "$DEVICE" || true - xcrun simctl bootstatus "$DEVICE" -b - flutter test integration_test/mobile_engine_test.dart -d "$DEVICE" - - run: flutter build ios --release --no-codesign - working-directory: app diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e8c3481..e0836008 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## 未发布 +- 桌面更新恢复时,若系统拒绝退出,助手释放后会显示“重新启动”,可直接重试。Windows 在窗口启动和销毁期间也能处理系统字体通知,调试控制台只会重定向成功打开的输出流。 +- Android 更换 Activity 时会结束原宿主上的安装校验,离开前发出的权限请求不会在新宿主上触发安装。 +- 不完整的电路数学标签会随原文保留。整理 Markdown 时,原文中的私用区字符和已配对的行内代码会保留,前面单独出现的反引号不影响后面的代码段。化学式的非零分母无论长度都按原数字转写。实时预览开启时,文本整理完成后会自动生成整理后的草稿。 + +- 内部重构涵盖工作台的文本整理、设置、预览和主题,桌面更新助手,以及 Rust 引擎的文档提取、段落换行、字形绘制与导出。HTTP、移动端和 MCP 的请求处理与后台任务分别归入对应模块。物理公式参数、LaTeX 节点输出和 Markdown 表格分隔各有独立入口。HTTP 任务存储统一管理下载租约,直到最后一个下载响应释放才允许清理成品。 + - 纸张设置只在已上传底纸时显示「底纸拍摄设备」。展开填写后可继续向下滚动到页边距。 - MCP 续稿时可按节和评语来源筛选历史。用 `read_section(view="trajectory", section=2, feedback_origin="user_quote")` 可直接找回第 2 节记录的用户原话、关联版本和复盘 ID。轨迹支持用游标续读,翻页时补录的评语会在下一轮查询中出现。 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 10eb8680..6e2853af 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -34,3 +34,5 @@ cargo fmt --all -- --check cargo clippy --locked --workspace --all-targets -- -D warnings cargo test --locked --workspace ``` + +对比两个提交的 Dart 函数复杂度、嵌套与长度,可使用[仓库自带的 Dart 结构计量命令](scripts/dart-quality/README.md)。 diff --git a/app/android/app/build.gradle.kts b/app/android/app/build.gradle.kts index ebf57bf9..91946d8c 100644 --- a/app/android/app/build.gradle.kts +++ b/app/android/app/build.gradle.kts @@ -4,6 +4,13 @@ plugins { id("dev.flutter.flutter-gradle-plugin") } +// Package the same architectures that the Rust build supplies. +val engineAbis = when (project.findProperty("target-platform") as? String) { + "android-arm64" -> listOf("arm64-v8a") + "android-x64" -> listOf("x86_64") + else -> listOf("arm64-v8a", "x86_64") +} + android { namespace = "io.github.sxpsimon.handwriting" compileSdk = flutter.compileSdkVersion @@ -23,13 +30,7 @@ android { // Flutter configures ABI splits itself. Combining splits with ndk ABI // filters is rejected by the Android Gradle plugin. if (project.findProperty("split-per-abi") != "true") { - val platforms = (project.findProperty("target-platform") as? String).orEmpty() - val abis = when (platforms) { - "android-arm64" -> listOf("arm64-v8a") - "android-x64" -> listOf("x86_64") - else -> listOf("arm64-v8a", "x86_64") - } - ndk { abiFilters += abis } + ndk { abiFilters += engineAbis } } targetSdk = flutter.targetSdkVersion // Uses the version code from pubspec.yaml. When using split APKs, 1000 * ABI_VERSION @@ -89,11 +90,8 @@ dependencies { val buildMobileEngine by tasks.registering(Exec::class) { val repository = rootProject.projectDir.parentFile.parentFile val output = layout.buildDirectory.dir("rust-jni").get().asFile - val platforms = (project.findProperty("target-platform") as? String).orEmpty() - val abis = if (platforms == "android-arm64") "arm64-v8a" - else if (platforms == "android-x64") "x86_64" else "arm64-v8a,x86_64" commandLine(if (System.getProperty("os.name").startsWith("Windows")) "python" else "python3", repository.resolve("scripts/build-mobile-engine.py"), "android", - "--ndk", android.ndkDirectory, "--output", output, "--abis", abis) + "--ndk", android.ndkDirectory, "--output", output, "--abis", engineAbis.joinToString(",")) } tasks.named("preBuild") { dependsOn(buildMobileEngine) } diff --git a/app/android/app/src/main/java/io/github/sxpsimon/handwriting/ApkInstallSession.java b/app/android/app/src/main/java/io/github/sxpsimon/handwriting/ApkInstallSession.java new file mode 100644 index 00000000..7777f81d --- /dev/null +++ b/app/android/app/src/main/java/io/github/sxpsimon/handwriting/ApkInstallSession.java @@ -0,0 +1,61 @@ +package io.github.sxpsimon.handwriting; + +import java.io.File; +import java.util.concurrent.Callable; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; + +/** Verification and settings round-trips for one attachment. Host entry points run on the UI thread. */ +final class ApkInstallSession implements AutoCloseable { + private static final AtomicInteger NEXT_PERMISSION_CODE = new AtomicInteger(7821); + private final ExecutorService worker = Executors.newSingleThreadExecutor(); + private final Executor ui; + private int permissionCode = -1; + + ApkInstallSession(Executor ui) { + this.ui = ui; + } + + void verify(Callable validate, Consumer install, Consumer fail) { + worker.execute(() -> { + final File file; + try { + file = validate.call(); + } catch (Exception error) { + ui.execute(() -> { + if (!worker.isShutdown()) fail.accept(error); + }); + return; + } + ui.execute(() -> { + if (worker.isShutdown()) return; + try { + install.accept(file); + } catch (Exception error) { + fail.accept(error); + } + }); + }); + } + + int beginPermissionRequest() { + // A replacement Activity can receive the result of the previous Activity's settings request. + permissionCode = NEXT_PERMISSION_CODE.getAndIncrement() & 0xffff; + return permissionCode; + } + + boolean consumePermissionResult(int code) { + if (permissionCode < 0 || code != permissionCode) return false; + permissionCode = -1; + return true; + } + + @Override + public void close() { + permissionCode = -1; + worker.shutdownNow(); + } +} diff --git a/app/android/app/src/main/kotlin/io/github/sxpsimon/handwriting/MainActivity.kt b/app/android/app/src/main/kotlin/io/github/sxpsimon/handwriting/MainActivity.kt index 20dd1d4f..80255692 100644 --- a/app/android/app/src/main/kotlin/io/github/sxpsimon/handwriting/MainActivity.kt +++ b/app/android/app/src/main/kotlin/io/github/sxpsimon/handwriting/MainActivity.kt @@ -10,24 +10,30 @@ import android.provider.Settings import androidx.core.content.FileProvider import java.io.File import java.security.MessageDigest -import java.util.concurrent.Executors import java.net.ProxySelector import java.net.Proxy import java.net.URI import java.net.InetSocketAddress class MainActivity : FlutterActivity() { - private var pending: MethodChannel.Result? = null - private var pendingPath: String? = null - private var pendingBuild: Long = 0 - private var pendingHash: String? = null - private val verifier = Executors.newSingleThreadExecutor() - private val permissionRequest = 7821 + private class InstallRequest( + val result: MethodChannel.Result, val path: String?, val build: Long, val hash: String? + ) + private var pending: InstallRequest? = null + private var updates: MethodChannel? = null + private lateinit var installSession: ApkInstallSession override fun configureFlutterEngine(flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) - MethodChannel(flutterEngine.dartExecutor.binaryMessenger, - "io.github.sxpsimon.panache/updates").setMethodCallHandler { call, result -> + installSession = ApkInstallSession { task -> runOnUiThread(task) } + val channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, + "io.github.sxpsimon.panache/updates") + updates = channel + channel.setMethodCallHandler { call, result -> + if (updates !== channel) { + result.error("install_unavailable", "Activity detached", null) + return@setMethodCallHandler + } when (call.method) { "supportedAbis" -> result.success(Build.SUPPORTED_ABIS.toList()) "cacheDirectory" -> result.success(File(cacheDir, "updates").absolutePath) @@ -43,10 +49,8 @@ class MainActivity : FlutterActivity() { if (pending != null) { result.error("busy", "An installation request is already open", null) } else { - pending = result - pendingPath = call.argument("path") - pendingBuild = call.argument("buildNumber")?.toLong() ?: 0 - pendingHash = call.argument("sha256") + pending = InstallRequest(result, call.argument("path"), + call.argument("buildNumber")?.toLong() ?: 0, call.argument("sha256")) verifyAndInstall(true) } } @@ -55,47 +59,53 @@ class MainActivity : FlutterActivity() { } } + override fun cleanUpFlutterEngine(flutterEngine: FlutterEngine) { + updates?.setMethodCallHandler(null) + updates = null + installSession.close() + val result = pending?.result + pending = null + result?.error("install_unavailable", "Activity detached", null) + super.cleanUpFlutterEngine(flutterEngine) + } + @Suppress("DEPRECATION") - private fun validateApk(): File { + private fun validateApk(request: InstallRequest): File { val root = File(cacheDir, "updates").canonicalFile - val file = File(pendingPath ?: "").canonicalFile + val file = File(request.path ?: "").canonicalFile require(file.parentFile?.parentFile == root && file.parentFile?.name?.startsWith("download-") == true && file.isFile && file.extension == "apk") val hash = MessageDigest.getInstance("SHA-256") file.inputStream().use { stream -> val buffer = ByteArray(65536) while (true) { + if (Thread.currentThread().isInterrupted) throw InterruptedException("Activity detached") val count = stream.read(buffer) if (count < 0) break hash.update(buffer, 0, count) } } - require(hash.digest().joinToString("") { "%02x".format(it) } == pendingHash) + require(hash.digest().joinToString("") { "%02x".format(it) } == request.hash) val archive = packageManager.getPackageArchiveInfo(file.path, 0) ?: error("Cannot read APK") val current = packageManager.getPackageInfo(packageName, 0) val archiveVersion = if (Build.VERSION.SDK_INT >= 28) archive.longVersionCode else archive.versionCode.toLong() val currentVersion = if (Build.VERSION.SDK_INT >= 28) current.longVersionCode else current.versionCode.toLong() - require(archive.packageName == packageName && archiveVersion == pendingBuild && archiveVersion > currentVersion) + require(archive.packageName == packageName && archiveVersion == request.build && archiveVersion > currentVersion) return file } private fun verifyAndInstall(allowPermissionRequest: Boolean) { - verifier.execute { - try { - val file = validateApk() - runOnUiThread { - try { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && - !packageManager.canRequestPackageInstalls()) { - check(allowPermissionRequest) { "Installation permission was not granted" } - startActivityForResult(Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, - Uri.parse("package:$packageName")), permissionRequest) - } else launchInstaller(file) - } catch (error: Exception) { fail(error) } - } - } catch (error: Exception) { runOnUiThread { fail(error) } } - } + val request = pending ?: return + installSession.verify({ validateApk(request) }, onVerified@{ file -> + if (pending !== request) return@onVerified + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && + !packageManager.canRequestPackageInstalls()) { + check(allowPermissionRequest) { "Installation permission was not granted" } + startActivityForResult(Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, + Uri.parse("package:$packageName")), installSession.beginPermissionRequest()) + } else launchInstaller(file) + }, { error -> if (pending === request) fail(error) }) } private fun launchInstaller(file: File) { @@ -108,21 +118,21 @@ class MainActivity : FlutterActivity() { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION) } startActivity(intent) - pending?.success(null) + val result = pending?.result pending = null - pendingPath = null + result?.success(null) } private fun fail(error: Exception) { - pending?.error("install_unavailable", error.message, null) + val result = pending?.result pending = null - pendingPath = null + result?.error("install_unavailable", error.message, null) } @Deprecated("Android activity permission flow still delivers this callback") override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) - if (requestCode != permissionRequest || pending == null) return + if (pending == null || !installSession.consumePermissionResult(requestCode)) return verifyAndInstall(false) } } diff --git a/app/lib/models/detected_paper_layout.dart b/app/lib/models/detected_paper_layout.dart new file mode 100644 index 00000000..c9045fbb --- /dev/null +++ b/app/lib/models/detected_paper_layout.dart @@ -0,0 +1,95 @@ +/// Writing lines and margins in the detector's pixel coordinates. +class DetectedPaperLayout { + const DetectedPaperLayout._({ + required this.left, + required this.right, + required this.top, + required this.bottom, + required this.spacing, + required this.size, + }); + + final int left, right, top, bottom, spacing; + final ({int width, int height})? size; + + factory DetectedPaperLayout.fromJson(Map result) { + int number(String key, {int? fallback, bool positive = false}) { + final value = result[key] ?? fallback; + if (value is! num || + !value.isFinite || + value < (positive ? 1 : 0) || + value > 100000) { + throw const FormatException('Invalid paper identification'); + } + return value.round(); + } + + final spacing = number('lineSpacing', positive: true); + final first = number('marginTop'); + final top = number( + 'layoutTopMargin', + fallback: first >= spacing ? first - spacing : first, + ); + final bottom = number( + 'layoutBottomMargin', + fallback: number('marginBottom'), + ); + final left = number('marginLeft'); + final right = number('marginRight'); + final width = result.containsKey('imageWidth') + ? number('imageWidth', positive: true) + : null; + final height = result.containsKey('imageHeight') + ? number('imageHeight', positive: true) + : null; + if ((width == null) != (height == null) || + (width != null && + height != null && + (left + right >= width || top + bottom + spacing >= height))) { + throw const FormatException('Invalid paper dimensions'); + } + return DetectedPaperLayout._( + left: left, + right: right, + top: top, + bottom: bottom, + spacing: spacing, + size: width != null && height != null + ? (width: width, height: height) + : null, + ); + } + + /// A corrected image can be downsampled independently on each axis. + DetectedPaperLayout scaledTo(int width, int height) { + final original = size!; + if (width == original.width && height == original.height) return this; + final horizontal = width / original.width; + final vertical = height / original.height; + return DetectedPaperLayout._( + left: (left * horizontal).round(), + right: (right * horizontal).round(), + top: (top * vertical).round(), + bottom: (bottom * vertical).round(), + spacing: (spacing * vertical).round().clamp(1, height), + size: (width: width, height: height), + ); + } + + Map settings(String? currentFontSize) { + final fontSize = num.tryParse(currentFontSize ?? ''); + return { + if (fontSize != null && fontSize >= spacing) + 'font_size': '${(spacing * 0.72).round().clamp(1, 100000)}', + 'left_margin': '$left', + 'right_margin': '$right', + 'top_margin': '$top', + 'bottom_margin': '$bottom', + 'line_spacing': '$spacing', + if (size case final dimensions?) ...{ + 'width': '${dimensions.width}', + 'height': '${dimensions.height}', + }, + }; + } +} diff --git a/app/lib/models/engine_failure.dart b/app/lib/models/engine_failure.dart index fc3bd720..49528d74 100644 --- a/app/lib/models/engine_failure.dart +++ b/app/lib/models/engine_failure.dart @@ -8,3 +8,10 @@ class EngineFailure implements Exception { @override String toString() => message; } + +class ApiException extends EngineFailure { + ApiException(super.message, {this.status, int? waitSeconds, super.code}) + : super(retryAfterSeconds: waitSeconds); + final int? status; + int? get waitSeconds => retryAfterSeconds; +} diff --git a/app/lib/models/fine_edit.dart b/app/lib/models/fine_edit.dart index 987c61e7..d501f90d 100644 --- a/app/lib/models/fine_edit.dart +++ b/app/lib/models/fine_edit.dart @@ -125,65 +125,19 @@ bool _validKey(String key) => RegExp(r'^[0-9a-f]{64}$').hasMatch(key); class FineEdits { FineEdits(this.key, Map glyphs) : glyphs = Map.unmodifiable(glyphs); + static const maxGlyphs = 10000; final String key; final Map glyphs; factory FineEdits.fromJson(Map json) { final key = json['key'] as String; final data = json['glyphs'] as List; - if (!_validKey(key) || data.length > 10000) { + if (!_validKey(key) || data.length > maxGlyphs) { throw const FormatException('Invalid fine edits'); } final result = {}; for (final row in data) { - final value = row as Map; - final rgb = value['color'] as List?; - if (rgb != null && - (rgb.length != 3 || rgb.any((c) => c is! int || c < 0 || c > 255))) { - throw const FormatException('Invalid fine edit color'); - } - final rawWarp = value['warp']; - if (rawWarp != null && - (rawWarp is! List || - rawWarp.length != 8 || - rawWarp.any( - (v) => v is! num || !v.isFinite || v.abs() > 65535, - ))) { - throw const FormatException('Invalid fine edit transform'); - } - final edit = ( - id: value['id'] as int, - dx: value['dx'] as int, - dy: value['dy'] as int, - scale: value['scale'] as int, - angle: value['angle'] as int, - opacity: value['opacity'] as int, - thickness: value['thickness'] as int? ?? 0, - softness: value['softness'] as int? ?? 0, - warp: rawWarp == null - ? null - : readWarp( - (rawWarp as List).map((v) => (v as num).toDouble()).toList(), - ), - color: rgb == null - ? null - : 0xff000000 + - (rgb[0] as int) * 65536 + - (rgb[1] as int) * 256 + - (rgb[2] as int), - ); - if (edit.id < 0 || - edit.dx.abs() > 65535 || - edit.dy.abs() > 65535 || - edit.scale < 50 || - edit.scale > 200 || - edit.angle.abs() > 45 || - edit.opacity < 0 || - edit.opacity > 100 || - edit.thickness.abs() > 20 || - edit.softness.abs() > 20) { - throw const FormatException('Invalid fine adjustment'); - } + final edit = _readAdjustment(row as Map); result[edit.id] = edit; } return FineEdits(key, result); @@ -214,3 +168,54 @@ class FineEdits { ], }; } + +FineAdjustment _readAdjustment(Map value) { + final color = _readColor(value['color'] as List?); + final warp = _readWarp(value['warp']); + final edit = ( + id: value['id'] as int, + dx: value['dx'] as int, + dy: value['dy'] as int, + scale: value['scale'] as int, + angle: value['angle'] as int, + opacity: value['opacity'] as int, + thickness: value['thickness'] as int? ?? 0, + softness: value['softness'] as int? ?? 0, + warp: warp, + color: color, + ); + if (edit.id < 0 || + edit.dx.abs() > 65535 || + edit.dy.abs() > 65535 || + edit.scale < 50 || + edit.scale > 200 || + edit.angle.abs() > 45 || + edit.opacity < 0 || + edit.opacity > 100 || + edit.thickness.abs() > 20 || + edit.softness.abs() > 20) { + throw const FormatException('Invalid fine adjustment'); + } + return edit; +} + +int? _readColor(List? rgb) { + if (rgb == null) return null; + if (rgb.length != 3 || rgb.any((c) => c is! int || c < 0 || c > 255)) { + throw const FormatException('Invalid fine edit color'); + } + return 0xff000000 + + (rgb[0] as int) * 65536 + + (rgb[1] as int) * 256 + + (rgb[2] as int); +} + +FineWarp? _readWarp(Object? value) { + if (value == null) return null; + if (value is! List || + value.length != 8 || + value.any((v) => v is! num || !v.isFinite || v.abs() > 65535)) { + throw const FormatException('Invalid fine edit transform'); + } + return readWarp(value.map((v) => (v as num).toDouble()).toList()); +} diff --git a/app/lib/models/fine_edit_history.dart b/app/lib/models/fine_edit_history.dart new file mode 100644 index 00000000..963ac89f --- /dev/null +++ b/app/lib/models/fine_edit_history.dart @@ -0,0 +1,64 @@ +import 'fine_edit.dart'; + +/// Glyph adjustments for a rendered layout and the draft text that produced it. +class FineEditHistory { + String? _text; + FineEdits? _current; + final _undo = []; + final _redo = []; + + FineEdits? forText(String text) => _text == text ? _current : null; + + Map adjustmentsFor(String key) => + _current?.key == key ? _current!.glyphs : const {}; + + bool restore(String text, Map json) { + try { + _current = FineEdits.fromJson(json); + _text = text; + return true; + } on FormatException { + _current = null; + } on TypeError { + _current = null; + } + return false; + } + + bool apply(String text, String key, List changes) { + final saved = forText(text); + final previous = saved?.key == key ? saved : null; + final next = {...?previous?.glyphs}; + var changed = false; + for (final value in changes) { + if (value == defaultFineAdjustment(value.id)) { + if (next.remove(value.id) != null) changed = true; + } else if (next[value.id] != value) { + next[value.id] = value; + changed = true; + } + } + if (!changed || next.length > FineEdits.maxGlyphs) return false; + if (previous == null && _current != null) _undo.clear(); + if (_undo.length >= 50) _undo.removeAt(0); + _undo.add(previous); + _redo.clear(); + _text = text; + _current = FineEdits(key, next); + return true; + } + + bool canStep(String text, String? key, {required bool redo}) => + key != null && + forText(text)?.key == key && + (redo ? _redo : _undo).isNotEmpty; + + bool step(String text, String? key, {required bool redo}) { + if (!canStep(text, key, redo: redo)) return false; + final from = redo ? _redo : _undo; + final to = redo ? _undo : _redo; + to.add(_current); + _current = from.removeLast() ?? FineEdits(_current!.key, const {}); + return true; + } +} diff --git a/app/lib/models/render_parameter.dart b/app/lib/models/render_parameter.dart new file mode 100644 index 00000000..8d965d41 --- /dev/null +++ b/app/lib/models/render_parameter.dart @@ -0,0 +1,145 @@ +const latinFonts = { + 'handlee': 'Handlee', + 'patrick_hand': 'Patrick Hand', + 'indie_flower': 'Indie Flower', + 'kalam': 'Kalam', + 'shadows_into_light': 'Shadows Into Light', +}; + +const latinScaleParameter = Parameter( + 'latin_font_scale', + '英文字号比例', + 'English font scale', + 100, + minimum: 50, + maximum: 150, +); + +class Parameter { + const Parameter( + this.key, + this.zh, + this.en, + this.value, { + this.minimum = 0, + this.maximum, + }); + final String key, zh, en; + final num value, minimum; + final num? maximum; + bool get integer => + !key.startsWith('strikethrough_') && + key != 'ink_depth_sigma' && + key != 'perturb_theta_sigma' && + !fractionalInk; + bool get fractionalInk => key == 'ink_thickness' || key == 'ink_softness'; + bool accepts(String? raw) { + final n = num.tryParse(raw ?? ''); + return n != null && + n.isFinite && + n >= minimum && + (maximum == null || n <= maximum!) && + (!fractionalInk || n * 10 == (n * 10).round()) && + (!integer || (n == n.roundToDouble() && !raw!.contains('.'))); + } + + /// Drafts from older versions may contain decimal values for integer fields. + String? valueFromDraft(Object? raw) { + final number = num.tryParse('$raw'); + if (number == null || + !number.isFinite || + number < minimum || + (maximum != null && number > maximum!) || + (fractionalInk && !accepts('$number'))) { + return null; + } + return integer ? '${number.toInt()}' : '$number'; + } +} + +const inkParameters = [ + Parameter('ink_opacity', '浓淡', 'Opacity', 100, maximum: 100), + Parameter( + 'ink_thickness', + '笔画粗细', + 'Stroke thickness', + 0, + minimum: -2, + maximum: 2, + ), + Parameter('ink_softness', '边缘柔化', 'Edge softness', 0, maximum: 2), +]; + +const parameters = [ + Parameter('font_size', '字号', 'Font size', 124, minimum: 1), + Parameter('line_spacing', '行距', 'Line spacing', 200, minimum: 1), + Parameter('word_spacing', '字间距', 'Character spacing', 1), + Parameter('width', '纸张宽度', 'Page width', 2481, minimum: 1), + Parameter('height', '纸张高度', 'Page height', 3507, minimum: 1), + Parameter('top_margin', '上边距', 'Top margin', 50), + Parameter('bottom_margin', '下边距', 'Bottom margin', 50), + Parameter('left_margin', '左边距', 'Left margin', 50), + Parameter('right_margin', '右边距', 'Right margin', 50), + Parameter('line_spacing_sigma', '行距扰动', 'Line spacing variation', 0), + Parameter('font_size_sigma', '字号扰动', 'Font size variation', 2), + Parameter('word_spacing_sigma', '字距扰动', 'Character spacing variation', 2), + Parameter('perturb_x_sigma', '水平扰动', 'Horizontal variation', 3), + Parameter('perturb_y_sigma', '垂直扰动', 'Vertical variation', 3), + Parameter( + 'perturb_theta_sigma', + '旋转扰动(弧度)', + 'Rotation variation (radians)', + .05, + ), + Parameter('ink_depth_sigma', '墨色扰动', 'Ink variation', 30), + Parameter( + 'strikethrough_probability', + '删除线概率', + 'Strikethrough probability', + .005, + maximum: 1, + ), + Parameter('strikethrough_width', '删除线宽度', 'Strikethrough width', 8), + Parameter( + 'strikethrough_length_sigma', + '删除线长度扰动', + 'Strikethrough length variation', + 2, + ), + Parameter( + 'strikethrough_width_sigma', + '删除线宽度扰动', + 'Strikethrough width variation', + 2, + ), + Parameter( + 'strikethrough_angle_sigma', + '删除线角度扰动', + 'Strikethrough angle variation', + 2, + ), +]; + +const legacyFields = { + 'fontSize': 'font_size', + 'lineSpacing': 'line_spacing', + 'wordSpacing': 'word_spacing', + 'marginTop': 'top_margin', + 'marginBottom': 'bottom_margin', + 'marginLeft': 'left_margin', + 'marginRight': 'right_margin', + 'lineSpacingSigma': 'line_spacing_sigma', + 'fontSizeSigma': 'font_size_sigma', + 'wordSpacingSigma': 'word_spacing_sigma', + 'perturbXSigma': 'perturb_x_sigma', + 'perturbYSigma': 'perturb_y_sigma', + 'perturbThetaSigma': 'perturb_theta_sigma', + 'width': 'width', + 'height': 'height', + 'ink_depth_sigma': 'ink_depth_sigma', + 'strikethrough_probability': 'strikethrough_probability', + 'strikethrough_width': 'strikethrough_width', + 'strikethrough_length_sigma': 'strikethrough_length_sigma', + 'strikethrough_width_sigma': 'strikethrough_width_sigma', + 'strikethrough_angle_sigma': 'strikethrough_angle_sigma', +}; diff --git a/app/lib/models/settings.dart b/app/lib/models/settings.dart index 58e77514..15b0a004 100644 --- a/app/lib/models/settings.dart +++ b/app/lib/models/settings.dart @@ -1,139 +1,9 @@ import 'ink_page.dart'; +import 'render_parameter.dart'; -enum PaperStyle { blank, ruled, grid, dots } - -const latinFonts = { - 'handlee': 'Handlee', - 'patrick_hand': 'Patrick Hand', - 'indie_flower': 'Indie Flower', - 'kalam': 'Kalam', - 'shadows_into_light': 'Shadows Into Light', -}; - -const latinScaleParameter = Parameter( - 'latin_font_scale', - '英文字号比例', - 'English font scale', - 100, - minimum: 50, - maximum: 150, -); - -class Parameter { - const Parameter( - this.key, - this.zh, - this.en, - this.value, { - this.minimum = 0, - this.maximum, - }); - final String key, zh, en; - final num value, minimum; - final num? maximum; - bool get integer => - !key.startsWith('strikethrough_') && - key != 'ink_depth_sigma' && - key != 'perturb_theta_sigma' && - !fractionalInk; - bool get fractionalInk => key == 'ink_thickness' || key == 'ink_softness'; - bool accepts(String? raw) { - final n = num.tryParse(raw ?? ''); - return n != null && - n.isFinite && - n >= minimum && - (maximum == null || n <= maximum!) && - (!fractionalInk || n * 10 == (n * 10).round()) && - (!integer || (n == n.roundToDouble() && !raw!.contains('.'))); - } -} - -const inkParameters = [ - Parameter('ink_opacity', '浓淡', 'Opacity', 100, maximum: 100), - Parameter( - 'ink_thickness', - '笔画粗细', - 'Stroke thickness', - 0, - minimum: -2, - maximum: 2, - ), - Parameter('ink_softness', '边缘柔化', 'Edge softness', 0, maximum: 2), -]; +export 'render_parameter.dart'; -const parameters = [ - Parameter('font_size', '字号', 'Font size', 124, minimum: 1), - Parameter('line_spacing', '行距', 'Line spacing', 200, minimum: 1), - Parameter('word_spacing', '字间距', 'Character spacing', 1), - Parameter('width', '纸张宽度', 'Page width', 2481, minimum: 1), - Parameter('height', '纸张高度', 'Page height', 3507, minimum: 1), - Parameter('top_margin', '上边距', 'Top margin', 50), - Parameter('bottom_margin', '下边距', 'Bottom margin', 50), - Parameter('left_margin', '左边距', 'Left margin', 50), - Parameter('right_margin', '右边距', 'Right margin', 50), - Parameter('line_spacing_sigma', '行距扰动', 'Line spacing variation', 0), - Parameter('font_size_sigma', '字号扰动', 'Font size variation', 2), - Parameter('word_spacing_sigma', '字距扰动', 'Character spacing variation', 2), - Parameter('perturb_x_sigma', '水平扰动', 'Horizontal variation', 3), - Parameter('perturb_y_sigma', '垂直扰动', 'Vertical variation', 3), - Parameter( - 'perturb_theta_sigma', - '旋转扰动(弧度)', - 'Rotation variation (radians)', - .05, - ), - Parameter('ink_depth_sigma', '墨色扰动', 'Ink variation', 30), - Parameter( - 'strikethrough_probability', - '删除线概率', - 'Strikethrough probability', - .005, - maximum: 1, - ), - Parameter('strikethrough_width', '删除线宽度', 'Strikethrough width', 8), - Parameter( - 'strikethrough_length_sigma', - '删除线长度扰动', - 'Strikethrough length variation', - 2, - ), - Parameter( - 'strikethrough_width_sigma', - '删除线宽度扰动', - 'Strikethrough width variation', - 2, - ), - Parameter( - 'strikethrough_angle_sigma', - '删除线角度扰动', - 'Strikethrough angle variation', - 2, - ), -]; - -const legacyFields = { - 'fontSize': 'font_size', - 'lineSpacing': 'line_spacing', - 'wordSpacing': 'word_spacing', - 'marginTop': 'top_margin', - 'marginBottom': 'bottom_margin', - 'marginLeft': 'left_margin', - 'marginRight': 'right_margin', - 'lineSpacingSigma': 'line_spacing_sigma', - 'fontSizeSigma': 'font_size_sigma', - 'wordSpacingSigma': 'word_spacing_sigma', - 'perturbXSigma': 'perturb_x_sigma', - 'perturbYSigma': 'perturb_y_sigma', - 'perturbThetaSigma': 'perturb_theta_sigma', - 'width': 'width', - 'height': 'height', - 'ink_depth_sigma': 'ink_depth_sigma', - 'strikethrough_probability': 'strikethrough_probability', - 'strikethrough_width': 'strikethrough_width', - 'strikethrough_length_sigma': 'strikethrough_length_sigma', - 'strikethrough_width_sigma': 'strikethrough_width_sigma', - 'strikethrough_angle_sigma': 'strikethrough_angle_sigma', -}; +enum PaperStyle { blank, ruled, grid, dots } class Settings { Settings(); @@ -256,37 +126,16 @@ class Settings { for (final entry in legacyFields.entries) if (json.containsKey(entry.key)) entry.value: json[entry.key], }; - camera.clear(); - for (final key in cameraKeys) { - final value = json[key]?.toString() ?? ''; - if (value.isNotEmpty && validCameraValue(key, value)) camera[key] = value; - } + _restoreCamera(json); for (final p in [...parameters, ...inkParameters]) { - final value = num.tryParse('${json[p.key]}'); - if (value != null && - value.isFinite && - value >= p.minimum && - (p.maximum == null || value <= p.maximum!) && - (!p.fractionalInk || p.accepts('$value'))) { - values[p.key] = p.integer ? '${value.toInt()}' : '$value'; - } - } - if (json['strikethroughEnabled'] is bool) { - strikethroughEnabled = json['strikethroughEnabled'] as bool; - } else if (json.containsKey('strikethrough_probability')) { - strikethroughEnabled = - (num.tryParse('${json['strikethrough_probability']}') ?? 0) > 0; + final value = p.valueFromDraft(json[p.key]); + if (value != null) values[p.key] = value; } + _restoreStrikethrough(json); layoutStyle = (json['layoutStyle'] ?? json['layout_style']) == 'homework' ? 'homework' : 'standard'; - if (json['fill'] is String) fill = json['fill']; - if (json['font_option'] is String) font = json['font_option']; - final latin = json['latin_font_option']; - latinFont = latin is String && latinFonts.containsKey(latin) ? latin : null; - final scale = '${json['latin_font_scale']}'; - latinScale = latinScaleParameter.accepts(scale) ? int.parse(scale) : 100; - latinDigits = json['digit_font'] == 'latin'; + _restoreInkAndFont(json); firstLineIndent = json['first_line_indent'] == true; monospaced = json['monospaced'] == true; _paperPattern = switch (json['paper_pattern']) { @@ -309,6 +158,33 @@ class Settings { } } + void _restoreCamera(Map json) { + camera.clear(); + for (final key in cameraKeys) { + final value = json[key]?.toString() ?? ''; + if (value.isNotEmpty && validCameraValue(key, value)) camera[key] = value; + } + } + + void _restoreStrikethrough(Map json) { + if (json['strikethroughEnabled'] is bool) { + strikethroughEnabled = json['strikethroughEnabled'] as bool; + } else if (json.containsKey('strikethrough_probability')) { + strikethroughEnabled = + (num.tryParse('${json['strikethrough_probability']}') ?? 0) > 0; + } + } + + void _restoreInkAndFont(Map json) { + if (json['fill'] is String) fill = json['fill']; + if (json['font_option'] is String) font = json['font_option']; + final latin = json['latin_font_option']; + latinFont = latin is String && latinFonts.containsKey(latin) ? latin : null; + final scale = '${json['latin_font_scale']}'; + latinScale = latinScaleParameter.accepts(scale) ? int.parse(scale) : 100; + latinDigits = json['digit_font'] == 'latin'; + } + bool get valid => camera.entries.every((e) => validCameraValue(e.key, e.value)) && parameters.every((p) => p.accepts(values[p.key])) && diff --git a/app/lib/models/task_phase.dart b/app/lib/models/task_phase.dart new file mode 100644 index 00000000..9d9644eb --- /dev/null +++ b/app/lib/models/task_phase.dart @@ -0,0 +1,17 @@ +enum TaskPhase { + pending, + processing, + cancelling, + completed, + failed, + cancelled; + + /// Older engines report failure as "error" and use "status" instead of + /// "task_status". Unknown states are not evidence that a worker has exited. + static TaskPhase? fromWire(Object? value) { + if (value == 'error') return failed; + return values.where((phase) => phase.name == value).firstOrNull; + } + + bool get terminal => this == completed || this == failed || this == cancelled; +} diff --git a/app/lib/models/upload.dart b/app/lib/models/upload.dart new file mode 100644 index 00000000..97b38900 --- /dev/null +++ b/app/lib/models/upload.dart @@ -0,0 +1,7 @@ +import 'dart:typed_data'; + +class Upload { + const Upload(this.name, this.bytes); + final String name; + final Uint8List bytes; +} diff --git a/app/lib/screens/dialogs/paper_area_dialog.dart b/app/lib/screens/dialogs/paper_area_dialog.dart index 0d74395f..2bd9b916 100644 --- a/app/lib/screens/dialogs/paper_area_dialog.dart +++ b/app/lib/screens/dialogs/paper_area_dialog.dart @@ -91,8 +91,10 @@ class _PaperAreaDialogState extends State { super.dispose(); } - void start(Offset screenPoint, double scale) { - final point = this.point(screenPoint, scale); + void _pointerDown(PointerDownEvent event, double scale) { + if (activePointer != null || event.buttons != kPrimaryButton) return; + activePointer = event.pointer; + final point = this.point(event.localPosition, scale); if (free) { setState(() { path = [point]; @@ -115,8 +117,9 @@ class _PaperAreaDialogState extends State { if (hit >= 0) anchor = corners[3 - hit]; } - void move(Offset screenPoint, double scale) { - final next = point(screenPoint, scale); + void _pointerMove(PointerMoveEvent event, double scale) { + if (activePointer != event.pointer) return; + final next = point(event.localPosition, scale); if (free) { appendLassoPoint(path, next, 4 / scale); setState(() => shownPath = [...path, next]); @@ -125,17 +128,109 @@ class _PaperAreaDialogState extends State { final start = anchor; if (start == null) return; setState(() { - area = Rect.fromPoints( - start, - Offset( - next.dx.clamp(0, widget.size.width), - next.dy.clamp(0, widget.size.height - 1), - ), - ); + area = Rect.fromPoints(start, next); + if (!editedRows) rows.text = suggestedRows; + }); + } + + void _pointerUp(PointerUpEvent event, double scale) { + if (activePointer != event.pointer) return; + activePointer = null; + if (!free) return; + setState(() { + shownPath = [...path, point(event.localPosition, scale)]; + enclosed = enclosedRectangle(shownPath); if (!editedRows) rows.text = suggestedRows; }); } + void _pointerCancel(PointerCancelEvent event) { + if (activePointer != event.pointer) return; + if (free) { + setState(() { + path = []; + shownPath = []; + enclosed = null; + }); + } else if (previous != null) { + setState(() => area = previous!); + } + if (!editedRows) rows.text = suggestedRows; + activePointer = null; + } + + Widget _paperSurface(Rect? paper, Map? layout, int count) { + return LayoutBuilder( + builder: (context, constraints) { + final maxHeight = math.min( + 540.0, + MediaQuery.sizeOf(context).height * .50, + ); + final scale = math.min( + constraints.maxWidth / widget.size.width, + maxHeight / widget.size.height, + ); + double? firstLine, step; + if (free && layout != null) { + final spacing = int.parse(layout['line_spacing']!); + firstLine = (int.parse(layout['top_margin']!) + spacing) * scale; + step = spacing * scale; + } + final scaledArea = paper == null + ? null + : Rect.fromLTRB( + paper.left * scale, + paper.top * scale, + paper.right * scale, + paper.bottom * scale, + ); + return Center( + child: SizedBox( + width: widget.size.width * scale, + height: widget.size.height * scale, + child: MouseRegion( + cursor: SystemMouseCursors.precise, + child: RawGestureDetector( + key: const ValueKey('paper-area-image'), + behavior: HitTestBehavior.opaque, + gestures: { + EagerGestureRecognizer: + GestureRecognizerFactoryWithHandlers< + EagerGestureRecognizer + >(EagerGestureRecognizer.new, (_) {}), + }, + child: Listener( + behavior: HitTestBehavior.opaque, + onPointerDown: (event) => _pointerDown(event, scale), + onPointerMove: (event) => _pointerMove(event, scale), + onPointerUp: (event) => _pointerUp(event, scale), + onPointerCancel: _pointerCancel, + child: Stack( + fit: StackFit.expand, + children: [ + Image.memory(widget.bytes, fit: BoxFit.fill), + CustomPaint( + painter: _PaperAreaPainter( + scaledArea, + layout == null ? 0 : count, + path: free + ? [for (final point in shownPath) point * scale] + : [], + firstLine: firstLine, + step: step, + ), + ), + ], + ), + ), + ), + ), + ), + ); + }, + ); + } + @override Widget build(BuildContext context) { final l = AppLocalizations.of(context)!; @@ -176,119 +271,7 @@ class _PaperAreaDialogState extends State { const SizedBox(height: 8), Text(free ? l.paperAreaLassoHelp : l.paperAreaHelp), const SizedBox(height: 12), - LayoutBuilder( - builder: (context, constraints) { - final maxHeight = math.min( - 540.0, - MediaQuery.sizeOf(context).height * .50, - ); - final scale = math.min( - constraints.maxWidth / widget.size.width, - maxHeight / widget.size.height, - ); - final scaledArea = paper == null - ? null - : Rect.fromLTRB( - paper.left * scale, - paper.top * scale, - paper.right * scale, - paper.bottom * scale, - ); - return Center( - child: SizedBox( - width: widget.size.width * scale, - height: widget.size.height * scale, - child: MouseRegion( - cursor: SystemMouseCursors.precise, - child: RawGestureDetector( - key: const ValueKey('paper-area-image'), - behavior: HitTestBehavior.opaque, - gestures: { - EagerGestureRecognizer: - GestureRecognizerFactoryWithHandlers< - EagerGestureRecognizer - >(EagerGestureRecognizer.new, (_) {}), - }, - child: Listener( - behavior: HitTestBehavior.opaque, - onPointerDown: (event) { - if (activePointer != null || - event.buttons != kPrimaryButton) { - return; - } - activePointer = event.pointer; - start(event.localPosition, scale); - }, - onPointerMove: (event) { - if (activePointer == event.pointer) { - move(event.localPosition, scale); - } - }, - onPointerUp: (event) { - if (activePointer == event.pointer) { - activePointer = null; - if (free) { - setState(() { - shownPath = [ - ...path, - point(event.localPosition, scale), - ]; - enclosed = enclosedRectangle(shownPath); - if (!editedRows) rows.text = suggestedRows; - }); - } - } - }, - onPointerCancel: (event) { - if (activePointer != event.pointer) return; - if (free) { - setState(() { - path = []; - shownPath = []; - enclosed = null; - }); - } else if (previous != null) { - setState(() => area = previous!); - } - if (!editedRows) rows.text = suggestedRows; - activePointer = null; - }, - child: Stack( - fit: StackFit.expand, - children: [ - Image.memory(widget.bytes, fit: BoxFit.fill), - CustomPaint( - painter: _PaperAreaPainter( - scaledArea, - layout == null ? 0 : count, - path: free - ? [ - for (final point in shownPath) - point * scale, - ] - : [], - firstLine: free && layout != null - ? (int.parse(layout['top_margin']!) + - int.parse( - layout['line_spacing']!, - )) * - scale - : null, - step: free && layout != null - ? int.parse(layout['line_spacing']!) * - scale - : null, - ), - ), - ], - ), - ), - ), - ), - ), - ); - }, - ), + _paperSurface(paper, layout, count), const SizedBox(height: 12), Wrap( spacing: 12, diff --git a/app/lib/screens/editor_preparation.dart b/app/lib/screens/editor_preparation.dart new file mode 100644 index 00000000..82a53a96 --- /dev/null +++ b/app/lib/screens/editor_preparation.dart @@ -0,0 +1,92 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../services/text_preparation/prepare.dart'; + +/// Coordinates a preparation job with the editor that requested it. The caller +/// owns the editor and its native undo stack; this stores one formatting step. +class EditorPreparation extends ChangeNotifier { + EditorPreparation({ + required this.readText, + required this.applyText, + required this.onFailure, + this.start = startTextPreparation, + }); + + final String Function() readText; + final ValueChanged applyText; + final VoidCallback onFailure; + final TextPreparationJob Function( + String, { + required String tableMode, + required bool english, + }) + start; + + String tableMode = 'latex'; + TextPreparationJob? _job; + bool _stopping = false; + ({String original, String formatted, String mode})? _last; + + bool get running => _job != null; + bool get stopping => _stopping; + + void forgetFormatting() => _last = null; + + String? undoText(String text) => + text == _last?.formatted ? _last?.original : null; + String? redoText(String text) => + text == _last?.original ? _last?.formatted : null; + + Future run(String mode, {required bool english}) async { + if (running) return; + tableMode = mode; + final input = readText(); + final previous = _last; + final alreadyFormatted = previous != null && input == previous.formatted; + if (alreadyFormatted && mode == previous.mode) return; + final original = alreadyFormatted ? previous.original : input; + final job = start(original, tableMode: mode, english: english); + _job = job; + _stopping = false; + notifyListeners(); + try { + final formatted = await job.result; + if (_job != job || + _stopping || + readText() != input || + formatted == input) { + return; + } + _last = (original: original, formatted: formatted, mode: mode); + applyText(formatted); + } on TextPreparationCancelled { + // Cancellation preserves the previous formatting step and editor text. + } catch (_) { + if (_job == job) onFailure(); + } finally { + if (_job == job) { + _job = null; + _stopping = false; + notifyListeners(); + } + } + } + + Future stop() async { + final job = _job; + if (job == null || _stopping) return; + _stopping = true; + notifyListeners(); + await job.cancel(); + } + + @override + void dispose() { + final job = _job; + _job = null; + if (job != null) unawaited(job.cancel()); + super.dispose(); + } +} diff --git a/app/lib/screens/live_preview_scheduler.dart b/app/lib/screens/live_preview_scheduler.dart new file mode 100644 index 00000000..aa450ba1 --- /dev/null +++ b/app/lib/screens/live_preview_scheduler.dart @@ -0,0 +1,51 @@ +import 'dart:async'; + +typedef LivePreviewDraft = ({int revision, int? previewRevision, bool full}); + +/// Debounces automatic previews. The editor supplies a draft only while +/// live submission is possible; the engine owns every job once submitted. +class LivePreviewScheduler { + LivePreviewScheduler({required this.readDraft, required this.submit}); + + final LivePreviewDraft? Function() readDraft; + final void Function() submit; + Timer? _pending; + int? _submitted; + bool _enabled = false; + bool get enabled => _enabled; + + void setEnabled(bool enabled) { + _enabled = enabled; + _submitted = null; + refresh(); + } + + /// Manual previews and fine editing can submit this same revision. + void markSubmitted(int revision) => _submitted = revision; + + LivePreviewDraft? _nextDraft() { + final draft = _enabled ? readDraft() : null; + if (draft == null || + draft.previewRevision == draft.revision || + _submitted == draft.revision) { + return null; + } + return draft; + } + + void refresh() { + _pending?.cancel(); + final draft = _nextDraft(); + if (draft == null) return; + _pending = Timer(Duration(milliseconds: draft.full ? 750 : 350), () { + // Locks and manual submissions may change during the debounce. + if (_nextDraft()?.revision != draft.revision) return; + _submitted = draft.revision; + submit(); + }); + } + + void dispose() { + _pending?.cancel(); + } +} diff --git a/app/lib/screens/pdf_workbench.dart b/app/lib/screens/pdf_workbench.dart index 20699e6a..e119f444 100644 --- a/app/lib/screens/pdf_workbench.dart +++ b/app/lib/screens/pdf_workbench.dart @@ -3,8 +3,11 @@ import 'dart:typed_data'; import 'package:flutter/material.dart'; import '../l10n/app_localizations.dart'; -import '../services/api.dart'; +import '../models/engine_failure.dart'; +import '../models/upload.dart'; import '../services/pdf_pages.dart'; +import '../services/pdf_writing_export.dart'; +import '../widgets/pdf_workbench_layout.dart'; import '../widgets/pdf_writing_surface.dart'; class PdfWorkbench extends StatefulWidget { @@ -167,50 +170,49 @@ class _PdfWorkbenchState extends State { }); } + Future _confirmExport(int issues) => showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text(l.pdfReview), + content: Text(l.pdfWarnings(issues)), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text(l.cancel), + ), + FilledButton( + onPressed: () => Navigator.pop(context, true), + child: Text(l.exportPdf), + ), + ], + ), + ); + Future export() async { final current = page; if (current == null || family == null || exporting != null) return; setState(() => exporting = 0); try { - final document = PdfPageExport(); - var issues = 0; - for (var i = 0; i < count; i++) { - if (!mounted || leaving) return; - setState(() => exporting = i + 1); - final source = i == current.index ? current : await readPage(i); - if (!mounted || leaving) return; - if (relevantWarnings(source).isNotEmpty || - (!fill && source.lines.isEmpty)) { - issues++; - } - final boxes = boxesFor(source); - final image = boxes.isEmpty - ? source.paper - : await renderPdfWritingPage(source, boxes, family!, widget.ink); - await document.add(source, image); - } - if (!mounted || leaving) return; - if (issues != 0) { - final confirmed = await showDialog( - context: context, - builder: (context) => AlertDialog( - title: Text(l.pdfReview), - content: Text(l.pdfWarnings(issues)), - actions: [ - TextButton( - onPressed: () => Navigator.pop(context), - child: Text(l.cancel), - ), - FilledButton( - onPressed: () => Navigator.pop(context, true), - child: Text(l.exportPdf), - ), - ], - ), - ); + final prepared = await assembleWritingPdf( + current: current, + readPage: readPage, + isActive: () => mounted && !leaving, + onPageStarted: (number) => setState(() => exporting = number), + writingFor: (source) => ( + needsReview: + relevantWarnings(source).isNotEmpty || + (!fill && source.lines.isEmpty), + boxes: boxesFor(source), + font: family!, + ink: widget.ink, + ), + ); + if (!mounted || leaving || prepared == null) return; + if (prepared.reviewCount != 0) { + final confirmed = await _confirmExport(prepared.reviewCount); if (!mounted || confirmed != true) return; } - final bytes = await document.finish(); + final bytes = await prepared.document.finish(); if (!mounted || leaving) return; await widget.save(bytes); } catch (e) { @@ -234,152 +236,73 @@ class _PdfWorkbenchState extends State { } } + String? _warningFor(PdfSourcePage? source) { + if (source == null) return null; + if (!fill && source.lines.isEmpty) return l.pdfNoText; + return relevantWarnings(source).isNotEmpty ? l.pdfPartial : null; + } + + Widget _pageContent(PdfSourcePage? source) { + final progress = exporting; + if (progress != null) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + const CircularProgressIndicator(), + const SizedBox(height: 12), + Text(l.pdfProgress(progress, count)), + ], + ); + } + final error = failure; + if (error != null) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text(errorText(error), textAlign: TextAlign.center), + const SizedBox(height: 8), + OutlinedButton.icon( + onPressed: () => load(index), + icon: const Icon(Icons.refresh), + label: Text(l.retry), + ), + ], + ); + } + if (source == null) return const CircularProgressIndicator(); + return PdfWritingSurface( + key: ValueKey(index), + page: source, + boxes: boxesFor(source), + family: family!, + ink: widget.ink, + fill: fill, + onAdd: (r) => editBox(r), + onEdit: (i) => editBox(boxesFor(source)[i].rect, at: i), + ); + } + @override Widget build(BuildContext context) { final source = page; final available = exporting == null; - final colors = Theme.of(context).colorScheme; - final warning = source == null - ? null - : !fill && source.lines.isEmpty - ? l.pdfNoText - : relevantWarnings(source).isNotEmpty - ? l.pdfPartial - : null; + final canNavigate = available && (source != null || failure != null); return PopScope( canPop: leaving || !dirty, onPopInvokedWithResult: (popped, _) { if (!popped) close(); }, - child: Scaffold( - appBar: AppBar( - leading: IconButton( - tooltip: l.close, - icon: const Icon(Icons.close), - onPressed: close, - ), - title: Text(fill ? l.pdfFill : l.pdfLayout), - actions: [ - Padding( - padding: const EdgeInsets.symmetric(horizontal: 8), - child: FilledButton.icon( - onPressed: source != null && available ? export : null, - icon: const Icon(Icons.file_download_outlined), - label: Text(l.exportPdf), - ), - ), - ], - ), - body: SafeArea( - child: Column( - children: [ - Padding( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 8), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - Icon( - Icons.picture_as_pdf_outlined, - size: 18, - color: colors.primary, - ), - const SizedBox(width: 8), - Expanded( - child: Text( - widget.file.name, - overflow: TextOverflow.ellipsis, - style: Theme.of(context).textTheme.titleSmall, - ), - ), - ], - ), - const SizedBox(height: 4), - Text(fill ? l.pdfFillHelp : l.pdfLayoutHelp), - if (warning != null) - Text(warning, style: TextStyle(color: colors.error)), - ], - ), - ), - const Divider(height: 1), - Expanded( - child: ColoredBox( - color: colors.surfaceContainerHighest, - child: Padding( - padding: const EdgeInsets.all(16), - child: Center( - child: exporting != null - ? Column( - mainAxisSize: MainAxisSize.min, - children: [ - const CircularProgressIndicator(), - const SizedBox(height: 12), - Text(l.pdfProgress(exporting!, count)), - ], - ) - : failure != null - ? Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - errorText(failure!), - textAlign: TextAlign.center, - ), - const SizedBox(height: 8), - OutlinedButton.icon( - onPressed: () => load(index), - icon: const Icon(Icons.refresh), - label: Text(l.retry), - ), - ], - ) - : source == null - ? const CircularProgressIndicator() - : PdfWritingSurface( - key: ValueKey(index), - page: source, - boxes: boxesFor(source), - family: family!, - ink: widget.ink, - fill: fill, - onAdd: (r) => editBox(r), - onEdit: (i) => - editBox(boxesFor(source)[i].rect, at: i), - ), - ), - ), - ), - ), - Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - IconButton( - tooltip: l.previousPage, - onPressed: - available && - index > 0 && - (page != null || failure != null) - ? () => load(index - 1) - : null, - icon: const Icon(Icons.chevron_left), - ), - Text(count == 0 ? '—' : '${index + 1} / $count'), - IconButton( - tooltip: l.nextPage, - onPressed: - available && - index + 1 < count && - (page != null || failure != null) - ? () => load(index + 1) - : null, - icon: const Icon(Icons.chevron_right), - ), - ], - ), - ], - ), - ), + child: PdfWorkbenchLayout( + fileName: widget.file.name, + fill: fill, + warning: _warningFor(source), + index: index, + count: count, + onClose: close, + onExport: source != null && available ? export : null, + onPrevious: canNavigate && index > 0 ? () => load(index - 1) : null, + onNext: canNavigate && index + 1 < count ? () => load(index + 1) : null, + child: _pageContent(source), ), ); } diff --git a/app/lib/screens/workbench.dart b/app/lib/screens/workbench.dart index 6e2c26ea..76029be1 100644 --- a/app/lib/screens/workbench.dart +++ b/app/lib/screens/workbench.dart @@ -21,14 +21,15 @@ import '../utils/image_data.dart'; import '../utils/image_markers.dart'; import 'dialogs/text_tools_dialogs.dart'; import 'dialogs/text_preview_dialog.dart'; -import '../services/api.dart'; +import '../models/upload.dart'; import '../services/illustration_import.dart'; import '../services/workspace.dart'; import '../models/fine_edit.dart'; import '../services/desktop_exit.dart'; import '../services/workspace_documents.dart'; import '../utils/text_tools.dart'; -import '../services/text_preparation/prepare.dart'; +import 'editor_preparation.dart'; +import 'live_preview_scheduler.dart'; import '../widgets/workbench_controls.dart'; import '../widgets/fine_preview.dart'; import '../widgets/workbench_editor.dart'; @@ -89,9 +90,7 @@ class _WorkbenchState extends State with WidgetsBindingObserver { final undo = UndoHistoryController(); int destination = 0, mobileTab = 0; SettingsSection settingsSection = SettingsSection.layout; - Timer? liveTimer; - int? liveSubmitted; - bool livePreview = false; + late final LivePreviewScheduler livePreview; bool fineFullscreen = false; bool composing = false; int navigationRevision = 0; @@ -101,17 +100,14 @@ class _WorkbenchState extends State with WidgetsBindingObserver { bool firstFrameReady = false; bool recoveryShown = false; UpdatePromptCoordinator? updatePrompts; - String tableMode = 'latex'; - TextPreparationJob? preparation; - bool preparationStopping = false; - ({String original, String formatted, String mode})? preparedText; + late final EditorPreparation preparation; WorkspaceDocuments get documents => WorkspaceDocuments(w); AppLocalizations get l => AppLocalizations.of(context)!; bool get english => Localizations.localeOf(context).languageCode == 'en'; bool get locked => w.busy || editingLocked; bool get editingLocked => operation || - preparation != null || + preparation.running || { UpdatePhase.preparing, UpdatePhase.restarting, @@ -125,6 +121,28 @@ class _WorkbenchState extends State with WidgetsBindingObserver { WidgetsBinding.instance.addObserver(this); destination = widget.initialDestination; w = widget.workspace ?? Workspace(); + preparation = EditorPreparation( + readText: () => editor.text, + applyText: (text) => replace(text, keepPreparation: true), + onFailure: () => notify(l.prepareTextFailed), + )..addListener(refreshPreparation); + livePreview = LivePreviewScheduler( + readDraft: () { + if (destination != 0 || + locked || + composing || + !w.generation.available || + editor.text.trim().isEmpty) { + return null; + } + return ( + revision: w.editRevision, + previewRevision: w.generation.previewRevision, + full: w.settings.fullPreview, + ); + }, + submit: () => unawaited(w.generate(live: true)), + ); editor.text = w.text; editor.addListener(rememberEditorSelection); w.addListener(refresh); @@ -166,6 +184,11 @@ class _WorkbenchState extends State with WidgetsBindingObserver { if (widget.workspace == null) unawaited(w.initialize()); } + void refreshPreparation() { + setState(() {}); + livePreview.refresh(); + } + void refreshUpdates() { if (mounted && !recoveryShown && @@ -185,19 +208,21 @@ class _WorkbenchState extends State with WidgetsBindingObserver { settingsRevision++; } if (editor.text != w.text) { - if (preparation != null) unawaited(stopPreparation()); - preparedText = null; + if (preparation.running) unawaited(preparation.stop()); + preparation.forgetFormatting(); editor.value = TextEditingValue( text: w.text, selection: TextSelection.collapsed(offset: w.text.length), ); } - if (livePreview && editor.text.trim().isEmpty && w.pages.isNotEmpty) { + if (livePreview.enabled && + editor.text.trim().isEmpty && + w.pages.isNotEmpty) { w.pages = []; w.page = 0; } setState(() {}); - scheduleLivePreview(); + livePreview.refresh(); updatePrompts?.evaluate(); } @@ -209,9 +234,8 @@ class _WorkbenchState extends State with WidgetsBindingObserver { @override void dispose() { - liveTimer?.cancel(); - final job = preparation; - if (job != null) unawaited(job.cancel()); + livePreview.dispose(); + preparation.dispose(); WidgetsBinding.instance.removeObserver(this); w.removeListener(refresh); widget.updates?.removeListener(refreshUpdates); @@ -245,7 +269,7 @@ class _WorkbenchState extends State with WidgetsBindingObserver { } finally { if (mounted) { setState(() => operation = false); - scheduleLivePreview(); + livePreview.refresh(); } } } @@ -290,7 +314,7 @@ class _WorkbenchState extends State with WidgetsBindingObserver { value.composing.isValid && !value.composing.isCollapsed; if (composing != composingNow) { composing = composingNow; - scheduleLivePreview(); + livePreview.refresh(); } if (value.selection.isValid && value.selection.end <= value.text.length) { lastEditorSelection = value; @@ -305,7 +329,7 @@ class _WorkbenchState extends State with WidgetsBindingObserver { Future enterFineEdit() async { w.text = editor.text; final result = await w.enterFineEdit(); - if (mounted && result) liveSubmitted = w.editRevision; + if (mounted && result) livePreview.markSubmitted(w.editRevision); return result; } @@ -323,7 +347,7 @@ class _WorkbenchState extends State with WidgetsBindingObserver { } void replace(String value, {bool keepPreparation = false}) { - if (!keepPreparation) preparedText = null; + if (!keepPreparation) preparation.forgetFormatting(); editor.text = value; w.text = value; w.edit(); @@ -417,37 +441,6 @@ class _WorkbenchState extends State with WidgetsBindingObserver { w.edit(); }); - void scheduleLivePreview() { - liveTimer?.cancel(); - if (!livePreview || - destination != 0 || - locked || - !w.generation.available || - editor.text.trim().isEmpty || - w.generation.previewRevision == w.editRevision || - liveSubmitted == w.editRevision || - composing) { - return; - } - liveTimer = Timer( - Duration(milliseconds: w.settings.fullPreview ? 750 : 350), - () { - if (!mounted || locked || destination != 0 || !livePreview) return; - if (composing) return; - liveSubmitted = w.editRevision; - unawaited(w.generate(live: true)); - }, - ); - } - - void setLivePreview(bool enabled) { - setState(() { - livePreview = enabled; - liveSubmitted = null; - }); - scheduleLivePreview(); - } - Future generate({bool preview = true, bool pdf = false}) async { if (!(form.currentState?.validate() ?? w.settings.valid)) { notify(l.validation); @@ -455,11 +448,11 @@ class _WorkbenchState extends State with WidgetsBindingObserver { } w.text = editor.text; if (!preview && w.finePreviewNeedsRefresh) { - liveSubmitted = w.editRevision; + livePreview.markSubmitted(w.editRevision); final refreshed = await w.generate(); if (!mounted || !refreshed || w.previewStale) return; } - if (preview) liveSubmitted = w.editRevision; + if (preview) livePreview.markSubmitted(w.editRevision); final navigation = navigationRevision; final succeeded = await w.generate(preview: preview, pdf: pdf); if (!mounted || !succeeded) return; @@ -498,7 +491,7 @@ class _WorkbenchState extends State with WidgetsBindingObserver { navigationRevision++; }); if (index == 1) widget.onGuideOpened?.call(); - scheduleLivePreview(); + livePreview.refresh(); } void openGuideTarget(GuideTarget target) { @@ -515,7 +508,7 @@ class _WorkbenchState extends State with WidgetsBindingObserver { } navigationRevision++; }); - scheduleLivePreview(); + livePreview.refresh(); } void selectSettingsSection(SettingsSection section) { @@ -601,8 +594,8 @@ class _WorkbenchState extends State with WidgetsBindingObserver { mobileTab: mobileTab, settingsSection: settingsSection, onSectionSelected: selectSettingsSection, - livePreview: livePreview, - onLivePreview: setLivePreview, + livePreview: livePreview.enabled, + onLivePreview: (value) => setState(() => livePreview.setEnabled(value)), fullPreview: w.settings.fullPreview, onFullPreview: (value) { w.settings.fullPreview = value; @@ -638,29 +631,29 @@ class _WorkbenchState extends State with WidgetsBindingObserver { onOpenGuide: () => selectDestination(1), guideUnread: widget.guideUnread, onUndo: () { - final prepared = preparedText; - if (prepared != null && editor.text == prepared.formatted) { - replace(prepared.original, keepPreparation: true); + final text = preparation.undoText(editor.text); + if (text != null) { + replace(text, keepPreparation: true); } else { undo.undo(); } }, onRedo: () { - final prepared = preparedText; - if (prepared != null && editor.text == prepared.original) { - replace(prepared.formatted, keepPreparation: true); + final text = preparation.redoText(editor.text); + if (text != null) { + replace(text, keepPreparation: true); } else { undo.redo(); } }, onChanged: (value) { - preparedText = null; + preparation.forgetFormatting(); w.text = collapseImages(value, w.images); w.edit(); }, - preparing: preparation != null, - preparationStopping: preparationStopping, - onStopPreparation: stopPreparation, + preparing: preparation.running, + preparationStopping: preparation.stopping, + onStopPreparation: preparation.stop, toolbar: EditorToolbar( moreLabel: l.editingTools, hint: l.editingToolsHint, @@ -922,58 +915,12 @@ class _WorkbenchState extends State with WidgetsBindingObserver { Future prepareTextDialog() async { if (locked) return; - final mode = await showPrepareTextDialog(context, initialMode: tableMode); - if (!mounted || mode == null || locked) return; - tableMode = mode; - final previous = preparedText; - if (previous != null && - editor.text == previous.formatted && - mode == previous.mode) { - return; - } - final original = previous != null && editor.text == previous.formatted - ? previous.original - : editor.text; - final input = editor.text; - final job = startTextPreparation( - original, - tableMode: mode, - english: english, + final mode = await showPrepareTextDialog( + context, + initialMode: preparation.tableMode, ); - setState(() { - preparation = job; - preparationStopping = false; - }); - try { - final formatted = await job.result; - if (!mounted || - preparation != job || - preparationStopping || - editor.text != input || - formatted == input) { - return; - } - preparedText = (original: original, formatted: formatted, mode: mode); - replace(formatted, keepPreparation: true); - } on TextPreparationCancelled { - // Keep the exact source and the previous undo snapshot after stopping. - } catch (_) { - if (mounted && preparation == job) notify(l.prepareTextFailed); - } finally { - if (mounted && preparation == job) { - setState(() { - preparation = null; - preparationStopping = false; - }); - } - } - } - - Future stopPreparation() async { - final job = preparation; - if (job == null || preparationStopping) return; - setState(() => preparationStopping = true); - await job.cancel(); + if (!mounted || mode == null || locked) return; + await preparation.run(mode, english: english); } Future letterDialog() async { diff --git a/app/lib/services/api.dart b/app/lib/services/api.dart index 4df0018b..45505e05 100644 --- a/app/lib/services/api.dart +++ b/app/lib/services/api.dart @@ -7,19 +7,11 @@ import 'package:flutter/foundation.dart' show kIsWeb; import 'package:http/http.dart' as http; import '../models/engine_failure.dart'; +import '../models/task_phase.dart'; +import '../models/upload.dart'; -class Upload { - const Upload(this.name, this.bytes); - final String name; - final Uint8List bytes; -} - -class ApiException extends EngineFailure { - ApiException(super.message, {this.status, int? waitSeconds, super.code}) - : super(retryAfterSeconds: waitSeconds); - final int? status; - int? get waitSeconds => retryAfterSeconds; -} +export '../models/engine_failure.dart' show ApiException; +export '../models/upload.dart' show Upload; class HandwritingApi { HandwritingApi(this.base, {http.Client? client, String? accessToken}) @@ -186,7 +178,7 @@ class HandwritingApi { while (true) { final data = await status(id); final phase = data['task_status'] ?? data['status']; - if (['completed', 'failed', 'error', 'cancelled'].contains(phase)) return; + if (TaskPhase.fromWire(phase)?.terminal == true) return; if (DateTime.now().isAfter(deadline)) { throw TimeoutException('Task cancellation has not been confirmed'); } diff --git a/app/lib/services/desktop_bootstrap.dart b/app/lib/services/desktop_bootstrap.dart index 19fc21dd..80b1a2a7 100644 --- a/app/lib/services/desktop_bootstrap.dart +++ b/app/lib/services/desktop_bootstrap.dart @@ -18,7 +18,13 @@ import 'mobile_api.dart'; export 'desktop_backend.dart' show usesDesktopBackend, usesMobileBackend; class DesktopBootstrap extends StatefulWidget { - const DesktopBootstrap({super.key, required this.builder}); + const DesktopBootstrap({ + super.key, + required this.builder, + this.recoverInterruptedUpdate = updater.recoverInterruptedUpdate, + }); + final Future Function(String) + recoverInterruptedUpdate; final Widget Function(Workspace) builder; @override @@ -57,6 +63,7 @@ class _DesktopBootstrapState extends State { Future start() async { if (starting) return; + final recoverInterruptedUpdate = widget.recoverInterruptedUpdate; setState(() { starting = true; failed = false; @@ -73,10 +80,9 @@ class _DesktopBootstrapState extends State { if (!usesMobileBackend) { updateStartup = updater.DesktopUpdateStartup.read(support); if (updateStartup == null) { - final recovery = await updater.recoverInterruptedUpdate(support); + final recovery = await recoverInterruptedUpdate(support); if (recovery != null) { - recovery.arm(); - if (!await requestDesktopUpdateExit()) await recovery.abort(); + await _recoverAndExit(recovery); return; } } @@ -103,12 +109,7 @@ class _DesktopBootstrapState extends State { if (!mounted || closing || !readyWorkspace.connected) { readyWorkspace.dispose(); await current.stop(); - if (mounted && !closing) { - setState(() { - failed = true; - starting = false; - }); - } + _showStartupFailure(); return; } setState(() { @@ -143,15 +144,30 @@ class _DesktopBootstrapState extends State { candidate?.dispose(); await current.stop(); debugPrint('Bundled backend startup failed: $error'); - if (mounted && !closing) { - setState(() { - failed = true; - starting = false; - }); - } + _showStartupFailure(); } } + Future _recoverAndExit(updater.PreparedDesktopUpdate recovery) async { + var exitAccepted = false; + try { + recovery.arm(); + exitAccepted = await requestDesktopUpdateExit(); + } finally { + // An accepted exit leaves the armed helper waiting for process EOF. + if (!exitAccepted) await recovery.abort(); + } + if (!exitAccepted) _showStartupFailure(); + } + + void _showStartupFailure() { + if (!mounted || closing) return; + setState(() { + failed = true; + starting = false; + }); + } + @override void dispose() { closing = true; diff --git a/app/lib/services/engine_contract.dart b/app/lib/services/engine_contract.dart new file mode 100644 index 00000000..d9bc59c5 --- /dev/null +++ b/app/lib/services/engine_contract.dart @@ -0,0 +1,99 @@ +import 'dart:typed_data'; + +import '../models/engine_failure.dart'; +import '../models/task_phase.dart'; +import '../models/upload.dart'; + +export '../models/task_phase.dart'; + +/// Owns the submitted values, including upload bytes, across asynchronous work. +class GenerationRequest { + GenerationRequest(Map fields, Map files) + : fields = Map.unmodifiable(fields), + files = Map.unmodifiable({ + for (final entry in files.entries) + entry.key: Upload( + entry.value.name, + Uint8List.fromList(entry.value.bytes).asUnmodifiableView(), + ), + }); + + final Map fields; + final Map files; +} + +class EngineTask { + const EngineTask({ + required this.phase, + required this.progress, + this.stage, + this.pagesCompleted = 0, + this.errorCode, + this.errorMessage, + }); + + final TaskPhase phase; + final int progress, pagesCompleted; + final String? stage, errorCode, errorMessage; + + factory EngineTask.fromJson(Map data) { + final value = data['task_status'] ?? data['status']; + final phase = TaskPhase.fromWire(value); + if (phase == null) throw ApiException('Unknown task status: $value'); + return EngineTask( + phase: phase, + progress: ((data['task_progress'] ?? data['progress']) as num? ?? 0) + .toInt() + .clamp(0, 100), + stage: data['task_stage'] as String?, + pagesCompleted: ((data['pages_completed'] as num?) ?? 0).toInt().clamp( + 0, + 1000000, + ), + errorCode: data['error_code'] as String?, + errorMessage: (data['error_message'] ?? data['message']) as String?, + ); + } +} + +class EngineInfo { + const EngineInfo({ + required this.version, + required this.canCancel, + required this.canChooseTaskId, + this.canFineEdit = false, + this.canListLocalFonts = false, + }); + final String version; + final bool canCancel, canChooseTaskId; + final bool canFineEdit, canListLocalFonts; + factory EngineInfo.fromJson(Map value) { + final capabilities = value['capabilities']; + return EngineInfo( + version: value['version'] as String? ?? '', + canCancel: + capabilities is Map && capabilities['task_cancellation'] == true, + canChooseTaskId: + capabilities is Map && capabilities['task_submission_id'] == true, + canListLocalFonts: + capabilities is Map && capabilities['local_fonts'] == true, + canFineEdit: capabilities is Map && capabilities['fine_edit'] == true, + ); + } +} + +abstract interface class EngineCatalog { + Future> loadFonts(); + Future loadInfo(); +} + +/// Business operations do not expose HTTP responses or FFI paths. +abstract interface class EngineGateway { + bool get supportsCancel; + String? createTaskId(); + Future submit(GenerationRequest request, {String? taskId}); + Future status(String id); + Future> preview(String id); + Future export(String id); + Future cancel(String id); +} diff --git a/app/lib/services/engine_gateway.dart b/app/lib/services/engine_gateway.dart index b764189d..4c8cfd2b 100644 --- a/app/lib/services/engine_gateway.dart +++ b/app/lib/services/engine_gateway.dart @@ -1,111 +1,9 @@ import 'dart:typed_data'; import 'api.dart'; +import 'engine_contract.dart'; -enum TaskPhase { - pending, - processing, - cancelling, - completed, - failed, - cancelled; - - bool get terminal => this == completed || this == failed || this == cancelled; -} - -/// Owns the submitted values, including upload bytes, across asynchronous work. -class GenerationRequest { - GenerationRequest(Map fields, Map files) - : fields = Map.unmodifiable(fields), - files = Map.unmodifiable({ - for (final entry in files.entries) - entry.key: Upload( - entry.value.name, - Uint8List.fromList(entry.value.bytes).asUnmodifiableView(), - ), - }); - - final Map fields; - final Map files; -} - -class EngineTask { - const EngineTask({ - required this.phase, - required this.progress, - this.stage, - this.pagesCompleted = 0, - this.errorCode, - this.errorMessage, - }); - - final TaskPhase phase; - final int progress, pagesCompleted; - final String? stage, errorCode, errorMessage; - - factory EngineTask.fromJson(Map data) { - final value = data['task_status'] ?? data['status']; - final phase = value == 'error' - ? TaskPhase.failed - : TaskPhase.values.where((phase) => phase.name == value).firstOrNull; - if (phase == null) throw ApiException('Unknown task status: $value'); - return EngineTask( - phase: phase, - progress: ((data['task_progress'] ?? data['progress']) as num? ?? 0) - .toInt() - .clamp(0, 100), - stage: data['task_stage'] as String?, - pagesCompleted: ((data['pages_completed'] as num?) ?? 0).toInt().clamp( - 0, - 1000000, - ), - errorCode: data['error_code'] as String?, - errorMessage: (data['error_message'] ?? data['message']) as String?, - ); - } -} - -class EngineInfo { - const EngineInfo({ - required this.version, - required this.canCancel, - required this.canChooseTaskId, - this.canFineEdit = false, - this.canListLocalFonts = false, - }); - final String version; - final bool canCancel, canChooseTaskId; - final bool canFineEdit, canListLocalFonts; - factory EngineInfo.fromJson(Map value) { - final capabilities = value['capabilities']; - return EngineInfo( - version: value['version'] as String? ?? '', - canCancel: - capabilities is Map && capabilities['task_cancellation'] == true, - canChooseTaskId: - capabilities is Map && capabilities['task_submission_id'] == true, - canListLocalFonts: - capabilities is Map && capabilities['local_fonts'] == true, - canFineEdit: capabilities is Map && capabilities['fine_edit'] == true, - ); - } -} - -abstract interface class EngineCatalog { - Future> loadFonts(); - Future loadInfo(); -} - -/// Business operations do not expose HTTP responses or FFI paths. -abstract interface class EngineGateway { - bool get supportsCancel; - String? createTaskId(); - Future submit(GenerationRequest request, {String? taskId}); - Future status(String id); - Future> preview(String id); - Future export(String id); - Future cancel(String id); -} +export 'engine_contract.dart'; /// Migration adapter for both existing HTTP and mobile transports. class ApiEngineGateway implements EngineGateway, EngineCatalog { @@ -120,8 +18,7 @@ class ApiEngineGateway implements EngineGateway, EngineCatalog { final value = Map.from( await api.getJson('/api/version') as Map, ); - final info = EngineInfo.fromJson(value); - return info; + return EngineInfo.fromJson(value); } void configure(EngineInfo info) => api.configureCapabilities({ diff --git a/app/lib/services/font_storage_contract.dart b/app/lib/services/font_storage_contract.dart new file mode 100644 index 00000000..d0ef7ec2 --- /dev/null +++ b/app/lib/services/font_storage_contract.dart @@ -0,0 +1,31 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import '../models/upload.dart'; + +/// Uploaded font bytes belong in binary storage, outside preference snapshots. +abstract interface class UploadedFontStorage { + Future read(); + Future write(Upload? font); +} + +Uint8List encodeFont(Upload font) { + final name = utf8.encode(font.name); + final result = Uint8List(4 + name.length + font.bytes.length); + ByteData.sublistView(result).setUint32(0, name.length); + result.setRange(4, 4 + name.length, name); + result.setRange(4 + name.length, result.length, font.bytes); + return result; +} + +Upload decodeFont(Uint8List data) { + if (data.length < 5) throw const FormatException('Invalid saved font'); + final length = ByteData.sublistView(data).getUint32(0); + if (length == 0 || length >= data.length - 4) { + throw const FormatException('Invalid saved font'); + } + return Upload( + utf8.decode(data.sublist(4, 4 + length)), + Uint8List.sublistView(data, 4 + length), + ); +} diff --git a/app/lib/services/illustration_import.dart b/app/lib/services/illustration_import.dart index be6d2d22..11cdeb1d 100644 --- a/app/lib/services/illustration_import.dart +++ b/app/lib/services/illustration_import.dart @@ -2,7 +2,7 @@ import 'dart:typed_data'; import 'package:file_picker/file_picker.dart'; -import 'api.dart'; +import '../models/upload.dart'; const maxIllustrationImportBytes = 12 * 1024 * 1024; diff --git a/app/lib/services/paper_background.dart b/app/lib/services/paper_background.dart index 61158701..b1cd8ea5 100644 --- a/app/lib/services/paper_background.dart +++ b/app/lib/services/paper_background.dart @@ -2,10 +2,10 @@ import 'dart:math' as math; import 'dart:ui' as ui; import 'dart:typed_data'; +import '../models/engine_failure.dart'; +import '../models/upload.dart'; import '../utils/paper_exif.dart'; -import 'api.dart'; - const mobileImageBytes = 16 * 1024 * 1024; const mobilePaperPixels = 12000000; @@ -22,77 +22,27 @@ Future<({Upload file, int width, int height})> preparePaperBackground( try { final width = descriptor.width; final height = descriptor.height; - final originalPixels = width * height; - if (correctedSize != null && - (width != correctedSize.width || - height != correctedSize.height || - originalPixels > 32000000)) { - throw const FormatException('Invalid corrected background dimensions'); - } - if (mobile && originalPixels > 64000000) { - throw ApiException( - 'Paper source exceeds 64 megapixels', - code: 'image_limit', - ); - } - - final reserveForDeskew = correctedSize == null; - // The Rust detector searches angles up to about 12.5 degrees. Deskew can - // expand both sides of the image, so leave space for that bounding box. - final area = reserveForDeskew - ? originalPixels + ((width * width + height * height) * .22).ceil() - : originalPixels; - final resize = - mobile && - (area > mobilePaperPixels || file.bytes.length > mobileImageBytes); - if (!resize && correctedSize == null) { + final plan = _decodePlan( + width, + height, + file.bytes.length, + mobile: mobile, + correctedSize: correctedSize, + ); + if (!plan.resize && correctedSize == null) { return (file: file, width: width, height: height); } - final exif = resize ? await readPaperExif?.call(file) : null; - Future<({Upload file, int width, int height})?> decode( - double scale, - ) async { - final codec = await descriptor.instantiateCodec( - targetWidth: math.max(1, (width * scale).floor()), - targetHeight: math.max(1, (height * scale).floor()), + final exif = plan.resize ? await readPaperExif?.call(file) : null; + for (final scale in plan.scales) { + final prepared = await _decodePaper( + descriptor, + file, + scale: scale, + resize: plan.resize, + exif: exif, ); - try { - final frame = await codec.getNextFrame(); - final image = frame.image; - try { - if (!resize) return (file: file, width: width, height: height); - final png = await image.toByteData(format: ui.ImageByteFormat.png); - if (png == null || - png.lengthInBytes + - (exif == null || exif.isEmpty ? 0 : exif.length + 12) > - mobileImageBytes) { - return null; - } - final stem = file.name.replaceFirst(RegExp(r'\.[^.]+$'), ''); - return ( - file: Upload( - '$stem.png', - withPaperExif(Uint8List.sublistView(png), exif), - ), - width: image.width, - height: image.height, - ); - } finally { - image.dispose(); - } - } finally { - codec.dispose(); - } + if (prepared != null) return prepared; } - - final scale = resize ? math.min(1.0, math.sqrt(11800000 / area)) : 1.0; - final prepared = await decode(scale); - if (prepared != null) return prepared; - // A 3.8 MP RGBA image leaves room for PNG overhead within 16 MiB. - final smaller = await decode( - math.min(scale, math.sqrt(3800000 / originalPixels)), - ); - if (smaller != null) return smaller; throw ApiException( 'Could not fit paper within mobile limits', code: 'image_limit', @@ -104,3 +54,81 @@ Future<({Upload file, int width, int height})> preparePaperBackground( buffer.dispose(); } } + +({bool resize, List scales}) _decodePlan( + int width, + int height, + int byteLength, { + required bool mobile, + required ({int width, int height})? correctedSize, +}) { + final originalPixels = width * height; + if (correctedSize != null && + (width != correctedSize.width || + height != correctedSize.height || + originalPixels > 32000000)) { + throw const FormatException('Invalid corrected background dimensions'); + } + if (mobile && originalPixels > 64000000) { + throw ApiException( + 'Paper source exceeds 64 megapixels', + code: 'image_limit', + ); + } + + final reserveForDeskew = correctedSize == null; + // The Rust detector searches angles up to about 12.5 degrees. Deskew can + // expand both sides of the image, so leave space for that bounding box. + final area = reserveForDeskew + ? originalPixels + ((width * width + height * height) * .22).ceil() + : originalPixels; + final resize = + mobile && (area > mobilePaperPixels || byteLength > mobileImageBytes); + if (!resize) return (resize: false, scales: const [1.0]); + final initial = math.min(1.0, math.sqrt(11800000 / area)); + // A 3.8 MP RGBA image leaves room for PNG overhead within 16 MiB. + final fallback = math.min(initial, math.sqrt(3800000 / originalPixels)); + return (resize: true, scales: [initial, fallback]); +} + +Future<({Upload file, int width, int height})?> _decodePaper( + ui.ImageDescriptor descriptor, + Upload file, { + required double scale, + required bool resize, + required Uint8List? exif, +}) async { + final codec = await descriptor.instantiateCodec( + targetWidth: math.max(1, (descriptor.width * scale).floor()), + targetHeight: math.max(1, (descriptor.height * scale).floor()), + ); + try { + final frame = await codec.getNextFrame(); + final image = frame.image; + try { + if (!resize) { + return (file: file, width: descriptor.width, height: descriptor.height); + } + final png = await image.toByteData(format: ui.ImageByteFormat.png); + if (png == null || + png.lengthInBytes + + (exif == null || exif.isEmpty ? 0 : exif.length + 12) > + mobileImageBytes) { + return null; + } + final stem = file.name.replaceFirst(RegExp(r'\.[^.]+$'), ''); + return ( + file: Upload( + '$stem.png', + withPaperExif(Uint8List.sublistView(png), exif), + ), + width: image.width, + height: image.height, + ); + } finally { + image.dispose(); + } + } finally { + codec.dispose(); + } +} diff --git a/app/lib/services/pdf_pages.dart b/app/lib/services/pdf_pages.dart index 63641990..04f2306c 100644 --- a/app/lib/services/pdf_pages.dart +++ b/app/lib/services/pdf_pages.dart @@ -10,7 +10,8 @@ import 'package:flutter/services.dart'; import 'package:pdf/pdf.dart'; import 'package:pdf/widgets.dart' as pw; -import 'api.dart'; +import '../models/engine_failure.dart'; +import '../models/upload.dart'; enum PdfImportMode { text, layout, fill } diff --git a/app/lib/services/pdf_writing_export.dart b/app/lib/services/pdf_writing_export.dart new file mode 100644 index 00000000..c21a5044 --- /dev/null +++ b/app/lib/services/pdf_writing_export.dart @@ -0,0 +1,41 @@ +import 'dart:ui'; + +import 'pdf_pages.dart'; + +typedef PdfPageWriting = ({ + List boxes, + String font, + Color ink, + bool needsReview, +}); + +/// Assemble pages in source order. The caller owns navigation, progress, +/// confirmation of questionable pages and the destination of the finished PDF. +Future<({PdfPageExport document, int reviewCount})?> assembleWritingPdf({ + required PdfSourcePage current, + required Future Function(int index) readPage, + required PdfPageWriting Function(PdfSourcePage page) writingFor, + required bool Function() isActive, + required void Function(int pageNumber) onPageStarted, +}) async { + final document = PdfPageExport(); + var reviewCount = 0; + for (var index = 0; index < current.count; index++) { + if (!isActive()) return null; + onPageStarted(index + 1); + final page = index == current.index ? current : await readPage(index); + if (!isActive()) return null; + final writing = writingFor(page); + if (writing.needsReview) reviewCount++; + final image = writing.boxes.isEmpty + ? page.paper + : await renderPdfWritingPage( + page, + writing.boxes, + writing.font, + writing.ink, + ); + await document.add(page, image); + } + return (document: document, reviewCount: reviewCount); +} diff --git a/app/lib/services/updates/update_controller.dart b/app/lib/services/updates/update_controller.dart index 95148201..87a87ab5 100644 --- a/app/lib/services/updates/update_controller.dart +++ b/app/lib/services/updates/update_controller.dart @@ -48,6 +48,7 @@ class UpdateController extends ChangeNotifier { DownloadCancellation? _cancellation; DesktopPreparedUpdate? _prepared; bool _restartIntent = false, _restartRunning = false; + bool get _restartRequested => _restartIntent && !_disposed; bool get desktopAutomatic => desktop && installed!.canRestartDesktop; bool get desktop => installed != null && @@ -242,8 +243,7 @@ class UpdateController extends ChangeNotifier { _restartIntent = true; try { if (phase != UpdatePhase.ready) await download(); - if (!_restartIntent || - _disposed || + if (!_restartRequested || phase != UpdatePhase.ready || _package == null || release == null) { @@ -265,40 +265,32 @@ class UpdateController extends ChangeNotifier { cancellation: preparingCancellation, ); _prepared = prepared; - if (!_restartIntent || _disposed) { - await prepared.abort(); - _prepared = null; - phase = UpdatePhase.ready; - return; - } - if (!await persist()) { - throw const UpdateException(UpdateProblem.saveFailed); - } - if (!_restartIntent || _disposed || !canRestart()) { - await prepared.abort(); - _prepared = null; - phase = UpdatePhase.ready; - problem = UpdateProblem.restartDeferred; - return; - } - prepared.arm(); - phase = UpdatePhase.restarting; - _emit(); - if (!await requestExit()) { - await prepared.abort(); - _prepared = null; - phase = UpdatePhase.ready; - problem = UpdateProblem.restartCancelled; + UpdateProblem? rollbackProblem; + if (_restartRequested) { + if (!await persist()) { + throw const UpdateException(UpdateProblem.saveFailed); + } + if (_restartRequested && canRestart()) { + prepared.arm(); + phase = UpdatePhase.restarting; + _emit(); + // An accepted exit leaves the armed helper waiting for process EOF. + if (await requestExit()) return; + rollbackProblem = UpdateProblem.restartCancelled; + } else { + rollbackProblem = UpdateProblem.restartDeferred; + } } - } on UpdateException catch (error) { - await _prepared?.abort(); + await prepared.abort(); _prepared = null; - problem = error.problem; - phase = downloadedPath == null ? UpdatePhase.failed : UpdatePhase.ready; - } catch (_) { + phase = UpdatePhase.ready; + if (rollbackProblem != null) problem = rollbackProblem; + } catch (error) { await _prepared?.abort(); _prepared = null; - problem = UpdateProblem.openFailed; + problem = error is UpdateException + ? error.problem + : UpdateProblem.openFailed; phase = downloadedPath == null ? UpdatePhase.failed : UpdatePhase.ready; } finally { _restartRunning = false; diff --git a/app/lib/services/uploaded_font_storage.dart b/app/lib/services/uploaded_font_storage.dart index 2553e09e..cc3b0a56 100644 --- a/app/lib/services/uploaded_font_storage.dart +++ b/app/lib/services/uploaded_font_storage.dart @@ -1,36 +1,8 @@ -import 'dart:convert'; -import 'dart:typed_data'; - -import 'api.dart'; +import 'font_storage_contract.dart'; import 'uploaded_font_storage_native.dart' if (dart.library.js_interop) 'uploaded_font_storage_web.dart' as platform; -/// Uploaded font bytes belong in binary storage, outside preference snapshots. -abstract interface class UploadedFontStorage { - Future read(); - Future write(Upload? font); -} +export 'font_storage_contract.dart'; UploadedFontStorage createUploadedFontStorage() => platform.FontStorage(); - -Uint8List encodeFont(Upload font) { - final name = utf8.encode(font.name); - final result = Uint8List(4 + name.length + font.bytes.length); - ByteData.sublistView(result).setUint32(0, name.length); - result.setRange(4, 4 + name.length, name); - result.setRange(4 + name.length, result.length, font.bytes); - return result; -} - -Upload decodeFont(Uint8List data) { - if (data.length < 5) throw const FormatException('Invalid saved font'); - final length = ByteData.sublistView(data).getUint32(0); - if (length == 0 || length >= data.length - 4) { - throw const FormatException('Invalid saved font'); - } - return Upload( - utf8.decode(data.sublist(4, 4 + length)), - Uint8List.sublistView(data, 4 + length), - ); -} diff --git a/app/lib/services/uploaded_font_storage_native.dart b/app/lib/services/uploaded_font_storage_native.dart index 28f3ee60..892244d7 100644 --- a/app/lib/services/uploaded_font_storage_native.dart +++ b/app/lib/services/uploaded_font_storage_native.dart @@ -2,8 +2,8 @@ import 'dart:io'; import 'package:path_provider/path_provider.dart'; -import 'api.dart'; -import 'uploaded_font_storage.dart'; +import '../models/upload.dart'; +import 'font_storage_contract.dart'; class FontStorage implements UploadedFontStorage { FontStorage({Future Function()? directory}) diff --git a/app/lib/services/uploaded_font_storage_web.dart b/app/lib/services/uploaded_font_storage_web.dart index 63edb604..c8e42a92 100644 --- a/app/lib/services/uploaded_font_storage_web.dart +++ b/app/lib/services/uploaded_font_storage_web.dart @@ -3,8 +3,8 @@ import 'dart:js_interop'; import 'package:web/web.dart' as web; -import 'api.dart'; -import 'uploaded_font_storage.dart'; +import '../models/upload.dart'; +import 'font_storage_contract.dart'; class FontStorage implements UploadedFontStorage { Future _open() { diff --git a/app/lib/services/workspace.dart b/app/lib/services/workspace.dart index facce90d..2b63b3f9 100644 --- a/app/lib/services/workspace.dart +++ b/app/lib/services/workspace.dart @@ -7,6 +7,7 @@ import 'package:shared_preferences/shared_preferences.dart'; import '../models/settings.dart'; import '../models/ink_page.dart'; import '../models/fine_edit.dart'; +import '../models/fine_edit_history.dart'; import '../utils/ink_effects.dart'; import '../utils/fine_raster.dart'; import '../utils/text_tools.dart'; @@ -46,19 +47,13 @@ class Workspace extends ChangeNotifier { Settings settings; String text = '', version = ''; bool fineEnabled = false; - String? _fineText; - FineEdits? _fineEdits; - final _fineUndo = []; - final _fineRedo = []; - bool get _currentFineHistory => - _fineEdits != null && - _fineText == text && - _fineEdits!.key == inkPages.elementAtOrNull(page)?.fine?.key; - bool get canFineUndo => _fineUndo.isNotEmpty && _currentFineHistory; - bool get canFineRedo => _fineRedo.isNotEmpty && _currentFineHistory; + final _fineHistory = FineEditHistory(); + String? get _finePageKey => inkPages.elementAtOrNull(page)?.fine?.key; + bool get canFineUndo => _fineHistory.canStep(text, _finePageKey, redo: false); + bool get canFineRedo => _fineHistory.canStep(text, _finePageKey, redo: true); Map fineAdjustments(FinePage page) => - _fineEdits?.key == page.key ? _fineEdits!.glyphs : const {}; + _fineHistory.adjustmentsFor(page.key); Future enterFineEdit() async { if (!api.supportsFineEdit || !generation.available) return false; @@ -73,42 +68,13 @@ class Workspace extends ChangeNotifier { } void applyFineEdits(FinePage page, List values) { - if (busy || - previewStale || - inkPages.elementAtOrNull(this.page)?.fine?.key != page.key) { - return; - } - final previous = _fineEdits?.key == page.key && _fineText == text - ? _fineEdits - : null; - final next = {...?previous?.glyphs}; - var changed = false; - for (final value in values) { - if (value == defaultFineAdjustment(value.id)) { - changed = next.remove(value.id) != null || changed; - } else if (next[value.id] != value) { - next[value.id] = value; - changed = true; - } - } - if (!changed || next.length > 10000) return; - if (previous == null && _fineEdits != null) _fineUndo.clear(); - if (_fineUndo.length >= 50) _fineUndo.removeAt(0); - _fineUndo.add(previous); - _fineRedo.clear(); - _fineText = text; - _fineEdits = FineEdits(page.key, next); - edit(inkOnly: true); + if (busy || previewStale || _finePageKey != page.key) return; + if (_fineHistory.apply(text, page.key, values)) edit(inkOnly: true); } void stepFineHistory({required bool redo}) { - if (busy || previewStale || !_currentFineHistory) return; - final from = redo ? _fineRedo : _fineUndo; - final to = redo ? _fineUndo : _fineRedo; - if (from.isEmpty) return; - to.add(_fineEdits); - _fineEdits = from.removeLast() ?? FineEdits(_fineEdits!.key, const {}); - edit(inkOnly: true); + if (busy || previewStale) return; + if (_fineHistory.step(text, _finePageKey, redo: redo)) edit(inkOnly: true); } final generation = GenerationViewModel(); @@ -206,39 +172,7 @@ class Workspace extends ChangeNotifier { final saved = storage!.read('flutter.workspace'); var restoreUploadedFont = false; if (saved != null && revision == _editRevision) { - try { - final data = jsonDecode(saved) as Map; - // Restore each valid field independently; one damaged field must not - // discard the user's otherwise readable draft. - if (data['text'] is String) text = data['text'] as String; - if (data['settings'] is Map) { - settings.restore(data['settings'] as Map); - } - restoreUploadedFont = data['uploadedFont'] == true; - if (data['images'] is Map) { - images = { - for (final entry in (data['images'] as Map).entries) - if (entry.key is String && - int.tryParse(entry.key as String) != null && - entry.value is String && - decodeImageData(entry.value as String) != null) - entry.key as String: entry.value as String, - }; - } - if (data['fineEdits'] case final Map edits) { - try { - _fineEdits = FineEdits.fromJson(edits); - _fineText = text; - fineEnabled = true; - } on FormatException { - _fineEdits = null; - } on TypeError { - _fineEdits = null; - } - } - } catch (_) { - /* Leave invalid drafts untouched until the next edit. */ - } + restoreUploadedFont = _restoreSavedDraft(saved); } if (restoreUploadedFont) { final fontRevision = _fontRevision; @@ -257,12 +191,7 @@ class Workspace extends ChangeNotifier { } if (disposed) return; if (saved == null && revision == _editRevision) { - final legacy = readLegacyDraft(); - if (legacy.isNotEmpty) { - settings.restore(legacy); - text = collapseImages('${legacy['text'] ?? ''}', images); - legacyFontIndex = int.tryParse('${legacy['selectedOption']}'); - } + _restoreLegacyDraft(); } final base = storage!.read('flutter.api'); if (base != null && base != api.base && !kIsWeb && !managedBackend) { @@ -275,6 +204,42 @@ class Workspace extends ChangeNotifier { await connect(); } + /// Restores readable draft fields and reports whether the binary font needs loading. + bool _restoreSavedDraft(String saved) { + var restoreUploadedFont = false; + try { + final data = jsonDecode(saved) as Map; + if (data['text'] case final String draftText) text = draftText; + if (data['settings'] case final Map values) { + settings.restore(values); + } + restoreUploadedFont = data['uploadedFont'] == true; + if (data['images'] case final Map entries) { + images = { + for (final MapEntry(:key, :value) in entries.entries) + if (int.tryParse(key) != null && + value is String && + decodeImageData(value) != null) + key: value, + }; + } + if (data['fineEdits'] case final Map edits) { + if (_fineHistory.restore(text, edits)) fineEnabled = true; + } + } catch (_) { + // Leave invalid drafts untouched until the next edit. + } + return restoreUploadedFont; + } + + void _restoreLegacyDraft() { + final legacy = readLegacyDraft(); + if (legacy.isEmpty) return; + settings.restore(legacy); + text = collapseImages('${legacy['text'] ?? ''}', images); + legacyFontIndex = int.tryParse('${legacy['selectedOption']}'); + } + Future connect() async { if (disposed) return; final connection = ++_connection; @@ -345,13 +310,14 @@ class Workspace extends ChangeNotifier { if (disposed) return Future.value(false); saveTimer?.cancel(); final font = fontFile; + final fineEdits = _fineHistory.forText(text); final snapshot = jsonEncode({ 'text': text, 'settings': settings.toJson(), 'images': images, 'uploadedFont': font != null || _fontRestorePending, - if (_fineText == text && (_fineEdits?.glyphs.isNotEmpty ?? false)) - 'fineEdits': _fineEdits!.toJson(), + if (fineEdits != null && fineEdits.glyphs.isNotEmpty) + 'fineEdits': fineEdits.toJson(), }); return _write( 'flutter.workspace', @@ -434,8 +400,9 @@ class Workspace extends ChangeNotifier { if (fineEnabled && api.supportsFineEdit) { fields['fine_edit'] = 'true'; fields['seed'] = '0'; - if (!preview && _fineText == text && _fineEdits != null) { - fields['fine_edits'] = jsonEncode(_fineEdits!.toJson()); + final fineEdits = _fineHistory.forText(text); + if (!preview && fineEdits != null) { + fields['fine_edits'] = jsonEncode(fineEdits.toJson()); } } if (background != null) { diff --git a/app/lib/services/workspace_documents.dart b/app/lib/services/workspace_documents.dart index 1ee1cc08..a8b7a340 100644 --- a/app/lib/services/workspace_documents.dart +++ b/app/lib/services/workspace_documents.dart @@ -1,8 +1,9 @@ import 'dart:convert'; import 'dart:typed_data'; +import '../models/detected_paper_layout.dart'; +import '../models/upload.dart'; import '../utils/text_tools.dart'; -import 'api.dart'; import 'paper_background.dart'; import 'workspace.dart'; @@ -95,43 +96,14 @@ class WorkspaceDocuments { jsonEncode(workspace.settings.toJson()) == settingsBefore; final result = await api.importFile('/api/imagefileprocess', background); if (!current()) return false; - int number(String key, {int? fallback, bool positive = false}) { - final value = result[key] ?? fallback; - if (value is! num || - !value.isFinite || - value < (positive ? 1 : 0) || - value > 100000) { - throw const FormatException('Invalid paper identification'); - } - return value.round(); - } - - var spacing = number('lineSpacing', positive: true); - final first = number('marginTop'); - final legacyTop = first >= spacing ? first - spacing : first; - var top = number('layoutTopMargin', fallback: legacyTop); - var bottom = number('layoutBottomMargin', fallback: number('marginBottom')); - var left = number('marginLeft'); - var right = number('marginRight'); - var width = result.containsKey('imageWidth') - ? number('imageWidth', positive: true) - : null; - var height = result.containsKey('imageHeight') - ? number('imageHeight', positive: true) - : null; - if ((width == null) != (height == null) || - (width != null && - height != null && - (left + right >= width || top + bottom + spacing >= height))) { - throw const FormatException('Invalid paper dimensions'); - } + var layout = DetectedPaperLayout.fromJson(result); Upload? replacement; final corrected = result['correctedBackground']; if (corrected != null) { + final size = layout.size; if (corrected is! String || corrected.length > 48 * 1024 * 1024 || - width == null || - height == null) { + size == null) { throw const FormatException('Invalid corrected background'); } final bytes = base64Decode(corrected); @@ -139,34 +111,14 @@ class WorkspaceDocuments { Upload('aligned-paper.png', bytes), mobile: api.usesMobilePaperLimits, readPaperExif: api.readPaperExif, - correctedSize: (width: width, height: height), + correctedSize: size, ); - if (prepared.width != width || prepared.height != height) { - final horizontal = prepared.width / width; - final vertical = prepared.height / height; - left = (left * horizontal).round(); - right = (right * horizontal).round(); - top = (top * vertical).round(); - bottom = (bottom * vertical).round(); - spacing = (spacing * vertical).round().clamp(1, prepared.height); - width = prepared.width; - height = prepared.height; - } + layout = layout.scaledTo(prepared.width, prepared.height); replacement = prepared.file; } if (!current()) return false; - final fontSize = num.tryParse(workspace.settings.values['font_size'] ?? ''); - workspace.settings.values.addAll({ - if (fontSize != null && fontSize >= spacing) - 'font_size': '${(spacing * 0.72).round().clamp(1, 100000)}', - 'left_margin': '$left', - 'right_margin': '$right', - 'top_margin': '$top', - 'bottom_margin': '$bottom', - 'line_spacing': '$spacing', - if (width != null) 'width': '$width', - if (height != null) 'height': '$height', - }); + final values = workspace.settings.values; + values.addAll(layout.settings(values['font_size'])); if (replacement != null) workspace.background = replacement; workspace.backgroundRuled = true; workspace.edit(); diff --git a/app/lib/theme/handwriting_controls.dart b/app/lib/theme/handwriting_controls.dart new file mode 100644 index 00000000..fe21a5d4 --- /dev/null +++ b/app/lib/theme/handwriting_controls.dart @@ -0,0 +1,122 @@ +import 'package:flutter/material.dart'; + +import 'handwriting_palette.dart'; + +WidgetStateProperty _whenEnabled(WidgetState state, T value) => + WidgetStateProperty.resolveWith( + (states) => + states.contains(state) && !states.contains(WidgetState.disabled) + ? value + : null, + ); + +InputDecorationTheme handwritingInputTheme(ColorScheme scheme) { + OutlineInputBorder fieldBorder(Color color, {double width = 1}) => + OutlineInputBorder( + borderRadius: const BorderRadius.all(Radius.circular(28)), + borderSide: BorderSide(color: color, width: width), + ); + return InputDecorationTheme( + isDense: true, + filled: true, + fillColor: scheme.brightness == Brightness.dark + ? NightSurfaces.writing + : scheme.surfaceContainerLowest, + border: fieldBorder(scheme.outlineVariant), + enabledBorder: fieldBorder(scheme.outlineVariant), + focusedBorder: fieldBorder(scheme.secondary, width: 2), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12), + ); +} + +SwitchThemeData handwritingSwitchTheme(ColorScheme scheme) => SwitchThemeData( + trackColor: _whenEnabled(WidgetState.selected, scheme.secondary), + thumbColor: _whenEnabled(WidgetState.selected, scheme.onSecondary), +); + +ButtonStyle handwritingFilledButton(HandwritingPalette palette) { + final scheme = palette.scheme; + return scheme.brightness == Brightness.dark + ? _nightFilledButton(scheme) + : ButtonStyle( + animationDuration: Duration.zero, + backgroundColor: _whenEnabled(WidgetState.hovered, palette.trim), + foregroundColor: _whenEnabled(WidgetState.hovered, palette.onTrim), + shape: const WidgetStatePropertyAll(StadiumBorder()), + side: WidgetStatePropertyAll(BorderSide(color: palette.trim)), + ); +} + +ButtonStyle handwritingOutlinedButton(ColorScheme scheme) => + OutlinedButton.styleFrom( + shape: const StadiumBorder(), + side: BorderSide(color: scheme.outlineVariant), + animationDuration: Duration.zero, + foregroundColor: scheme.onSurface, + ).copyWith( + side: scheme.brightness == Brightness.dark + ? WidgetStateProperty.resolveWith( + (states) => BorderSide( + color: states.contains(WidgetState.disabled) + ? scheme.outlineVariant + : states.contains(WidgetState.focused) + ? scheme.secondary + : states.contains(WidgetState.hovered) || + states.contains(WidgetState.pressed) + ? scheme.primary + : scheme.outline, + width: states.contains(WidgetState.focused) ? 2 : 1, + ), + ) + : null, + ); + +ButtonStyle handwritingSegmentedButton(ColorScheme scheme) => ButtonStyle( + animationDuration: Duration.zero, + shape: const WidgetStatePropertyAll(StadiumBorder()), + backgroundColor: _whenEnabled( + WidgetState.selected, + scheme.secondaryContainer, + ), + foregroundColor: WidgetStateProperty.resolveWith((states) { + if (states.contains(WidgetState.disabled)) return null; + return states.contains(WidgetState.selected) + ? scheme.onSecondaryContainer + : scheme.onSurfaceVariant; + }), +); + +ButtonStyle _nightFilledButton(ColorScheme colors) { + return ButtonStyle( + shape: const WidgetStatePropertyAll(StadiumBorder()), + animationDuration: Duration.zero, + // Keep the native base colors of filled and tonal variants. + overlayColor: WidgetStateProperty.resolveWith((states) { + if (states.contains(WidgetState.disabled)) return Colors.transparent; + if (states.contains(WidgetState.pressed)) { + return colors.surface.withValues(alpha: .18); + } + if (states.contains(WidgetState.hovered)) { + return Colors.white.withValues(alpha: .15); + } + return null; + }), + backgroundColor: WidgetStateProperty.resolveWith( + (states) => states.contains(WidgetState.disabled) + ? colors.surfaceContainerHigh + : null, + ), + foregroundColor: WidgetStateProperty.resolveWith( + (states) => states.contains(WidgetState.disabled) + ? colors.onSurfaceVariant.withValues(alpha: .62) + : null, + ), + side: WidgetStateProperty.resolveWith((states) { + if (states.contains(WidgetState.disabled)) return BorderSide.none; + if (states.contains(WidgetState.focused)) { + return BorderSide(color: colors.onSurface, width: 2); + } + return BorderSide.none; + }), + ); +} diff --git a/app/lib/theme/handwriting_palette.dart b/app/lib/theme/handwriting_palette.dart new file mode 100644 index 00000000..465b3863 --- /dev/null +++ b/app/lib/theme/handwriting_palette.dart @@ -0,0 +1,171 @@ +import 'package:flutter/material.dart'; + +import 'nouveau_ornament.dart'; + +const defaultThemeColor = NouveauColors.wisteria; +const defaultSecondaryThemeColor = NouveauColors.forest; + +/// Black ink layers over a single opaque, neutral workbench background. +abstract final class NightSurfaces { + static const panel = Color(0x40000000); + static const navigation = Color(0x52000000); + static const writing = Color(0x35000000); + static const preview = Color(0x20000000); + + static LinearGradient backdrop(Color base) => LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [ + Color.lerp(base, const Color(0xffa7a8ad), .22)!, + base, + Color.lerp(base, const Color(0xff202124), .48)!, + ], + ); +} + +/// Seed-derived colors used by both Material surfaces and custom controls. +class HandwritingPalette { + const HandwritingPalette._(this.scheme, this.appBarBackground, this.trim); + + final ColorScheme scheme; + final Color appBarBackground; + final Color trim; + Color get onTrim => _onSolidColor(trim); + + factory HandwritingPalette( + Brightness brightness, + Color seedColor, + Color secondaryColor, + ) { + final dark = brightness == Brightness.dark; + final hue = HSLColor.fromColor(seedColor); + // Large surfaces share a neutral ramp. Hue adds only a trace of warmth or + // coolness; saturated user-picked colors stay on small interactive elements. + final saturation = hue.saturation.clamp(0.0, dark ? .035 : .085); + Color surfaceTone(double daylight, double moonlight) => HSLColor.fromAHSL( + 1, + hue.hue, + saturation, + dark ? moonlight : daylight, + ).toColor(); + final surface = surfaceTone(.943, .285); + final raised = surfaceTone(.982, .232); + final foreground = dark ? NouveauColors.ivory : surfaceTone(.17, .943); + final muted = surfaceTone(.355, .788); + final outline = surfaceTone(.45, .66); + final base = ColorScheme.fromSeed( + seedColor: dark && seedColor == defaultThemeColor + ? NouveauColors.moonIris + : seedColor, + brightness: brightness, + ); + final primary = dark + ? (seedColor == defaultThemeColor + ? NouveauColors.moonIris + : base.primary) + : seedColor == defaultThemeColor + ? _contrastingInk(seedColor, NouveauColors.ivory, false) + : _readableAccent(seedColor, surface, foreground, 0, 4.5); + final primaryContainer = Color.alphaBlend( + (dark ? primary : seedColor).withValues(alpha: dark ? .16 : .20), + raised, + ); + final secondaryContainer = Color.alphaBlend( + (dark && secondaryColor == defaultSecondaryThemeColor + ? NouveauColors.nightSage + : secondaryColor) + .withValues(alpha: dark ? .16 : .13), + dark ? const Color(0xFF383B41) : const Color(0xFFFAF9F7), + ); + final secondary = dark && secondaryColor == defaultSecondaryThemeColor + ? NouveauColors.nightSage + : _contrastingInk(secondaryColor, secondaryContainer, dark); + final trim = hue.withLightness(.60).toColor(); + final border = Color.lerp( + surfaceTone(.81, .325), + dark ? primary : trim, + dark ? .08 : .15, + )!; + final scheme = base.copyWith( + primary: primary, + onPrimary: !dark && seedColor == defaultThemeColor + ? NouveauColors.ivory + : _onSolidColor(primary), + primaryContainer: primaryContainer, + onPrimaryContainer: foreground, + secondary: secondary, + onSecondary: _onSolidColor(secondary), + secondaryContainer: secondaryContainer, + onSecondaryContainer: secondary, + tertiary: dark + ? const Color(0xFFB8A982) + : hue.withLightness(.34).toColor(), + surface: surface, + onSurface: foreground, + onSurfaceVariant: muted, + surfaceDim: surfaceTone(.907, .166), + surfaceBright: surfaceTone(.995, .315), + surfaceContainerLowest: surfaceTone(.963, .198), + surfaceContainerLow: surfaceTone(.971, .212), + surfaceContainer: raised, + surfaceContainerHigh: surfaceTone(.924, .258), + surfaceContainerHighest: surfaceTone(.899, .28), + outline: outline, + outlineVariant: border, + surfaceTint: Colors.transparent, + ); + + return HandwritingPalette._( + scheme, + dark + ? Color.alphaBlend(NightSurfaces.navigation, surface) + : surfaceTone(.966, .222), + trim, + ); + } +} + +Color _onSolidColor(Color background) => + background.computeLuminance() > .179 ? Colors.black : Colors.white; + +// Keep the chosen hue and saturation, adjusting lightness only when the +// selected control's label would otherwise fall below 4.5:1 contrast. +Color _contrastingInk(Color seed, Color container, bool dark) { + final background = container.computeLuminance() + .05; + bool readable(Color color) { + final ink = color.computeLuminance() + .05; + return (dark ? ink / background : background / ink) >= 4.5; + } + + if (readable(seed)) return seed; + final hsl = HSLColor.fromColor(seed); + var near = hsl.lightness; + var far = dark ? 1.0 : 0.0; + for (var i = 0; i < 8; i++) { + final middle = (near + far) / 2; + if (readable(hsl.withLightness(middle).toColor())) { + far = middle; + } else { + near = middle; + } + } + return hsl.withLightness(far).toColor(); +} + +Color _readableAccent( + Color seed, + Color background, + Color foreground, + double blend, + double minimumContrast, +) { + final backgroundLightness = background.computeLuminance(); + final accent = Color.lerp(seed, foreground, blend)!; + final accentLightness = accent.computeLuminance(); + final contrast = accentLightness > backgroundLightness + ? (accentLightness + .05) / (backgroundLightness + .05) + : (backgroundLightness + .05) / (accentLightness + .05); + return contrast >= minimumContrast + ? accent + : Color.lerp(seed, foreground, .8)!; +} diff --git a/app/lib/theme/handwriting_theme.dart b/app/lib/theme/handwriting_theme.dart index 780ab358..14c3a93b 100644 --- a/app/lib/theme/handwriting_theme.dart +++ b/app/lib/theme/handwriting_theme.dart @@ -1,27 +1,10 @@ import 'package:flutter/material.dart'; -import 'nouveau_ornament.dart'; +import 'handwriting_controls.dart'; +import 'handwriting_palette.dart'; -const defaultThemeColor = NouveauColors.wisteria; -const defaultSecondaryThemeColor = NouveauColors.forest; - -/// Black ink layers over a single opaque, neutral workbench background. -abstract final class NightSurfaces { - static const panel = Color(0x40000000); - static const navigation = Color(0x52000000); - static const writing = Color(0x35000000); - static const preview = Color(0x20000000); - - static LinearGradient backdrop(Color base) => LinearGradient( - begin: Alignment.topLeft, - end: Alignment.bottomRight, - colors: [ - Color.lerp(base, const Color(0xffa7a8ad), .22)!, - base, - Color.lerp(base, const Color(0xff202124), .48)!, - ], - ); -} +export 'handwriting_palette.dart' + show NightSurfaces, defaultThemeColor, defaultSecondaryThemeColor; /// An opaque base lets translucent dark surfaces composite consistently. Widget handwritingBackdrop(BuildContext context, Widget? child) => @@ -33,150 +16,50 @@ ThemeData handwritingTheme( Color seedColor = defaultThemeColor, Color secondaryColor = defaultSecondaryThemeColor, }) { + final palette = HandwritingPalette(brightness, seedColor, secondaryColor); + final scheme = palette.scheme; final dark = brightness == Brightness.dark; - final hue = HSLColor.fromColor(seedColor); - // Large surfaces share a neutral ramp. Hue adds only a trace of warmth or - // coolness; saturated user-picked colors stay on small interactive elements. - final saturation = hue.saturation.clamp(0.0, dark ? .035 : .085); - Color surfaceTone(double daylight, double moonlight) => HSLColor.fromAHSL( - 1, - hue.hue, - saturation, - dark ? moonlight : daylight, - ).toColor(); - final surface = surfaceTone(.943, .285); - final raised = surfaceTone(.982, .232); - final foreground = dark ? NouveauColors.ivory : surfaceTone(.17, .943); - final muted = surfaceTone(.355, .788); - final outline = surfaceTone(.45, .66); - final base = ColorScheme.fromSeed( - seedColor: dark && seedColor == defaultThemeColor - ? NouveauColors.moonIris - : seedColor, - brightness: brightness, - ); - final primary = dark - ? (seedColor == defaultThemeColor ? NouveauColors.moonIris : base.primary) - : seedColor == defaultThemeColor - ? _contrastingInk(seedColor, NouveauColors.ivory, false) - : _readableAccent(seedColor, surface, foreground, 0, 4.5); - final primaryContainer = Color.alphaBlend( - (dark ? primary : seedColor).withValues(alpha: dark ? .16 : .20), - raised, - ); - final secondaryContainer = Color.alphaBlend( - (dark && secondaryColor == defaultSecondaryThemeColor - ? NouveauColors.nightSage - : secondaryColor) - .withValues(alpha: dark ? .16 : .13), - dark ? const Color(0xFF383B41) : const Color(0xFFFAF9F7), - ); - final secondary = dark && secondaryColor == defaultSecondaryThemeColor - ? NouveauColors.nightSage - : _contrastingInk(secondaryColor, secondaryContainer, dark); - final trim = hue.withLightness(.60).toColor(); - final border = Color.lerp( - surfaceTone(.81, .325), - dark ? primary : trim, - dark ? .08 : .15, - )!; - final scheme = base.copyWith( - primary: primary, - onPrimary: !dark && seedColor == defaultThemeColor - ? NouveauColors.ivory - : _onSolidColor(primary), - primaryContainer: primaryContainer, - onPrimaryContainer: foreground, - secondary: secondary, - onSecondary: _onSolidColor(secondary), - secondaryContainer: secondaryContainer, - onSecondaryContainer: secondary, - tertiary: dark ? const Color(0xFFB8A982) : hue.withLightness(.34).toColor(), - surface: surface, - onSurface: foreground, - onSurfaceVariant: muted, - surfaceDim: surfaceTone(.907, .166), - surfaceBright: surfaceTone(.995, .315), - surfaceContainerLowest: surfaceTone(.963, .198), - surfaceContainerLow: surfaceTone(.971, .212), - surfaceContainer: raised, - surfaceContainerHigh: surfaceTone(.924, .258), - surfaceContainerHighest: surfaceTone(.899, .28), - outline: outline, - outlineVariant: border, - surfaceTint: Colors.transparent, - ); - - const controlShape = StadiumBorder(); final cardShape = RoundedRectangleBorder( borderRadius: BorderRadius.circular(32), - side: BorderSide(color: border), + side: BorderSide(color: scheme.outlineVariant), ); - OutlineInputBorder fieldBorder(Color color, {double width = 1}) => - OutlineInputBorder( - borderRadius: const BorderRadius.all(Radius.circular(28)), - borderSide: BorderSide(color: color, width: width), - ); final theme = ThemeData( useMaterial3: true, fontFamily: 'packages/handwriting_assets/LXGW WenKai', colorScheme: scheme, - scaffoldBackgroundColor: surface, + scaffoldBackgroundColor: scheme.surface, appBarTheme: AppBarThemeData( - backgroundColor: dark - ? Color.alphaBlend(NightSurfaces.navigation, surface) - : surfaceTone(.966, .222), - foregroundColor: foreground, + backgroundColor: palette.appBarBackground, + foregroundColor: scheme.onSurface, elevation: 0, scrolledUnderElevation: 0, ), - dividerTheme: DividerThemeData(color: border), + dividerTheme: DividerThemeData(color: scheme.outlineVariant), sliderTheme: SliderThemeData( - activeTrackColor: secondary, - thumbColor: secondary, - inactiveTrackColor: secondaryContainer, + activeTrackColor: scheme.secondary, + thumbColor: scheme.secondary, + inactiveTrackColor: scheme.secondaryContainer, activeTickMarkColor: scheme.onSecondary, inactiveTickMarkColor: scheme.onSecondaryContainer, - overlayColor: secondary.withValues(alpha: .12), - ), - switchTheme: SwitchThemeData( - trackColor: WidgetStateProperty.resolveWith( - (states) => - states.contains(WidgetState.selected) && - !states.contains(WidgetState.disabled) - ? secondary - : null, - ), - thumbColor: WidgetStateProperty.resolveWith( - (states) => - states.contains(WidgetState.selected) && - !states.contains(WidgetState.disabled) - ? scheme.onSecondary - : null, - ), + overlayColor: scheme.secondary.withValues(alpha: .12), ), + switchTheme: handwritingSwitchTheme(scheme), chipTheme: ChipThemeData( shape: const StadiumBorder(), - side: BorderSide(color: border), - selectedColor: secondaryContainer, - secondarySelectedColor: secondaryContainer, - checkmarkColor: secondary, - ), - inputDecorationTheme: InputDecorationTheme( - isDense: true, - filled: true, - fillColor: dark ? NightSurfaces.writing : scheme.surfaceContainerLowest, - border: fieldBorder(border), - enabledBorder: fieldBorder(border), - focusedBorder: fieldBorder(secondary, width: 2), - contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12), + side: BorderSide(color: scheme.outlineVariant), + selectedColor: scheme.secondaryContainer, + secondarySelectedColor: scheme.secondaryContainer, + checkmarkColor: scheme.secondary, ), + inputDecorationTheme: handwritingInputTheme(scheme), cardTheme: CardThemeData( elevation: dark ? 0 : 2, - shadowColor: dark ? Colors.black54 : foreground.withValues(alpha: .22), + shadowColor: dark + ? Colors.black54 + : scheme.onSurface.withValues(alpha: .22), margin: EdgeInsets.zero, - color: dark ? NightSurfaces.panel : raised, + color: dark ? NightSurfaces.panel : scheme.surfaceContainer, shape: cardShape, ), // ButtonStyleButton interpolates an entire nested ThemeData per button. @@ -189,87 +72,38 @@ ThemeData handwritingTheme( style: ButtonStyle(animationDuration: Duration.zero), ), filledButtonTheme: FilledButtonThemeData( - style: dark - ? _nightFilledButton(scheme) - : ButtonStyle( - animationDuration: Duration.zero, - backgroundColor: WidgetStateProperty.resolveWith( - (states) => - states.contains(WidgetState.hovered) && - !states.contains(WidgetState.disabled) - ? trim - : null, - ), - foregroundColor: WidgetStateProperty.resolveWith( - (states) => - states.contains(WidgetState.hovered) && - !states.contains(WidgetState.disabled) - ? _onSolidColor(trim) - : null, - ), - shape: const WidgetStatePropertyAll(controlShape), - side: WidgetStatePropertyAll(BorderSide(color: trim)), - ), + style: handwritingFilledButton(palette), ), outlinedButtonTheme: OutlinedButtonThemeData( - style: - OutlinedButton.styleFrom( - shape: controlShape, - side: BorderSide(color: border), - animationDuration: Duration.zero, - foregroundColor: foreground, - ).copyWith( - side: dark - ? WidgetStateProperty.resolveWith( - (states) => BorderSide( - color: states.contains(WidgetState.disabled) - ? border - : states.contains(WidgetState.focused) - ? secondary - : states.contains(WidgetState.hovered) || - states.contains(WidgetState.pressed) - ? primary - : outline, - width: states.contains(WidgetState.focused) ? 2 : 1, - ), - ) - : null, - ), + style: handwritingOutlinedButton(scheme), ), textButtonTheme: TextButtonThemeData( style: TextButton.styleFrom( animationDuration: Duration.zero, - shape: controlShape, - foregroundColor: foreground, + shape: const StadiumBorder(), + foregroundColor: scheme.onSurface, ), ), segmentedButtonTheme: SegmentedButtonThemeData( - style: ButtonStyle( - animationDuration: Duration.zero, - shape: const WidgetStatePropertyAll(controlShape), - backgroundColor: WidgetStateProperty.resolveWith( - (states) => - states.contains(WidgetState.selected) && - !states.contains(WidgetState.disabled) - ? secondaryContainer - : null, - ), - foregroundColor: WidgetStateProperty.resolveWith((states) { - if (states.contains(WidgetState.disabled)) return null; - return states.contains(WidgetState.selected) - ? scheme.onSecondaryContainer - : scheme.onSurfaceVariant; - }), - ), + style: handwritingSegmentedButton(scheme), + ), + dialogTheme: DialogThemeData( + backgroundColor: scheme.surfaceContainer, + shape: cardShape, ), - dialogTheme: DialogThemeData(backgroundColor: raised, shape: cardShape), bottomSheetTheme: BottomSheetThemeData( - backgroundColor: raised, - modalBackgroundColor: raised, - dragHandleColor: outline, + backgroundColor: scheme.surfaceContainer, + modalBackgroundColor: scheme.surfaceContainer, + dragHandleColor: scheme.outline, ), ); - final railLabel = theme.textTheme.labelMedium!; + return theme.copyWith( + textTheme: _handwritingText(theme.textTheme), + navigationRailTheme: _navigationRail(scheme, theme.textTheme.labelMedium!), + ); +} + +TextTheme _handwritingText(TextTheme text) { TextStyle? heading(TextStyle? style) => style?.copyWith( fontFamily: 'Playfair Display', fontFamilyFallback: const [ @@ -278,113 +112,35 @@ ThemeData handwritingTheme( 'serif', ], ); - return theme.copyWith( - textTheme: theme.textTheme.copyWith( - displayLarge: heading(theme.textTheme.displayLarge) - ?.copyWith(fontSize: 60, height: 1.1, fontWeight: FontWeight.w700), - displayMedium: heading(theme.textTheme.displayMedium), - displaySmall: heading(theme.textTheme.displaySmall), - headlineSmall: heading(theme.textTheme.headlineSmall), - headlineMedium: heading(theme.textTheme.headlineMedium), - titleSmall: heading(theme.textTheme.titleSmall), - headlineLarge: heading(theme.textTheme.headlineLarge) - ?.copyWith(fontSize: 36, height: 1.25, fontWeight: FontWeight.w700), - titleLarge: heading(theme.textTheme.titleLarge) - ?.copyWith(fontSize: 26, height: 1.35, fontWeight: FontWeight.w700), - titleMedium: heading(theme.textTheme.titleMedium) - ?.copyWith(fontSize: 20, height: 1.25, fontWeight: FontWeight.w700), - bodyLarge: theme.textTheme.bodyLarge?.copyWith(height: 1.8), - ), - navigationRailTheme: NavigationRailThemeData( - backgroundColor: surface, - indicatorColor: primaryContainer, - selectedIconTheme: IconThemeData(color: primary), - unselectedIconTheme: IconThemeData(color: muted), - selectedLabelTextStyle: railLabel.copyWith( - color: foreground, - fontWeight: FontWeight.w600, - ), - unselectedLabelTextStyle: railLabel.copyWith(color: muted), - ), + return text.copyWith( + displayLarge: heading(text.displayLarge) + ?.copyWith(fontSize: 60, height: 1.1, fontWeight: FontWeight.w700), + displayMedium: heading(text.displayMedium), + displaySmall: heading(text.displaySmall), + headlineSmall: heading(text.headlineSmall), + headlineMedium: heading(text.headlineMedium), + titleSmall: heading(text.titleSmall), + headlineLarge: heading(text.headlineLarge) + ?.copyWith(fontSize: 36, height: 1.25, fontWeight: FontWeight.w700), + titleLarge: heading(text.titleLarge) + ?.copyWith(fontSize: 26, height: 1.35, fontWeight: FontWeight.w700), + titleMedium: heading(text.titleMedium) + ?.copyWith(fontSize: 20, height: 1.25, fontWeight: FontWeight.w700), + bodyLarge: text.bodyLarge?.copyWith(height: 1.8), ); } -Color _onSolidColor(Color background) => - background.computeLuminance() > .179 ? Colors.black : Colors.white; - -// Keep the chosen hue and saturation, adjusting lightness only when the -// selected control's label would otherwise fall below 4.5:1 contrast. -Color _contrastingInk(Color seed, Color container, bool dark) { - final background = container.computeLuminance() + .05; - bool readable(Color color) { - final ink = color.computeLuminance() + .05; - return (dark ? ink / background : background / ink) >= 4.5; - } - - if (readable(seed)) return seed; - final hsl = HSLColor.fromColor(seed); - var near = hsl.lightness; - var far = dark ? 1.0 : 0.0; - for (var i = 0; i < 8; i++) { - final middle = (near + far) / 2; - if (readable(hsl.withLightness(middle).toColor())) { - far = middle; - } else { - near = middle; - } - } - return hsl.withLightness(far).toColor(); -} - -Color _readableAccent( - Color seed, - Color background, - Color foreground, - double blend, - double minimumContrast, -) { - final backgroundLightness = background.computeLuminance(); - final accent = Color.lerp(seed, foreground, blend)!; - final accentLightness = accent.computeLuminance(); - final contrast = accentLightness > backgroundLightness - ? (accentLightness + .05) / (backgroundLightness + .05) - : (backgroundLightness + .05) / (accentLightness + .05); - return contrast >= minimumContrast - ? accent - : Color.lerp(seed, foreground, .8)!; -} - -ButtonStyle _nightFilledButton(ColorScheme colors) { - return ButtonStyle( - shape: const WidgetStatePropertyAll(StadiumBorder()), - animationDuration: Duration.zero, - // Keep the native base colors of filled and tonal variants. - overlayColor: WidgetStateProperty.resolveWith((states) { - if (states.contains(WidgetState.disabled)) return Colors.transparent; - if (states.contains(WidgetState.pressed)) { - return colors.surface.withValues(alpha: .18); - } - if (states.contains(WidgetState.hovered)) { - return Colors.white.withValues(alpha: .15); - } - return null; - }), - backgroundColor: WidgetStateProperty.resolveWith( - (states) => states.contains(WidgetState.disabled) - ? colors.surfaceContainerHigh - : null, - ), - foregroundColor: WidgetStateProperty.resolveWith( - (states) => states.contains(WidgetState.disabled) - ? colors.onSurfaceVariant.withValues(alpha: .62) - : null, - ), - side: WidgetStateProperty.resolveWith((states) { - if (states.contains(WidgetState.disabled)) return BorderSide.none; - if (states.contains(WidgetState.focused)) { - return BorderSide(color: colors.onSurface, width: 2); - } - return BorderSide.none; - }), - ); -} +NavigationRailThemeData _navigationRail( + ColorScheme scheme, + TextStyle railLabel, +) => NavigationRailThemeData( + backgroundColor: scheme.surface, + indicatorColor: scheme.primaryContainer, + selectedIconTheme: IconThemeData(color: scheme.primary), + unselectedIconTheme: IconThemeData(color: scheme.onSurfaceVariant), + selectedLabelTextStyle: railLabel.copyWith( + color: scheme.onSurface, + fontWeight: FontWeight.w600, + ), + unselectedLabelTextStyle: railLabel.copyWith(color: scheme.onSurfaceVariant), +); diff --git a/app/lib/utils/course_latex.dart b/app/lib/utils/course_latex.dart index 55a4cbb7..94c758af 100644 --- a/app/lib/utils/course_latex.dart +++ b/app/lib/utils/course_latex.dart @@ -1,7 +1,6 @@ import 'physics_latex.dart'; +import 'siunitx_latex.dart'; -// A deliberately small siunitx subset. Unrecognised options, units and numeric -// uncertainties remain source, so a course formula cannot silently change units. String normalizeCourseLatex(String source) { source = normalizePhysicsLatex(source); final out = StringBuffer(); @@ -17,52 +16,36 @@ String normalizeCourseLatex(String source) { out.write(source[cursor++]); continue; } - final rawName = command[1]!; - final name = rawName == 'qty' - ? 'SI' - : rawName == 'unit' - ? 'si' - : rawName; + final name = command[1]!; final end = cursor + command[0]!.length; final first = _argument(source, end); - if ({ - 'text', - 'textrm', - 'textbf', - 'textit', - 'texttt', - 'verb', - }.contains(name) && - first != null) { - out.write(source.substring(cursor, first.end)); - cursor = first.end; - continue; - } - if (name == 'ce' && first != null) { - out.write( - _chemicalFormula(first.body) ?? source.substring(cursor, first.end), - ); - cursor = first.end; - continue; - } - if (!{'SI', 'si', 'num'}.contains(name) || first == null) { + if (first == null) { out.write(command[0]); cursor = end; continue; } - final second = name == 'SI' ? _argument(source, first.end) : null; - final number = name == 'si' ? null : _number(first.body); - final unit = name == 'num' - ? null - : _unit(name == 'si' ? first.body : second?.body ?? ''); - final replacement = name == 'num' - ? number - : unit == null || (name == 'SI' && number == null) - ? null - : name == 'si' - ? unit - : '$number\\,$unit'; - final consumed = second?.end ?? first.end; + var consumed = first.end; + final String? replacement; + switch (name) { + case 'text' || 'textrm' || 'textbf' || 'textit' || 'texttt' || 'verb': + replacement = null; + case 'ce': + replacement = _chemicalFormula(first.body); + case 'num': + replacement = normalizeSiNumber(first.body); + case 'si' || 'unit': + replacement = normalizeSiUnit(first.body); + case 'SI' || 'qty': + final second = _argument(source, first.end); + consumed = second?.end ?? first.end; + replacement = second == null + ? null + : normalizeSiQuantity(first.body, second.body); + default: + out.write(command[0]); + cursor = end; + continue; + } out.write(replacement ?? source.substring(cursor, consumed)); cursor = consumed; } @@ -88,114 +71,6 @@ String normalizeCourseLatex(String source) { return null; } -String? _number(String value) { - final match = RegExp( - r'^([+-]?(?:\d+(?:\.\d*)?|\.\d+))(?:[eE]([+-]?\d{1,3}))?$', - ).firstMatch(value.trim()); - if (match == null) return null; - return match[2] == null - ? match[1] - : '${match[1]}\\times10^{${int.parse(match[2]!)}}'; -} - -const _prefixes = { - 'pico': 'p', - 'nano': 'n', - 'micro': 'μ', - 'milli': 'm', - 'centi': 'c', - 'deci': 'd', - 'kilo': 'k', - 'mega': 'M', - 'giga': 'G', - 'tera': 'T', -}; -const _units = { - 'metre': 'm', - 'meter': 'm', - 'second': 's', - 'ampere': 'A', - 'kelvin': 'K', - 'mole': 'mol', - 'candela': 'cd', - 'gram': 'g', - 'kilogram': 'kg', - 'hertz': 'Hz', - 'newton': 'N', - 'pascal': 'Pa', - 'joule': 'J', - 'watt': 'W', - 'coulomb': 'C', - 'volt': 'V', - 'farad': 'F', - 'ohm': 'Ω', - 'siemens': 'S', - 'weber': 'Wb', - 'tesla': 'T', - 'henry': 'H', - 'radian': 'rad', - 'steradian': 'sr', - 'degree': '°', - 'degreeCelsius': '°C', - 'liter': 'L', - 'litre': 'L', - 'electronvolt': 'eV', - 'decibel': 'dB', - 'percent': r'\%', - 'bit': 'bit', - 'byte': 'B', -}; - -String? _unit(String source) { - final tokens = RegExp(r'\\([A-Za-z]+)(?:\{([+-]?\d{1,3})\})?'); - final numerator = [], denominator = []; - var cursor = 0, prefix = '', divided = false, powered = false; - List? lastTarget; - for (final token in tokens.allMatches(source)) { - if (source.substring(cursor, token.start).trim().isNotEmpty) return null; - cursor = token.end; - final name = token[1]!; - final target = divided ? denominator : numerator; - if (name == 'per' && token[2] == null) { - if (divided || prefix.isNotEmpty) return null; - divided = true; - powered = false; - lastTarget = null; - } else if (_prefixes.containsKey(name) && token[2] == null) { - if (prefix.isNotEmpty) return null; - prefix = _prefixes[name]!; - } else if (_units.containsKey(name) && token[2] == null) { - target.add('\\mathrm{$prefix${_units[name]}}'); - lastTarget = target; - divided = false; - prefix = ''; - powered = false; - } else if ({'squared', 'cubed', 'tothe'}.contains(name)) { - if (lastTarget == null || prefix.isNotEmpty || powered) return null; - final power = name == 'tothe' - ? token[2] - : token[2] == null - ? (name == 'squared' ? '2' : '3') - : null; - if (power == null) return null; - lastTarget[lastTarget.length - 1] += '^{${int.parse(power)}}'; - powered = true; - } else { - return null; - } - } - if (source.substring(cursor).trim().isNotEmpty || - prefix.isNotEmpty || - (numerator.isEmpty && denominator.isEmpty) || - divided) { - return null; - } - final top = numerator.isEmpty ? '1' : numerator.join(r'\,'); - if (denominator.isEmpty) return top; - final bottom = denominator.join(r'\,'); - return '$top/${denominator.length > 1 ? '($bottom)' : bottom}'; -} - String calligraphicCapitals(String value) { if (!RegExp(r'^[A-Z]+$').hasMatch(value)) { throw const FormatException('Unsupported calligraphic symbol'); @@ -241,54 +116,58 @@ String? _chemicalSpecies(String source) { value = value.substring(0, ion.start); } final coefficient = RegExp(r'^(\d+\/\d+|\d+(?:\.\d+)?)\s*').firstMatch(value); - var result = coefficient?[1] ?? ''; - if (result.contains('/')) { - final parts = result.split('/'); - if (int.parse(parts[1]) == 0) return null; - result = '\\frac{${parts[0]}}{${parts[1]}}\\,'; + var prefix = coefficient?[1] ?? ''; + if (prefix.contains('/')) { + final parts = prefix.split('/'); + if (!RegExp(r'[1-9]').hasMatch(parts[1])) return null; + prefix = '\\frac{${parts[0]}}{${parts[1]}}\\,'; } - if (coefficient != null) value = value.substring(coefficient.end); - final stack = []; - var atoms = 0, previous = false; + final body = _chemicalSpeciesBody(value.substring(coefficient?.end ?? 0)); + if (body == null) return null; + return '\\mathrm{$prefix$body$charge}$suffix'; +} + +final _elementSymbol = RegExp(r'[A-Z][a-z]?|e'); +final _atomCount = RegExp(r'\d+'); + +String? _chemicalSpeciesBody(String value) { + final result = StringBuffer(); + final closingBrackets = []; + var canEndGroup = false; for (var cursor = 0; cursor < value.length;) { - final rest = value.substring(cursor); - final element = RegExp(r'^(?:[A-Z][a-z]?|e)').firstMatch(rest); + final element = _elementSymbol.matchAsPrefix(value, cursor); if (element != null) { - result += element[0]!; - atoms++; - previous = true; - cursor += element.end; + result.write(element[0]); + canEndGroup = true; + cursor = element.end; continue; } - final count = RegExp(r'^\d+').firstMatch(rest); - if (count != null && previous) { - if (count[0]!.length > 3) return null; - result += '_{${count[0]}}'; - previous = true; - cursor += count.end; + final count = _atomCount.matchAsPrefix(value, cursor); + if (count != null && canEndGroup) { + if (count.end - cursor > 3) return null; + result.write('_{${count[0]}}'); + cursor = count.end; continue; } final char = value[cursor]; if (char == '(' || char == '[') { - if (stack.length >= 8) return null; - stack.add(char); - result += char; - previous = false; + if (closingBrackets.length >= 8) return null; + closingBrackets.add(char == '(' ? ')' : ']'); + canEndGroup = false; } else if (char == ')' || char == ']') { - if (!previous || - stack.isEmpty || - stack.removeLast() != (char == ')' ? '(' : '[')) { + if (!canEndGroup || + closingBrackets.isEmpty || + closingBrackets.removeLast() != char) { return null; } - result += char; - previous = true; } else { return null; } + result.write(char); cursor++; } - if (atoms == 0 || stack.isNotEmpty) return null; - return '\\mathrm{$result$charge}$suffix'; + if (!canEndGroup || closingBrackets.isNotEmpty) return null; + return result.toString(); } String? _chemicalFormula(String source) { diff --git a/app/lib/utils/latex.dart b/app/lib/utils/latex.dart index adaf628d..02398a57 100644 --- a/app/lib/utils/latex.dart +++ b/app/lib/utils/latex.dart @@ -1,359 +1,9 @@ -import 'physics_latex.dart'; - -import 'dart:convert' show jsonEncode; -import 'dart:ui' show FontStyle; - -import 'package:flutter_math_fork/ast.dart'; import 'package:flutter_math_fork/tex.dart'; -import 'math_segments.dart'; import 'course_latex.dart'; - -const _superSource = '0123456789+-=()nixykm'; -const _superTarget = '⁰¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ⁿⁱˣʸᵏᵐ'; -const _subSource = '0123456789+-=()aehijklmnoprstuvxy'; -const _subTarget = '₀₁₂₃₄₅₆₇₈₉₊₋₌₍₎ₐₑₕᵢⱼₖₗₘₙₒₚᵣₛₜᵤᵥₓᵧ'; -String _script(String value, bool sup) { - if (sup && value == '∘') return '°'; - if (sup && RegExp(r'^[′″‴⁗]+$').hasMatch(value)) return value; - final source = sup ? _superSource : _subSource; - final target = sup ? _superTarget : _subTarget; - final chars = value.runes.map(String.fromCharCode).toList(); - return chars.isNotEmpty && chars.every(source.contains) - ? chars.map((c) => target[source.indexOf(c)]).join() - : '${sup ? '^' : '_'}($value)'; -} - -const _fractions = { - '1/2': '½', - '1/3': '⅓', - '2/3': '⅔', - '1/4': '¼', - '3/4': '¾', - '1/5': '⅕', - '2/5': '⅖', - '3/5': '⅗', - '4/5': '⅘', - '1/6': '⅙', - '5/6': '⅚', - '1/8': '⅛', - '3/8': '⅜', - '5/8': '⅝', - '7/8': '⅞', -}; -String _blackboard(String s) => s.runes.map((r) { - final legacy = { - 'C': 'ℂ', - 'H': 'ℍ', - 'N': 'ℕ', - 'P': 'ℙ', - 'Q': 'ℚ', - 'R': 'ℝ', - 'Z': 'ℤ', - }; - final c = String.fromCharCode(r); - if (legacy.containsKey(c)) return legacy[c]!; - if (r >= 65 && r <= 90) return String.fromCharCode(0x1d538 + r - 65); - // The internal AMS fallback supplies capitals. Unsupported styled lowercase - // and digits retain source rather than becoming unavailable Unicode glyphs. - throw const FormatException('Unsupported blackboard symbol'); -}).join(); -String _symbol(String s) => - const { - '−': '-', - '∣': '|', - '∥': '||', - '…': '...', - '⋯': '···', - '∼': '~', - '∗': '*', - '⋅': '·', - '⟹': '⇒', - '⟸': '⇐', - '⟺': '⇔', - '⟶': '→', - '⟵': '←', - '⟷': '↔', - '⪯': '≼', - '⪰': '≽', - }[s] ?? - s; -String _group(String s) { - if (s.runes.length <= 1) return s; - const pairs = {'(': ')', '[': ']', '{': '}', '⟨': '⟩'}; - if (pairs.containsKey(s[0])) { - final stack = []; - for (var i = 0; i < s.length; i++) { - if (pairs.containsKey(s[i])) { - stack.add(pairs[s[i]]!); - } else if (pairs.containsValue(s[i])) { - if (stack.isEmpty || stack.removeLast() != s[i]) return '($s)'; - if (stack.isEmpty) return i == s.length - 1 ? s : '($s)'; - } - } - } - return '($s)'; -} - -bool _uprightLabel(GreenNode? node, String text) { - if (node is EquationRowNode && node.children.length == 1) { - return _uprightLabel(node.children.single, text); - } - if (node is! StyleNode || !RegExp(r'^[A-Za-z]+$').hasMatch(text)) { - return false; - } - final font = node.optionsDiff.mathFontOptions; - // Upright labels and element symbols must not gain literal parentheses: - // SO₄ is chemically different from (SO)₄. Expressions still need grouping. - return font?.fontFamily == 'Main' && font?.fontShape == FontStyle.normal; -} - -// Conversion uses the same public AST as the preview widget. Unknown semantic -// nodes fail the whole formula instead of silently deleting mathematical data. -String _node(GreenNode? n, [int depth = 0, String mode = 'standalone']) { - if (depth > 64) throw const FormatException('Math nesting limit'); - String child(GreenNode? v, [String? m]) => _node(v, depth + 1, m ?? mode); - if (n == null) return ''; - if (n is SymbolNode) return _symbol(n.symbol); - if (n is EquationRowNode) return n.children.map(child).join(); - if (n is StyleNode) { - final body = n.children.map(child).join(); - final family = n.optionsDiff.mathFontOptions?.fontFamily; - if (family == 'AMS') return _blackboard(body); - if (family == 'Caligraphic') return calligraphicCapitals(body); - if (family != null && - !{'Main', 'Math', 'SansSerif', 'Typewriter'}.contains(family)) { - throw const FormatException('Unsupported math font'); - } - return body; - } - if (n is FracNode) { - if (n.barSize?.value == 0) { - throw const FormatException('Unwrapped binomial'); - } - final a = child(n.numerator).trim(), b = child(n.denominator).trim(); - return _fractions['$a/$b'] ?? '($a)/($b)'; - } - if (n is SqrtNode) { - final index = n.index == null ? '' : _script(child(n.index), true); - if (index.startsWith('^')) { - throw const FormatException('Unsupported root index'); - } - return '$index√(${child(n.base)})'; - } - if (n is MultiscriptsNode) { - if (n.presub != null || n.presup != null) { - throw const FormatException('Prescripts'); - } - final base = child(n.base); - final ungrouped = - _uprightLabel(n.base, base) || - RegExp(r'^(?:lim|max|min|det|sin|cos|tan|log|ln|[|]+)$').hasMatch(base); - return '${ungrouped ? base : _group(base)}${n.sub == null ? '' : _script(child(n.sub), false)}${n.sup == null ? '' : _script(child(n.sup), true)}'; - } - if (n is NaryOperatorNode) { - return '${_symbol(n.operator)}${n.lowerLimit == null ? '' : _script(child(n.lowerLimit), false)}${n.upperLimit == null ? '' : _script(child(n.upperLimit), true)}${child(n.naryand)}'; - } - if (n is FunctionNode) { - final name = child(n.functionName), argument = child(n.argument); - final first = n.argument.children.firstOrNull; - final space = - argument.isEmpty || - (first is! FracNode && RegExp(r'^[\s([{]').hasMatch(argument)) - ? '' - : ' '; - return '$name$space$argument'; - } - if (n is AccentNode) { - final mark = const { - '¯': '\u0304', - '^': '\u0302', - '→': '\u20d7', - '˙': '\u0307', - '¨': '\u0308', - '~': '\u0303', - '˘': '\u0306', - '´': '\u0301', - '`': '\u0300', - 'ˇ': '\u030c', - '⏞': '', - '⏟': '', - }[n.label]; - if (mark == null) throw FormatException('Unsupported accent ${n.label}'); - final base = child(n.base); - return mark.isEmpty ? base : '${_group(base)}$mark'; - } - if (n is AccentUnderNode) { - if (n.label != '¯' && n.label != '⏟') { - throw const FormatException('Unsupported under accent'); - } - final base = child(n.base); - return n.label == '⏟' ? base : '${_group(base)}\u0332'; - } - if (n is OverNode) { - return '${_group(child(n.base))}${_script(child(n.above), true)}'; - } - if (n is UnderNode) { - return '${child(n.base) == 'lim' ? 'lim' : _group(child(n.base))}${_script(child(n.below), false)}'; - } - if (n is StretchyOpNode) { - return '${_symbol(n.symbol)}${n.below == null ? '' : _script(child(n.below), false)}${n.above == null ? '' : _script(child(n.above), true)}'; - } - if (n is LeftRightNode) { - final left = _symbol(n.leftDelim ?? ''), - right = _symbol(n.rightDelim ?? ''); - if (left == '(' && - right == ')' && - n.body.length == 1 && - n.body.first.children.length == 1) { - final frac = n.body.first.children.first; - if (frac is FracNode && frac.barSize?.value == 0) { - return 'C(${child(frac.numerator)}, ${child(frac.denominator)})'; - } - } - final cases = left == '{' && right.isEmpty; - if (n.body.length == 1 && n.body.first.children.length == 1) { - final content = n.body.first.children.first; - final kind = const { - '()': 'pmatrix', - '[]': 'bmatrix', - '{}': 'Bmatrix', - '||': 'vmatrix', - '||||': 'Vmatrix', - '{': 'cases', - }['$left$right']; - if (kind != null && - (content is MatrixNode || content is EquationArrayNode)) { - return child(content, kind); - } - } - final body = StringBuffer(); - for (var i = 0; i < n.body.length; i++) { - if (i > 0) body.write(_symbol(n.middle[i - 1] ?? '')); - body.write(child(n.body[i], cases ? 'cases' : 'matrix')); - } - return '$left$body${cases ? ' }' : right}'; - } - if (n is MatrixNode) { - if (n.body.isEmpty || - n.body.length > 32 || - n.body.any((row) => row.isEmpty || row.length > 32)) { - throw const FormatException('Matrix dimensions exceed renderer limits'); - } - final ruled = - n.vLines.any((v) => v != MatrixSeparatorStyle.none) || - n.hLines.any((v) => v != MatrixSeparatorStyle.none); - String rule(MatrixSeparatorStyle style, bool horizontal) => switch (style) { - MatrixSeparatorStyle.none => '', - MatrixSeparatorStyle.solid => horizontal ? '──' : '|', - MatrixSeparatorStyle.dashed => horizontal ? '╌╌' : '┆', - }; - final lines = []; - for (var row = 0; row <= n.body.length; row++) { - final horizontal = rule(n.hLines[row], true); - if (horizontal.isNotEmpty) lines.add(horizontal); - if (row == n.body.length) break; - final cells = StringBuffer(); - for (var col = 0; col <= n.body[row].length; col++) { - final vertical = rule(n.vLines[col], false); - if (vertical.isNotEmpty) { - if (col > 0) cells.write(' '); - cells.write(vertical); - } - if (col == n.body[row].length) break; - if (col > 0 || vertical.isNotEmpty) { - cells.write(vertical.isEmpty ? ' ' : ' '); - } - final value = child(n.body[row][col]); - if ((mode == 'standalone' || - mode.endsWith('matrix') || - mode == 'cases') && - (value.isEmpty || - RegExp( - r'^\s*(?:matrix|pmatrix|bmatrix|Bmatrix|vmatrix|Vmatrix|cases):', - ).hasMatch(value) || - RegExp(r'[;|┆⟦⟧"\\]').hasMatch(value) || - value.contains(' ') || - value.trim() == '──' || - value.trim() == '╌╌')) { - cells.write(jsonEncode(value)); - } else { - cells.write(value); - } - } - lines.add(cells.toString()); - } - final rows = lines.join(' ; '); - if (mode == 'standalone') return ruled ? '⟦ $rows ⟧' : '⟦ matrix: $rows ⟧'; - if (mode.endsWith('matrix') || mode == 'cases') return '⟦ $mode: $rows ⟧'; - return ' $rows '; - } - if (n is EquationArrayNode) { - if (mode == 'cases' && (n.body.isEmpty || n.body.length > 32)) { - throw const FormatException('Cases dimensions exceed renderer limits'); - } - if (n.hlines.any((v) => v != MatrixSeparatorStyle.none)) { - throw const FormatException('Equation rules'); - } - final rows = n.body.map((row) { - if (mode == 'cases') { - final cells = []; - var cell = StringBuffer(); - var inside = false; - for (final item in row.children) { - if (item is SpaceNode && item.alignerOrSpacer) { - if (inside) { - cells.add(cell.toString()); - cell = StringBuffer(); - } - inside = !inside; - } else if (inside) { - cell.write(child(item)); - } - } - if (inside) throw const FormatException('Incomplete cases column'); - if (cells.length != 2) { - throw const FormatException('Cases need two columns'); - } - return cells - .map( - (value) => - value.isEmpty || - RegExp(r'[;|┆⟦⟧"\\]').hasMatch(value) || - value.contains(' ') - ? jsonEncode(value) - : value, - ) - .join(' '); - } - var columns = 0; - final out = StringBuffer(); - for (var i = 0; i < row.children.length; i++) { - final item = row.children[i]; - if (item is SpaceNode && item.alignerOrSpacer) { - columns++; - if (columns.isEven && i + 1 < row.children.length) out.write(' '); - } else { - out.write(child(item)); - } - } - return out.toString(); - }).toList(); - return mode == 'cases' ? '⟦ cases: ${rows.join(' ; ')} ⟧' : rows.join('\n'); - } - if (n is EnclosureNode) { - if (n.notation.isNotEmpty) { - throw const FormatException('Mathematical strike enclosure'); - } - return child(n.base); - } - if (n is SpaceNode) { - if (n.alignerOrSpacer || n.width.value <= 0) return ''; - if (n.fill) throw const FormatException('Rule'); - return mode == 'cases' ? ' ' : ' '; - } - throw FormatException('Unsupported ${n.runtimeType}'); -} +import 'latex_ast.dart'; +import 'math_segments.dart'; +import 'physics_latex.dart'; String? _formula(String source) { if (!withinMathBudget(source)) return null; @@ -392,7 +42,7 @@ String? _formula(String source) { strict: Strict.ignore, ), ).parse(); - return _node(tree); + return renderLatexNode(tree); } on Object { return null; } @@ -437,125 +87,165 @@ int _argumentEnd(String text, int start) { String _bareText(String text) { final lines = text.split('\n'); return [ - for (var li = 0; li < lines.length; li++) - (() { - final line = lines[li]; - if (!withinMathBudget(line)) return line; - // Keep all physics arguments in view before the generic token scanner. - if (RegExp(r'\\(?:dv|pdv|abs|norm)(?![A-Za-z])').hasMatch(line)) { - final normalized = normalizePhysicsLatex(line); - return normalized == line ? line : _bareText(normalized); - } - if (RegExp(r'\\\\[ \t]*(?:\[[^\]]*\])?[ \t]*$').hasMatch(line)) { - final prefix = line.replaceFirst( - RegExp(r'\\\\[ \t]*(?:\[[^\]]*\])?[ \t]*$'), - '', - ); - return '${_bareText(prefix)}${li < lines.length - 1 ? '' : '\n'}'; - } - if (_isBare(line.trim())) { - var converted = _formula(line.trim()); - if (converted == null) return line; - if (li < lines.length - 1 && converted.endsWith('\n')) { - converted = converted.substring(0, converted.length - 1); - } - return '${RegExp(r'^\s*').firstMatch(line)![0]}$converted${RegExp(r'\s*$').firstMatch(line)![0]}'; - } - final command = RegExp( - r'\\([a-zA-Z]+|[^a-zA-Z\n])|(? start && - after < line.length && - (line[after] == '^' || line[after] == '_')) { - end = after; - while (end < line.length && - (line[end] == '^' || line[end] == '_')) { - final next = _argumentEnd(line, end + 1); - if (next == end + 1) break; - end = next; - } - } - } - if (name == 'left') { - final pairedEnd = bareDelimiterEnd(line, start); - if (pairedEnd > start) end = pairedEnd; - } - if (name != null) { - if (name == r'\') { - out.write('${line.substring(cursor, start)}\n'); - cursor = end; - search = end; - continue; - } - final arity = - RegExp( - r'^(?:frac|dfrac|tfrac|binom|dbinom|tbinom|overset|underset|SI|qty)$', - ).hasMatch(name) - ? 2 - : RegExp( - r'^(?:sqrt|boxed|fbox|text|mathrm|mathbb|mathcal|mathfrak|mathbf|mathit|mathsf|mathtt|operatorname|bar|overline|underline|hat|widehat|vec|tilde|widetilde|dot|ddot|underbrace|overbrace|breve|acute|grave|check|ce|si|unit|num)$', - ).hasMatch(name) - ? 1 - : 0; - if (arity > 0 && - RegExp(r'^\s+[a-zA-Z]').hasMatch(line.substring(end))) { - out.write(line.substring(cursor, end)); - cursor = end; - search = end; - continue; - } - if (name == 'sqrt') { - final next = - end + - RegExp(r'^\s*').firstMatch(line.substring(end))![0]!.length; - if (next < line.length && line[next] == '[') { - end = _argumentEnd(line, next); - } - } - for (var a = 0; a < arity; a++) { - final next = - end + - RegExp(r'^\s*').firstMatch(line.substring(end))![0]!.length; - final after = _argumentEnd(line, next); - if (after == next) { - end = line.length; - break; - } - end = after; - } - while (end < line.length && line[end] == '{') { - final after = _argumentEnd(line, end); - if (after == end) break; - end = after; - } - while (end < line.length && - (line[end] == '_' || line[end] == '^')) { - final after = _argumentEnd(line, end + 1); - if (after == end + 1) break; - end = after; - } - } - final raw = line.substring(start, end); - out.write('${line.substring(cursor, start)}${_formula(raw) ?? raw}'); - cursor = end; - search = end; - } - out.write(line.substring(cursor)); - return out.toString(); - })(), + for (var i = 0; i < lines.length; i++) + _bareLine(lines[i], hasNextLine: i < lines.length - 1), ].join('\n'); } +final _lineBreak = RegExp(r'\\\\[ \t]*(?:\[[^\]]*\])?[ \t]*$'); + +String _bareLine(String line, {required bool hasNextLine}) { + if (!withinMathBudget(line)) return line; + // Keep all physics arguments in view before the generic token scanner. + if (RegExp(r'\\(?:dv|pdv|abs|norm)(?![A-Za-z])').hasMatch(line)) { + final normalized = normalizePhysicsLatex(line); + return normalized == line ? line : _bareText(normalized); + } + if (_lineBreak.hasMatch(line)) { + final prefix = line.replaceFirst(_lineBreak, ''); + return '${_bareText(prefix)}${hasNextLine ? '' : '\n'}'; + } + if (_isBare(line.trim())) { + var converted = _formula(line.trim()); + if (converted == null) return line; + if (hasNextLine && converted.endsWith('\n')) { + converted = converted.substring(0, converted.length - 1); + } + return '${RegExp(r'^\s*').firstMatch(line)![0]}$converted${RegExp(r'\s*$').firstMatch(line)![0]}'; + } + return _convertBareTokens(line); +} + +final _bareCommand = RegExp( + r'\\([a-zA-Z]+|[^a-zA-Z\n])|(? start && + after < line.length && + (line[after] == '^' || line[after] == '_')) { + end = _scriptsEnd(line, after); + } + } + if (name == 'left') { + final paired = bareDelimiterEnd(line, start); + if (paired > start) end = paired; + } + if (name != null) { + final arity = _commandArity(name); + if (arity > 0 && + RegExp(r'\s+[a-zA-Z]').matchAsPrefix(line, end) != null) { + out.write(line.substring(start, end)); + cursor = end; + continue; + } + end = _commandEnd(line, end, name, arity); + } + final raw = line.substring(start, end); + out.write(_formula(raw) ?? raw); + cursor = end; + } + out.write(line.substring(cursor)); + return out.toString(); +} + String convertLatex(String text) { final out = StringBuffer(); var cursor = 0; diff --git a/app/lib/utils/latex_ast.dart b/app/lib/utils/latex_ast.dart new file mode 100644 index 00000000..99c8abb2 --- /dev/null +++ b/app/lib/utils/latex_ast.dart @@ -0,0 +1,391 @@ +import 'dart:convert' show jsonEncode; +import 'dart:ui' show FontStyle; + +import 'package:flutter_math_fork/ast.dart'; + +import 'course_latex.dart'; + +const _superSource = '0123456789+-=()nixykm'; +const _superTarget = '⁰¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ⁿⁱˣʸᵏᵐ'; +const _subSource = '0123456789+-=()aehijklmnoprstuvxy'; +const _subTarget = '₀₁₂₃₄₅₆₇₈₉₊₋₌₍₎ₐₑₕᵢⱼₖₗₘₙₒₚᵣₛₜᵤᵥₓᵧ'; +String _script(String value, bool sup) { + if (sup && value == '∘') return '°'; + if (sup && RegExp(r'^[′″‴⁗]+$').hasMatch(value)) return value; + final source = sup ? _superSource : _subSource; + final target = sup ? _superTarget : _subTarget; + final chars = value.runes.map(String.fromCharCode).toList(); + return chars.isNotEmpty && chars.every(source.contains) + ? chars.map((c) => target[source.indexOf(c)]).join() + : '${sup ? '^' : '_'}($value)'; +} + +const _fractions = { + '1/2': '½', + '1/3': '⅓', + '2/3': '⅔', + '1/4': '¼', + '3/4': '¾', + '1/5': '⅕', + '2/5': '⅖', + '3/5': '⅗', + '4/5': '⅘', + '1/6': '⅙', + '5/6': '⅚', + '1/8': '⅛', + '3/8': '⅜', + '5/8': '⅝', + '7/8': '⅞', +}; +String _blackboard(String s) => s.runes.map((r) { + final legacy = { + 'C': 'ℂ', + 'H': 'ℍ', + 'N': 'ℕ', + 'P': 'ℙ', + 'Q': 'ℚ', + 'R': 'ℝ', + 'Z': 'ℤ', + }; + final c = String.fromCharCode(r); + if (legacy.containsKey(c)) return legacy[c]!; + if (r >= 65 && r <= 90) return String.fromCharCode(0x1d538 + r - 65); + // The internal AMS fallback supplies capitals. Unsupported styled lowercase + // and digits retain source rather than becoming unavailable Unicode glyphs. + throw const FormatException('Unsupported blackboard symbol'); +}).join(); +String _symbol(String s) => + const { + '−': '-', + '∣': '|', + '∥': '||', + '…': '...', + '⋯': '···', + '∼': '~', + '∗': '*', + '⋅': '·', + '⟹': '⇒', + '⟸': '⇐', + '⟺': '⇔', + '⟶': '→', + '⟵': '←', + '⟷': '↔', + '⪯': '≼', + '⪰': '≽', + }[s] ?? + s; +String _group(String s) { + if (s.runes.length <= 1) return s; + const pairs = {'(': ')', '[': ']', '{': '}', '⟨': '⟩'}; + if (pairs.containsKey(s[0])) { + final stack = []; + for (var i = 0; i < s.length; i++) { + if (pairs.containsKey(s[i])) { + stack.add(pairs[s[i]]!); + } else if (pairs.containsValue(s[i])) { + if (stack.isEmpty || stack.removeLast() != s[i]) return '($s)'; + if (stack.isEmpty) return i == s.length - 1 ? s : '($s)'; + } + } + } + return '($s)'; +} + +bool _uprightLabel(GreenNode? node, String text) { + if (node is EquationRowNode && node.children.length == 1) { + return _uprightLabel(node.children.single, text); + } + if (node is! StyleNode || !RegExp(r'^[A-Za-z]+$').hasMatch(text)) { + return false; + } + final font = node.optionsDiff.mathFontOptions; + // Upright labels and element symbols must not gain literal parentheses: + // SO₄ is chemically different from (SO)₄. Expressions still need grouping. + return font?.fontFamily == 'Main' && font?.fontShape == FontStyle.normal; +} + +// Conversion uses the same public AST as the preview widget. Unknown semantic +// nodes fail the whole formula instead of silently deleting mathematical data. +String renderLatexNode( + GreenNode? n, [ + int depth = 0, + String mode = 'standalone', +]) { + if (depth > 64) throw const FormatException('Math nesting limit'); + String child(GreenNode? v, [String? m]) => + renderLatexNode(v, depth + 1, m ?? mode); + if (n == null) return ''; + if (n is SymbolNode) return _symbol(n.symbol); + if (n is EquationRowNode) return n.children.map(child).join(); + if (n is StyleNode) return _styled(n, child); + if (n is FracNode) return _fraction(n, child); + if (n is SqrtNode) return _root(n, child); + if (n is MultiscriptsNode) return _multiscript(n, child); + if (n is NaryOperatorNode) { + return '${_symbol(n.operator)}${_scripts(n.lowerLimit, n.upperLimit, child)}${child(n.naryand)}'; + } + if (n is FunctionNode) return _function(n, child); + if (n is AccentNode) return _accent(n, child); + if (n is AccentUnderNode) return _underAccent(n, child); + if (n is OverNode) { + return '${_group(child(n.base))}${_script(child(n.above), true)}'; + } + if (n is UnderNode) return _under(n, child); + if (n is StretchyOpNode) { + return '${_symbol(n.symbol)}${_scripts(n.below, n.above, child)}'; + } + if (n is LeftRightNode) return _delimited(n, child); + if (n is MatrixNode) return _matrix(n, mode, child); + if (n is EquationArrayNode) return _equationArray(n, mode, child); + if (n is EnclosureNode) return _enclosure(n, child); + if (n is SpaceNode) return _space(n, mode); + throw FormatException('Unsupported ${n.runtimeType}'); +} + +typedef _Child = String Function(GreenNode?, [String?]); + +String _styled(StyleNode n, _Child child) { + final body = n.children.map(child).join(); + final family = n.optionsDiff.mathFontOptions?.fontFamily; + if (family == 'AMS') return _blackboard(body); + if (family == 'Caligraphic') return calligraphicCapitals(body); + if (family != null && + !{'Main', 'Math', 'SansSerif', 'Typewriter'}.contains(family)) { + throw const FormatException('Unsupported math font'); + } + return body; +} + +String _fraction(FracNode n, _Child child) { + if (n.barSize?.value == 0) { + throw const FormatException('Unwrapped binomial'); + } + final numerator = child(n.numerator).trim(); + final denominator = child(n.denominator).trim(); + return _fractions['$numerator/$denominator'] ?? '($numerator)/($denominator)'; +} + +String _root(SqrtNode n, _Child child) { + final index = n.index == null ? '' : _script(child(n.index), true); + if (index.startsWith('^')) { + throw const FormatException('Unsupported root index'); + } + return '$index√(${child(n.base)})'; +} + +String _function(FunctionNode n, _Child child) { + final name = child(n.functionName); + final argument = child(n.argument); + if (argument.isEmpty) return name; + final first = n.argument.children.firstOrNull; + if (first is! FracNode && RegExp(r'^[\s([{]').hasMatch(argument)) { + return '$name$argument'; + } + return '$name $argument'; +} + +String _scripts(GreenNode? sub, GreenNode? sup, _Child child) { + final lower = sub == null ? '' : _script(child(sub), false); + final upper = sup == null ? '' : _script(child(sup), true); + return '$lower$upper'; +} + +String _multiscript(MultiscriptsNode n, _Child child) { + if (n.presub != null || n.presup != null) { + throw const FormatException('Prescripts'); + } + final base = child(n.base); + final ungrouped = + _uprightLabel(n.base, base) || + RegExp(r'^(?:lim|max|min|det|sin|cos|tan|log|ln|[|]+)$').hasMatch(base); + return '${ungrouped ? base : _group(base)}${_scripts(n.sub, n.sup, child)}'; +} + +String _accent(AccentNode n, _Child child) { + final mark = const { + '¯': '\u0304', + '^': '\u0302', + '→': '\u20d7', + '˙': '\u0307', + '¨': '\u0308', + '~': '\u0303', + '˘': '\u0306', + '´': '\u0301', + '`': '\u0300', + 'ˇ': '\u030c', + '⏞': '', + '⏟': '', + }[n.label]; + if (mark == null) throw FormatException('Unsupported accent ${n.label}'); + final base = child(n.base); + return mark.isEmpty ? base : '${_group(base)}$mark'; +} + +String _underAccent(AccentUnderNode n, _Child child) { + if (n.label != '¯' && n.label != '⏟') { + throw const FormatException('Unsupported under accent'); + } + final base = child(n.base); + return n.label == '⏟' ? base : '${_group(base)}\u0332'; +} + +String _under(UnderNode n, _Child child) { + final base = child(n.base); + return '${base == 'lim' ? base : _group(base)}${_script(child(n.below), false)}'; +} + +String _enclosure(EnclosureNode n, _Child child) { + if (n.notation.isNotEmpty) { + throw const FormatException('Mathematical strike enclosure'); + } + return child(n.base); +} + +String _space(SpaceNode n, String mode) { + if (n.alignerOrSpacer || n.width.value <= 0) return ''; + if (n.fill) throw const FormatException('Rule'); + return mode == 'cases' ? ' ' : ' '; +} + +String _delimited(LeftRightNode n, _Child child) { + final left = _symbol(n.leftDelim ?? ''), right = _symbol(n.rightDelim ?? ''); + final cases = left == '{' && right.isEmpty; + final single = n.body.length == 1 && n.body.first.children.length == 1 + ? n.body.first.children.first + : null; + if (left == '(' && + right == ')' && + single is FracNode && + single.barSize?.value == 0) { + return 'C(${child(single.numerator)}, ${child(single.denominator)})'; + } + if (single is MatrixNode || single is EquationArrayNode) { + final kind = const { + '()': 'pmatrix', + '[]': 'bmatrix', + '{}': 'Bmatrix', + '||': 'vmatrix', + '||||': 'Vmatrix', + '{': 'cases', + }['$left$right']; + if (kind != null) return child(single, kind); + } + final body = StringBuffer(); + for (var i = 0; i < n.body.length; i++) { + if (i > 0) body.write(_symbol(n.middle[i - 1] ?? '')); + body.write(child(n.body[i], cases ? 'cases' : 'matrix')); + } + return '$left$body${cases ? ' }' : right}'; +} + +bool _needsCellQuotes(String value) => + value.isEmpty || + RegExp(r'[;|┆⟦⟧"\\]').hasMatch(value) || + value.contains(' '); + +String _matrixCell(String value, String mode) { + if (!(mode == 'standalone' || mode.endsWith('matrix') || mode == 'cases')) { + return value; + } + final reserved = + RegExp(r'^\s*(?:matrix|pmatrix|bmatrix|Bmatrix|vmatrix|Vmatrix|cases):') + .hasMatch(value) || + value.trim() == '──' || + value.trim() == '╌╌'; + return reserved || _needsCellQuotes(value) ? jsonEncode(value) : value; +} + +String _matrix(MatrixNode n, String mode, _Child child) { + if (n.body.isEmpty || + n.body.length > 32 || + n.body.any((row) => row.isEmpty || row.length > 32)) { + throw const FormatException('Matrix dimensions exceed renderer limits'); + } + final ruled = + n.vLines.any((v) => v != MatrixSeparatorStyle.none) || + n.hLines.any((v) => v != MatrixSeparatorStyle.none); + String rule(MatrixSeparatorStyle style, bool horizontal) => switch (style) { + MatrixSeparatorStyle.none => '', + MatrixSeparatorStyle.solid => horizontal ? '──' : '|', + MatrixSeparatorStyle.dashed => horizontal ? '╌╌' : '┆', + }; + final lines = []; + for (var row = 0; row <= n.body.length; row++) { + final horizontal = rule(n.hLines[row], true); + if (horizontal.isNotEmpty) lines.add(horizontal); + if (row == n.body.length) break; + final cells = StringBuffer(); + for (var col = 0; col <= n.body[row].length; col++) { + final vertical = rule(n.vLines[col], false); + if (vertical.isNotEmpty) { + if (col > 0) cells.write(' '); + cells.write(vertical); + } + if (col == n.body[row].length) break; + if (col > 0 || vertical.isNotEmpty) { + cells.write(vertical.isEmpty ? ' ' : ' '); + } + final value = child(n.body[row][col]); + cells.write(_matrixCell(value, mode)); + } + lines.add(cells.toString()); + } + final rows = lines.join(' ; '); + if (mode == 'standalone') return ruled ? '⟦ $rows ⟧' : '⟦ matrix: $rows ⟧'; + if (mode.endsWith('matrix') || mode == 'cases') return '⟦ $mode: $rows ⟧'; + return ' $rows '; +} + +String _equationArray(EquationArrayNode n, String mode, _Child child) { + if (mode == 'cases' && (n.body.isEmpty || n.body.length > 32)) { + throw const FormatException('Cases dimensions exceed renderer limits'); + } + if (n.hlines.any((v) => v != MatrixSeparatorStyle.none)) { + throw const FormatException('Equation rules'); + } + final rows = n.body.map( + (row) => mode == 'cases' + ? _casesRow(row.children, child) + : _alignedRow(row.children, child), + ); + return mode == 'cases' ? '⟦ cases: ${rows.join(' ; ')} ⟧' : rows.join('\n'); +} + +String _casesRow(List items, _Child child) { + final cells = []; + var cell = StringBuffer(); + var inside = false; + for (final item in items) { + if (item is SpaceNode && item.alignerOrSpacer) { + if (inside) { + cells.add(cell.toString()); + cell = StringBuffer(); + } + inside = !inside; + } else if (inside) { + cell.write(child(item)); + } + } + if (inside) throw const FormatException('Incomplete cases column'); + if (cells.length != 2) { + throw const FormatException('Cases need two columns'); + } + return cells + .map((value) => _needsCellQuotes(value) ? jsonEncode(value) : value) + .join(' '); +} + +String _alignedRow(List items, _Child child) { + var columns = 0; + final out = StringBuffer(); + for (var i = 0; i < items.length; i++) { + final item = items[i]; + if (item is SpaceNode && item.alignerOrSpacer) { + columns++; + if (columns.isEven && i + 1 < items.length) out.write(' '); + } else { + out.write(child(item)); + } + } + return out.toString(); +} diff --git a/app/lib/utils/markdown_literals.dart b/app/lib/utils/markdown_literals.dart index 15c182bf..f58b112f 100644 --- a/app/lib/utils/markdown_literals.dart +++ b/app/lib/utils/markdown_literals.dart @@ -1,16 +1,39 @@ +// Quote a literal occurrence at the document boundary before inserting tokens. +const markdownTokenStart = '\uFDD0'; + +/// Only exact tokens issued by this cleanup stage can restore a saved value. +class MarkdownPlaceholders { + MarkdownPlaceholders(this.prefix, this.suffix); + + final String prefix; + final String suffix; + final _values = {}; + late final _pattern = RegExp('${RegExp.escape(prefix)}[0-9]+$suffix'); + + String save(String value) { + final token = '$prefix${_values.length}$suffix'; + _values[token] = value; + return token; + } + + String restore(String text) => _values.isEmpty + ? text + : text.replaceAllMapped(_pattern, (match) { + final token = match[0]!; + return _values[token] ?? token; + }); +} + ({String text, String Function(String) restore}) protectMarkdownCode( String source, { bool inline = true, }) { - var prefix = '\uE110CODE'; + var prefix = '${markdownTokenStart}CODE'; while (source.contains(prefix)) { - prefix += '\uE110'; - } - final values = []; - String save(String value) { - values.add(value); - return '$prefix${values.length - 1}\uE111'; + prefix += markdownTokenStart; } + // A fenced block can be temporarily hidden from the inline pass. + final values = MarkdownPlaceholders(prefix, inline ? '\uE111' : '\uE113'); final lines = source.replaceAll(RegExp(r'\r\n?'), '\n').split('\n'); final output = []; @@ -36,22 +59,27 @@ final leading = RegExp(r'^ *').firstMatch(current)![0]!.length; body.add(current.substring(indent < leading ? indent : leading)); } - output.add(save(body.where((line) => line.trim().isNotEmpty).join('\n'))); + output.add( + values.save(body.where((line) => line.trim().isNotEmpty).join('\n')), + ); } final joined = output.join('\n'); final result = StringBuffer(); final runs = inline ? RegExp(r'`+').allMatches(joined).toList() : []; + final nextByLength = {}; + final nextRun = List.filled(runs.length, null); + for (var i = runs.length - 1; i >= 0; i--) { + final length = runs[i].end - runs[i].start; + nextRun[i] = nextByLength[length]; + nextByLength[length] = i; + } var cursor = 0; for (var index = 0; index < runs.length; index++) { final opening = runs[index]; - var closing = index + 1; - while (closing < runs.length && - runs[closing][0]!.length != opening[0]!.length) { - closing++; - } - if (closing == runs.length) break; + final closing = nextRun[index]; + if (closing == null) continue; var value = joined .substring(opening.end, runs[closing].start) .replaceAll('\n', ' '); @@ -61,18 +89,12 @@ value = value.substring(1, value.length - 1); } result.write(joined.substring(cursor, opening.start)); - result.write(save(value)); + result.write(values.save(value)); cursor = runs[closing].end; index = closing; } result.write(joined.substring(cursor)); - return ( - text: result.toString(), - restore: (value) => value.replaceAllMapped( - RegExp('${RegExp.escape(prefix)}(\\d+)\uE111'), - (match) => values[int.parse(match[1]!)], - ), - ); + return (text: result.toString(), restore: values.restore); } String stripMarkdownLinks(String source) { diff --git a/app/lib/utils/math_segments.dart b/app/lib/utils/math_segments.dart index f4d1f9fb..ace93496 100644 --- a/app/lib/utils/math_segments.dart +++ b/app/lib/utils/math_segments.dart @@ -53,22 +53,90 @@ final _env = RegExp(r'^\\(begin|end)\{([a-zA-Z][a-zA-Z0-9*]*)\}'); // cleanup agree about where source must be preserved. List scanMathSegments(String text) { final result = []; + final links = _LinkDelimiters(text); + for (var cursor = 0; cursor < text.length;) { + if (text.startsWith(r'\left', cursor)) { + final end = bareDelimiterEnd(text, cursor); + if (end > cursor) { + cursor = end; + continue; + } + } + final segment = _segmentAt(text, cursor, links); + if (segment == null) { + cursor += text.startsWith(r'\\', cursor) ? 2 : 1; + } else { + result.add(segment); + cursor = segment.end; + } + } + return result; +} + +MathSegment? _segmentAt(String text, int start, _LinkDelimiters links) { + final c = text[start]; + if (c == '`' || (c == '~' && text.startsWith('~~~', start))) { + final end = _codeEnd(text, start, c); + return MathSegment(start, end, text.substring(start, end)); + } + if (c == '⟦') { + final end = _matrixEnd(text, start); + return MathSegment( + start, + end, + text.substring(start, end), + safeMathLiteral: true, + ); + } + final boundary = + start == 0 || RegExp(r'''[\s"'([{::,;]''').hasMatch(text[start - 1]); + if (!boundary && !{'h', 'f', r'\', r'$', '!', '['}.contains(c)) return null; + final tail = text.substring(start, (start + 512).clamp(0, text.length)); + final literal = _pathEnd(text, start, tail, boundary) ?? links.endAt(start); + if (literal != null) { + return MathSegment(start, literal, text.substring(start, literal)); + } + if ((c != r'\' && c != r'$') || + text.startsWith(r'\\', start) || + _escaped(text, start)) { + return null; + } + final enclosure = RegExp(r'^\\(?:boxed|fbox)\s*\{').firstMatch(tail); + if (enclosure != null) return _enclosure(text, start, start + enclosure.end); + final env = _env.firstMatch(tail); + if (env != null && env[1] == 'begin') return _environment(text, start, env); + final delimiter = _Delimiter.at(text, start); + return delimiter == null + ? null + : _delimitedMath(text, start, tail, delimiter); +} + +class _LinkDelimiters { // Index link delimiters once: incomplete pasted links must not scan the rest // of a long document again at every opening bracket. - final linkEnds = {}, parentheses = []; - final brackets = []; - for (var i = 0; i < text.length; i++) { - if (text[i] == r'\') { - i++; - continue; - } - if (text[i] == ']') brackets.add(i); - if (text[i] == '(') parentheses.add(i); - if (text[i] == ')' && parentheses.isNotEmpty) { - linkEnds[parentheses.removeLast()] = i + 1; + _LinkDelimiters(this.text); + final String text; + late final _index = _buildIndex(); + + ({Map ends, List brackets}) _buildIndex() { + final linkEnds = {}, brackets = []; + final parentheses = []; + for (var i = 0; i < text.length; i++) { + if (text[i] == r'\') { + i++; + continue; + } + if (text[i] == ']') brackets.add(i); + if (text[i] == '(') parentheses.add(i); + if (text[i] == ')' && parentheses.isNotEmpty) { + linkEnds[parentheses.removeLast()] = i + 1; + } } + return (ends: linkEnds, brackets: brackets); } - int nextBracket(int start) { + + int? nextBracket(int start) { + final brackets = _index.brackets; var low = 0, high = brackets.length; while (low < high) { final middle = (low + high) ~/ 2; @@ -78,283 +146,251 @@ List scanMathSegments(String text) { high = middle; } } - return low == brackets.length ? text.length : brackets[low]; + return low == brackets.length ? null : brackets[low]; } - var cursor = 0; - void add( - int start, - int end, { - String? body, - bool math = false, - bool display = false, - bool safe = false, - }) { - result.add( - MathSegment( - start, - end, - body ?? text.substring(start, end), - math: math, - display: display, - safeMathLiteral: safe, - ), - ); - cursor = end; + int? endAt(int start) { + final image = text.startsWith('![', start); + if (!image && text[start] != '[') return null; + final bracket = nextBracket(start + (image ? 2 : 1)); + if (bracket == null) return null; + var end = bracket + 1; + if (end < text.length && text[end] == '(') { + end = _index.ends[end] ?? text.length; + } + return image || text[end - 1] == ')' ? end : null; } +} - while (cursor < text.length) { - final start = cursor, c = text[cursor]; - if (c == '`' || (c == '~' && text.startsWith('~~~', cursor))) { - var count = 1; - while (cursor + count < text.length && text[cursor + count] == c) { - count++; - } - final fence = c * count; - var end = text.indexOf(fence, cursor + count); - while (end >= 0 && - ((end > 0 && text[end - 1] == c) || - (end + count < text.length && text[end + count] == c))) { - end = text.indexOf(fence, end + count); +int _codeEnd(String text, int start, String c) { + var count = 1; + while (start + count < text.length && text[start + count] == c) { + count++; + } + final fence = c * count; + var end = text.indexOf(fence, start + count); + while (end >= 0 && + ((end > 0 && text[end - 1] == c) || + (end + count < text.length && text[end + count] == c))) { + end = text.indexOf(fence, end + count); + } + final newline = text.indexOf('\n', start); + if (end >= 0) return end + count; + return count >= 3 || newline < 0 ? text.length : newline; +} + +int _matrixEnd(String text, int start) { + var end = start + 1, depth = 1; + var quoted = false, escaped = false; + while (end < text.length && depth > 0) { + final value = text[end++]; + if (quoted) { + if (escaped) { + escaped = false; + } else if (value == r'\') { + escaped = true; + } else if (value == '"') { + quoted = false; } - final newline = text.indexOf('\n', cursor); - add( - start, - end < 0 - ? (count >= 3 || newline < 0 ? text.length : newline) - : end + count, - ); continue; } - if (c == '⟦') { - var end = cursor + 1, depth = 1; - var quoted = false, escaped = false; - while (end < text.length && depth > 0) { - final value = text[end++]; - if (quoted) { - if (escaped) { - escaped = false; - } else if (value == r'\') { - escaped = true; - } else if (value == '"') { - quoted = false; - } - continue; - } - if (value == '"') { - quoted = true; - } else if (value == '⟦') { - depth++; - } else if (value == '⟧') { - depth--; - } - } - add(start, end, safe: true); - continue; + if (value == '"') { + quoted = true; + } else if (value == '⟦') { + depth++; + } else if (value == '⟧') { + depth--; } - if (text.startsWith(r'\left', cursor)) { - final end = bareDelimiterEnd(text, cursor); - if (end > cursor) { - cursor = end; - continue; - } + } + return end; +} + +int? _pathEnd(String text, int start, String tail, bool boundary) { + final url = RegExp(r'^(?:(?:https?|ftp)://|www\.)').hasMatch(tail); + final path = + RegExp(r'^[a-zA-Z]:[\\/]|^\\\\[^\s\\/]+[\\/][^\s]').hasMatch(tail) || + (boundary && + RegExp( + r'''^(?:/[^\s/]+/|\.{1,2}/)[^\s]|^(?:[\p{L}\p{N}_.-]{2,}[\\/]|[\p{L}\p{N}_.-]+[\\/][^\s<>"']*\.[a-zA-Z0-9]{1,10}(?=$|[\s.,;:)]))''', + unicode: true, + ).hasMatch(tail)); + if (url || path) { + var end = start; + final stop = url ? RegExp(r'[\s<>,。;:!?]') : RegExp(r'''[\s<>"',。;:!?]'''); + while (end < text.length && !stop.hasMatch(text[end])) { + end++; } - final boundary = - cursor == 0 || RegExp(r'''[\s"'([{::,;]''').hasMatch(text[cursor - 1]); - if (!boundary && !{'h', 'f', r'\', r'$', '!', '['}.contains(c)) { - cursor++; + return end; + } + return null; +} + +MathSegment _enclosure(String text, int start, int contentStart) { + var end = contentStart, depth = 1; + while (end < text.length && depth > 0) { + if (text[end] == r'\') { + end += 2; continue; } - // Prefix matching never copies the remaining document. - final tail = text.substring(cursor, (cursor + 512).clamp(0, text.length)); - final url = RegExp(r'^(?:(?:https?|ftp)://|www\.)').hasMatch(tail); - final path = - RegExp(r'^[a-zA-Z]:[\\/]|^\\\\[^\s\\/]+[\\/][^\s]').hasMatch(tail) || - (boundary && - RegExp( - r'''^(?:/[^\s/]+/|\.{1,2}/)[^\s]|^(?:[\p{L}\p{N}_.-]{2,}[\\/]|[\p{L}\p{N}_.-]+[\\/][^\s<>"']*\.[a-zA-Z0-9]{1,10}(?=$|[\s.,;:)]))''', - unicode: true, - ).hasMatch(tail)); - if (url || path) { - var end = cursor; - final stop = url - ? RegExp(r'[\s<>,。;:!?]') - : RegExp(r'''[\s<>"',。;:!?]'''); - while (end < text.length && !stop.hasMatch(text[end])) { - end++; - } - add(start, end); + if (text[end] == '{') depth++; + if (text[end] == '}') depth--; + end++; + } + final closed = depth == 0; + if (!closed) end = text.length; + final body = text.substring(start, end); + final valid = closed && withinMathBudget(body); + return MathSegment(start, end, body, math: valid, safeMathLiteral: !valid); +} + +int? _environmentEnd(String text, int contentStart, String name) { + final stack = [name]; + var end = contentStart; + while (end < text.length) { + if (text[end] == '%' && !_escaped(text, end)) { + final newline = text.indexOf('\n', end); + end = newline < 0 ? text.length : newline + 1; continue; } - if (text.startsWith('![', cursor) || c == '[') { - var end = nextBracket(cursor + (c == '!' ? 2 : 1)); - if (end < text.length) { - end++; - if (end < text.length && text[end] == '(') { - end = linkEnds[end] ?? text.length; - } - if (c == '!' || text[end - 1] == ')') { - add(start, end); - continue; - } - } + if (text.startsWith(r'\\', end)) { + end += 2; + continue; } - if (text.startsWith(r'\\', cursor)) { - cursor += 2; + final tag = text[end] == r'\' + ? _env.firstMatch( + text.substring(end, (end + 100).clamp(0, text.length)), + ) + : null; + if (tag == null) { + end++; continue; } - if ((c == r'\' || c == r'$') && !_escaped(text, cursor)) { - // Keep a bare enclosure together: an environment inside it must not be - // split from its enclosing command before the formula parser sees it. - final enclosure = RegExp(r'^\\(?:boxed|fbox)\s*\{').firstMatch(tail); - if (enclosure != null) { - var end = cursor + enclosure[0]!.length, depth = 1; - while (end < text.length && depth > 0) { - if (text[end] == r'\') { - end += 2; - continue; - } - if (text[end] == '{') depth++; - if (text[end] == '}') depth--; - end++; - } - if (depth == 0) { - final body = text.substring(start, end); - final valid = withinMathBudget(body); - add(start, end, math: valid, safe: !valid); - continue; - } - add(start, text.length, safe: true); - continue; + end += tag[0]!.length; + if (tag[1] == 'begin') { + stack.add(tag[2]!); + if (stack.length > 64) { + return null; } - final env = _env.firstMatch(tail); - if (env != null && env[1] == 'begin') { - // Circuit topology and labels belong to the engine, not the math AST. - // Keep the whole environment intact through both editing tools. - final circuit = env[2] == 'circuitikz'; - final stack = [env[2]!]; - var end = cursor + env[0]!.length, valid = false; - while (end < text.length) { - if (text[end] == '%' && !_escaped(text, end)) { - final newline = text.indexOf('\n', end); - end = newline < 0 ? text.length : newline + 1; - continue; - } - if (text.startsWith(r'\\', end)) { - end += 2; - continue; - } - final tag = text[end] == r'\' - ? _env.firstMatch( - text.substring(end, (end + 100).clamp(0, text.length)), - ) - : null; - if (tag == null) { - end++; - continue; - } - end += tag[0]!.length; - if (tag[1] == 'begin') { - stack.add(tag[2]!); - if (stack.length > 64) { - end = text.length; - break; - } - } else { - if (stack.removeLast() != tag[2]) { - end = text.length; - break; - } - if (stack.isEmpty) { - valid = true; - break; - } - } - } - final body = text.substring(start, end); - valid = valid && withinMathBudget(body); - add( - start, - end, - math: valid && !circuit, - display: true, - safe: !valid || circuit, - ); - continue; - } - String? open, close; - var display = false; - if (text.startsWith(r'$$', cursor)) { - open = close = r'$$'; - display = true; - } else if (c == r'$') { - open = close = r'$'; - } else if (text.startsWith(r'\[', cursor)) { - open = r'\['; - close = r'\]'; - display = true; - } else if (text.startsWith(r'\(', cursor)) { - open = r'\('; - close = r'\)'; + } else { + if (stack.removeLast() != tag[2]) { + return null; } - if (open != null) { - var end = cursor + open.length; - var closed = false, currency = false; - while (end < text.length) { - if (open == r'$' && (text[end] == '\n' || text[end] == '\r')) break; - if (text.startsWith(close!, end) && !_escaped(text, end)) { - if (close == r'$' && - ((end > 0 && text[end - 1] == r'$') || - (end + 1 < text.length && text[end + 1] == r'$'))) { - end++; - continue; - } - final body = text.substring(cursor + open.length, end); - currency = - open == r'$' && - RegExp(r'^\d[\d,.]*(?:[ \t]+[a-zA-Z]+)*[ \t]*$') - .hasMatch(body) && - ((end + 1 < text.length && - RegExp(r'\d').hasMatch(text[end + 1])) || - RegExp(r'\s$').hasMatch(body)); - closed = true; - break; - } - end++; - } - final amount = open == r'$' - ? RegExp(r'^\$\d[\d,.]*').firstMatch(tail) - : null; - final amountEnd = cursor + (amount?[0]?.length ?? 0); - final amountBoundary = - amount != null && - (amountEnd >= text.length || - !RegExp(r'[a-zA-Z+\-*/^_={\\<>]').hasMatch(text[amountEnd])); - currency = - currency || - (amountBoundary && - closed && - end > amountEnd && - RegExp(r'^[\s;:!?,。;:!?]+$') - .hasMatch(text.substring(amountEnd, end))); - if (currency || (amountBoundary && !closed)) { - add(start, amount == null ? cursor + 1 : amountEnd); - continue; - } - final body = text.substring(start + open.length, end); - final valid = closed && withinMathBudget(body); - add( - start, - closed ? end + close!.length : end, - body: body, - math: valid, - display: display, - safe: !valid, - ); - continue; + if (stack.isEmpty) { + return end; } } - cursor++; } - return result; + return null; +} + +MathSegment _environment(String text, int start, RegExpMatch opening) { + final name = opening[2]!; + final close = _environmentEnd(text, start + opening.end, name); + final end = close ?? text.length; + final body = text.substring(start, end); + // Circuit topology and labels belong to the engine and must stay editable. + final math = close != null && withinMathBudget(body) && name != 'circuitikz'; + return MathSegment( + start, + end, + body, + math: math, + display: true, + safeMathLiteral: !math, + ); +} + +enum _Delimiter { + displayDollar(r'$$', r'$$', display: true), + inlineDollar(r'$', r'$'), + bracket(r'\[', r'\]', display: true), + paren(r'\(', r'\)'); + + const _Delimiter(this.open, this.close, {this.display = false}); + final String open, close; + final bool display; + + static _Delimiter? at(String text, int start) { + for (final delimiter in values) { + if (text.startsWith(delimiter.open, start)) return delimiter; + } + return null; + } +} + +({int end, bool closed}) _closingDelimiter( + String text, + int content, + _Delimiter delimiter, +) { + final single = delimiter == _Delimiter.inlineDollar; + for (var end = content; end < text.length; end++) { + if (single && (text[end] == '\n' || text[end] == '\r')) { + return (end: end, closed: false); + } + if (!text.startsWith(delimiter.close, end) || _escaped(text, end)) continue; + if (single && + ((end > 0 && text[end - 1] == r'$') || + (end + 1 < text.length && text[end + 1] == r'$'))) { + continue; + } + return (end: end, closed: true); + } + return (end: text.length, closed: false); +} + +int? _currencyEnd( + String text, + String tail, + int start, + int end, + String body, + bool closed, +) { + final amount = RegExp(r'^\$\d[\d,.]*').firstMatch(tail); + final amountEnd = start + (amount?.end ?? 0); + final boundary = + amount != null && + (amountEnd >= text.length || + !RegExp(r'[a-zA-Z+\-*/^_={\\<>]').hasMatch(text[amountEnd])); + final currency = + closed && + RegExp(r'^\d[\d,.]*(?:[ \t]+[a-zA-Z]+)*[ \t]*$').hasMatch(body) && + ((end + 1 < text.length && RegExp(r'\d').hasMatch(text[end + 1])) || + RegExp(r'\s$').hasMatch(body)); + if (currency) return amount == null ? start + 1 : amountEnd; + if (boundary && + (!closed || + (end > amountEnd && + RegExp(r'^[\s;:!?,。;:!?]+$') + .hasMatch(text.substring(amountEnd, end))))) { + return amountEnd; + } + return null; +} + +MathSegment _delimitedMath( + String text, + int start, + String tail, + _Delimiter delimiter, +) { + final content = start + delimiter.open.length; + final (:end, :closed) = _closingDelimiter(text, content, delimiter); + final body = text.substring(content, end); + if (delimiter == _Delimiter.inlineDollar) { + final amount = _currencyEnd(text, tail, start, end, body, closed); + if (amount != null) { + return MathSegment(start, amount, text.substring(start, amount)); + } + } + final valid = closed && withinMathBudget(body); + return MathSegment( + start, + closed ? end + delimiter.close.length : end, + body, + math: valid, + display: delimiter.display, + safeMathLiteral: !valid, + ); } diff --git a/app/lib/utils/paper_exif.dart b/app/lib/utils/paper_exif.dart index 4128425e..b1a44931 100644 --- a/app/lib/utils/paper_exif.dart +++ b/app/lib/utils/paper_exif.dart @@ -28,65 +28,74 @@ Uint8List withPaperExif(Uint8List png, Uint8List? exif) { Uint8List? paperExifSource(Uint8List bytes) { if (bytes.length < 12) return null; final data = ByteData.sublistView(bytes); - final png = - data.getUint32(0) == 0x89504e47 && data.getUint32(4) == 0x0d0a1a0a; - final webp = - data.getUint32(0) == 0x52494646 && data.getUint32(8) == 0x57454250; - if (png || webp) { - var offset = png ? 8 : 12; - while (offset + 8 <= bytes.length) { - final type = data.getUint32(offset + (png ? 4 : 0)); - final size = data.getUint32( - offset + (png ? 0 : 4), - png ? Endian.big : Endian.little, - ); - final start = offset + 8; - final end = start + size; - if (end > bytes.length) return null; - if (type == (png ? 0x65584966 : 0x45584946)) { - // Some WebP writers include the JPEG APP1 prefix before the TIFF header. - final prefix = - webp && - size >= 6 && - data.getUint32(start) == 0x45786966 && - data.getUint16(start + 4) == 0; - return Uint8List.sublistView(bytes, start + (prefix ? 6 : 0), end); - } - offset = - end + - (png - ? 4 - : size.isOdd - ? 1 - : 0); - } - return null; + if (data.getUint32(0) == 0x89504e47 && data.getUint32(4) == 0x0d0a1a0a) { + return _pngExif(data); } - if (data.getUint16(0) == 0xffd8) { - var offset = 2; - while (offset < bytes.length && bytes[offset] == 0xff) { - while (offset < bytes.length && bytes[offset] == 0xff) { - offset++; - } - if (offset >= bytes.length) break; - final marker = bytes[offset++]; - if (marker == 0xda || marker == 0xd9) break; - if (marker == 1 || (marker >= 0xd0 && marker <= 0xd7)) continue; - if (offset + 2 > bytes.length) break; - final size = data.getUint16(offset); - if (size < 2 || offset + size > bytes.length) break; - if (marker == 0xe1 && - size >= 8 && - data.getUint32(offset + 2) == 0x45786966 && - data.getUint16(offset + 6) == 0) { - return Uint8List.sublistView(bytes, offset + 8, offset + size); - } - offset += size; - } - return null; + if (data.getUint32(0) == 0x52494646 && data.getUint32(8) == 0x57454250) { + return _webpExif(data); } + if (data.getUint16(0) == 0xffd8) return _jpegExif(data); // Non-chunked formats (including TIFF) can store their first IFD in the file header. return bytes.length > 64 * 1024 * 1024 ? Uint8List.sublistView(bytes, 0, 16 * 1024 * 1024) : bytes; } + +Uint8List? _pngExif(ByteData data) { + var offset = 8; + while (offset + 8 <= data.lengthInBytes) { + final start = offset + 8; + final end = start + data.getUint32(offset); + if (end > data.lengthInBytes) return null; + if (data.getUint32(offset + 4) == 0x65584966) { + return Uint8List.sublistView(data, start, end); + } + offset = end + 4; // Skip the chunk CRC. + } + return null; +} + +Uint8List? _webpExif(ByteData data) { + var offset = 12; + while (offset + 8 <= data.lengthInBytes) { + final start = offset + 8; + final size = data.getUint32(offset + 4, Endian.little); + final end = start + size; + if (end > data.lengthInBytes) return null; + if (data.getUint32(offset) == 0x45584946) { + // Some WebP writers include the JPEG APP1 prefix before the TIFF header. + final tiff = _hasExifPrefix(data, start, end) ? start + 6 : start; + return Uint8List.sublistView(data, tiff, end); + } + offset = end + (size.isOdd ? 1 : 0); // RIFF chunks are word aligned. + } + return null; +} + +Uint8List? _jpegExif(ByteData data) { + var offset = 2; + while (offset < data.lengthInBytes && data.getUint8(offset) == 0xff) { + do { + offset++; + } while (offset < data.lengthInBytes && data.getUint8(offset) == 0xff); + if (offset == data.lengthInBytes) return null; + final marker = data.getUint8(offset++); + if (marker == 0xda || marker == 0xd9) return null; + if (marker == 1 || (marker >= 0xd0 && marker <= 0xd7)) continue; + if (offset + 2 > data.lengthInBytes) return null; + final size = data.getUint16(offset); + final start = offset + 2; + final end = offset + size; + if (size < 2 || end > data.lengthInBytes) return null; + if (marker == 0xe1 && _hasExifPrefix(data, start, end)) { + return Uint8List.sublistView(data, start + 6, end); + } + offset = end; + } + return null; +} + +bool _hasExifPrefix(ByteData data, int start, int end) => + end - start >= 6 && + data.getUint32(start) == 0x45786966 && + data.getUint16(start + 4) == 0; diff --git a/app/lib/utils/physics_latex.dart b/app/lib/utils/physics_latex.dart index e69a6a53..90634e64 100644 --- a/app/lib/utils/physics_latex.dart +++ b/app/lib/utils/physics_latex.dart @@ -4,6 +4,17 @@ const _maxSource = 32768; const _maxGroup = 4096; const _maxDepth = 16; +final _command = RegExp(r'\\([A-Za-z]+|[^A-Za-z])'); +final _derivativeOrder = RegExp(r'\[([1-9]\d?|[A-Za-z])\]'); +const _literalCommands = { + 'text', + 'textrm', + 'textbf', + 'textit', + 'texttt', + 'operatorname', + 'ce', +}; final _variable = RegExp( r'^(?:[A-Za-zΑ-Ωα-ωϑϕϖϱϵϰ]|\\[A-Za-z]+)(?:_(?:[A-Za-z0-9]|\{(?:[A-Za-z0-9]{1,16}|\\[A-Za-z]+)\}))?$', ); @@ -32,75 +43,85 @@ int _skipSpace(String source, int offset) { return null; } +typedef _PhysicsArguments = ({ + String? operand, + String? variable, + String order, + int end, +}); + +_PhysicsArguments? _readArguments(String source, int offset, String name) { + final derivative = name == 'dv' || name == 'pdv'; + var order = ''; + offset = _skipSpace(source, offset); + if (derivative && source.startsWith('[', offset)) { + final option = _derivativeOrder.matchAsPrefix(source, offset); + if (option == null) return null; + order = option[1]!; + offset = option.end; + } + + final first = _groupAt(source, offset); + if (first == null || first.body.trim().isEmpty) return null; + if (!derivative) { + return (operand: first.body, variable: null, order: '', end: first.end); + } + + final second = _groupAt(source, first.end); + final end = second?.end ?? first.end; + final tailOffset = _skipSpace(source, end); + final tail = tailOffset < source.length ? source[tailOffset] : ''; + if (tail == '{' || tail == '(' || tail == '[') return null; + final variable = (second?.body ?? first.body).trim(); + if (!_variable.hasMatch(variable)) return null; + return ( + operand: second == null ? null : first.body, + variable: variable, + order: order, + end: end, + ); +} + +String? _expandCommand(String name, _PhysicsArguments arguments, int depth) { + final operand = arguments.operand; + final body = operand == null ? '' : _normalizeFragment(operand, depth + 1); + if (body == null) return null; + + final variable = arguments.variable; + if (variable == null) { + final delimiter = name == 'abs' ? '|' : r'\Vert'; + return '\\left$delimiter{$body}\\right$delimiter'; + } + final differential = name == 'dv' ? r'\mathrm{d}' : r'\partial'; + final order = arguments.order; + final power = order.isNotEmpty && order != '1' ? '^{$order}' : ''; + final numerator = body.isEmpty ? '' : '{$body}'; + return '\\frac{$differential$power$numerator}{$differential{$variable}$power}'; +} + String? _normalizeFragment(String source, int depth) { if (depth > _maxDepth) return null; - final commands = RegExp(r'\\([A-Za-z]+|[^A-Za-z])'); final result = StringBuffer(); var cursor = 0, scan = 0; while (scan < source.length) { - final matches = commands.allMatches(source, scan).iterator; + final matches = _command.allMatches(source, scan).iterator; if (!matches.moveNext()) break; final match = matches.current; - final start = match.start; scan = match.end; - final name = match.group(1)!; - if (const [ - 'text', - 'textrm', - 'textbf', - 'textit', - 'texttt', - 'operatorname', - 'ce', - ].contains(name)) { - final text = _groupAt(source, scan); - if (text != null) scan = text.end; + final name = match[1]!; + if (_literalCommands.contains(name)) { + scan = _groupAt(source, scan)?.end ?? scan; continue; } - if (!const ['dv', 'pdv', 'abs', 'norm'].contains(name)) continue; - var offset = _skipSpace(source, scan); - var order = ''; - if ((name == 'dv' || name == 'pdv') && - offset < source.length && - source[offset] == '[') { - final option = RegExp(r'^\[([1-9]\d?|[A-Za-z])\]') - .firstMatch(source.substring(offset)); - if (option == null) return null; - order = option.group(1)!; - offset += option.end; - } - final first = _groupAt(source, offset); - if (first == null || first.body.trim().isEmpty) return null; - var end = first.end; - final String replacement; - if (name == 'abs' || name == 'norm') { - final body = _normalizeFragment(first.body, depth + 1); - if (body == null) return null; - final delimiter = name == 'abs' ? '|' : r'\Vert'; - replacement = '\\left$delimiter{$body}\\right$delimiter'; - } else { - final second = _groupAt(source, first.end); - end = second?.end ?? first.end; - final tailOffset = _skipSpace(source, end); - final tail = tailOffset < source.length ? source[tailOffset] : ''; - if (tail == '{' || tail == '(' || tail == '[') return null; - final variable = (second?.body ?? first.body).trim(); - if (!_variable.hasMatch(variable)) return null; - final body = second != null - ? _normalizeFragment(first.body, depth + 1) - : ''; - if (body == null) return null; - final differential = name == 'dv' ? r'\mathrm{d}' : r'\partial'; - final power = order.isNotEmpty && order != '1' ? '^{$order}' : ''; - final numerator = body.isEmpty ? '' : '{$body}'; - replacement = - '\\frac{$differential$power$numerator}' - '{$differential{$variable}$power}'; - } - result.write(source.substring(cursor, start)); + if (!const {'dv', 'pdv', 'abs', 'norm'}.contains(name)) continue; + final arguments = _readArguments(source, scan, name); + if (arguments == null) return null; + final replacement = _expandCommand(name, arguments, depth); + if (replacement == null) return null; + result.write(source.substring(cursor, match.start)); result.write(replacement); - cursor = end; - scan = end; + cursor = arguments.end; + scan = arguments.end; } result.write(source.substring(cursor)); return result.toString(); diff --git a/app/lib/utils/siunitx_latex.dart b/app/lib/utils/siunitx_latex.dart new file mode 100644 index 00000000..2b2b8e33 --- /dev/null +++ b/app/lib/utils/siunitx_latex.dart @@ -0,0 +1,133 @@ +// The supported siunitx grammar accepts decimal numbers and products of units. +String? normalizeSiNumber(String value) { + final match = RegExp( + r'^([+-]?(?:\d+(?:\.\d*)?|\.\d+))(?:[eE]([+-]?\d{1,3}))?$', + ).firstMatch(value.trim()); + if (match == null) return null; + return match[2] == null + ? match[1] + : '${match[1]}\\times10^{${int.parse(match[2]!)}}'; +} + +const _prefixes = { + 'pico': 'p', + 'nano': 'n', + 'micro': 'μ', + 'milli': 'm', + 'centi': 'c', + 'deci': 'd', + 'kilo': 'k', + 'mega': 'M', + 'giga': 'G', + 'tera': 'T', +}; +const _units = { + 'metre': 'm', + 'meter': 'm', + 'second': 's', + 'ampere': 'A', + 'kelvin': 'K', + 'mole': 'mol', + 'candela': 'cd', + 'gram': 'g', + 'kilogram': 'kg', + 'hertz': 'Hz', + 'newton': 'N', + 'pascal': 'Pa', + 'joule': 'J', + 'watt': 'W', + 'coulomb': 'C', + 'volt': 'V', + 'farad': 'F', + 'ohm': 'Ω', + 'siemens': 'S', + 'weber': 'Wb', + 'tesla': 'T', + 'henry': 'H', + 'radian': 'rad', + 'steradian': 'sr', + 'degree': '°', + 'degreeCelsius': '°C', + 'liter': 'L', + 'litre': 'L', + 'electronvolt': 'eV', + 'decibel': 'dB', + 'percent': r'\%', + 'bit': 'bit', + 'byte': 'B', +}; + +String? normalizeSiQuantity(String numberSource, String unitSource) { + final number = normalizeSiNumber(numberSource); + final unit = normalizeSiUnit(unitSource); + if (number == null || unit == null) return null; + return '$number\\,$unit'; +} + +String? normalizeSiUnit(String source) { + final reader = _UnitReader(source); + final numerator = [], denominator = []; + while (!reader.atEnd) { + final target = reader.takePer() ? denominator : numerator; + final factor = reader.readFactor(); + if (factor == null) return null; + target.add(factor); + } + if (numerator.isEmpty && denominator.isEmpty) return null; + final top = numerator.isEmpty ? '1' : numerator.join(r'\,'); + if (denominator.isEmpty) return top; + final bottom = denominator.join(r'\,'); + return '$top/${denominator.length > 1 ? '($bottom)' : bottom}'; +} + +// Each factor has an optional prefix, a required bare unit and an optional +// power. A preceding \per puts just this factor in the denominator. +class _UnitReader { + _UnitReader(this.source) { + _advance(); + } + + final String source; + static final _command = RegExp(r'\\([A-Za-z]+)(?:\{([+-]?\d{1,3})\})?'); + int _offset = 0; + Match? _token; + + bool get atEnd => _offset == source.length && _token == null; + String? get _bareName { + if (_token?[2] != null) return null; + return _token?[1]; + } + + void _advance() { + while (_offset < source.length && source[_offset].trim().isEmpty) { + _offset++; + } + _token = _command.matchAsPrefix(source, _offset); + if (_token != null) _offset = _token!.end; + } + + bool takePer() { + if (_bareName != 'per') return false; + _advance(); + return true; + } + + String? readFactor() { + final prefix = _prefixes[_bareName]; + if (prefix != null) _advance(); + final unit = _units[_bareName]; + if (unit == null) return null; + _advance(); + + final symbol = '\\mathrm{${prefix ?? ''}$unit}'; + final power = switch ((_token?[1], _token?[2])) { + ('squared', null) => 2, + ('cubed', null) => 3, + ('tothe', final String exponent) => int.parse(exponent), + _ => null, + }; + if (power == null) return symbol; + _advance(); + return '$symbol^{$power}'; + } +} diff --git a/app/lib/utils/text_tools.dart b/app/lib/utils/text_tools.dart index d9026fcb..2bda83bb 100644 --- a/app/lib/utils/text_tools.dart +++ b/app/lib/utils/text_tools.dart @@ -51,91 +51,94 @@ String collapseImages(String text, Map images) => return '![插图 $id$scale]'; }); +// Literal ranges from the shared scanner keep their original spelling unless replaced. +String _replaceSegments(String text, String? Function(String) replacement) { + final out = StringBuffer(); + var cursor = 0; + for (final segment in scanMathSegments(text)) { + final value = replacement(text.substring(segment.start, segment.end)); + if (value == null) continue; + out.write(text.substring(cursor, segment.start)); + out.write(value); + cursor = segment.end; + } + if (cursor == 0) return text; + out.write(text.substring(cursor)); + return out.toString(); +} + String cleanMarkdown( String text, { String tableMode = 'latex', bool english = false, String Function(String)? transformMath, }) { - var s = text.replaceAll('\r\n', '\n').replaceAll('\r', '\n'); + const quotedStart = '$markdownTokenStart\uFDD1'; + var s = text + .replaceAll(markdownTokenStart, quotedStart) + .replaceAll('\r\n', '\n') + .replaceAll('\r', '\n'); final code = protectMarkdownCode(s, inline: false); s = code.text; - final protected = []; - final scriptStars = []; - var tokenPrefix = '\uE100HW'; - while (s.contains(tokenPrefix)) { - tokenPrefix += '\uE100'; - } - String protect(String source) { - protected.add(source); - return '$tokenPrefix${protected.length - 1}\uE101'; - } + final protected = MarkdownPlaceholders('${markdownTokenStart}HW', '\uE101'); + final scriptStars = MarkdownPlaceholders( + '${markdownTokenStart}HWSTAR', + '\uE101', + ); // A diagram can contain pipes and Markdown-looking labels. Mask its entire // source before table recognition so an unsupported diagram stays editable. - final diagrams = StringBuffer(); - var diagramCursor = 0; - for (final segment in scanMathSegments(s)) { - final source = s.substring(segment.start, segment.end); - if (!source.contains(r'\begin{circuitikz}')) continue; - diagrams.write(s.substring(diagramCursor, segment.start)); - diagrams.write(protect(source)); - diagramCursor = segment.end; - } - diagrams.write(s.substring(diagramCursor)); - s = diagrams.toString(); + s = _replaceSegments( + s, + (source) => + source.contains(r'\begin{circuitikz}') ? protected.save(source) : null, + ); if (tableMode == 'latex') { - s = _convertMarkdownTables(s, protect); + s = _convertMarkdownTables(s, protected.save); } - final math = StringBuffer(); - var cursor = 0; - for (final segment in scanMathSegments(s)) { - math.write(s.substring(cursor, segment.start)); - final source = s.substring(segment.start, segment.end); + s = _replaceSegments(s, (source) { + // Links and images retain the existing Markdown extraction rules. + if (source.startsWith('![') || + source.startsWith('[') || + source.startsWith('`')) { + return null; + } final fenced = RegExp(r'^(`{3,}|~{3,})[^\n]*\n([\s\S]*?)\1$') .firstMatch(source); - // Links and images retain the existing Markdown extraction rules. - math.write( - source.startsWith('![') || - source.startsWith('[') || - source.startsWith('`') - ? source - : protect(fenced?[2] ?? source), - ); - cursor = segment.end; - } - math.write(s.substring(cursor)); - final bodyCode = protectMarkdownCode(math.toString()); + return protected.save(fenced?[2] ?? source); + }); + final bodyCode = protectMarkdownCode(s); s = bodyCode.text; // Converted script stars must not become Markdown emphasis on a second cleanup. - s = s.replaceAllMapped(RegExp(r'[_^](?:\(\*\)|\{\*\}|\*)'), (match) { - scriptStars.add(match[0]!); - return '${tokenPrefix}STAR${scriptStars.length - 1}\uE101'; - }); + s = s.replaceAllMapped( + RegExp(r'[_^](?:\(\*\)|\{\*\}|\*)'), + (match) => scriptStars.save(match[0]!), + ); final bareMath = StringBuffer(); - cursor = 0; + var cursor = 0; for (final match in RegExp(r'\\left\b').allMatches(s)) { if (match.start < cursor) continue; final end = bareDelimiterEnd(s, match.start); if (end <= match.start) continue; bareMath.write(s.substring(cursor, match.start)); - bareMath.write(protect(s.substring(match.start, end))); + bareMath.write(protected.save(s.substring(match.start, end))); cursor = end; } bareMath.write(s.substring(cursor)); final unprotectedImages = bareMath.toString(); s = _replaceEmbeddedImages( unprotectedImages, - (match, end) => protect(unprotectedImages.substring(match.start, end + 1)), + (match, end) => + protected.save(unprotectedImages.substring(match.start, end + 1)), ); s = s.replaceAllMapped( RegExp( r'!\[[^\]]*\]\(img:?_?\d+\)|!\[插图(?:[ \t]*[#:_-]?[ \t]*\d+)?(?:\|[^\]]+)?\](?!\()', ), (m) { - return protect(m[0]!); + return protected.save(m[0]!); }, ); s = s.replaceFirst( @@ -154,70 +157,47 @@ String cleanMarkdown( ), '', ); + s = s.replaceAllMapped(RegExp(r'~~~[^\n]*\n([\s\S]*?)~~~'), (m) => m[1]!); + s = stripMarkdownLinks(s); + s = _cleanLines(s, tableMode, english); + for (final marker in ['***', '___', '**', '__', '~~', '==']) { + s = s.replaceAllMapped( + RegExp('${RegExp.escape(marker)}(.+?)${RegExp.escape(marker)}'), + (m) => m[1]!, + ); + } s = s.replaceAllMapped( - RegExp(r'```[^\n]*\n([\s\S]*?)```|~~~[^\n]*\n([\s\S]*?)~~~'), - (m) => m[1] ?? m[2]!, + RegExp(r'(^|[^\w*])\*([^\s*][^*\n]*?)\*(?=[^\w*]|$)'), + (m) => '${m[1]}${m[2]}', ); - s = s.replaceAllMapped(RegExp(r'`([^`\n]+)`'), (m) => m[1]!); - s = stripMarkdownLinks(s); + s = s.replaceAllMapped( + RegExp(r'(^|[^\w_])_([^\s_][^_\n]*?)_(?=[^\w_]|$)'), + (m) => '${m[1]}${m[2]}', + ); + s = protected.restore(s); + s = s + .split('\n') + .where((line) => line.trim().isNotEmpty && line.trim() != '---') + .join('\n') + .trim(); + // Keep literal code masked until both cleanup stages have finished. + s = transformMath?.call(s) ?? s; + s = scriptStars.restore(s); + return code + .restore(bodyCode.restore(s)) + .replaceAll(quotedStart, markdownTokenStart); +} + +String _cleanLines(String source, String tableMode, bool english) { final output = [], table = []; void flush() { if (table.isEmpty) return; - final rows = table - .where((line) => !RegExp(r'^[\s|:\-]+$').hasMatch(line)) - .map( - (line) => line - .trim() - .replaceAll(RegExp(r'^\||\|$'), '') - .split('|') - .map((c) => c.trim()) - .toList(), - ) - .toList(); - if (rows.isNotEmpty) { - if (tableMode == 'list' && rows.length > 1) { - final headers = rows.first; - for (var i = 1; i < rows.length; i++) { - final row = rows[i]; - final fields = [ - for (var j = 1; j < row.length; j++) - '${j < headers.length ? headers[j] : '${english ? 'Column' : '列'}${j + 1}'}: ${row[j].isEmpty ? '-' : row[j]}', - ]; - output.add( - '$i. ${headers.first}: ${row.first}${fields.isEmpty ? '' : ' (${fields.join('; ')})'}', - ); - } - } else if (tableMode == 'aligned') { - int width(String value) => - value.runes.fold(0, (a, b) => a + (b > 255 ? 2 : 1)); - final columns = rows - .map((r) => r.length) - .reduce((a, b) => a > b ? a : b); - final widths = List.generate( - columns, - (i) => rows - .map((r) => i < r.length ? width(r[i]) : 0) - .reduce((a, b) => a > b ? a : b), - ); - output.addAll( - rows.map( - (r) => [ - for (var i = 0; i < r.length; i++) - r[i] + ' ' * (widths[i] - width(r[i]) + 2), - ].join().trimRight(), - ), - ); - } else { - output.addAll( - rows.map((r) => r.join(tableMode == 'raw_pipe' ? ' | ' : ' ')), - ); - } - } + output.addAll(_formatTable(table, tableMode, english)); table.clear(); } var listContinuation = false; - for (var line in s.split('\n')) { + for (var line in source.split('\n')) { if (tableMode != 'latex' && RegExp(r'^\s*\|.*\|\s*$').hasMatch(line)) { table.add(line); continue; @@ -242,37 +222,63 @@ String cleanMarkdown( output.add(line.trimRight()); } flush(); - s = output.join('\n'); - for (final marker in ['***', '___', '**', '__', '~~', '==']) { - s = s.replaceAllMapped( - RegExp('${RegExp.escape(marker)}(.+?)${RegExp.escape(marker)}'), - (m) => m[1]!, - ); + return output.join('\n'); +} + +Iterable _formatTable( + List table, + String tableMode, + bool english, +) { + final rows = table + .where((line) => !RegExp(r'^[\s|:\-]+$').hasMatch(line)) + .map( + (line) => line + .trim() + .replaceAll(RegExp(r'^\||\|$'), '') + .split('|') + .map((c) => c.trim()) + .toList(), + ) + .toList(); + if (rows.isEmpty) return const []; + if (tableMode == 'list' && rows.length > 1) return _listRows(rows, english); + if (tableMode == 'aligned') return _alignedRows(rows); + return rows.map((row) => row.join(tableMode == 'raw_pipe' ? ' | ' : ' ')); +} + +Iterable _listRows(List> rows, bool english) sync* { + final headers = rows.first; + for (var i = 1; i < rows.length; i++) { + final row = rows[i]; + final fields = [ + for (var j = 1; j < row.length; j++) + '${j < headers.length ? headers[j] : '${english ? 'Column' : '列'}${j + 1}'}: ${row[j].isEmpty ? '-' : row[j]}', + ]; + yield '$i. ${headers.first}: ${row.first}${fields.isEmpty ? '' : ' (${fields.join('; ')})'}'; } - s = s.replaceAllMapped( - RegExp(r'(^|[^\w*])\*([^\s*][^*\n]*?)\*(?=[^\w*]|$)'), - (m) => '${m[1]}${m[2]}', - ); - s = s.replaceAllMapped( - RegExp(r'(^|[^\w_])_([^\s_][^_\n]*?)_(?=[^\w_]|$)'), - (m) => '${m[1]}${m[2]}', - ); - s = s.replaceAllMapped( - RegExp('${RegExp.escape(tokenPrefix)}(\\d+)\uE101'), - (m) => protected[int.parse(m[1]!)], - ); - s = s - .split('\n') - .where((line) => line.trim().isNotEmpty && line.trim() != '---') - .join('\n') - .trim(); - // Keep literal code masked until both cleanup stages have finished. - s = transformMath?.call(s) ?? s; - s = s.replaceAllMapped( - RegExp('${RegExp.escape(tokenPrefix)}STAR(\\d+)\uE101'), - (match) => scriptStars[int.parse(match[1]!)], +} + +Iterable _alignedRows(List> rows) { + int width(String value) => + value.runes.fold(0, (a, b) => a + (b > 255 ? 2 : 1)); + final widths = []; + for (final row in rows) { + for (var i = 0; i < row.length; i++) { + final size = width(row[i]); + if (i == widths.length) { + widths.add(size); + } else if (size > widths[i]) { + widths[i] = size; + } + } + } + return rows.map( + (r) => [ + for (var i = 0; i < r.length; i++) + r[i] + ' ' * (widths[i] - width(r[i]) + 2), + ].join().trimRight(), ); - return code.restore(bodyCode.restore(s)); } // Markdown 表格仅在完整分隔行后识别;不完整或超宽数据保持原文。 @@ -331,76 +337,56 @@ String _convertMarkdownTables(String source, String Function(String) protect) { return output.join('\n'); } -List? _tableCells(String line) { - final value = line.trim(); - if (value.isEmpty || value.startsWith('⟦')) return null; - final cells = []; - final cell = StringBuffer(); - var ticks = 0; - var dollar = false; - var paren = false; - var split = false; - for (var i = 0; i < value.length; i++) { - final char = value[i]; - if (char == '\\' && i + 1 < value.length) { - final next = value[i + 1]; - if (next == '(' && ticks == 0 && !dollar) paren = true; - if (next == ')' && ticks == 0 && !dollar) paren = false; - cell.write(char); - cell.write(next); - i++; +// A backslash consumes the next character, even inside code. A backtick run +// must match its opening width and temporarily suspends any surrounding math. +final _tableTokens = RegExp(r'\\.|`+|[$|]', dotAll: true); + +Iterable _tableSeparators(String row) sync* { + String? codeFence, mathEnd; + for (final match in _tableTokens.allMatches(row)) { + final token = match[0]!; + if (codeFence != null) { + if (token == codeFence) codeFence = null; continue; } - if (char == '`') { - var count = 1; - while (i + count < value.length && value[i + count] == '`') { - count++; - } - ticks = ticks == count - ? 0 - : ticks == 0 - ? count - : ticks; - cell.write('`' * count); - i += count - 1; + if (token.startsWith('`')) { + codeFence = token; continue; } - if (char == r'$' && ticks == 0 && !paren) dollar = !dollar; - if (char == '|' && ticks == 0 && !dollar && !paren) { - cells.add(cell.toString().trim()); - cell.clear(); - split = true; - } else { - cell.write(char); + if (mathEnd != null) { + if (token == mathEnd) mathEnd = null; + continue; + } + switch (token) { + case r'\(': + mathEnd = r'\)'; + case r'$': + mathEnd = token; + case '|': + yield match.start; } } - cells.add(cell.toString().trim()); - if (!split) return null; - if (value.startsWith('|')) cells.removeAt(0); - if (value.endsWith('|') && cells.last.isEmpty) cells.removeLast(); +} + +List? _tableCells(String line) { + final row = line.trim(); + if (!row.contains('|') || row.startsWith('⟦')) return null; + final cells = []; + var start = 0; + for (final end in _tableSeparators(row)) { + if (end > 0) cells.add(row.substring(start, end).trim()); + start = end + 1; + } + if (start == 0) return null; + if (start < row.length) cells.add(row.substring(start).trim()); return cells.isEmpty ? null : cells; } String _tableLatexCell(String cell) { // Clean paired decorations before splitting a cell into text and formulas. - var prefix = '\uE130CELL'; - while (cell.contains(prefix)) { - prefix += '\uE130'; - } - final saved = []; - final masked = StringBuffer(); - var end = 0; - for (final segment in scanMathSegments(cell)) { - masked.write(cell.substring(end, segment.start)); - masked.write('$prefix${saved.length}\uE131'); - saved.add(cell.substring(segment.start, segment.end)); - end = segment.end; - } - masked.write(cell.substring(end)); - cell = cleanMarkdown(masked.toString(), tableMode: 'clean').replaceAllMapped( - RegExp('${RegExp.escape(prefix)}(\\d+)\uE131'), - (match) => saved[int.parse(match[1]!)], - ); + final saved = MarkdownPlaceholders('${markdownTokenStart}CELL', '\uE131'); + final masked = _replaceSegments(cell, saved.save); + cell = saved.restore(cleanMarkdown(masked, tableMode: 'clean')); final output = StringBuffer(); var cursor = 0; for (final segment in scanMathSegments(cell)) { diff --git a/app/lib/view_models/fine_selection.dart b/app/lib/view_models/fine_selection.dart index 488638ee..3fec630b 100644 --- a/app/lib/view_models/fine_selection.dart +++ b/app/lib/view_models/fine_selection.dart @@ -51,6 +51,26 @@ class FineSelection { } } + void selectSource(FinePage page, FineRange range) { + if (!page.glyphs.any((glyph) => glyph.source != null)) return; + select( + page.glyphs + .where((glyph) { + final span = glyph.source; + return span != null && + span.start < range.end && + span.end > range.start; + }) + .map((glyph) => glyph.id), + ); + } + + void selectIllustration(FinePage page, int group) => select( + page.glyphs + .where((glyph) => glyph.illustrationId == group) + .map((glyph) => glyph.id), + ); + void box( FinePage page, Map edits, @@ -270,6 +290,30 @@ class FineSelection { ); } + List adjust( + Map edits, { + int? scale, + int? angle, + int? opacity, + int? color, + int? thickness, + int? softness, + }) => change( + edits, + (v) => ( + id: v.id, + dx: v.dx, + dy: v.dy, + scale: scale ?? v.scale, + angle: angle ?? v.angle, + opacity: opacity ?? v.opacity, + color: color ?? v.color, + thickness: thickness ?? v.thickness, + softness: softness ?? v.softness, + warp: v.warp, + ), + ); + List change( Map edits, FineAdjustment Function(FineAdjustment) update, diff --git a/app/lib/view_models/fine_selection_drag.dart b/app/lib/view_models/fine_selection_drag.dart new file mode 100644 index 00000000..f097e1d5 --- /dev/null +++ b/app/lib/view_models/fine_selection_drag.dart @@ -0,0 +1,149 @@ +import 'dart:ui'; + +import '../models/fine_edit.dart'; +import '../utils/lasso.dart'; +import 'fine_selection.dart'; + +enum FineDragAction { tap, move, box, lasso } + +/// A primary pointer keeps the tool and hit from the moment it touches the page. +/// Hit testing and outlines use paper coordinates. Drag slop uses screen pixels. +class FineSelectionDrag { + FineSelectionDrag._( + this.pointer, + this.start, + this._screen, + this._hit, + this._append, + this.action, + ) : _path = action == FineDragAction.lasso ? [start] : null; + + factory FineSelectionDrag.begin( + FineSelection selection, + FinePage page, + Map edits, { + required int pointer, + required Offset start, + required Offset screen, + required bool touch, + required bool shift, + }) { + final hit = selection.hit(page, edits, start); + final append = !touch && shift; + final group = selection.bounds(page, edits); + final inSelection = + group != null && + group.contains(start) && + (hit == null || selection.selected.contains(hit.id)); + final action = switch (selection.tool) { + FineTool.move => FineDragAction.move, + FineTool.select when touch => FineDragAction.tap, + FineTool.select when !append && (inSelection || hit != null) => + FineDragAction.move, + FineTool.lasso => FineDragAction.lasso, + _ => FineDragAction.box, + }; + return FineSelectionDrag._(pointer, start, screen, hit, append, action); + } + + final int pointer; + final Offset start, _screen; + final FineGlyph? _hit; + final bool _append; + final FineDragAction action; + final List? _path; + bool moved = false; + Rect? box; + List lasso = []; + + bool acceptsMove(int id, Offset screen) => + pointer == id && (moved || (screen - _screen).distance >= 4); + + bool selectMoveTarget(FineSelection selection, {required bool mouse}) { + final hit = _hit; + if (moved || + action != FineDragAction.move || + !mouse || + hit == null || + selection.selected.contains(hit.id)) { + return false; + } + selection.select([hit.id]); + return true; + } + + void outline(Offset point, double minimum) { + final path = _path; + if (path == null) { + box = Rect.fromPoints(start, point); + } else { + appendLassoPoint(path, point, minimum); + lasso = [...path, point]; + } + } + + bool finishSelection( + FineSelection selection, + FinePage page, + Map edits, + Offset point, { + required bool mouse, + }) { + if (!moved) { + if (!mouse && action == FineDragAction.move) return false; + selection.select([if (_hit case final hit?) hit.id], append: _append); + return true; + } + switch (action) { + case FineDragAction.lasso: + selection.lasso(page, edits, [..._path!, point], append: _append); + case FineDragAction.box: + selection.box( + page, + edits, + Rect.fromPoints(start, point), + append: _append, + ); + case FineDragAction.tap: + case FineDragAction.move: + return false; + } + return true; + } +} + +/// A perspective drag retains the original frame even as its live outline moves. +class FineCornerDrag { + FineCornerDrag._(this.pointer, this.index, this.start, this.frame); + final int pointer, index; + final Offset start; + final FinePerspectiveFrame frame; + FinePerspectiveChange? latest; + + static FineCornerDrag? hit( + int pointer, + Offset at, + FinePerspectiveFrame? frame, + double radius, + ) { + if (frame == null) return null; + var nearest = radius; + int? index; + for (final (i, point) in frame.points.indexed) { + final distance = (at - point).distance; + if (distance <= nearest) { + nearest = distance; + index = i; + } + } + return index == null ? null : FineCornerDrag._(pointer, index, at, frame); + } + + FinePerspectiveChange? project( + FineSelection selection, + FinePage page, + Map edits, + Offset point, + Size size, + ) => selection.corner(page, edits, frame, index, point - start, size); +} diff --git a/app/lib/view_models/generation_view_model.dart b/app/lib/view_models/generation_view_model.dart index 11f9b51c..69619550 100644 --- a/app/lib/view_models/generation_view_model.dart +++ b/app/lib/view_models/generation_view_model.dart @@ -4,14 +4,22 @@ import 'package:flutter/foundation.dart'; import '../models/engine_failure.dart'; import '../models/ink_page.dart'; -import '../services/engine_gateway.dart'; +import '../services/engine_contract.dart'; class _GenerationOperation { _GenerationOperation(this.engine); final EngineGateway engine; - final submitted = Completer(); + final _submitted = Completer(); bool cancelled = false; Future? stopping; + + // Both user cancellation and shutdown must wait for the original engine's + // identity. A locally reserved ID is usable before submission completes. + void resolveId(String? id) { + if (!_submitted.isCompleted) _submitted.complete(id); + } + + Future get id => _submitted.future; } /// Task state owns engine operations; it has no navigation or editor controllers. @@ -53,26 +61,15 @@ class GenerationViewModel extends ChangeNotifier { bool current() => !disposed && generation == _generation && !operation.cancelled; var succeeded = false; - busy = true; - taskId = ''; - error = ''; - errorCode = null; - queueWaitSeconds = null; - progress = 0; - phase = 'pending'; - stage = 'preparing'; - pagesCompleted = 0; - emit(); + _begin(); try { final requestedId = engine.createTaskId(); if (requestedId != null) { taskId = requestedId; - operation.submitted.complete(requestedId); + operation.resolveId(requestedId); } final submittedId = await engine.submit(request, taskId: requestedId); - if (!operation.submitted.isCompleted) { - operation.submitted.complete(submittedId); - } + operation.resolveId(submittedId); if (!current()) return false; taskId = submittedId; await onSubmitted?.call(); @@ -81,22 +78,7 @@ class GenerationViewModel extends ChangeNotifier { while (current()) { final task = await engine.status(submittedId); if (!current()) return false; - phase = task.phase.name; - progress = task.progress; - stage = task.stage ?? ''; - pagesCompleted = task.pagesCompleted; - emit(); - if (task.phase == TaskPhase.failed || - task.phase == TaskPhase.cancelled) { - throw EngineFailure( - task.errorMessage ?? 'Task failed', - code: task.errorCode, - ); - } - if (task.phase == TaskPhase.completed) break; - if (DateTime.now().isAfter(deadline)) { - throw TimeoutException('Task timed out'); - } + if (_publishStatus(task, deadline)) break; await Future.delayed(const Duration(seconds: 2)); } if (!current()) return false; @@ -104,16 +86,12 @@ class GenerationViewModel extends ChangeNotifier { if (acceptPreview?.call() == false) return false; final rendered = await engine.preview(submittedId); if (!current() || acceptPreview?.call() == false) return false; - inkPages = rendered.map(InkPage.fromPacket).toList(growable: false); - pages = [ - for (var i = 0; i < rendered.length; i++) - inkPages[i]?.paper ?? rendered[i], - ]; - previewRevision = revision; - previewTaskId = submittedId; - page = acceptPreview == null || pages.isEmpty - ? 0 - : page.clamp(0, pages.length - 1); + _publishPreview( + rendered, + submittedId, + revision, + keepPage: acceptPreview != null, + ); } else { final bytes = await engine.export(submittedId); if (!current()) return false; @@ -124,22 +102,13 @@ class GenerationViewModel extends ChangeNotifier { succeeded = true; } on EngineFailure catch (e) { if (!current()) return false; - error = e.message; - errorCode = e.code; - queueWaitSeconds = e.retryAfterSeconds; - if (e.retryAfterSeconds != null) { - retryAt = DateTime.now().add(Duration(seconds: e.retryAfterSeconds!)); - } + _publishFailure(e); } catch (e) { if (!current()) return false; error = '$e'; } finally { - if (!operation.submitted.isCompleted) operation.submitted.complete(null); - if (!succeeded && - current() && - taskId.isNotEmpty && - engine.supportsCancel && - !['completed', 'failed', 'error', 'cancelled'].contains(phase)) { + operation.resolveId(null); + if (!succeeded && current() && _needsStop(engine)) { final failure = error; await cancel(); if (!disposed && !busy) { @@ -156,6 +125,68 @@ class GenerationViewModel extends ChangeNotifier { return current() && succeeded; } + void _begin() { + busy = true; + taskId = ''; + error = ''; + errorCode = null; + queueWaitSeconds = null; + progress = 0; + phase = 'pending'; + stage = 'preparing'; + pagesCompleted = 0; + emit(); + } + + bool _publishStatus(EngineTask task, DateTime deadline) { + phase = task.phase.name; + progress = task.progress; + stage = task.stage ?? ''; + pagesCompleted = task.pagesCompleted; + emit(); + if (task.phase == TaskPhase.failed || task.phase == TaskPhase.cancelled) { + throw EngineFailure( + task.errorMessage ?? 'Task failed', + code: task.errorCode, + ); + } + if (task.phase == TaskPhase.completed) return true; + if (DateTime.now().isAfter(deadline)) { + throw TimeoutException('Task timed out'); + } + return false; + } + + void _publishPreview( + List rendered, + String id, + int revision, { + required bool keepPage, + }) { + inkPages = rendered.map(InkPage.fromPacket).toList(growable: false); + pages = [ + for (var i = 0; i < rendered.length; i++) + inkPages[i]?.paper ?? rendered[i], + ]; + previewRevision = revision; + previewTaskId = id; + page = !keepPage || pages.isEmpty ? 0 : page.clamp(0, pages.length - 1); + } + + void _publishFailure(EngineFailure e) { + error = e.message; + errorCode = e.code; + queueWaitSeconds = e.retryAfterSeconds; + if (e.retryAfterSeconds != null) { + retryAt = DateTime.now().add(Duration(seconds: e.retryAfterSeconds!)); + } + } + + bool _needsStop(EngineGateway engine) => + taskId.isNotEmpty && + engine.supportsCancel && + TaskPhase.fromWire(phase)?.terminal != true; + Future cancel() { final operation = _operation; if (!busy || @@ -170,7 +201,7 @@ class GenerationViewModel extends ChangeNotifier { error = ''; final stopped = () async { try { - final id = await operation.submitted.future; + final id = await operation.id; if (id != null) await operation.engine.cancel(id); if (disposed || !identical(operation, _operation)) return; ++_generation; @@ -203,7 +234,7 @@ class GenerationViewModel extends ChangeNotifier { operation.cancelled = true; unawaited(() async { try { - final id = await operation.submitted.future; + final id = await operation.id; if (id != null) await operation.engine.cancel(id); } catch (_) { // Shutdown cannot publish a new UI error. diff --git a/app/lib/widgets/app_update_card.dart b/app/lib/widgets/app_update_card.dart index dc98a23c..039b954d 100644 --- a/app/lib/widgets/app_update_card.dart +++ b/app/lib/widgets/app_update_card.dart @@ -1,13 +1,12 @@ import 'package:flutter/material.dart'; -import 'workbench_card.dart'; - import 'package:url_launcher/url_launcher.dart'; import '../l10n/app_localizations.dart'; import '../services/updates/update_controller.dart'; import '../services/updates/update_model.dart'; import '../services/updates/update_notes.dart'; +import 'workbench_card.dart'; class AppUpdateCard extends StatelessWidget { const AppUpdateCard({ @@ -29,35 +28,6 @@ class AppUpdateCard extends StatelessWidget { final l = AppLocalizations.of(context)!; final c = controller; final changes = summarizeReleaseNotes(c.release?.notes ?? ''); - final status = switch (c.phase) { - UpdatePhase.idle => l.updateIdle, - UpdatePhase.checking => l.updateChecking, - UpdatePhase.current => l.updateCurrent, - UpdatePhase.available => l.updateAvailable, - UpdatePhase.downloading => l.updateDownloading, - UpdatePhase.ready => l.updateReady, - UpdatePhase.preparing => l.updatePreparing, - UpdatePhase.restarting => l.updateRestarting, - UpdatePhase.failed => l.updateFailed, - }; - final problem = switch (c.problem) { - null => null, - UpdateProblem.network => l.updateNetwork, - UpdateProblem.rateLimited => l.updateRateLimited, - UpdateProblem.invalidResponse => l.updateInvalidResponse, - UpdateProblem.unknownVersion => l.updateUnknownVersion, - UpdateProblem.unsupportedPlatform => l.updateUnsupported, - UpdateProblem.missingAsset => l.updateMissingAsset, - UpdateProblem.verification => l.updateVerification, - UpdateProblem.cancelled => l.updateCancelled, - UpdateProblem.storage => l.updateStorage, - UpdateProblem.openFailed => l.updateOpenFailed, - UpdateProblem.desktopUnavailable => l.updateDesktopUnavailable, - UpdateProblem.saveFailed => l.updateSaveFailed, - UpdateProblem.restartDeferred => l.updateRestartDeferred, - UpdateProblem.restartCancelled => l.updateRestartCancelled, - UpdateProblem.anotherInstance => l.updateAnotherInstance, - }; return WorkbenchCard( key: const ValueKey('app-updates'), child: Padding( @@ -81,158 +51,9 @@ class AppUpdateCard extends StatelessWidget { ], ), const SizedBox(height: 12), - Text( - '${l.updateInstalled}: ${c.installed?.version.isNotEmpty == true ? c.installed!.version : l.updateVersionUnknown}', - ), - if (c.release != null || c.deployed != null) - Text( - '${l.updateLatest}: ${c.web ? c.deployed!.version : c.release!.version}', - ), - const SizedBox(height: 12), - Text( - status, - key: const ValueKey('update-status'), - style: Theme.of(context).textTheme.titleMedium, - ), - if (problem != null) - Padding( - padding: const EdgeInsets.only(top: 8), - child: Text(problem, key: const ValueKey('update-problem')), - ), - const SizedBox(height: 8), - Text( - c.web - ? l.updateWebHelp - : c.installed?.target.os == 'android' - ? l.updateAndroidSummary - : c.installed?.target.os == 'ios' - ? l.updateIosHelp - : c.desktopAutomatic - ? l.updateDesktopSummary - : l.updateDesktopUnavailable, - ), - if ({ - UpdatePhase.preparing, - UpdatePhase.restarting, - }.contains(c.phase)) ...[ - const SizedBox(height: 16), - const LinearProgressIndicator(), - ], - if (c.phase == UpdatePhase.downloading) ...[ - const SizedBox(height: 16), - LinearProgressIndicator( - value: c.total == 0 ? null : c.received / c.total, - ), - const SizedBox(height: 8), - Text( - '${(c.received / 1048576).toStringAsFixed(1)} / ${(c.total / 1048576).toStringAsFixed(1)} MB', - ), - ], - if (c.downloadedPath != null) ...[ - const SizedBox(height: 12), - SelectableText( - c.release?.packageFor(c.installed!.target)?.name ?? '', - ), - if (c.installed?.target.os != 'android') - ExpansionTile( - tilePadding: EdgeInsets.zero, - title: Text(l.updateSavedLocation), - children: [SelectableText(c.downloadedPath!)], - ), - ], + ..._status(context, l), const SizedBox(height: 16), - Wrap( - spacing: 10, - runSpacing: 10, - children: [ - if (!compact) - OutlinedButton.icon( - key: const ValueKey('check-updates'), - onPressed: c.busy || c.opening ? null : c.check, - icon: const Icon(Icons.refresh), - label: Text(l.checkUpdates), - ), - if ({ - UpdatePhase.downloading, - UpdatePhase.preparing, - UpdatePhase.restarting, - }.contains(c.phase)) - TextButton.icon( - onPressed: c.cancel, - icon: const Icon(Icons.close), - label: Text(l.cancel), - ), - if (!c.web && - c.release != null && - c.canDownload && - { - UpdatePhase.available, - UpdatePhase.failed, - }.contains(c.phase)) - FilledButton.icon( - key: const ValueKey('download-update'), - onPressed: c.desktopAutomatic && onRestart != null - ? onRestart - : c.download, - icon: const Icon(Icons.download_outlined), - label: Text( - c.desktopAutomatic && onRestart != null - ? l.updateRestart - : l.updateDownload, - ), - ), - if (c.phase == UpdatePhase.ready) - FilledButton.icon( - key: const ValueKey('open-update'), - onPressed: c.opening - ? null - : c.desktopAutomatic && - onRestart != null && - c.problem != UpdateProblem.desktopUnavailable - ? onRestart - : c.open, - icon: const Icon(Icons.open_in_new), - label: Text( - c.installed?.target.os == 'android' - ? l.updateInstall - : c.desktopAutomatic && - onRestart != null && - c.problem != UpdateProblem.desktopUnavailable - ? l.updateRestart - : l.updateOpenArchive, - ), - ), - if (c.phase == UpdatePhase.ready && - c.problem == UpdateProblem.anotherInstance) - OutlinedButton.icon( - key: const ValueKey('manual-update'), - onPressed: c.opening ? null : c.open, - icon: const Icon(Icons.folder_open), - label: Text(l.updateOpenArchive), - ), - if (c.web) - FilledButton.icon( - onPressed: c.busy ? null : onReload, - icon: const Icon(Icons.refresh), - label: Text(l.updateReload), - ), - OutlinedButton.icon( - onPressed: () async { - if (!await launchUrl( - c.release?.page ?? releasesPage, - mode: LaunchMode.externalApplication, - ) && - context.mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(l.updateOpenFailed)), - ); - } - }, - icon: const Icon(Icons.open_in_new), - label: Text(l.updateReleasePage), - ), - ], - ), + _actions(context, l), if (!compact) SwitchListTile.adaptive( key: const ValueKey('auto-check-updates'), @@ -276,4 +97,202 @@ class AppUpdateCard extends StatelessWidget { ); }, ); + + List _status(BuildContext context, AppLocalizations l) { + final c = controller; + final problem = _problemLabel(c.problem, l); + return [ + Text( + '${l.updateInstalled}: ${c.installed?.version.isNotEmpty == true ? c.installed!.version : l.updateVersionUnknown}', + ), + if (c.release != null || c.deployed != null) + Text( + '${l.updateLatest}: ${c.web ? c.deployed!.version : c.release!.version}', + ), + const SizedBox(height: 12), + Text( + _phaseLabel(c.phase, l), + key: const ValueKey('update-status'), + style: Theme.of(context).textTheme.titleMedium, + ), + if (problem != null) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(problem, key: const ValueKey('update-problem')), + ), + const SizedBox(height: 8), + Text(_platformHelp(c, l)), + if ({ + UpdatePhase.preparing, + UpdatePhase.restarting, + }.contains(c.phase)) ...[ + const SizedBox(height: 16), + const LinearProgressIndicator(), + ], + if (c.phase == UpdatePhase.downloading) ...[ + const SizedBox(height: 16), + LinearProgressIndicator( + value: c.total == 0 ? null : c.received / c.total, + ), + const SizedBox(height: 8), + Text( + '${(c.received / 1048576).toStringAsFixed(1)} / ${(c.total / 1048576).toStringAsFixed(1)} MB', + ), + ], + if (c.downloadedPath != null) ...[ + const SizedBox(height: 12), + SelectableText(c.release?.packageFor(c.installed!.target)?.name ?? ''), + if (c.installed?.target.os != 'android') + ExpansionTile( + tilePadding: EdgeInsets.zero, + title: Text(l.updateSavedLocation), + children: [SelectableText(c.downloadedPath!)], + ), + ], + ]; + } + + Widget _actions(BuildContext context, AppLocalizations l) { + final c = controller; + return Wrap( + spacing: 10, + runSpacing: 10, + children: [ + if (!compact) + OutlinedButton.icon( + key: const ValueKey('check-updates'), + onPressed: c.busy || c.opening ? null : c.check, + icon: const Icon(Icons.refresh), + label: Text(l.checkUpdates), + ), + ..._packageActions(l), + if (c.web) + FilledButton.icon( + onPressed: c.busy ? null : onReload, + icon: const Icon(Icons.refresh), + label: Text(l.updateReload), + ), + OutlinedButton.icon( + onPressed: () async { + if (!await launchUrl( + c.release?.page ?? releasesPage, + mode: LaunchMode.externalApplication, + ) && + context.mounted) { + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text(l.updateOpenFailed))); + } + }, + icon: const Icon(Icons.open_in_new), + label: Text(l.updateReleasePage), + ), + ], + ); + } + + List _packageActions(AppLocalizations l) { + final c = controller; + final restart = c.desktopAutomatic ? onRestart : null; + switch (c.phase) { + case UpdatePhase.downloading: + case UpdatePhase.preparing: + case UpdatePhase.restarting: + return [ + TextButton.icon( + onPressed: c.cancel, + icon: const Icon(Icons.close), + label: Text(l.cancel), + ), + ]; + case UpdatePhase.available: + case UpdatePhase.failed: + if (c.web || c.release == null || !c.canDownload) return const []; + return [ + FilledButton.icon( + key: const ValueKey('download-update'), + onPressed: restart ?? c.download, + icon: const Icon(Icons.download_outlined), + label: Text(restart == null ? l.updateDownload : l.updateRestart), + ), + ]; + case UpdatePhase.ready: + return _readyActions(l, restart); + case UpdatePhase.idle: + case UpdatePhase.checking: + case UpdatePhase.current: + return const []; + } + } + + List _readyActions( + AppLocalizations l, + Future Function()? restart, + ) { + final c = controller; + final restartReady = c.problem == UpdateProblem.desktopUnavailable + ? null + : restart; + final desktopLabel = restartReady == null + ? l.updateOpenArchive + : l.updateRestart; + return [ + FilledButton.icon( + key: const ValueKey('open-update'), + onPressed: c.opening ? null : restartReady ?? c.open, + icon: const Icon(Icons.open_in_new), + label: Text( + c.installed?.target.os == 'android' ? l.updateInstall : desktopLabel, + ), + ), + if (c.problem == UpdateProblem.anotherInstance) + OutlinedButton.icon( + key: const ValueKey('manual-update'), + onPressed: c.opening ? null : c.open, + icon: const Icon(Icons.folder_open), + label: Text(l.updateOpenArchive), + ), + ]; + } +} + +String _phaseLabel(UpdatePhase phase, AppLocalizations l) => switch (phase) { + UpdatePhase.idle => l.updateIdle, + UpdatePhase.checking => l.updateChecking, + UpdatePhase.current => l.updateCurrent, + UpdatePhase.available => l.updateAvailable, + UpdatePhase.downloading => l.updateDownloading, + UpdatePhase.ready => l.updateReady, + UpdatePhase.preparing => l.updatePreparing, + UpdatePhase.restarting => l.updateRestarting, + UpdatePhase.failed => l.updateFailed, +}; + +String? _problemLabel(UpdateProblem? problem, AppLocalizations l) => + switch (problem) { + null => null, + UpdateProblem.network => l.updateNetwork, + UpdateProblem.rateLimited => l.updateRateLimited, + UpdateProblem.invalidResponse => l.updateInvalidResponse, + UpdateProblem.unknownVersion => l.updateUnknownVersion, + UpdateProblem.unsupportedPlatform => l.updateUnsupported, + UpdateProblem.missingAsset => l.updateMissingAsset, + UpdateProblem.verification => l.updateVerification, + UpdateProblem.cancelled => l.updateCancelled, + UpdateProblem.storage => l.updateStorage, + UpdateProblem.openFailed => l.updateOpenFailed, + UpdateProblem.desktopUnavailable => l.updateDesktopUnavailable, + UpdateProblem.saveFailed => l.updateSaveFailed, + UpdateProblem.restartDeferred => l.updateRestartDeferred, + UpdateProblem.restartCancelled => l.updateRestartCancelled, + UpdateProblem.anotherInstance => l.updateAnotherInstance, + }; + +String _platformHelp(UpdateController c, AppLocalizations l) { + if (c.web) return l.updateWebHelp; + return switch (c.installed?.target.os) { + 'android' => l.updateAndroidSummary, + 'ios' => l.updateIosHelp, + _ => + c.desktopAutomatic ? l.updateDesktopSummary : l.updateDesktopUnavailable, + }; } diff --git a/app/lib/widgets/editor_illustration_strip.dart b/app/lib/widgets/editor_illustration_strip.dart new file mode 100644 index 00000000..bdc5ac17 --- /dev/null +++ b/app/lib/widgets/editor_illustration_strip.dart @@ -0,0 +1,107 @@ +import 'package:flutter/material.dart'; + +import '../l10n/app_localizations.dart'; +import '../utils/image_data.dart'; +import '../utils/image_markers.dart'; + +class EditorIllustrationStrip extends StatelessWidget { + const EditorIllustrationStrip({ + super.key, + required this.markers, + required this.images, + required this.onEditImage, + }); + + final List markers; + final Map images; + final ValueChanged? onEditImage; + + @override + Widget build(BuildContext context) => SizedBox( + height: 72, + child: ListView( + scrollDirection: Axis.horizontal, + children: [ + for (final marker in markers) + Padding( + padding: const EdgeInsets.all(4), + child: Semantics( + identifier: 'illustration-${marker.start}', + button: true, + child: OutlinedButton( + key: ValueKey('illustration-${marker.start}'), + onPressed: onEditImage == null + ? null + : () => onEditImage!(marker), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + _IllustrationThumbnail(source: images[marker.id] ?? ''), + const SizedBox(width: 8), + Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text('#${marker.id} · ${marker.scale}%'), + const Icon(Icons.tune, size: 20), + ], + ), + ], + ), + ), + ), + ), + ], + ), + ); +} + +/// Retain decoded bytes across editor rebuilds instead of decoding base64 on +/// every keystroke and missing the image cache with a new Uint8List identity. +class _IllustrationThumbnail extends StatefulWidget { + const _IllustrationThumbnail({required this.source}); + final String source; + @override + State<_IllustrationThumbnail> createState() => _IllustrationThumbnailState(); +} + +class _IllustrationThumbnailState extends State<_IllustrationThumbnail> { + late var bytes = decodeImageData(widget.source); + @override + void didUpdateWidget(_IllustrationThumbnail oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.source != widget.source) { + bytes = decodeImageData(widget.source); + } + } + + @override + Widget build(BuildContext context) { + final fallback = SizedBox( + width: 48, + height: 48, + child: Center( + child: Text( + AppLocalizations.of(context)!.imageUnavailable, + textAlign: TextAlign.center, + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + ), + ); + final data = bytes; + if (data == null) return fallback; + return Image( + image: ResizeImage( + MemoryImage(data), + width: 128, + height: 128, + policy: ResizeImagePolicy.fit, + ), + width: 48, + height: 48, + fit: BoxFit.contain, + gaplessPlayback: true, + errorBuilder: (_, error, stack) => fallback, + ); + } +} diff --git a/app/lib/widgets/fine_adjustment_sliders.dart b/app/lib/widgets/fine_adjustment_sliders.dart new file mode 100644 index 00000000..ad4a51b7 --- /dev/null +++ b/app/lib/widgets/fine_adjustment_sliders.dart @@ -0,0 +1,164 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; + +import '../l10n/app_localizations.dart'; +import '../models/fine_edit.dart'; +import '../models/ink_page.dart'; + +class FineAdjustmentSliders extends StatelessWidget { + const FineAdjustmentSliders({ + super.key, + required this.current, + required this.selectionCount, + required this.baseLook, + required this.transformDraft, + required this.onAdjust, + required this.onTransform, + required this.onCommit, + }); + final FineAdjustment current; + final int selectionCount; + final InkLook baseLook; + final ({String field, int value})? transformDraft; + final void Function({ + int? scale, + int? angle, + int? opacity, + int? thickness, + int? softness, + }) + onAdjust; + final void Function(String field, int value) onTransform; + final VoidCallback onCommit; + + int _transformValue(String field) => + transformDraft?.field == field ? transformDraft!.value : 0; + + Widget _slider( + String key, + String label, + int value, + int min, + int max, + String unit, + ValueChanged change, { + bool delta = false, + }) { + final display = delta + ? '${value > 0 ? '+' : ''}${(value / 10).toStringAsFixed(1)}$unit' + : '$value$unit'; + return SizedBox( + width: 107, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text(label, textAlign: TextAlign.center), + Text(display, softWrap: false), + Slider( + key: ValueKey(key), + value: value.toDouble(), + min: min.toDouble(), + max: max.toDouble(), + divisions: max - min, + label: display, + onChanged: (v) => change(v.round()), + onChangeEnd: (_) => onCommit(), + ), + ], + ), + ); + } + + @override + Widget build(BuildContext context) { + final l = AppLocalizations.of(context)!; + return Wrap( + spacing: 10, + runSpacing: 4, + alignment: WrapAlignment.center, + children: [ + _slider( + 'fine-scale', + l.fineScale, + current.scale, + 50, + 200, + '%', + (v) => onAdjust(scale: v), + ), + if (selectionCount == 1) + _slider( + 'fine-angle', + l.fineAngle, + current.angle, + -45, + 45, + '°', + (v) => onAdjust(angle: v), + ), + if (selectionCount > 1) + _slider( + 'fine-transform-angle', + l.fineGroupAngle, + _transformValue('angle'), + -45, + 45, + '°', + (value) => onTransform('angle', value), + ), + _slider( + 'fine-transform-horizontal', + l.finePerspectiveX, + _transformValue('horizontal'), + -35, + 35, + '%', + (value) => onTransform('horizontal', value), + ), + _slider( + 'fine-transform-vertical', + l.finePerspectiveY, + _transformValue('vertical'), + -35, + 35, + '%', + (value) => onTransform('vertical', value), + ), + _slider( + 'fine-opacity', + l.fineOpacity, + current.opacity, + 0, + 100, + '%', + (v) => onAdjust(opacity: v), + ), + _slider( + 'fine-thickness', + l.fineThickness, + current.thickness, + math + .min(current.thickness, -20 - (baseLook.thickness * 10).round()) + .clamp(-20, 0), + math + .max(current.thickness, 20 - (baseLook.thickness * 10).round()) + .clamp(0, 20), + ' px', + (v) => onAdjust(thickness: v), + delta: true, + ), + _slider( + 'fine-softness', + l.fineSoftness, + current.softness, + math.min(current.softness, -(baseLook.softness * 10).round()), + math.max(current.softness, 20 - (baseLook.softness * 10).round()), + ' px', + (v) => onAdjust(softness: v), + delta: true, + ), + ], + ); + } +} diff --git a/app/lib/widgets/fine_preview.dart b/app/lib/widgets/fine_preview.dart index dc7e2c9c..64bd08ff 100644 --- a/app/lib/widgets/fine_preview.dart +++ b/app/lib/widgets/fine_preview.dart @@ -2,8 +2,6 @@ import 'dart:async'; import 'dart:math' as math; import 'dart:ui' as ui; -import '../utils/lasso.dart'; - import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -13,7 +11,11 @@ import '../models/fine_edit.dart'; import '../models/ink_page.dart'; import '../utils/fine_raster.dart'; import '../view_models/fine_selection.dart'; +import '../view_models/fine_selection_drag.dart'; import 'color_picker_dialog.dart'; +import 'fine_adjustment_sliders.dart'; +import 'fine_preview_painter.dart'; +import 'fine_selection_inspector.dart'; import 'preview_image_actions.dart'; import 'preview_zoom.dart'; import 'workbench_controls.dart'; @@ -76,25 +78,6 @@ class FinePreview extends StatefulWidget { State createState() => _FinePreviewState(); } -typedef _Gesture = ({ - int pointer, - Offset start, - Offset screen, - FineGlyph? hit, - bool move, - bool add, - bool tap, - List? lasso, -}); - -class _CornerDrag { - _CornerDrag(this.pointer, this.index, this.start, this.frame); - final int pointer, index; - final Offset start; - final FinePerspectiveFrame frame; - FinePerspectiveChange? latest; -} - class _FinePreviewState extends State { final _selection = FineSelection(); final _focus = FocusNode(); @@ -102,17 +85,15 @@ class _FinePreviewState extends State { FinePage get model => widget.page.fine!; FineRaster? _raster; ui.Image? _committed; - _Gesture? _gesture; - _CornerDrag? _cornerDrag; + FineSelectionDrag? _gesture; + FineCornerDrag? _cornerDrag; List? get _corners => _selection.tool != FineTool.perspective ? null : _cornerDrag?.latest?.points ?? _selection.perspectiveFrame(model, widget.edits)?.points; - Rect? _box; - List _lasso = []; ({String field, int value})? _transformDraft; List _draft = []; - bool _moved = false, _painting = false, _pending = false, _failed = false; + bool _painting = false, _pending = false, _failed = false; bool _awaitingPixels = false; bool _shapeDraft = false; bool? _zoomLayout; @@ -161,19 +142,7 @@ class _FinePreviewState extends State { void _sourceSelection() { final range = widget.source; - if (range == null || !model.glyphs.any((glyph) => glyph.source != null)) { - return; - } - _selection.select( - model.glyphs - .where((glyph) { - final span = glyph.source; - return span != null && - span.start < range.end && - span.end > range.start; - }) - .map((glyph) => glyph.id), - ); + if (range != null) _selection.selectSource(model, range); } Future _paintCommitted() async { @@ -301,61 +270,48 @@ class _FinePreviewState extends State { event.kind == PointerDeviceKind.stylus; final at = event.localPosition / fit; if (_selection.tool == FineTool.perspective) { - final frame = _selection.perspectiveFrame(model, widget.edits); - if (frame == null) return; - final radius = - (touch ? 22 : 15) / (fit * _zoom.value.getMaxScaleOnAxis()); - var nearest = radius; - int? index; - for (final (i, point) in frame.points.indexed) { - final distance = (at - point).distance; - if (distance <= nearest) { - nearest = distance; - index = i; - } - } - if (index != null) { - _cornerDrag = _CornerDrag(event.pointer, index, at, frame); - _focus.requestFocus(); - } + _cornerDrag = FineCornerDrag.hit( + event.pointer, + at, + _selection.perspectiveFrame(model, widget.edits), + (touch ? 22 : 15) / (fit * _zoom.value.getMaxScaleOnAxis()), + ); + if (_cornerDrag != null) _focus.requestFocus(); return; } - final hit = _selection.hit(model, widget.edits, at); - final add = !touch && HardwareKeyboard.instance.isShiftPressed; - final group = _selection.bounds(model, widget.edits); - final selected = - group != null && - group.contains(at) && - (hit == null || _selection.selected.contains(hit.id)); - final move = switch (_selection.tool) { - FineTool.move => true, - FineTool.select => !touch && !add && (selected || hit != null), - _ => false, - }; - _gesture = ( + _gesture = FineSelectionDrag.begin( + _selection, + model, + widget.edits, pointer: event.pointer, start: at, screen: event.position, - hit: hit, - move: move, - add: add, - tap: touch && _selection.tool == FineTool.select, - lasso: _selection.tool == FineTool.lasso ? [at] : null, + touch: touch, + shift: HardwareKeyboard.instance.isShiftPressed, ); - _moved = false; _focus.requestFocus(); } + List _moveSelection( + FineSelectionDrag gesture, + Offset point, + ) => _selection.move( + model, + widget.edits, + point - gesture.start, + _size, + snapToLine: !HardwareKeyboard.instance.isAltPressed, + ); + void _move(PointerMoveEvent event, double fit) { + final point = event.localPosition / fit; final corner = _cornerDrag; if (corner != null && corner.pointer == event.pointer) { - final delta = event.localPosition / fit - corner.start; - final result = _selection.corner( + final result = corner.project( + _selection, model, widget.edits, - corner.frame, - corner.index, - delta, + point, _size, ); if (result != null) { @@ -368,56 +324,32 @@ class _FinePreviewState extends State { } final gesture = _gesture; if (gesture == null || - gesture.pointer != event.pointer || - (!_moved && (event.position - gesture.screen).distance < 4)) { + !gesture.acceptsMove(event.pointer, event.position)) { return; } - if (!_moved && - gesture.move && - gesture.hit != null && - !_selection.selected.contains(gesture.hit!.id) && - event.kind == PointerDeviceKind.mouse) { - _selection.select([gesture.hit!.id]); + if (gesture.selectMoveTarget( + _selection, + mouse: event.kind == PointerDeviceKind.mouse, + )) { widget.onCanvasSelect?.call(); } - _moved = true; - if (gesture.tap) return; - final point = event.localPosition / fit; + gesture.moved = true; + if (gesture.action == FineDragAction.tap) return; setState(() { - if (gesture.move) { - _draft = _selection.move( - model, - widget.edits, - point - gesture.start, - _size, - snapToLine: !HardwareKeyboard.instance.isAltPressed, - ); - } else if (gesture.lasso case final path?) { - appendLassoPoint( - path, - point, - (3 / fit) / _zoom.value.getMaxScaleOnAxis(), - ); - _lasso = [...path, point]; + if (gesture.action == FineDragAction.move) { + _draft = _moveSelection(gesture, point); } else { - _box = Rect.fromPoints(gesture.start, point); + gesture.outline(point, (3 / fit) / _zoom.value.getMaxScaleOnAxis()); } }); } void _up(PointerUpEvent event, double fit) { + final point = event.localPosition / fit; final corner = _cornerDrag; if (corner != null && corner.pointer == event.pointer) { - final delta = event.localPosition / fit - corner.start; final result = - _selection.corner( - model, - widget.edits, - corner.frame, - corner.index, - delta, - _size, - ) ?? + corner.project(_selection, model, widget.edits, point, _size) ?? corner.latest; if (result != null && result.changes.isNotEmpty) { _selection.rememberCorner(corner.frame, result); @@ -428,40 +360,16 @@ class _FinePreviewState extends State { } final gesture = _gesture; if (gesture == null || gesture.pointer != event.pointer) return; - final point = event.localPosition / fit; - if (!_moved) { - if (event.kind == PointerDeviceKind.mouse || !gesture.move) { - _selection.select([ - if (gesture.hit case final glyph?) glyph.id, - ], append: gesture.add); - widget.onCanvasSelect?.call(); - } - } else if (!gesture.tap) { - if (gesture.move) { - _finish( - _selection.move( - model, - widget.edits, - point - gesture.start, - _size, - snapToLine: !HardwareKeyboard.instance.isAltPressed, - ), - ); - } else if (gesture.lasso case final path?) { - _selection.lasso(model, widget.edits, [ - ...path, - point, - ], append: gesture.add); - widget.onCanvasSelect?.call(); - } else { - _selection.box( - model, - widget.edits, - Rect.fromPoints(gesture.start, point), - append: gesture.add, - ); - widget.onCanvasSelect?.call(); - } + if (gesture.moved && gesture.action == FineDragAction.move) { + _finish(_moveSelection(gesture, point)); + } else if (gesture.finishSelection( + _selection, + model, + widget.edits, + point, + mouse: event.kind == PointerDeviceKind.mouse, + )) { + widget.onCanvasSelect?.call(); } _cancelGesture(); } @@ -469,8 +377,6 @@ class _FinePreviewState extends State { void _cancelGesture() => setState(() { _gesture = null; _cornerDrag = null; - _box = null; - _lasso = []; _draft = []; _transformDraft = null; }); @@ -504,20 +410,14 @@ class _FinePreviewState extends State { final changesShape = thickness != null || softness != null; setState(() { _shapeDraft = changesShape; - _draft = _selection.change( + _draft = _selection.adjust( widget.edits, - (v) => ( - id: v.id, - dx: v.dx, - dy: v.dy, - scale: scale ?? v.scale, - angle: angle ?? v.angle, - opacity: opacity ?? v.opacity, - color: color ?? v.color, - thickness: thickness ?? v.thickness, - softness: softness ?? v.softness, - warp: v.warp, - ), + scale: scale, + angle: angle, + opacity: opacity, + color: color, + thickness: thickness, + softness: softness, ); }); if (changesShape) unawaited(_paintCommitted()); @@ -538,9 +438,6 @@ class _FinePreviewState extends State { }); } - int _transformValue(String field) => - _transformDraft?.field == field ? _transformDraft!.value : 0; - void _commitDraft() { final wasShaping = _shapeDraft; _finish(_draft); @@ -671,6 +568,35 @@ class _FinePreviewState extends State { }); } + void _scheduleDefaultZoom() { + if (!widget.toolbar) return; + final wide = widget.inspector != null; + if (_zoomLayout != wide) { + _zoomLayout = wide; + _manualZoom = false; + _defaultZoomViewport = null; + } + if (!_manualZoom && + (_defaultZoomViewport == null || + wide && _defaultZoomViewport != _viewport)) { + _defaultZoomViewport = _viewport; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted || _zoomLayout != wide || _manualZoom) return; + final top = model.glyphs.fold( + _size.height, + (top, glyph) => math.min(top, glyph.y.toDouble()), + ); + _zoom.value = wide + ? initialPreviewZoom( + _viewport, + _size, + contentTop: model.glyphs.isEmpty ? 0 : top, + ) + : Matrix4.identity(); + }); + } + } + Widget _paper(BuildContext context) { final l = AppLocalizations.of(context)!; final raster = _raster; @@ -688,33 +614,7 @@ class _FinePreviewState extends State { ); if (fit <= 0 || !fit.isFinite) return const SizedBox.shrink(); _updateViewport(bounds.biggest, fit); - if (widget.toolbar) { - final wide = widget.inspector != null; - if (_zoomLayout != wide) { - _zoomLayout = wide; - _manualZoom = false; - _defaultZoomViewport = null; - } - if (!_manualZoom && - (_defaultZoomViewport == null || - wide && _defaultZoomViewport != _viewport)) { - _defaultZoomViewport = _viewport; - WidgetsBinding.instance.addPostFrameCallback((_) { - if (!mounted || _zoomLayout != wide || _manualZoom) return; - final top = model.glyphs.fold( - _size.height, - (top, glyph) => math.min(top, glyph.y.toDouble()), - ); - _zoom.value = wide - ? initialPreviewZoom( - _viewport, - _size, - contentTop: model.glyphs.isEmpty ? 0 : top, - ) - : Matrix4.identity(); - }); - } - } + _scheduleDefaultZoom(); final surface = SizedBox.fromSize( size: _size * fit, child: PreviewImageActions( @@ -731,7 +631,7 @@ class _FinePreviewState extends State { onPointerUp: (event) => _up(event, fit), onPointerCancel: (_) => _cancelGesture(), child: CustomPaint( - painter: _FinePainter( + painter: FinePreviewPainter( raster, image, widget.look, @@ -748,8 +648,8 @@ class _FinePreviewState extends State { FinePose(glyph, _visible[glyph.id]).bounds, } : {}, - box: _box, - lasso: _lasso, + box: _gesture?.box, + lasso: _gesture?.lasso ?? const [], color: color, ), ), @@ -968,6 +868,11 @@ class _FinePreviewState extends State { ); } + void _selectDrawing(int group) { + setState(() => _selection.selectIllustration(model, group)); + widget.onCanvasSelect?.call(); + } + Widget _inspector( BuildContext context, double maxHeight, { @@ -976,7 +881,6 @@ class _FinePreviewState extends State { }) { final l = AppLocalizations.of(context)!; final selection = _selection.selected; - final scrollActions = settingsOnly || maxHeight < 160; final first = selection.firstOrNull; final current = _visible[first] ?? defaultFineAdjustment(first ?? 0); final glyph = model.glyphs.where((g) => g.id == first).firstOrNull; @@ -984,262 +888,54 @@ class _FinePreviewState extends State { final baseLook = glyph == null ? widget.look : fineInkLook(glyph, widget.look); - final summary = Text( - first == null - ? l.fineHint - : selection.length == 1 && group != null - ? (first == group ? l.fineDrawingLines : l.fineDrawingDetail) - : l.fineSelected(selection.length), - maxLines: 1, - overflow: TextOverflow.ellipsis, - textAlign: _compact || sidebar ? TextAlign.center : TextAlign.start, - style: Theme.of(context).textTheme.bodySmall, - ); - final parameterActions = Wrap( - spacing: 4, - alignment: WrapAlignment.center, - crossAxisAlignment: WrapCrossAlignment.center, - children: [ - TextButton.icon( - key: const ValueKey('fine-color'), - onPressed: () => _pickColor(current, baseLook), - icon: ColorSwatchIndicator(Color(current.color ?? baseLook.color)), - label: Text(l.fineColor), - ), - if (group != null) - TextButton.icon( - key: const ValueKey('fine-select-drawing'), - onPressed: () { - setState( - () => _selection.select( - model.glyphs - .where((g) => g.illustrationId == group) - .map((g) => g.id), - ), - ); - widget.onCanvasSelect?.call(); - }, - icon: const Icon(Icons.select_all), - label: Text(l.fineSelectDrawing), - ), - FilterChip( - label: Text(l.fineSnap), - selected: _selection.snap, - onSelected: (value) => setState(() => _selection.snap = value), - ), - TextButton.icon( - key: const ValueKey('fine-reset'), - label: Text(l.fineReset), - icon: const Icon(Icons.restart_alt), - onPressed: () => - _finish(selection.map(defaultFineAdjustment).toList()), - ), - ], - ); - return ConstrainedBox( - constraints: BoxConstraints(maxHeight: maxHeight), - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Flexible( - child: SingleChildScrollView( - primary: false, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - if (_compact || sidebar || settingsOnly) summary, - if (!settingsOnly) - Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - if (!_compact && !sidebar) Flexible(child: summary), - Flexible( - child: Wrap( - alignment: WrapAlignment.center, - children: [ - ..._historyActions(l), - _zoomButton(l, zoomIn: false), - _zoomButton(l, zoomIn: true), - if (!_touchNavigation) - IconButton( - isSelected: _selection.tool == FineTool.pan, - tooltip: l.finePan, - onPressed: () => setState(() { - _selection.tool = - _selection.tool == FineTool.pan - ? FineTool.select - : FineTool.pan; - }), - icon: const Icon(Icons.pan_tool_outlined), - selectedIcon: const Icon(Icons.pan_tool), - ), - ], - ), - ), - ], - ), - if (!settingsOnly && widget.inspector == null) - _selectionTools(context), - if (!settingsOnly && - _selection.tool == FineTool.perspective) - Text(l.finePerspectiveHint, textAlign: TextAlign.center), - Visibility( - visible: first != null, - maintainState: true, - maintainAnimation: true, - maintainSize: true, - child: Wrap( - spacing: 10, - runSpacing: 4, - alignment: WrapAlignment.center, - children: [ - _slider( - 'fine-scale', - l.fineScale, - current.scale, - 50, - 200, - '%', - (v) => _adjust(scale: v), - ), - if (selection.length == 1) - _slider( - 'fine-angle', - l.fineAngle, - current.angle, - -45, - 45, - '°', - (v) => _adjust(angle: v), - ), - if (selection.length > 1) - _slider( - 'fine-transform-angle', - l.fineGroupAngle, - _transformValue('angle'), - -45, - 45, - '°', - (value) => _transform('angle', value), - ), - _slider( - 'fine-transform-horizontal', - l.finePerspectiveX, - _transformValue('horizontal'), - -35, - 35, - '%', - (value) => _transform('horizontal', value), - ), - _slider( - 'fine-transform-vertical', - l.finePerspectiveY, - _transformValue('vertical'), - -35, - 35, - '%', - (value) => _transform('vertical', value), - ), - _slider( - 'fine-opacity', - l.fineOpacity, - current.opacity, - 0, - 100, - '%', - (v) => _adjust(opacity: v), - ), - _slider( - 'fine-thickness', - l.fineThickness, - current.thickness, - math - .min( - current.thickness, - -20 - (baseLook.thickness * 10).round(), - ) - .clamp(-20, 0), - math - .max( - current.thickness, - 20 - (baseLook.thickness * 10).round(), - ) - .clamp(0, 20), - ' px', - (v) => _adjust(thickness: v), - delta: true, - ), - _slider( - 'fine-softness', - l.fineSoftness, - current.softness, - math.min( - current.softness, - -(baseLook.softness * 10).round(), - ), - math.max( - current.softness, - 20 - (baseLook.softness * 10).round(), - ), - ' px', - (v) => _adjust(softness: v), - delta: true, - ), - ], - ), - ), - if (scrollActions && first != null) parameterActions, - ], - ), - ), + return FineSelectionInspector( + maxHeight: maxHeight, + centerSummary: _compact || sidebar, + count: selection.length, + glyph: glyph, + navigation: settingsOnly + ? null + : Wrap( + alignment: WrapAlignment.center, + children: [ + ..._historyActions(l), + _zoomButton(l, zoomIn: false), + _zoomButton(l, zoomIn: true), + if (!_touchNavigation) + IconButton( + isSelected: _selection.tool == FineTool.pan, + tooltip: l.finePan, + onPressed: () => setState(() { + _selection.tool = _selection.tool == FineTool.pan + ? FineTool.select + : FineTool.pan; + }), + icon: const Icon(Icons.pan_tool_outlined), + selectedIcon: const Icon(Icons.pan_tool), + ), + ], ), - if (!scrollActions) - Visibility( - visible: first != null, - maintainState: true, - maintainAnimation: true, - maintainSize: true, - child: parameterActions, - ), - ], - ), + tools: !settingsOnly && widget.inspector == null + ? _selectionTools(context) + : null, + showPerspectiveHint: + !settingsOnly && _selection.tool == FineTool.perspective, + sliders: FineAdjustmentSliders( + current: current, + selectionCount: selection.length, + baseLook: baseLook, + transformDraft: _transformDraft, + onAdjust: _adjust, + onTransform: _transform, + onCommit: _commitDraft, ), - ); - } - - Widget _slider( - String key, - String label, - int value, - int min, - int max, - String unit, - ValueChanged change, { - bool delta = false, - }) { - final display = delta - ? '${value > 0 ? '+' : ''}${(value / 10).toStringAsFixed(1)}$unit' - : '$value$unit'; - return SizedBox( - width: 107, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text(label, textAlign: TextAlign.center), - Text(display, softWrap: false), - Slider( - key: ValueKey(key), - value: value.toDouble(), - min: min.toDouble(), - max: max.toDouble(), - divisions: max - min, - label: display, - onChanged: (v) => change(v.round()), - onChangeEnd: (_) => _commitDraft(), - ), - ], + actions: FineSelectionActions( + color: Color(current.color ?? baseLook.color), + snap: _selection.snap, + onPickColor: () => _pickColor(current, baseLook), + onSelectDrawing: group == null ? null : () => _selectDrawing(group), + onSnapChanged: (value) => setState(() => _selection.snap = value), + onReset: () => _finish(selection.map(defaultFineAdjustment).toList()), ), ); } @@ -1281,79 +977,3 @@ bool mapEqualsFine(Map a, Map b) => identical(a, b) || a.length == b.length && a.entries.every((entry) => entry.value == b[entry.key]); - -class _FinePainter extends CustomPainter { - _FinePainter( - this.raster, - this.image, - this.look, - this.edits, { - required this.draft, - required this.outlines, - required this.corners, - required this.handleScale, - required this.box, - required this.lasso, - required this.color, - }); - final FineRaster raster; - final ui.Image image; - final InkLook look; - final Map edits; - final bool draft; - final Set outlines; - final List? corners; - final double handleScale; - final Rect? box; - final List lasso; - final Color color; - - @override - void paint(Canvas canvas, Size size) { - canvas.save(); - final fit = size.width / image.width; - canvas.scale(fit); - if (draft) { - raster.paint(canvas, edits, look); - } else { - canvas.drawImage( - image, - Offset.zero, - Paint()..filterQuality = FilterQuality.low, - ); - } - final fill = Paint()..color = color.withValues(alpha: .14); - final line = Paint() - ..color = color - ..style = PaintingStyle.stroke - ..strokeWidth = 1 / fit; - for (final rect in [...outlines, ?box]) { - canvas.drawRect(rect, fill); - canvas.drawRect(rect, line); - } - if (lasso.length > 1) { - final path = Path() - ..fillType = PathFillType.evenOdd - ..addPolygon(lasso, true); - canvas.drawPath(path, fill); - canvas.drawPath(path, line); - } - if (corners case final points?) { - final scale = fit * handleScale; - canvas.drawPath( - Path()..addPolygon(points, true), - line..strokeWidth = 2 / scale, - ); - final handle = Paint()..color = color; - final edge = Paint()..color = Colors.white; - for (final point in points) { - canvas.drawCircle(point, 7 / scale, edge); - canvas.drawCircle(point, 5 / scale, handle); - } - } - canvas.restore(); - } - - @override - bool shouldRepaint(covariant _FinePainter oldDelegate) => true; -} diff --git a/app/lib/widgets/fine_preview_painter.dart b/app/lib/widgets/fine_preview_painter.dart new file mode 100644 index 00000000..7f2ae4f9 --- /dev/null +++ b/app/lib/widgets/fine_preview_painter.dart @@ -0,0 +1,84 @@ +import 'dart:ui' as ui; + +import 'package:flutter/material.dart'; + +import '../models/fine_edit.dart'; +import '../models/ink_page.dart'; +import '../utils/fine_raster.dart'; + +/// Draws in paper coordinates, keeping perspective handles a constant screen size. +class FinePreviewPainter extends CustomPainter { + FinePreviewPainter( + this.raster, + this.image, + this.look, + this.edits, { + required this.draft, + required this.outlines, + required this.corners, + required this.handleScale, + required this.box, + required this.lasso, + required this.color, + }); + final FineRaster raster; + final ui.Image image; + final InkLook look; + final Map edits; + final bool draft; + final Set outlines; + final List? corners; + final double handleScale; + final Rect? box; + final List lasso; + final Color color; + + @override + void paint(Canvas canvas, Size size) { + canvas.save(); + final fit = size.width / image.width; + canvas.scale(fit); + if (draft) { + raster.paint(canvas, edits, look); + } else { + canvas.drawImage( + image, + Offset.zero, + Paint()..filterQuality = FilterQuality.low, + ); + } + final fill = Paint()..color = color.withValues(alpha: .14); + final line = Paint() + ..color = color + ..style = PaintingStyle.stroke + ..strokeWidth = 1 / fit; + for (final rect in [...outlines, ?box]) { + canvas.drawRect(rect, fill); + canvas.drawRect(rect, line); + } + if (lasso.length > 1) { + final path = Path() + ..fillType = PathFillType.evenOdd + ..addPolygon(lasso, true); + canvas.drawPath(path, fill); + canvas.drawPath(path, line); + } + if (corners case final points?) { + final scale = fit * handleScale; + canvas.drawPath( + Path()..addPolygon(points, true), + line..strokeWidth = 2 / scale, + ); + final handle = Paint()..color = color; + final edge = Paint()..color = Colors.white; + for (final point in points) { + canvas.drawCircle(point, 7 / scale, edge); + canvas.drawCircle(point, 5 / scale, handle); + } + } + canvas.restore(); + } + + @override + bool shouldRepaint(covariant FinePreviewPainter oldDelegate) => true; +} diff --git a/app/lib/widgets/fine_selection_inspector.dart b/app/lib/widgets/fine_selection_inspector.dart new file mode 100644 index 00000000..f10b08e5 --- /dev/null +++ b/app/lib/widgets/fine_selection_inspector.dart @@ -0,0 +1,153 @@ +import 'package:flutter/material.dart'; + +import '../l10n/app_localizations.dart'; +import '../models/fine_edit.dart'; +import 'color_picker_dialog.dart'; + +class FineSelectionInspector extends StatelessWidget { + const FineSelectionInspector({ + super.key, + required this.maxHeight, + required this.centerSummary, + required this.count, + required this.glyph, + required this.navigation, + required this.tools, + required this.showPerspectiveHint, + required this.sliders, + required this.actions, + }); + + final double maxHeight; + final bool centerSummary; + final int count; + final FineGlyph? glyph; + final Widget? navigation, tools; + final bool showPerspectiveHint; + final Widget sliders, actions; + + String _summary(AppLocalizations l) { + if (count == 0) return l.fineHint; + final group = glyph?.illustrationId; + if (count == 1 && group != null) { + return glyph!.id == group ? l.fineDrawingLines : l.fineDrawingDetail; + } + return l.fineSelected(count); + } + + @override + Widget build(BuildContext context) { + final l = AppLocalizations.of(context)!; + final scrollActions = navigation == null || maxHeight < 160; + final summary = Text( + _summary(l), + maxLines: 1, + overflow: TextOverflow.ellipsis, + textAlign: centerSummary ? TextAlign.center : TextAlign.start, + style: Theme.of(context).textTheme.bodySmall, + ); + return ConstrainedBox( + constraints: BoxConstraints(maxHeight: maxHeight), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: SingleChildScrollView( + primary: false, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (centerSummary || navigation == null) summary, + if (navigation != null) + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + if (!centerSummary) Flexible(child: summary), + Flexible(child: navigation!), + ], + ), + ?tools, + if (showPerspectiveHint) + Text(l.finePerspectiveHint, textAlign: TextAlign.center), + Visibility( + visible: count != 0, + maintainState: true, + maintainAnimation: true, + maintainSize: true, + child: sliders, + ), + if (scrollActions && count != 0) actions, + ], + ), + ), + ), + if (!scrollActions) + Visibility( + visible: count != 0, + maintainState: true, + maintainAnimation: true, + maintainSize: true, + child: actions, + ), + ], + ), + ), + ); + } +} + +class FineSelectionActions extends StatelessWidget { + const FineSelectionActions({ + super.key, + required this.color, + required this.snap, + required this.onPickColor, + required this.onSelectDrawing, + required this.onSnapChanged, + required this.onReset, + }); + + final Color color; + final bool snap; + final VoidCallback onPickColor, onReset; + final VoidCallback? onSelectDrawing; + final ValueChanged onSnapChanged; + + @override + Widget build(BuildContext context) { + final l = AppLocalizations.of(context)!; + return Wrap( + spacing: 4, + alignment: WrapAlignment.center, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + TextButton.icon( + key: const ValueKey('fine-color'), + onPressed: onPickColor, + icon: ColorSwatchIndicator(color), + label: Text(l.fineColor), + ), + if (onSelectDrawing != null) + TextButton.icon( + key: const ValueKey('fine-select-drawing'), + onPressed: onSelectDrawing, + icon: const Icon(Icons.select_all), + label: Text(l.fineSelectDrawing), + ), + FilterChip( + label: Text(l.fineSnap), + selected: snap, + onSelected: onSnapChanged, + ), + TextButton.icon( + key: const ValueKey('fine-reset'), + label: Text(l.fineReset), + icon: const Icon(Icons.restart_alt), + onPressed: onReset, + ), + ], + ); + } +} diff --git a/app/lib/widgets/manuscript_text_field.dart b/app/lib/widgets/manuscript_text_field.dart new file mode 100644 index 00000000..8defe826 --- /dev/null +++ b/app/lib/widgets/manuscript_text_field.dart @@ -0,0 +1,111 @@ +import 'package:flutter/material.dart'; + +import '../l10n/app_localizations.dart'; +import '../theme/handwriting_theme.dart'; + +class ManuscriptTextField extends StatelessWidget { + const ManuscriptTextField({ + super.key, + required this.controller, + required this.focusNode, + required this.undo, + required this.enabled, + required this.onChanged, + }); + + final TextEditingController controller; + final FocusNode focusNode; + final UndoHistoryController undo; + final bool enabled; + final ValueChanged onChanged; + + @override + Widget build(BuildContext context) { + final l = AppLocalizations.of(context)!; + final theme = Theme.of(context); + final colors = theme.colorScheme; + return Semantics( + identifier: 'text-input', + child: DecoratedBox( + decoration: BoxDecoration( + color: theme.brightness == Brightness.dark + ? NightSurfaces.writing + : colors.surface, + borderRadius: BorderRadius.circular(28), + border: Border.all( + color: theme.brightness == Brightness.dark + ? colors.outlineVariant + : colors.tertiary.withValues(alpha: .5), + ), + ), + child: CustomPaint( + painter: controller.text.isEmpty + ? _ManuscriptRuling(colors.tertiary) + : null, + child: TextField( + key: const ValueKey('text-editor'), + controller: controller, + focusNode: focusNode, + undoController: undo, + enabled: enabled, + expands: true, + maxLines: null, + minLines: null, + textAlignVertical: TextAlignVertical.top, + keyboardType: TextInputType.multiline, + style: theme.textTheme.bodyLarge?.copyWith(height: 1.75), + decoration: InputDecoration( + contentPadding: const EdgeInsets.symmetric( + horizontal: 22, + vertical: 17, + ), + border: InputBorder.none, + enabledBorder: InputBorder.none, + disabledBorder: InputBorder.none, + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(28), + borderSide: BorderSide(color: colors.primary, width: 1.5), + ), + hintText: l.editorHint, + filled: false, + ), + onChanged: onChanged, + ), + ), + ), + ); + } +} + +/// Faint writing guides on the unused portion of the blank manuscript. +class _ManuscriptRuling extends CustomPainter { + const _ManuscriptRuling(this.ink); + final Color ink; + + @override + void paint(Canvas canvas, Size size) { + if (size.width < 72) return; + final pen = Paint() + ..color = ink.withValues(alpha: .18) + ..style = PaintingStyle.stroke + ..strokeWidth = .8; + for (double y = 78; y < size.height - 23; y += 32) { + canvas.drawPath( + Path() + ..moveTo(23, y) + ..cubicTo( + size.width * .34, + y - 1.6, + size.width * .67, + y + 1.6, + size.width - 23, + y, + ), + pen, + ); + } + } + + @override + bool shouldRepaint(_ManuscriptRuling oldDelegate) => ink != oldDelegate.ink; +} diff --git a/app/lib/widgets/pdf_workbench_layout.dart b/app/lib/widgets/pdf_workbench_layout.dart new file mode 100644 index 00000000..dcc65039 --- /dev/null +++ b/app/lib/widgets/pdf_workbench_layout.dart @@ -0,0 +1,120 @@ +import 'package:flutter/material.dart'; + +import '../l10n/app_localizations.dart'; + +class PdfWorkbenchLayout extends StatelessWidget { + const PdfWorkbenchLayout({ + super.key, + required this.fileName, + required this.fill, + required this.warning, + required this.index, + required this.count, + required this.onClose, + required this.onExport, + required this.onPrevious, + required this.onNext, + required this.child, + }); + + final String fileName; + final bool fill; + final String? warning; + final int index, count; + final VoidCallback onClose; + final VoidCallback? onExport, onPrevious, onNext; + final Widget child; + + Widget _header(BuildContext context, AppLocalizations l) { + final theme = Theme.of(context); + return Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon( + Icons.picture_as_pdf_outlined, + size: 18, + color: theme.colorScheme.primary, + ), + const SizedBox(width: 8), + Expanded( + child: Text( + fileName, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.titleSmall, + ), + ), + ], + ), + const SizedBox(height: 4), + Text(fill ? l.pdfFillHelp : l.pdfLayoutHelp), + if (warning case final message?) + Text(message, style: TextStyle(color: theme.colorScheme.error)), + ], + ), + ); + } + + Widget _navigation(AppLocalizations l) => Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + IconButton( + tooltip: l.previousPage, + onPressed: onPrevious, + icon: const Icon(Icons.chevron_left), + ), + Text(count == 0 ? '—' : '${index + 1} / $count'), + IconButton( + tooltip: l.nextPage, + onPressed: onNext, + icon: const Icon(Icons.chevron_right), + ), + ], + ); + + @override + Widget build(BuildContext context) { + final l = AppLocalizations.of(context)!; + return Scaffold( + appBar: AppBar( + leading: IconButton( + tooltip: l.close, + icon: const Icon(Icons.close), + onPressed: onClose, + ), + title: Text(fill ? l.pdfFill : l.pdfLayout), + actions: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: FilledButton.icon( + onPressed: onExport, + icon: const Icon(Icons.file_download_outlined), + label: Text(l.exportPdf), + ), + ), + ], + ), + body: SafeArea( + child: Column( + children: [ + _header(context, l), + const Divider(height: 1), + Expanded( + child: ColoredBox( + color: Theme.of(context).colorScheme.surfaceContainerHighest, + child: Padding( + padding: const EdgeInsets.all(16), + child: Center(child: child), + ), + ), + ), + _navigation(l), + ], + ), + ), + ); + } +} diff --git a/app/lib/widgets/preview_pager.dart b/app/lib/widgets/preview_pager.dart index 4ee8affe..2cba8b31 100644 --- a/app/lib/widgets/preview_pager.dart +++ b/app/lib/widgets/preview_pager.dart @@ -1,17 +1,13 @@ import 'package:flutter/material.dart'; -import 'package:flutter/gestures.dart'; import 'package:flutter/services.dart'; import '../l10n/app_localizations.dart'; import '../models/ink_page.dart'; import '../models/fine_edit.dart'; import '../services/image_clipboard.dart'; -import '../utils/ink_effects.dart'; -import 'live_ink_preview.dart'; -import 'fine_preview.dart'; import 'preview_image_actions.dart'; -import 'preview_zoom.dart'; import 'workbench_motion.dart'; +import 'zoomable_preview_page.dart'; /// A controlled image viewer. Page intent is reported without waiting for motion; /// drag progress, zoom and animation lifetimes never enter the workspace model. @@ -159,7 +155,7 @@ class _PreviewPagerState extends State { : null, onPageChanged: _pageChanged, itemCount: widget.pages.length, - itemBuilder: (context, index) => _ZoomablePage( + itemBuilder: (context, index) => ZoomablePreviewPage( key: ValueKey((index, widget.pages[index])), bytes: widget.pages[index], ink: index < widget.inkPages.length @@ -278,364 +274,6 @@ class _PageNumber extends StatelessWidget { } } -class _ZoomablePage extends StatefulWidget { - const _ZoomablePage({ - super.key, - required this.bytes, - required this.heroTag, - required this.active, - required this.reset, - required this.onZoomChanged, - required this.onOpen, - required this.copyImage, - required this.readerMode, - required this.ink, - required this.look, - required this.fineEdits, - required this.enlargeInitially, - }); - final Uint8List bytes; - final Object heroTag; - final bool active; - final int reset; - final ValueChanged onZoomChanged; - final VoidCallback? onOpen; - final ImageClipboardWriter copyImage; - final bool readerMode; - final InkPage? ink; - final InkLook look; - final Map fineEdits; - final bool enlargeInitially; - - @override - State<_ZoomablePage> createState() => _ZoomablePageState(); -} - -class _ZoomablePageState extends State<_ZoomablePage> - with SingleTickerProviderStateMixin { - late final _transform = TransformationController()..addListener(_changed); - late final _animation = AnimationController( - vsync: this, - duration: WorkbenchMotion.page, - )..addListener(_animate); - // Translation events leave the reader scale controls unchanged. - final _readerControls = ValueNotifier((100, true, true)); - Matrix4Tween? _tween; - bool _zoomed = false; - bool _mouse = false; - bool _dragging = false; - bool _manualZoom = false; - Size? _defaultZoomViewport; - Offset _doubleTapPoint = Offset.zero; - Size _viewport = Size.zero; - double get _scale => _transform.value.getMaxScaleOnAxis(); - double get _minScale => widget.readerMode ? .25 : 1; - double get _maxScale => widget.readerMode ? 8 : 5; - - void _animate() { - _transform.value = _tween!.transform( - Curves.easeOutCubic.transform(_animation.value), - ); - } - - void _to(Matrix4 destination) { - _animation.stop(); - if (MediaQuery.disableAnimationsOf(context)) { - _transform.value = destination; - } else { - _tween = Matrix4Tween(begin: _transform.value.clone(), end: destination); - _animation.forward(from: 0); - } - } - - void _zoomTo(double scale, Offset focalPoint) { - final target = scale.clamp(_minScale, _maxScale); - final scene = _transform.toScene(focalPoint); - _to( - Matrix4.identity() - ..translateByDouble( - focalPoint.dx - scene.dx * target, - focalPoint.dy - scene.dy * target, - 0, - 1, - ) - ..scaleByDouble(target, target, target, 1), - ); - } - - void _reset() => _to(Matrix4.identity()); - - void _updateReaderControls() { - if (!widget.readerMode) return; - final scale = _scale; - _readerControls.value = ( - (scale * 100).round(), - scale > _minScale + .001, - scale < _maxScale - .001, - ); - } - - void _changed() { - _updateReaderControls(); - final zoomed = widget.readerMode - ? (_scale - 1).abs() > .001 || - _transform.value.getTranslation().length > .1 - : _scale > 1.01; - final changed = zoomed != _zoomed; - if (!changed) return; - setState(() => _zoomed = zoomed); - if (changed && widget.active) widget.onZoomChanged(zoomed); - } - - @override - void didUpdateWidget(_ZoomablePage oldWidget) { - super.didUpdateWidget(oldWidget); - final layoutChanged = oldWidget.enlargeInitially != widget.enlargeInitially; - if (layoutChanged || oldWidget.active != widget.active) { - _defaultZoomViewport = null; - _manualZoom = false; - } else if (oldWidget.reset != widget.reset && widget.active) { - _manualZoom = true; - } - if (layoutChanged || - oldWidget.reset != widget.reset || - oldWidget.active && !widget.active) { - // Parent already clears its zoom flag; do not notify during its build. - _animation.stop(); - _transform.removeListener(_changed); - _transform.value = Matrix4.identity(); - _zoomed = false; - _transform.addListener(_changed); - } - _updateReaderControls(); - } - - void _scheduleInitialZoom() { - if (_manualZoom || - _viewport == _defaultZoomViewport || - !widget.active || - !widget.enlargeInitially || - _viewport.isEmpty) { - return; - } - final size = previewPngSize(widget.bytes); - if (size == null) return; - _defaultZoomViewport = _viewport; - WidgetsBinding.instance.addPostFrameCallback((_) { - if (!mounted || - _manualZoom || - !widget.active || - !widget.enlargeInitially || - _viewport.isEmpty) { - return; - } - final glyphs = widget.ink?.fine?.glyphs; - var top = size.height; - for (final glyph in glyphs ?? const []) { - if (glyph.y < top) top = glyph.y.toDouble(); - } - _transform.value = initialPreviewZoom( - _viewport, - size, - contentTop: top == size.height ? 0 : top, - ); - }); - } - - @override - void dispose() { - _animation.dispose(); - _transform.dispose(); - _readerControls.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - final ink = widget.ink; - final look = widget.look; - final copy = widget.copyImage; - final l = AppLocalizations.of(context)!; - final viewer = RepaintBoundary( - child: Padding( - padding: const EdgeInsets.all(12), - child: LayoutBuilder( - builder: (context, constraints) { - _viewport = constraints.biggest; - _scheduleInitialZoom(); - return MouseRegion( - cursor: widget.readerMode - ? (_dragging - ? SystemMouseCursors.grabbing - : SystemMouseCursors.grab) - : MouseCursor.defer, - child: Listener( - onPointerDown: (event) { - _animation.stop(); - if (widget.readerMode) { - setState(() { - _mouse = event.kind == PointerDeviceKind.mouse; - _dragging = - _mouse && event.buttons == kPrimaryMouseButton; - }); - } - }, - onPointerUp: (_) { - if (_dragging) setState(() => _dragging = false); - }, - onPointerMove: (event) { - if (!_dragging || event.buttons != kPrimaryMouseButton) { - return; - } - // Mouse panning follows every delta, including a short drag - // that would otherwise only cross the scale gesture slop. - final matrix = _transform.value.clone(); - matrix.setEntry( - 0, - 3, - matrix.entry(0, 3) + event.localDelta.dx, - ); - matrix.setEntry( - 1, - 3, - matrix.entry(1, 3) + event.localDelta.dy, - ); - _transform.value = matrix; - }, - onPointerCancel: (_) { - if (_dragging) setState(() => _dragging = false); - }, - child: GestureDetector( - onDoubleTapDown: widget.readerMode - ? (details) => _doubleTapPoint = details.localPosition - : null, - onDoubleTap: widget.readerMode - ? () => _zoomed ? _reset() : _zoomTo(2.5, _doubleTapPoint) - : null, - child: InteractiveViewer( - key: widget.readerMode - ? const ValueKey('reader-canvas') - : null, - transformationController: _transform, - onInteractionStart: (_) { - _manualZoom = true; - _animation.stop(); - }, - panEnabled: _zoomed && !_dragging, - boundaryMargin: widget.readerMode - ? const EdgeInsets.all(double.infinity) - : EdgeInsets.zero, - minScale: _minScale, - maxScale: _maxScale, - child: Center( - child: HeroMode( - enabled: - widget.active && - !MediaQuery.disableAnimationsOf(context), - child: Hero( - tag: widget.heroTag, - transitionOnUserGestures: true, - child: ink?.fine != null - ? SizedBox.expand( - child: FinePreview( - page: ink!, - look: look, - edits: widget.fineEdits, - copyImage: copy, - ), - ) - : PreviewImageActions( - bytes: widget.bytes, - onOpen: widget.onOpen, - copyImage: ink == null - ? copy - : (_) async => copy( - await compositeInkPage(ink, look), - ), - child: Semantics( - identifier: widget.active - ? 'preview-image' - : null, - child: ink != null - ? LiveInkPreview( - page: ink, - look: look, - label: l.preview, - ) - : Image.memory( - widget.bytes, - fit: BoxFit.contain, - gaplessPlayback: true, - semanticLabel: l.preview, - ), - ), - ), - ), - ), - ), - ), - ), - ), - ); - }, - ), - ), - ); - if (!widget.readerMode) return viewer; - return Column( - children: [ - Expanded(child: viewer), - ValueListenableBuilder( - valueListenable: _readerControls, - builder: (_, controls, _) => Wrap( - alignment: WrapAlignment.center, - crossAxisAlignment: WrapCrossAlignment.center, - children: [ - TextButton.icon( - key: const ValueKey('reader-zoom-out'), - onPressed: controls.$2 - ? () => _zoomTo(_scale / 1.5, _viewport.center(Offset.zero)) - : null, - icon: const Icon(Icons.zoom_out), - label: Text(l.previewZoomOut), - ), - Tooltip( - message: l.previewZoomRatioHint, - child: Text( - '${controls.$1}%', - key: const ValueKey('reader-zoom-ratio'), - ), - ), - TextButton.icon( - key: const ValueKey('reader-zoom-in'), - onPressed: controls.$3 - ? () => _zoomTo(_scale * 1.5, _viewport.center(Offset.zero)) - : null, - icon: const Icon(Icons.zoom_in), - label: Text(l.previewZoomIn), - ), - TextButton.icon( - key: const ValueKey('preview-reset-zoom'), - onPressed: _reset, - icon: const Icon(Icons.fit_screen_outlined), - label: Text(l.resetPreviewZoom), - ), - ], - ), - ), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), - child: Text( - l.previewReaderHint, - textAlign: TextAlign.center, - style: Theme.of(context).textTheme.bodySmall, - ), - ), - ], - ); - } -} - Future showFullscreenPreview( BuildContext context, { required List pages, diff --git a/app/lib/widgets/settings/ink_settings.dart b/app/lib/widgets/settings/ink_settings.dart new file mode 100644 index 00000000..023986d4 --- /dev/null +++ b/app/lib/widgets/settings/ink_settings.dart @@ -0,0 +1,41 @@ +import 'package:flutter/material.dart'; + +import '../../l10n/app_localizations.dart'; +import '../../models/settings.dart'; +import 'settings_fields.dart'; + +List inkSettings( + AppLocalizations l, + SettingsFields fields, + Widget? inkControls, +) { + final settings = fields.settings; + return [ + if (inkControls case final controls?) + settingsGroup('ink', l.inkEffects, Icons.tune, [ + controls, + ], collapsible: false), + settingsGroup('variation', l.variation, Icons.gesture, [ + fields.parameterGrid( + parameters.where( + (p) => + p.key.endsWith('_sigma') && !p.key.startsWith('strikethrough_'), + ), + ), + ], expanded: false), + settingsGroup('strike', l.strike, Icons.strikethrough_s, [ + SwitchListTile( + key: const ValueKey('enable-strikethrough'), + contentPadding: EdgeInsets.zero, + title: Text(l.enableStrikethrough), + value: settings.strikethroughEnabled, + onChanged: fields.edited( + (enabled) => settings.setStrikethroughEnabled(enabled), + ), + ), + fields.parameterGrid( + parameters.where((p) => p.key.startsWith('strikethrough_')), + ), + ], expanded: false), + ]; +} diff --git a/app/lib/widgets/settings/layout_settings.dart b/app/lib/widgets/settings/layout_settings.dart new file mode 100644 index 00000000..b06d2b46 --- /dev/null +++ b/app/lib/widgets/settings/layout_settings.dart @@ -0,0 +1,183 @@ +import 'package:flutter/material.dart'; + +import '../../l10n/app_localizations.dart'; +import '../../models/settings.dart'; +import '../../models/upload.dart'; +import '../ink_color_control.dart'; +import '../ink_parameter_controls.dart'; +import 'settings_fields.dart'; + +Widget fontSettings( + AppLocalizations l, + SettingsFields fields, { + required List fonts, + required Upload? fontFile, + required bool showInkColor, + required ValueChanged onSelectFont, + required ValueChanged onColorSelected, + required VoidCallback onUploadFont, + required VoidCallback onRemoveFont, + required VoidCallback? onBrowseLocalFonts, +}) { + final settings = fields.settings; + return settingsGroup('font', l.fontChoices, Icons.font_download_outlined, [ + Semantics( + identifier: 'font-select', + child: SettingsFieldLabel( + label: l.font, + child: DropdownButtonFormField( + key: ValueKey('font-${settings.font}-${fontFile?.name}'), + hint: Text(l.chooseBundledFont), + initialValue: fontFile == null && fonts.contains(settings.font) + ? settings.font + : null, + isExpanded: true, + items: fonts + .map( + (f) => DropdownMenuItem( + value: f, + child: Text(f, overflow: TextOverflow.ellipsis), + ), + ) + .toList(), + onChanged: fields.locked ? null : onSelectFont, + ), + ), + ), + const SizedBox(height: 6), + if (fontFile != null) + ListTile( + dense: true, + contentPadding: EdgeInsets.zero, + leading: const Icon(Icons.font_download_outlined), + title: Text(fontFile.name, overflow: TextOverflow.ellipsis), + trailing: IconButton( + tooltip: l.remove, + onPressed: fields.locked ? null : onRemoveFont, + icon: const Icon(Icons.close), + ), + ), + if (onBrowseLocalFonts != null) + FilledButton.tonalIcon( + onPressed: fields.locked ? null : onBrowseLocalFonts, + icon: const Icon(Icons.font_download_outlined), + label: Text(l.localFonts), + ), + OutlinedButton.icon( + onPressed: fields.locked ? null : onUploadFont, + icon: const Icon(Icons.file_open_outlined), + label: Text(l.importFontFile), + ), + const SizedBox(height: 10), + SettingsFieldLabel( + label: l.latinFont, + child: DropdownButtonFormField( + key: ValueKey('latin-font-${fields.settingsRevision}'), + isExpanded: true, + initialValue: settings.latinFont ?? '', + items: [ + DropdownMenuItem(value: '', child: Text(l.inheritLatinFont)), + for (final entry in latinFonts.entries) + DropdownMenuItem( + value: entry.key, + child: Text(entry.value, overflow: TextOverflow.ellipsis), + ), + ], + onChanged: fields.edited( + (value) => settings.latinFont = value == '' ? null : value, + ), + ), + ), + NumericSlider( + label: l.latinFontScale, + id: 'latin-font-scale', + value: settings.latinScale.toDouble(), + parameter: latinScaleParameter, + unit: '%', + onChanged: fields.edited((value) => settings.latinScale = value.round()), + ), + fields.settingSwitch( + l.digitsLatin, + settings.latinDigits, + (value) => settings.latinDigits = value, + ), + if (showInkColor) + Align( + alignment: AlignmentDirectional.centerStart, + child: InkColorControl( + key: const ValueKey('settings-ink-color'), + color: Color(settings.inkLook.color), + onChanged: fields.locked ? null : onColorSelected, + ), + ), + ], collapsible: false); +} + +Widget layoutPresetSettings( + BuildContext context, + AppLocalizations l, + SettingsFields fields, +) { + final settings = fields.settings; + return settingsGroup('layout', l.layoutPreset, Icons.space_bar, [ + LayoutBuilder( + builder: (context, constraints) => SegmentedButton( + key: const ValueKey('layout-style'), + showSelectedIcon: false, + direction: + constraints.maxWidth < MediaQuery.textScalerOf(context).scale(170) + ? Axis.vertical + : Axis.horizontal, + segments: [ + for (final (value, label) in [ + ('standard', l.layoutStandard), + ('homework', l.layoutHomework), + ]) + ButtonSegment( + value: value, + label: Text( + label, + style: settings.layoutStyle == value + ? const TextStyle(fontWeight: FontWeight.w700) + : null, + ), + ), + ], + selected: {settings.layoutStyle}, + onSelectionChanged: fields.edited( + (selection) => settings.layoutStyle = selection.single, + ), + ), + ), + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text( + l.layoutPresetHint, + style: Theme.of(context).textTheme.bodySmall, + ), + ), + ], collapsible: false); +} + +Widget spacingSettings(AppLocalizations l, SettingsFields fields) { + final settings = fields.settings; + return settingsGroup('spacing', l.sizeSpacing, Icons.format_size, [ + fields.parameterGrid(parameters.take(3)), + fields.settingSwitch( + l.indentFirstLine, + settings.firstLineIndent, + (value) => settings.firstLineIndent = value, + ), + fields.settingSwitch( + l.fixedWidthText, + settings.monospaced, + (value) => settings.monospaced = value, + ), + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: Text(l.englishSpacing), + value: settings.englishSpacing, + onChanged: fields.edited((v) => settings.englishSpacing = v), + ), + ], collapsible: false); +} diff --git a/app/lib/widgets/settings/paper_settings.dart b/app/lib/widgets/settings/paper_settings.dart new file mode 100644 index 00000000..d93371e7 --- /dev/null +++ b/app/lib/widgets/settings/paper_settings.dart @@ -0,0 +1,127 @@ +import 'package:flutter/material.dart'; + +import '../../l10n/app_localizations.dart'; +import '../../models/settings.dart'; +import '../../models/upload.dart'; +import '../paper_style_picker.dart'; +import 'settings_fields.dart'; + +List paperSettings( + AppLocalizations l, + SettingsFields fields, { + required Upload? background, + required VoidCallback onUploadBackground, + required VoidCallback onRemoveBackground, + required VoidCallback onDetectBackground, + required VoidCallback? onAdjustBackground, +}) { + final settings = fields.settings; + return [ + settingsGroup('paper', l.paperBackground, Icons.description_outlined, [ + if (background == null) ...[ + SettingsFieldLabel( + label: l.paperStyle, + child: PaperStylePicker( + value: settings.paperStyle, + onChanged: fields.edited((style) => settings.paperStyle = style), + ), + ), + const SizedBox(height: 8), + ], + if (background != null) + ClipRRect( + borderRadius: BorderRadius.circular(12), + child: Image.memory( + background.bytes, + height: 120, + fit: BoxFit.contain, + ), + ), + FilledButton.tonalIcon( + onPressed: fields.locked ? null : onUploadBackground, + icon: const Icon(Icons.image_outlined), + label: Text( + background?.name ?? l.uploadBackground, + overflow: TextOverflow.ellipsis, + ), + ), + if (background != null) + Wrap( + spacing: 6, + runSpacing: 4, + children: [ + if (onAdjustBackground != null) + FilledButton.tonalIcon( + key: const ValueKey('adjust-paper-area'), + onPressed: fields.locked ? null : onAdjustBackground, + icon: const Icon(Icons.crop_free), + label: Text(l.paperAreaAction), + ), + TextButton.icon( + key: const ValueKey('identify-paper'), + onPressed: fields.locked ? null : onDetectBackground, + icon: const Icon(Icons.format_line_spacing), + label: Text(l.detectBackground), + ), + TextButton( + onPressed: fields.locked ? null : onRemoveBackground, + child: Text(l.remove), + ), + ], + ), + fields.settingSwitch( + l.transparentPng, + settings.transparentBackground, + (value) => settings.transparentBackground = value, + icon: Icons.texture, + ), + if (background != null) _paperCamera(l, fields), + ], collapsible: false), + settingsGroup('dimensions', l.paperSizeAndMargins, Icons.space_bar, [ + fields.parameterGrid( + parameters.where( + (p) => + p.key == 'width' || + p.key == 'height' || + p.key.endsWith('_margin'), + ), + ), + ], collapsible: false), + ]; +} + +Widget _paperCamera(AppLocalizations l, SettingsFields fields) => ExpansionTile( + title: Text(l.paperCamera), + children: [ + Text(l.paperCameraHint), + for (final field in [ + ('camera_make', l.cameraMake), + ('camera_model', l.cameraModel), + ('camera_lens', l.cameraLens), + ('camera_iso', 'ISO'), + ]) + TextFormField( + // Keep the field's scroll offset separate from the tile's expanded state. + key: PageStorageKey('${field.$1}-${fields.settingsRevision}'), + initialValue: fields.settings.camera[field.$1] ?? '', + enabled: !fields.locked, + maxLength: field.$1 == 'camera_iso' ? 5 : 96, + keyboardType: field.$1 == 'camera_iso' + ? TextInputType.number + : TextInputType.text, + decoration: InputDecoration(labelText: field.$2), + autovalidateMode: AutovalidateMode.onUserInteraction, + validator: (value) => Settings.validCameraValue(field.$1, value ?? '') + ? null + : l.cameraValueHint, + onChanged: (s) { + if (s.isEmpty) { + fields.settings.camera.remove(field.$1); + } else { + fields.settings.camera[field.$1] = s; + } + fields.onEdited(); + }, + ), + ], +); diff --git a/app/lib/widgets/settings/settings_fields.dart b/app/lib/widgets/settings/settings_fields.dart new file mode 100644 index 00000000..c010b290 --- /dev/null +++ b/app/lib/widgets/settings/settings_fields.dart @@ -0,0 +1,135 @@ +import 'package:flutter/material.dart'; + +import '../../l10n/app_localizations.dart'; +import '../../models/settings.dart'; +import '../workbench_controls.dart'; + +Widget settingsGroup( + String id, + String title, + IconData icon, + List children, { + bool expanded = false, + bool collapsible = true, +}) { + return SettingsGroup( + key: PageStorageKey('settings-$id'), + title: title, + icon: icon, + initiallyExpanded: collapsible ? expanded : null, + children: children, + ); +} + +/// Shared binding for settings fields. File and navigation actions stay with +/// the section that presents them. +class SettingsFields { + const SettingsFields( + this.settings, + this.settingsRevision, + this.locked, + this.onEdited, + ); + + final Settings settings; + final int settingsRevision; + final bool locked; + final VoidCallback onEdited; + + ValueChanged? edited(ValueChanged change) => locked + ? null + : (value) { + change(value); + onEdited(); + }; + + Widget settingSwitch( + String title, + bool value, + ValueChanged change, { + IconData? icon, + }) => SwitchListTile( + contentPadding: EdgeInsets.zero, + title: Text(title), + secondary: icon == null ? null : Icon(icon), + value: value, + onChanged: edited(change), + ); + + Widget parameterGrid(Iterable fields) => LayoutBuilder( + builder: (context, constraints) { + final minWidth = 140 * MediaQuery.textScalerOf(context).scale(1); + final columns = constraints.maxWidth >= minWidth * 2 + 8 ? 2 : 1; + return Wrap( + spacing: 8, + runSpacing: 12, + children: [ + for (final p in fields) + SizedBox( + // TextField scroll offsets must not share the tile's stored bool. + key: PageStorageKey('parameter-${p.key}'), + width: (constraints.maxWidth - 8 * (columns - 1)) / columns, + child: Semantics( + identifier: p.key, + child: SettingsFieldLabel( + label: Localizations.localeOf(context).languageCode == 'en' + ? p.en + : p.zh, + child: TextFormField( + key: ValueKey( + p.key.startsWith('strikethrough_') + ? '${p.key}-$settingsRevision-${settings.strikethroughEnabled}' + : '${p.key}-$settingsRevision', + ), + initialValue: settings.values[p.key], + enabled: + !locked && + (!p.key.startsWith('strikethrough_') || + settings.strikethroughEnabled), + keyboardType: const TextInputType.numberWithOptions( + decimal: true, + ), + validator: (s) => p.accepts(s) + ? null + : AppLocalizations.of(context)!.validation, + onChanged: (s) { + settings.values[p.key] = s; + onEdited(); + }, + ), + ), + ), + ), + ], + ); + }, + ); +} + +/// Labels participate in layout rather than painting above an outlined field. +/// This keeps them inside scrolling and animated expansion clip boundaries. +class SettingsFieldLabel extends StatelessWidget { + const SettingsFieldLabel({ + super.key, + required this.label, + required this.child, + }); + + final String label; + final Widget child; + + @override + Widget build(BuildContext context) => Semantics( + label: label, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + ExcludeSemantics( + child: Text(label, style: Theme.of(context).textTheme.labelLarge), + ), + const SizedBox(height: 6), + child, + ], + ), + ); +} diff --git a/app/lib/widgets/workbench_editor.dart b/app/lib/widgets/workbench_editor.dart index 622bdd02..1216402c 100644 --- a/app/lib/widgets/workbench_editor.dart +++ b/app/lib/widgets/workbench_editor.dart @@ -3,9 +3,9 @@ import 'dart:math' as math; import 'package:flutter/material.dart'; import '../l10n/app_localizations.dart'; -import '../theme/handwriting_theme.dart'; -import '../utils/image_data.dart'; import '../utils/image_markers.dart'; +import 'editor_illustration_strip.dart'; +import 'manuscript_text_field.dart'; import 'workbench_controls.dart'; import 'workbench_guide.dart'; @@ -59,11 +59,34 @@ class WorkbenchEditor extends StatelessWidget { final ValueChanged? onEditImage; final VoidCallback? onUndo, onRedo, onOpenGuide; final bool guideUnread; + + Widget _historyControls(ThemeData theme, AppLocalizations l) => Wrap( + alignment: WrapAlignment.spaceBetween, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Text( + '${controller.text.runes.length} ${l.characters}', + style: theme.textTheme.labelMedium?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + TextButton.icon( + label: Text(l.undo), + onPressed: locked ? null : (onUndo ?? undo.undo), + icon: const Icon(Icons.undo), + ), + TextButton.icon( + label: Text(l.redo), + onPressed: locked ? null : (onRedo ?? undo.redo), + icon: const Icon(Icons.redo), + ), + ], + ); + @override Widget build(BuildContext context) { final l = AppLocalizations.of(context)!; final theme = Theme.of(context); - final colors = theme.colorScheme; final markers = illustrationMarkers(controller.text); return WorkbenchPanel( title: l.editor, @@ -113,85 +136,16 @@ class WorkbenchEditor extends StatelessWidget { 152, constraints.maxHeight - (markers.isEmpty ? 168 : 248), ), - child: Semantics( - identifier: 'text-input', - child: DecoratedBox( - decoration: BoxDecoration( - color: theme.brightness == Brightness.dark - ? NightSurfaces.writing - : colors.surface, - borderRadius: BorderRadius.circular(28), - border: Border.all( - color: theme.brightness == Brightness.dark - ? colors.outlineVariant - : colors.tertiary.withValues(alpha: .5), - ), - ), - child: CustomPaint( - painter: controller.text.isEmpty - ? _ManuscriptRuling(colors.tertiary) - : null, - child: TextField( - key: const ValueKey('text-editor'), - controller: controller, - focusNode: focusNode, - undoController: undo, - enabled: !locked, - expands: true, - maxLines: null, - minLines: null, - textAlignVertical: TextAlignVertical.top, - keyboardType: TextInputType.multiline, - style: theme.textTheme.bodyLarge?.copyWith( - height: 1.75, - ), - decoration: InputDecoration( - contentPadding: const EdgeInsets.symmetric( - horizontal: 22, - vertical: 17, - ), - border: InputBorder.none, - enabledBorder: InputBorder.none, - disabledBorder: InputBorder.none, - focusedBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(28), - borderSide: BorderSide( - color: colors.primary, - width: 1.5, - ), - ), - hintText: l.editorHint, - filled: false, - ), - onChanged: onChanged, - ), - ), - ), + child: ManuscriptTextField( + controller: controller, + focusNode: focusNode, + undo: undo, + enabled: !locked, + onChanged: onChanged, ), ), const SizedBox(height: 8), - Wrap( - alignment: WrapAlignment.spaceBetween, - crossAxisAlignment: WrapCrossAlignment.center, - children: [ - Text( - '${controller.text.runes.length} ${l.characters}', - style: theme.textTheme.labelMedium?.copyWith( - color: colors.onSurfaceVariant, - ), - ), - TextButton.icon( - label: Text(l.undo), - onPressed: locked ? null : (onUndo ?? undo.undo), - icon: const Icon(Icons.undo), - ), - TextButton.icon( - label: Text(l.redo), - onPressed: locked ? null : (onRedo ?? undo.redo), - icon: const Icon(Icons.redo), - ), - ], - ), + _historyControls(theme, l), ListenableBuilder( listenable: Listenable.merge([controller, focusNode]), builder: (context, _) { @@ -211,43 +165,10 @@ class WorkbenchEditor extends StatelessWidget { l.editIllustrationHelp, style: Theme.of(context).textTheme.bodySmall, ), - SizedBox( - height: 72, - child: ListView( - scrollDirection: Axis.horizontal, - children: [ - for (final marker in markers) - Padding( - padding: const EdgeInsets.all(4), - child: Semantics( - identifier: 'illustration-${marker.start}', - button: true, - child: OutlinedButton( - key: ValueKey('illustration-${marker.start}'), - onPressed: locked || onEditImage == null - ? null - : () => onEditImage!(marker), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - _IllustrationThumbnail( - source: images[marker.id] ?? '', - ), - const SizedBox(width: 8), - Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text('#${marker.id} · ${marker.scale}%'), - const Icon(Icons.tune, size: 20), - ], - ), - ], - ), - ), - ), - ), - ], - ), + EditorIllustrationStrip( + markers: markers, + images: images, + onEditImage: locked ? null : onEditImage, ), ], ], @@ -257,87 +178,3 @@ class WorkbenchEditor extends StatelessWidget { ); } } - -/// Faint writing guides on the unused portion of the blank manuscript. -class _ManuscriptRuling extends CustomPainter { - const _ManuscriptRuling(this.ink); - final Color ink; - - @override - void paint(Canvas canvas, Size size) { - if (size.width < 72) return; - final pen = Paint() - ..color = ink.withValues(alpha: .18) - ..style = PaintingStyle.stroke - ..strokeWidth = .8; - for (double y = 78; y < size.height - 23; y += 32) { - canvas.drawPath( - Path() - ..moveTo(23, y) - ..cubicTo( - size.width * .34, - y - 1.6, - size.width * .67, - y + 1.6, - size.width - 23, - y, - ), - pen, - ); - } - } - - @override - bool shouldRepaint(_ManuscriptRuling oldDelegate) => ink != oldDelegate.ink; -} - -/// Retain decoded bytes across editor rebuilds instead of decoding base64 on -/// every keystroke and missing the image cache with a new Uint8List identity. -class _IllustrationThumbnail extends StatefulWidget { - const _IllustrationThumbnail({required this.source}); - final String source; - @override - State<_IllustrationThumbnail> createState() => _IllustrationThumbnailState(); -} - -class _IllustrationThumbnailState extends State<_IllustrationThumbnail> { - late var bytes = decodeImageData(widget.source); - @override - void didUpdateWidget(_IllustrationThumbnail oldWidget) { - super.didUpdateWidget(oldWidget); - if (oldWidget.source != widget.source) { - bytes = decodeImageData(widget.source); - } - } - - @override - Widget build(BuildContext context) { - final fallback = SizedBox( - width: 48, - height: 48, - child: Center( - child: Text( - AppLocalizations.of(context)!.imageUnavailable, - textAlign: TextAlign.center, - maxLines: 2, - overflow: TextOverflow.ellipsis, - ), - ), - ); - final data = bytes; - if (data == null) return fallback; - return Image( - image: ResizeImage( - MemoryImage(data), - width: 128, - height: 128, - policy: ResizeImagePolicy.fit, - ), - width: 48, - height: 48, - fit: BoxFit.contain, - gaplessPlayback: true, - errorBuilder: (_, error, stack) => fallback, - ); - } -} diff --git a/app/lib/widgets/workbench_layout.dart b/app/lib/widgets/workbench_layout.dart index 267077ed..eda67174 100644 --- a/app/lib/widgets/workbench_layout.dart +++ b/app/lib/widgets/workbench_layout.dart @@ -6,6 +6,8 @@ import '../theme/nouveau_ornament.dart'; import 'atelier_ornament.dart'; import 'fine_preview.dart'; import 'workbench_motion.dart'; +import 'workbench_navigation.dart'; +import 'workbench_task_status.dart'; import 'workbench_settings.dart'; class WorkbenchLayout extends StatelessWidget { @@ -109,74 +111,20 @@ class WorkbenchLayout extends StatelessWidget { @override Widget build(BuildContext context) { - final l = AppLocalizations.of(context)!; - final taskStatus = generating - ? Padding( - padding: const EdgeInsets.all(16), - child: Column( - children: [ - const LinearProgressIndicator(), - const SizedBox(height: 8), - if (onCancel != null) - TextButton.icon( - key: const ValueKey('cancel-generation'), - onPressed: onCancel, - icon: const Icon(Icons.cancel_outlined), - label: Text(l.stopGeneration), - ), - Text( - generating - ? switch (phase) { - 'pending' => l.pending, - 'completed' => l.completed, - 'cancelling' => l.stoppingTask, - _ => - stage == 'exporting' - ? l.exportingTask - : l.processing, - } - : l.processing, - ), - if (pagesCompleted > 0) Text(l.generatedPages(pagesCompleted)), - ], - ), - ) - : const SizedBox(width: double.infinity); final content = Column( children: [ - if (!fineFullscreen && error.isNotEmpty) - Padding( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 0), - child: Material( - animationDuration: Duration.zero, - color: Theme.of(context).colorScheme.errorContainer, - borderRadius: BorderRadius.circular(16), - child: ListTile( - leading: const Icon(Icons.error_outline), - title: Text( - error == 'validation' - ? l.validation - : queueWaitSeconds != null - ? '${l.queueFull} ${queueWaitSeconds}s' - : error, - ), - trailing: TextButton.icon( - label: Text(l.close), - onPressed: onDismissError, - icon: const Icon(Icons.close), - ), - ), - ), - ), if (!fineFullscreen) - MediaQuery.disableAnimationsOf(context) - ? taskStatus - : AnimatedSize( - duration: WorkbenchMotion.pane, - curve: Curves.easeInOut, - alignment: Alignment.topCenter, - child: taskStatus, - ), + ...workbenchTaskStatus( + context, + error: error, + queueWaitSeconds: queueWaitSeconds, + generating: generating, + phase: phase, + stage: stage, + pagesCompleted: pagesCompleted, + onCancel: onCancel, + onDismissError: onDismissError, + ), Expanded( key: const ValueKey('workbench-panes'), child: Form( @@ -201,92 +149,10 @@ class WorkbenchLayout extends StatelessWidget { child: previewActions(context, mobile: true), ), const NouveauWaveDivider(height: 6), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2), - child: Column( - children: [ - Row( - children: [ - for (final (i, key, icon, label) in [ - ( - 0, - 'back-to-editor', - Icons.edit_outlined, - l.mobileEditor, - ), - (1, 'open-paper', Icons.tune, l.parametersShort), - ( - 2, - 'open-preview', - Icons.visibility_outlined, - l.mobilePreview, - ), - ]) - Expanded( - child: Semantics( - selected: mobileTab == i, - child: TextButton( - key: ValueKey(key), - style: mobileTab == i - ? selectedToolStyle(context) - : null, - onPressed: () => onTabChanged(i), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - AnimatedSlide( - offset: mobileTab == i - ? const Offset(0, -.1) - : Offset.zero, - duration: - MediaQuery.disableAnimationsOf(context) - ? Duration.zero - : WorkbenchMotion.selection, - curve: WorkbenchMotion.enter, - child: Icon(icon, size: 20), - ), - Text(label, textAlign: TextAlign.center), - ], - ), - ), - ), - ), - ], - ), - SizedBox( - height: 4, - width: double.infinity, - child: Align( - alignment: AlignmentDirectional.centerStart, - child: FractionallySizedBox( - widthFactor: 1 / 3, - child: AnimatedSlide( - offset: Offset( - mobileTab.toDouble() * - (Directionality.of(context) == TextDirection.rtl - ? -1 - : 1), - 0, - ), - duration: MediaQuery.disableAnimationsOf(context) - ? Duration.zero - : WorkbenchMotion.selection, - curve: WorkbenchMotion.enter, - child: Center( - child: DecoratedBox( - decoration: ShapeDecoration( - color: Theme.of(context).colorScheme.primary, - shape: const StadiumBorder(), - ), - child: const SizedBox(width: 22, height: 3), - ), - ), - ), - ), - ), - ), - ], - ), + mobilePaneNavigation( + context, + selected: mobileTab, + onSelected: onTabChanged, ), ], ], @@ -309,21 +175,12 @@ class WorkbenchLayout extends StatelessWidget { ); } - ButtonStyle selectedToolStyle(BuildContext context) { - final colors = Theme.of(context).colorScheme; - return TextButton.styleFrom( - backgroundColor: colors.brightness == Brightness.dark - ? colors.primary.withValues(alpha: .12) - : colors.primary, - foregroundColor: colors.brightness == Brightness.dark - ? colors.primary - : colors.onPrimary, - ); - } + bool get _expanded => WorkbenchWidth.from(width) == WorkbenchWidth.expanded; + double get _paneGap => _expanded ? 16 : 8; Widget wideWorkspace(BuildContext context) { return Padding( - padding: EdgeInsets.all(width >= 1100 ? 16 : 8), + padding: EdgeInsets.all(_paneGap), child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ @@ -334,7 +191,7 @@ class WorkbenchLayout extends StatelessWidget { inspector?.hasSelection == true ? inspector : null, ), ), - SizedBox(width: width >= 1100 ? 16 : 8), + SizedBox(width: _paneGap), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, @@ -367,7 +224,7 @@ class WorkbenchLayout extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ SizedBox( - width: width >= 1100 ? 134 : 108, + width: _expanded ? 134 : 108, child: DecoratedBox( decoration: BoxDecoration( color: colors.brightness == Brightness.dark @@ -382,7 +239,7 @@ class WorkbenchLayout extends StatelessWidget { builder: (context, bounds) => Stack( children: [ if (bounds.maxHeight > 570 && - width >= 1100 && + _expanded && MediaQuery.textScalerOf(context).scale(16) < 24) Positioned( bottom: 16, @@ -442,7 +299,7 @@ class WorkbenchLayout extends StatelessWidget { ), ), ), - SizedBox(width: width >= 1100 ? 16 : 8), + SizedBox(width: _paneGap), SizedBox( width: (width * .29).clamp(260.0, 430.0), child: RetainedPaneSwitcher( @@ -479,12 +336,15 @@ class WorkbenchLayout extends StatelessWidget { selected: selected, child: TextButton( key: ValueKey('workspace-tool-$id'), - style: (selected ? selectedToolStyle(context) : TextButton.styleFrom()) - .copyWith( - padding: const WidgetStatePropertyAll( - EdgeInsets.symmetric(horizontal: 5, vertical: 8), - ), - ), + style: + (selected + ? selectedWorkbenchToolStyle(context) + : TextButton.styleFrom()) + .copyWith( + padding: const WidgetStatePropertyAll( + EdgeInsets.symmetric(horizontal: 5, vertical: 8), + ), + ), onPressed: select, child: Row( children: [ diff --git a/app/lib/widgets/workbench_masthead.dart b/app/lib/widgets/workbench_masthead.dart new file mode 100644 index 00000000..3668a5e2 --- /dev/null +++ b/app/lib/widgets/workbench_masthead.dart @@ -0,0 +1,101 @@ +import 'package:flutter/material.dart'; + +import '../l10n/app_localizations.dart'; +import '../theme/nouveau_ornament.dart'; +import 'atelier_ornament.dart'; +import 'project_source_link.dart'; +import 'workbench_navigation.dart'; + +AppBar workbenchMasthead( + BuildContext context, { + required WorkbenchWidth size, + required String title, + required Color foreground, + required ColorScheme? palette, + required List actions, + required VoidCallback? onDismissKeyboard, +}) { + final compact = size == WorkbenchWidth.compact; + return AppBar( + toolbarHeight: compact ? 64 : 84, + titleSpacing: compact ? 6 : 18, + automaticallyImplyLeading: false, + centerTitle: false, + surfaceTintColor: Colors.transparent, + flexibleSpace: Stack( + children: [ + if (size == WorkbenchWidth.expanded) + Positioned( + top: 0, + bottom: 0, + left: 425, + right: 355, + child: Align( + alignment: Alignment.centerLeft, + child: CustomPaint( + size: const Size(340, 84), + painter: AtelierTendrils(palette: palette), + ), + ), + ), + const Align( + alignment: Alignment.bottomCenter, + child: NouveauWaveDivider(height: 7), + ), + ], + ), + title: Row( + children: [ + CustomPaint( + size: Size.square(compact ? 48 : 78), + painter: AtelierIris(palette: palette), + ), + SizedBox(width: compact ? 7 : 12), + Flexible( + child: Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.headlineLarge?.copyWith( + color: foreground, + fontSize: compact ? 22 : 37, + fontFamily: 'Playfair Display', + fontFamilyFallback: const [ + 'packages/handwriting_assets/LXGW WenKai', + ], + height: 1.1, + letterSpacing: compact ? 0 : 1, + ), + ), + ), + if (!compact) ...[ + const SizedBox(width: 20), + Material( + animationDuration: Duration.zero, + color: foreground.withValues(alpha: .07), + borderRadius: BorderRadius.circular(32), + child: ProjectSourceLink(foreground: foreground), + ), + ], + ], + ), + bottom: onDismissKeyboard != null + ? PreferredSize( + preferredSize: const Size.fromHeight(40), + child: Align( + alignment: Alignment.centerRight, + child: TextButton.icon( + style: TextButton.styleFrom(foregroundColor: foreground), + onPressed: onDismissKeyboard, + icon: const Icon(Icons.keyboard_hide_outlined), + label: Text(AppLocalizations.of(context)!.dismissKeyboard), + ), + ), + ) + : null, + actions: [ + ...actions, + SizedBox(width: compact ? 3 : 16), + ], + ); +} diff --git a/app/lib/widgets/workbench_navigation.dart b/app/lib/widgets/workbench_navigation.dart new file mode 100644 index 00000000..3c54400b --- /dev/null +++ b/app/lib/widgets/workbench_navigation.dart @@ -0,0 +1,176 @@ +import 'package:flutter/material.dart'; + +import '../l10n/app_localizations.dart'; +import 'workbench_guide.dart'; +import 'workbench_motion.dart'; + +/// Classify the window for its toolbar and the available body for its panes. +enum WorkbenchWidth { + compact, + medium, + expanded; + + static WorkbenchWidth from(double width) { + if (width < 900) return compact; + if (width < 1100) return medium; + return expanded; + } +} + +List workbenchAppActions( + AppLocalizations l, { + required WorkbenchWidth size, + required bool guideUnread, + required bool updateAvailable, + required Color foreground, + required Color unreadColor, + required ValueChanged onDestinationSelected, + required VoidCallback onPreferences, + required VoidCallback onToggleLocale, + required VoidCallback onToggleTheme, +}) { + final compact = size == WorkbenchWidth.compact; + return [ + if (!compact) ...[ + IconButton( + key: const ValueKey('open-guide'), + tooltip: guideUnread ? '${l.guide} · ${l.guideUnread}' : l.guide, + onPressed: () => onDestinationSelected(1), + icon: GuideUnreadBadge( + unread: guideUnread, + child: const Icon(Icons.menu_book_outlined), + ), + ), + IconButton( + tooltip: l.about, + onPressed: () => onDestinationSelected(2), + icon: Badge( + isLabelVisible: updateAvailable, + child: const Icon(Icons.info_outline), + ), + ), + ], + Semantics( + hint: guideUnread && compact ? l.guideUnread : null, + child: TextButton.icon( + key: const ValueKey('app-preferences'), + style: TextButton.styleFrom(foregroundColor: foreground), + onPressed: onPreferences, + icon: Badge( + isLabelVisible: compact && (updateAvailable || guideUnread), + backgroundColor: updateAvailable ? null : unreadColor, + child: const Icon(Icons.tune), + ), + label: Text(l.appPreferences), + ), + ), + if (size == WorkbenchWidth.expanded) ...[ + IconButton( + tooltip: l.language, + onPressed: onToggleLocale, + icon: const Icon(Icons.translate), + ), + IconButton( + tooltip: l.theme, + onPressed: onToggleTheme, + icon: const Icon(Icons.contrast), + ), + ], + ]; +} + +Widget mobilePaneNavigation( + BuildContext context, { + required int selected, + required ValueChanged onSelected, +}) { + final l = AppLocalizations.of(context)!; + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2), + child: Column( + children: [ + Row( + children: [ + for (final (i, key, icon, label) in [ + (0, 'back-to-editor', Icons.edit_outlined, l.mobileEditor), + (1, 'open-paper', Icons.tune, l.parametersShort), + (2, 'open-preview', Icons.visibility_outlined, l.mobilePreview), + ]) + Expanded( + child: Semantics( + selected: selected == i, + child: TextButton( + key: ValueKey(key), + style: selected == i + ? selectedWorkbenchToolStyle(context) + : null, + onPressed: () => onSelected(i), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + AnimatedSlide( + offset: selected == i + ? const Offset(0, -.1) + : Offset.zero, + duration: MediaQuery.disableAnimationsOf(context) + ? Duration.zero + : WorkbenchMotion.selection, + curve: WorkbenchMotion.enter, + child: Icon(icon, size: 20), + ), + Text(label, textAlign: TextAlign.center), + ], + ), + ), + ), + ), + ], + ), + SizedBox( + height: 4, + width: double.infinity, + child: Align( + alignment: AlignmentDirectional.centerStart, + child: FractionallySizedBox( + widthFactor: 1 / 3, + child: AnimatedSlide( + offset: Offset( + selected.toDouble() * + (Directionality.of(context) == TextDirection.rtl + ? -1 + : 1), + 0, + ), + duration: MediaQuery.disableAnimationsOf(context) + ? Duration.zero + : WorkbenchMotion.selection, + curve: WorkbenchMotion.enter, + child: Center( + child: DecoratedBox( + decoration: ShapeDecoration( + color: Theme.of(context).colorScheme.primary, + shape: const StadiumBorder(), + ), + child: const SizedBox(width: 22, height: 3), + ), + ), + ), + ), + ), + ), + ], + ), + ); +} + +ButtonStyle selectedWorkbenchToolStyle(BuildContext context) { + final colors = Theme.of(context).colorScheme; + return TextButton.styleFrom( + backgroundColor: colors.brightness == Brightness.dark + ? colors.primary.withValues(alpha: .12) + : colors.primary, + foregroundColor: colors.brightness == Brightness.dark + ? colors.primary + : colors.onPrimary, + ); +} diff --git a/app/lib/widgets/workbench_preferences.dart b/app/lib/widgets/workbench_preferences.dart new file mode 100644 index 00000000..45897550 --- /dev/null +++ b/app/lib/widgets/workbench_preferences.dart @@ -0,0 +1,90 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../l10n/app_localizations.dart'; + +Widget mcpConnectionTile( + BuildContext context, + BuildContext sheetContext, + AppLocalizations l, + String mcpConfig, +) => ListTile( + key: const ValueKey('connect-ai-client'), + leading: const Icon(Icons.hub_outlined), + title: Text(l.connectAiClient), + subtitle: Text(l.copyMcpConfig), + trailing: const Icon(Icons.copy_outlined), + onTap: () async { + final messenger = ScaffoldMessenger.of(context); + try { + await Clipboard.setData(ClipboardData(text: mcpConfig)); + } on PlatformException { + if (messenger.mounted) { + messenger.showSnackBar(SnackBar(content: Text(l.mcpCopyFailed))); + } + return; + } + if (!sheetContext.mounted) return; + Navigator.pop(sheetContext); + messenger.showSnackBar(SnackBar(content: Text(l.mcpConfigCopied))); + }, +); + +Widget themePreferenceTile( + BuildContext context, + AppLocalizations l, { + required ThemeMode themeMode, + required Future Function(ThemeMode)? onThemeModeChanged, + required VoidCallback onToggleTheme, +}) => ListTile( + leading: const Icon(Icons.contrast), + title: Text(l.theme), + subtitle: Text(switch (themeMode) { + ThemeMode.system => l.themeSystem, + ThemeMode.light => l.themeLight, + ThemeMode.dark => l.themeDark, + }), + trailing: onThemeModeChanged == null + ? null + : PopupMenuButton( + tooltip: l.chooseTheme, + icon: const Icon(Icons.expand_more), + initialValue: themeMode, + itemBuilder: (_) => [ + for (final (mode, label) in [ + (ThemeMode.system, l.themeSystem), + (ThemeMode.light, l.themeLight), + (ThemeMode.dark, l.themeDark), + ]) + CheckedPopupMenuItem( + value: mode, + checked: themeMode == mode, + child: Text(label), + ), + ], + onSelected: (value) { + final nextBrightness = switch (value) { + ThemeMode.system => MediaQuery.platformBrightnessOf(context), + ThemeMode.light => Brightness.light, + ThemeMode.dark => Brightness.dark, + }; + if (Theme.of(context).brightness == nextBrightness) { + Navigator.pop(context); + } else { + _dismissForAppearanceChange(context); + } + onThemeModeChanged(value); + }, + ), + onTap: () { + _dismissForAppearanceChange(context); + onToggleTheme(); + }, +); + +// The global appearance transition already blends the painted sheet into the +// new workbench. Retiring its route immediately avoids laying out and animating +// the outgoing sheet in a second theme on every frame of that same gesture. +void _dismissForAppearanceChange(BuildContext sheetContext) { + Navigator.of(sheetContext).removeRoute(ModalRoute.of(sheetContext)!); +} diff --git a/app/lib/widgets/workbench_preview.dart b/app/lib/widgets/workbench_preview.dart index 6133da65..026c3115 100644 --- a/app/lib/widgets/workbench_preview.dart +++ b/app/lib/widgets/workbench_preview.dart @@ -141,6 +141,217 @@ class _WorkbenchPreviewState extends State { ); } + Future _toggleFineEdit(bool selected) async { + if (!selected) { + _closeFineEdit(); + return; + } + if (await widget.onFineEdit!() && mounted) { + setState(() => _fineEditing = true); + } + } + + Widget _fullscreenHeader(AppLocalizations l, ThemeData theme) => Row( + children: [ + IconButton( + key: const ValueKey('exit-fullscreen-fine-edit'), + tooltip: l.fineExitFullscreen, + onPressed: () => widget.onFineFullscreen?.call(false), + icon: const BackButtonIcon(), + ), + Expanded(child: Text(l.fineEdit, style: theme.textTheme.titleMedium)), + if (widget.pages.length > 1) + Padding( + padding: const EdgeInsetsDirectional.only(end: 16), + child: Text('${widget.page + 1} / ${widget.pages.length}'), + ), + ], + ); + + Widget _previewActions( + AppLocalizations l, + FinePage? fine, + ColorScheme colors, + ) { + final canExpandEditor = + _fineEditing && + fine != null && + widget.onFineFullscreen != null && + !widget.stale; + return Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Align( + alignment: AlignmentDirectional.centerEnd, + child: Wrap( + alignment: WrapAlignment.end, + spacing: 6, + runSpacing: 4, + children: [ + if (widget.onFineEdit != null) + FilterChip( + key: const ValueKey('fine-edit-toggle'), + label: Text(l.fineEdit), + avatar: const Icon(Icons.select_all, size: 17), + selected: _fineEditing, + onSelected: widget.locked ? null : _toggleFineEdit, + ), + if (widget.onAdjustBackground != null) + FilledButton.tonalIcon( + key: const ValueKey('preview-adjust-paper-area'), + onPressed: widget.locked ? null : widget.onAdjustBackground, + icon: const Icon(Icons.crop_free), + label: Text(l.paperAreaAction), + ), + if (widget.onInkChanged != null) + Semantics( + expanded: _inkExpanded, + child: FilledButton.tonalIcon( + style: _inkExpanded + ? FilledButton.styleFrom( + backgroundColor: colors.primaryContainer, + foregroundColor: colors.onPrimaryContainer, + ) + : null, + key: const ValueKey('preview-ink-effects'), + onPressed: () => setState(() => _inkExpanded = !_inkExpanded), + icon: Icon(_inkExpanded ? Icons.expand_less : Icons.tune), + label: Text(l.inkEffects), + ), + ), + if (canExpandEditor) + OutlinedButton.icon( + key: const ValueKey('fullscreen-fine-edit'), + onPressed: widget.locked + ? null + : () => widget.onFineFullscreen?.call(true), + icon: const Icon(Icons.open_in_full), + label: Text(l.fineFullscreen), + ) + else if (widget.pages.isNotEmpty) + OutlinedButton.icon( + key: const ValueKey('expand-preview'), + onPressed: _expand, + icon: const Icon(Icons.open_in_full), + label: Text(l.expandPreview), + ), + if (widget.fineInspector case final slot? when _fineEditing) + ValueListenableBuilder( + valueListenable: slot, + builder: (context, inspector, _) => IconButton( + key: const ValueKey('fine-fit-page'), + tooltip: l.resetPreviewZoom, + onPressed: inspector?.fitPage, + icon: const Icon(Icons.fit_screen_outlined), + ), + ), + ], + ), + ), + ); + } + + Widget _emptyPreview(AppLocalizations l, ThemeData theme) { + final background = widget.backgroundBytes; + if (background != null) { + return Image.memory(background, fit: BoxFit.contain); + } + return LayoutBuilder( + builder: (context, space) => Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + IrisQuill(height: (space.maxHeight * .48).clamp(42.0, 300.0)), + const SizedBox(height: 16), + Text( + l.previewHint, + textAlign: TextAlign.center, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + ), + ); + } + + Widget _previewContent( + AppLocalizations l, + ThemeData theme, + InkPage? current, + ) { + if (widget.pages.isEmpty) return _emptyPreview(l, theme); + final fine = current?.fine; + if (_fineEditing && fine != null && current != null) { + return Column( + children: [ + Expanded(child: _editor(current, fine)), + if (!widget.fineFullscreen && widget.pages.length > 1) + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + IconButton( + tooltip: l.previousPage, + onPressed: widget.page > 0 + ? () => widget.onPageChanged(widget.page - 1) + : null, + icon: const Icon(Icons.chevron_left), + ), + Text('${widget.page + 1} / ${widget.pages.length}'), + IconButton( + tooltip: l.nextPage, + onPressed: widget.page + 1 < widget.pages.length + ? () => widget.onPageChanged(widget.page + 1) + : null, + icon: const Icon(Icons.chevron_right), + ), + ], + ), + ], + ); + } + return PreviewPager( + pages: widget.pages, + page: widget.page, + heroOwner: _heroOwner, + onOpen: _expand, + copyImage: widget.copyImage, + inkPages: widget.inkPages, + inkLook: widget.inkLook, + fineEdits: _fineEdits(), + enlargeInitially: widget.fineInspector != null, + onPageChanged: widget.onPageChanged, + ); + } + + Widget _saveActions(AppLocalizations l) => Wrap( + alignment: WrapAlignment.center, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + if (widget.onCancel != null) + TextButton.icon( + onPressed: widget.onCancel, + icon: const Icon(Icons.cancel_outlined), + label: Text(l.cancel), + ), + if (widget.pages.isNotEmpty) + TextButton.icon( + onPressed: widget.locked ? null : widget.onSaveImage, + icon: const Icon(Icons.download), + label: Text(l.saveImage), + ), + if (widget.onSaveExport != null) + TextButton.icon( + onPressed: widget.locked ? null : widget.onSaveExport, + icon: const Icon(Icons.save_alt), + label: Text(l.saveExport), + ), + ], + ); + @override Widget build(BuildContext context) { final l = AppLocalizations.of(context)!; @@ -150,13 +361,7 @@ class _WorkbenchPreviewState extends State { final paperActions = widget.onAdjustBackground != null; final inkActions = widget.onInkChanged != null; final current = widget.inkPages.elementAtOrNull(widget.page); - final fine = current?.fine; final fullscreen = widget.fineFullscreen; - final canExpandEditor = - _fineEditing && - fine != null && - widget.onFineFullscreen != null && - !widget.stale; return WorkbenchPanel( title: l.previewTitle, icon: Icons.description_outlined, @@ -165,113 +370,12 @@ class _WorkbenchPreviewState extends State { child: Column( children: [ if (fullscreen) - Row( - children: [ - IconButton( - key: const ValueKey('exit-fullscreen-fine-edit'), - tooltip: l.fineExitFullscreen, - onPressed: () => widget.onFineFullscreen?.call(false), - icon: const BackButtonIcon(), - ), - Expanded( - child: Text(l.fineEdit, style: theme.textTheme.titleMedium), - ), - if (widget.pages.length > 1) - Padding( - padding: const EdgeInsetsDirectional.only(end: 16), - child: Text('${widget.page + 1} / ${widget.pages.length}'), - ), - ], - ) + _fullscreenHeader(l, theme) else if (paperActions || inkActions || hasPages || widget.onFineEdit != null) - Padding( - padding: const EdgeInsets.only(bottom: 6), - child: Align( - alignment: AlignmentDirectional.centerEnd, - child: Wrap( - alignment: WrapAlignment.end, - spacing: 6, - runSpacing: 4, - children: [ - if (widget.onFineEdit != null) - FilterChip( - key: const ValueKey('fine-edit-toggle'), - label: Text(l.fineEdit), - avatar: const Icon(Icons.select_all, size: 17), - selected: _fineEditing, - onSelected: widget.locked - ? null - : (selected) async { - if (!selected) { - _closeFineEdit(); - return; - } - if (await widget.onFineEdit!() && mounted) { - setState(() => _fineEditing = true); - } - }, - ), - if (paperActions) - FilledButton.tonalIcon( - key: const ValueKey('preview-adjust-paper-area'), - onPressed: widget.locked - ? null - : widget.onAdjustBackground, - icon: const Icon(Icons.crop_free), - label: Text(l.paperAreaAction), - ), - if (inkActions) - Semantics( - expanded: _inkExpanded, - child: FilledButton.tonalIcon( - style: _inkExpanded - ? FilledButton.styleFrom( - backgroundColor: colors.primaryContainer, - foregroundColor: colors.onPrimaryContainer, - ) - : null, - key: const ValueKey('preview-ink-effects'), - onPressed: () => - setState(() => _inkExpanded = !_inkExpanded), - icon: Icon( - _inkExpanded ? Icons.expand_less : Icons.tune, - ), - label: Text(l.inkEffects), - ), - ), - if (canExpandEditor) - OutlinedButton.icon( - key: const ValueKey('fullscreen-fine-edit'), - onPressed: widget.locked - ? null - : () => widget.onFineFullscreen?.call(true), - icon: const Icon(Icons.open_in_full), - label: Text(l.fineFullscreen), - ) - else if (hasPages) - OutlinedButton.icon( - key: const ValueKey('expand-preview'), - onPressed: _expand, - icon: const Icon(Icons.open_in_full), - label: Text(l.expandPreview), - ), - if (widget.fineInspector case final slot? when _fineEditing) - ValueListenableBuilder( - valueListenable: slot, - builder: (context, inspector, _) => IconButton( - key: const ValueKey('fine-fit-page'), - tooltip: l.resetPreviewZoom, - onPressed: inspector?.fitPage, - icon: const Icon(Icons.fit_screen_outlined), - ), - ), - ], - ), - ), - ), + _previewActions(l, current?.fine, colors), if (!fullscreen && _inkExpanded && inkActions) InkParameterControls( look: widget.inkLook, @@ -303,109 +407,11 @@ class _WorkbenchPreviewState extends State { borderRadius: fullscreen ? null : BorderRadius.circular(28), ), clipBehavior: Clip.antiAlias, - child: widget.pages.isEmpty - ? widget.backgroundBytes != null - ? Image.memory( - widget.backgroundBytes!, - fit: BoxFit.contain, - ) - : LayoutBuilder( - builder: (context, space) => Center( - child: SingleChildScrollView( - padding: const EdgeInsets.all(16), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - IrisQuill( - height: (space.maxHeight * .48).clamp( - 42.0, - 300.0, - ), - ), - const SizedBox(height: 16), - Text( - l.previewHint, - textAlign: TextAlign.center, - style: theme.textTheme.bodySmall - ?.copyWith( - color: colors.onSurfaceVariant, - ), - ), - ], - ), - ), - ), - ) - : _fineEditing && fine != null && current != null - ? Column( - children: [ - Expanded(child: _editor(current, fine)), - if (!fullscreen && widget.pages.length > 1) - Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - IconButton( - tooltip: l.previousPage, - onPressed: widget.page > 0 - ? () => - widget.onPageChanged(widget.page - 1) - : null, - icon: const Icon(Icons.chevron_left), - ), - Text( - '${widget.page + 1} / ${widget.pages.length}', - ), - IconButton( - tooltip: l.nextPage, - onPressed: widget.page + 1 < widget.pages.length - ? () => - widget.onPageChanged(widget.page + 1) - : null, - icon: const Icon(Icons.chevron_right), - ), - ], - ), - ], - ) - : PreviewPager( - pages: widget.pages, - page: widget.page, - heroOwner: _heroOwner, - onOpen: _expand, - copyImage: widget.copyImage, - inkPages: widget.inkPages, - inkLook: widget.inkLook, - fineEdits: _fineEdits(), - enlargeInitially: widget.fineInspector != null, - onPageChanged: widget.onPageChanged, - ), + child: _previewContent(l, theme, current), ), ), if (!fullscreen && (hasPages || widget.onCancel != null)) - Wrap( - alignment: WrapAlignment.center, - crossAxisAlignment: WrapCrossAlignment.center, - children: [ - if (widget.onCancel != null) - TextButton.icon( - onPressed: widget.onCancel, - icon: const Icon(Icons.cancel_outlined), - label: Text(l.cancel), - ), - if (hasPages) - TextButton.icon( - onPressed: widget.locked ? null : widget.onSaveImage, - icon: const Icon(Icons.download), - label: Text(l.saveImage), - ), - if (widget.onSaveExport != null) - TextButton.icon( - onPressed: widget.locked ? null : widget.onSaveExport, - icon: const Icon(Icons.save_alt), - label: Text(l.saveExport), - ), - ], - ), + _saveActions(l), if (!fullscreen && widget.version.isNotEmpty) Semantics( identifier: 'app-version', diff --git a/app/lib/widgets/workbench_settings.dart b/app/lib/widgets/workbench_settings.dart index 4c2c871b..cdb8ac0c 100644 --- a/app/lib/widgets/workbench_settings.dart +++ b/app/lib/widgets/workbench_settings.dart @@ -2,12 +2,15 @@ import 'package:flutter/material.dart'; import '../l10n/app_localizations.dart'; import '../models/settings.dart'; -import '../services/api.dart'; -import 'ink_color_control.dart'; -import 'ink_parameter_controls.dart'; -import 'paper_style_picker.dart'; +import '../models/upload.dart'; +import 'settings/ink_settings.dart'; +import 'settings/layout_settings.dart'; +import 'settings/paper_settings.dart'; +import 'settings/settings_fields.dart'; import 'workbench_controls.dart'; +export 'settings/settings_fields.dart' show SettingsFieldLabel; + enum SettingsSection { layout, paper, @@ -84,45 +87,10 @@ class WorkbenchSettings extends StatelessWidget { final ValueChanged? onSectionChanged; final Widget? inkControls; - Widget _paperCamera(AppLocalizations l) => ExpansionTile( - title: Text(l.paperCamera), - children: [ - Text(l.paperCameraHint), - for (final field in [ - ('camera_make', l.cameraMake), - ('camera_model', l.cameraModel), - ('camera_lens', l.cameraLens), - ('camera_iso', 'ISO'), - ]) - TextFormField( - // Keep the field's scroll offset separate from the tile's expanded state. - key: PageStorageKey('${field.$1}-$settingsRevision'), - initialValue: settings.camera[field.$1] ?? '', - enabled: !locked, - maxLength: field.$1 == 'camera_iso' ? 5 : 96, - keyboardType: field.$1 == 'camera_iso' - ? TextInputType.number - : TextInputType.text, - decoration: InputDecoration(labelText: field.$2), - autovalidateMode: AutovalidateMode.onUserInteraction, - validator: (value) => Settings.validCameraValue(field.$1, value ?? '') - ? null - : l.cameraValueHint, - onChanged: (s) { - if (s.isEmpty) { - settings.camera.remove(field.$1); - } else { - settings.camera[field.$1] = s; - } - onEdited(); - }, - ), - ], - ); - @override Widget build(BuildContext context) { final l = AppLocalizations.of(context)!; + final fields = SettingsFields(settings, settingsRevision, locked, onEdited); bool show(SettingsSection group) => activeSection == null || activeSection == group; return WorkbenchPanel( @@ -168,344 +136,59 @@ class WorkbenchSettings extends StatelessWidget { key: PageStorageKey(activeSection), children: [ if (show(SettingsSection.layout)) ...[ - section('font', l.fontChoices, Icons.font_download_outlined, [ - Semantics( - identifier: 'font-select', - child: SettingsFieldLabel( - label: l.font, - child: DropdownButtonFormField( - key: ValueKey( - 'font-${settings.font}-${fontFile?.name}', - ), - hint: Text(l.chooseBundledFont), - initialValue: - fontFile == null && fonts.contains(settings.font) - ? settings.font - : null, - isExpanded: true, - items: fonts - .map( - (f) => DropdownMenuItem( - value: f, - child: Text( - f, - overflow: TextOverflow.ellipsis, - ), - ), - ) - .toList(), - onChanged: locked - ? null - : (value) { - onSelectFont(value); - }, - ), - ), - ), - const SizedBox(height: 6), - if (fontFile != null) - ListTile( - dense: true, - contentPadding: EdgeInsets.zero, - leading: const Icon(Icons.font_download_outlined), - title: Text( - fontFile!.name, - overflow: TextOverflow.ellipsis, - ), - trailing: IconButton( - tooltip: l.remove, - onPressed: locked ? null : onRemoveFont, - icon: const Icon(Icons.close), - ), - ), - if (onBrowseLocalFonts != null) - FilledButton.tonalIcon( - onPressed: locked ? null : onBrowseLocalFonts, - icon: const Icon(Icons.font_download_outlined), - label: Text(l.localFonts), - ), - OutlinedButton.icon( - onPressed: locked ? null : onUploadFont, - icon: const Icon(Icons.file_open_outlined), - label: Text(l.importFontFile), - ), - const SizedBox(height: 10), - SettingsFieldLabel( - label: l.latinFont, - child: DropdownButtonFormField( - key: ValueKey('latin-font-$settingsRevision'), - isExpanded: true, - initialValue: settings.latinFont ?? '', - items: [ - DropdownMenuItem( - value: '', - child: Text(l.inheritLatinFont), - ), - for (final entry in latinFonts.entries) - DropdownMenuItem( - value: entry.key, - child: Text( - entry.value, - overflow: TextOverflow.ellipsis, - ), - ), - ], - onChanged: locked - ? null - : (value) { - settings.latinFont = value == '' ? null : value; - onEdited(); - }, - ), - ), - NumericSlider( - label: l.latinFontScale, - id: 'latin-font-scale', - value: settings.latinScale.toDouble(), - parameter: latinScaleParameter, - unit: '%', - onChanged: locked - ? null - : (value) { - settings.latinScale = value.round(); - onEdited(); - }, - ), - settingSwitch( - l.digitsLatin, - settings.latinDigits, - (value) => settings.latinDigits = value, - ), - if (activeSection == null) - Align( - alignment: AlignmentDirectional.centerStart, - child: InkColorControl( - key: const ValueKey('settings-ink-color'), - color: Color(settings.inkLook.color), - onChanged: locked ? null : onColorSelected, - ), - ), - ], collapsible: false), - section('layout', l.layoutPreset, Icons.space_bar, [ - LayoutBuilder( - builder: (context, constraints) => - SegmentedButton( - key: const ValueKey('layout-style'), - showSelectedIcon: false, - direction: - constraints.maxWidth < - MediaQuery.textScalerOf(context).scale(170) - ? Axis.vertical - : Axis.horizontal, - segments: [ - for (final (value, label) in [ - ('standard', l.layoutStandard), - ('homework', l.layoutHomework), - ]) - ButtonSegment( - value: value, - label: Text( - label, - style: settings.layoutStyle == value - ? const TextStyle( - fontWeight: FontWeight.w700, - ) - : null, - ), - ), - ], - selected: {settings.layoutStyle}, - onSelectionChanged: locked - ? null - : (selection) { - settings.layoutStyle = selection.single; - onEdited(); - }, - ), - ), - Padding( - padding: const EdgeInsets.only(top: 8), - child: Text( - l.layoutPresetHint, - style: Theme.of(context).textTheme.bodySmall, - ), - ), - ], collapsible: false), - section('spacing', l.sizeSpacing, Icons.format_size, [ - parameterGrid(context, parameters.take(3).toList()), - settingSwitch( - l.indentFirstLine, - settings.firstLineIndent, - (value) => settings.firstLineIndent = value, - ), - settingSwitch( - l.fixedWidthText, - settings.monospaced, - (value) => settings.monospaced = value, - ), - SwitchListTile( - contentPadding: EdgeInsets.zero, - title: Text(l.englishSpacing), - value: settings.englishSpacing, - onChanged: locked - ? null - : (v) { - settings.englishSpacing = v; - onEdited(); - }, - ), - ], collapsible: false), + fontSettings( + l, + fields, + fonts: fonts, + fontFile: fontFile, + showInkColor: activeSection == null, + onSelectFont: onSelectFont, + onColorSelected: onColorSelected, + onUploadFont: onUploadFont, + onRemoveFont: onRemoveFont, + onBrowseLocalFonts: onBrowseLocalFonts, + ), + layoutPresetSettings(context, l, fields), + spacingSettings(l, fields), ], - if (show(SettingsSection.paper)) ...[ - section( - 'paper', - l.paperBackground, - Icons.description_outlined, - [ - if (background == null) ...[ - SettingsFieldLabel( - label: l.paperStyle, - child: PaperStylePicker( - value: settings.paperStyle, - onChanged: locked - ? null - : (style) { - settings.paperStyle = style; - onEdited(); - }, - ), - ), - const SizedBox(height: 8), - ], - if (background != null) - ClipRRect( - borderRadius: BorderRadius.circular(12), - child: Image.memory( - background!.bytes, - height: 120, - fit: BoxFit.contain, - ), - ), - FilledButton.tonalIcon( - onPressed: locked ? null : onUploadBackground, - icon: const Icon(Icons.image_outlined), - label: Text( - background?.name ?? l.uploadBackground, - overflow: TextOverflow.ellipsis, - ), - ), - if (background != null) - Wrap( - spacing: 6, - runSpacing: 4, - children: [ - if (onAdjustBackground != null) - FilledButton.tonalIcon( - key: const ValueKey('adjust-paper-area'), - onPressed: locked ? null : onAdjustBackground, - icon: const Icon(Icons.crop_free), - label: Text(l.paperAreaAction), - ), - TextButton.icon( - key: const ValueKey('identify-paper'), - onPressed: locked ? null : onDetectBackground, - icon: const Icon(Icons.format_line_spacing), - label: Text(l.detectBackground), - ), - TextButton( - onPressed: locked ? null : onRemoveBackground, - child: Text(l.remove), - ), - ], - ), - settingSwitch( - l.transparentPng, - settings.transparentBackground, - (value) => settings.transparentBackground = value, - icon: Icons.texture, - ), - if (background != null) _paperCamera(l), - ], - collapsible: false, + if (show(SettingsSection.paper)) + ...paperSettings( + l, + fields, + background: background, + onUploadBackground: onUploadBackground, + onRemoveBackground: onRemoveBackground, + onDetectBackground: onDetectBackground, + onAdjustBackground: onAdjustBackground, ), - section( - 'dimensions', - l.paperSizeAndMargins, - Icons.space_bar, + if (show(SettingsSection.ink)) + ...inkSettings(l, fields, inkControls), + if (show(SettingsSection.presets)) + settingsGroup( + 'presets', + l.presets, + Icons.bookmarks_outlined, [ - parameterGrid( - context, - parameters - .where( - (p) => - p.key == 'width' || - p.key == 'height' || - p.key.endsWith('_margin'), - ) - .toList(), + Wrap( + spacing: 6, + children: [ + for (final preset in [ + (l.defaultPreset, onDefaultPreset), + (l.smallPreset, onSmallPreset), + (l.savePreset, onSavePreset), + (l.loadPreset, onLoadPreset), + (l.exportPreset, onExportPreset), + (l.importPreset, onImportPreset), + ]) + ActionChip( + label: Text(preset.$1), + onPressed: locked ? null : preset.$2, + ), + ], ), ], collapsible: false, ), - ], - if (show(SettingsSection.ink)) ...[ - if (inkControls case final controls?) - section('ink', l.inkEffects, Icons.tune, [ - controls, - ], collapsible: false), - section('variation', l.variation, Icons.gesture, [ - parameterGrid( - context, - parameters - .where( - (p) => - p.key.endsWith('_sigma') && - !p.key.startsWith('strikethrough_'), - ) - .toList(), - ), - ], expanded: false), - section('strike', l.strike, Icons.strikethrough_s, [ - SwitchListTile( - key: const ValueKey('enable-strikethrough'), - contentPadding: EdgeInsets.zero, - title: Text(l.enableStrikethrough), - value: settings.strikethroughEnabled, - onChanged: locked - ? null - : (enabled) { - settings.setStrikethroughEnabled(enabled); - onEdited(); - }, - ), - parameterGrid( - context, - parameters - .where((p) => p.key.startsWith('strikethrough_')) - .toList(), - ), - ], expanded: false), - ], - if (show(SettingsSection.presets)) - section('presets', l.presets, Icons.bookmarks_outlined, [ - Wrap( - spacing: 6, - children: [ - for (final preset in [ - (l.defaultPreset, onDefaultPreset), - (l.smallPreset, onSmallPreset), - (l.savePreset, onSavePreset), - (l.loadPreset, onLoadPreset), - (l.exportPreset, onExportPreset), - (l.importPreset, onImportPreset), - ]) - ActionChip( - label: Text(preset.$1), - onPressed: locked ? null : preset.$2, - ), - ], - ), - ], collapsible: false), ], ), ), @@ -513,119 +196,4 @@ class WorkbenchSettings extends StatelessWidget { ), ); } - - Widget section( - String id, - String title, - IconData icon, - List children, { - bool expanded = false, - bool collapsible = true, - }) { - return SettingsGroup( - key: PageStorageKey('settings-$id'), - title: title, - icon: icon, - initiallyExpanded: collapsible ? expanded : null, - children: children, - ); - } - - Widget settingSwitch( - String title, - bool value, - ValueChanged change, { - IconData? icon, - }) => SwitchListTile( - contentPadding: EdgeInsets.zero, - title: Text(title), - secondary: icon == null ? null : Icon(icon), - value: value, - onChanged: locked - ? null - : (next) { - change(next); - onEdited(); - }, - ); - - Widget parameterGrid( - BuildContext context, - List fields, - ) => LayoutBuilder( - builder: (context, constraints) { - final minWidth = 140 * MediaQuery.textScalerOf(context).scale(1); - final columns = constraints.maxWidth >= minWidth * 2 + 8 ? 2 : 1; - return Wrap( - spacing: 8, - runSpacing: 12, - children: [ - for (final p in fields) - SizedBox( - // TextField scroll offsets must not share the tile's stored bool. - key: PageStorageKey('parameter-${p.key}'), - width: (constraints.maxWidth - 8 * (columns - 1)) / columns, - child: Semantics( - identifier: p.key, - child: SettingsFieldLabel( - label: Localizations.localeOf(context).languageCode == 'en' - ? p.en - : p.zh, - child: TextFormField( - key: ValueKey( - p.key.startsWith('strikethrough_') - ? '${p.key}-$settingsRevision-${settings.strikethroughEnabled}' - : '${p.key}-$settingsRevision', - ), - initialValue: settings.values[p.key], - enabled: - !locked && - (!p.key.startsWith('strikethrough_') || - settings.strikethroughEnabled), - keyboardType: const TextInputType.numberWithOptions( - decimal: true, - ), - validator: (s) => p.accepts(s) - ? null - : AppLocalizations.of(context)!.validation, - onChanged: (s) { - settings.values[p.key] = s; - onEdited(); - }, - ), - ), - ), - ), - ], - ); - }, - ); -} - -/// Labels participate in layout rather than painting above an outlined field. -/// This keeps them inside scrolling and animated expansion clip boundaries. -class SettingsFieldLabel extends StatelessWidget { - const SettingsFieldLabel({ - super.key, - required this.label, - required this.child, - }); - - final String label; - final Widget child; - - @override - Widget build(BuildContext context) => Semantics( - label: label, - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - ExcludeSemantics( - child: Text(label, style: Theme.of(context).textTheme.labelLarge), - ), - const SizedBox(height: 6), - child, - ], - ), - ); } diff --git a/app/lib/widgets/workbench_shell.dart b/app/lib/widgets/workbench_shell.dart index 462d93a5..dc0fee7b 100644 --- a/app/lib/widgets/workbench_shell.dart +++ b/app/lib/widgets/workbench_shell.dart @@ -1,17 +1,17 @@ import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; +import '../l10n/app_localizations.dart'; import '../services/mcp_connection_stub.dart' if (dart.library.io) '../services/mcp_connection_native.dart'; - -import '../l10n/app_localizations.dart'; +import '../theme/handwriting_theme.dart'; import '../theme/nouveau_ornament.dart'; -import 'atelier_ornament.dart'; import 'project_source_link.dart'; +import 'theme_color_editor.dart'; import 'workbench_guide.dart'; +import 'workbench_masthead.dart'; import 'workbench_motion.dart'; -import 'theme_color_editor.dart'; -import '../theme/handwriting_theme.dart'; +import 'workbench_navigation.dart'; +import 'workbench_preferences.dart'; /// Adaptive app navigation and visible preference actions. Selection belongs to /// the caller; this shell only presents callbacks and responsive navigation. @@ -58,165 +58,54 @@ class WorkbenchShell extends StatelessWidget { @override Widget build(BuildContext context) { final l = AppLocalizations.of(context)!; - final showKeyboardDismiss = - MediaQuery.sizeOf(context).width < 1100 && - MediaQuery.viewInsetsOf(context).bottom > 0; - final labels = [l.workspace, l.guide, l.about]; - final compact = MediaQuery.sizeOf(context).width < 900; - final colors = Theme.of(context).colorScheme; - final dark = colors.brightness == Brightness.dark; - final mastheadInk = - Theme.of(context).appBarTheme.foregroundColor ?? colors.onSurface; - final usePaletteArt = + final size = WorkbenchWidth.from(MediaQuery.sizeOf(context).width); + final keyboardDismissAt = + !fineFullscreen && MediaQuery.viewInsetsOf(context).bottom > 0 + ? size + : null; + final theme = Theme.of(context); + final colors = theme.colorScheme; + final foreground = theme.appBarTheme.foregroundColor ?? colors.onSurface; + final palette = themeColor != defaultThemeColor || - secondaryThemeColor != defaultSecondaryThemeColor; + secondaryThemeColor != defaultSecondaryThemeColor + ? colors + : null; + void dismissKeyboard() => FocusScope.of(context).unfocus(); return Scaffold( appBar: fineFullscreen ? null - : AppBar( - toolbarHeight: compact ? 64 : 84, - titleSpacing: compact ? 6 : 18, - automaticallyImplyLeading: false, - centerTitle: false, - surfaceTintColor: Colors.transparent, - flexibleSpace: Stack( - children: [ - if (MediaQuery.sizeOf(context).width >= 1100) - Positioned( - top: 0, - bottom: 0, - left: 425, - right: 355, - child: Align( - alignment: Alignment.centerLeft, - child: CustomPaint( - size: const Size(340, 84), - painter: AtelierTendrils( - palette: usePaletteArt ? colors : null, - ), - ), - ), - ), - const Align( - alignment: Alignment.bottomCenter, - child: NouveauWaveDivider(height: 7), - ), - ], - ), - title: Row( - children: [ - CustomPaint( - size: Size.square(compact ? 48 : 78), - painter: AtelierIris( - palette: usePaletteArt ? colors : null, - ), - ), - SizedBox(width: compact ? 7 : 12), - Flexible( - child: Text( - compact ? labels[destination] : 'Panache', - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: Theme.of(context).textTheme.headlineLarge - ?.copyWith( - color: mastheadInk, - fontSize: compact ? 22 : 37, - fontFamily: 'Playfair Display', - fontFamilyFallback: const [ - 'packages/handwriting_assets/LXGW WenKai', - ], - height: 1.1, - letterSpacing: compact ? 0 : 1, - ), - ), - ), - if (!compact) ...[ - const SizedBox(width: 20), - Material( - animationDuration: Duration.zero, - color: mastheadInk.withValues(alpha: .07), - borderRadius: BorderRadius.circular(32), - child: ProjectSourceLink(foreground: mastheadInk), - ), - ], - ], - ), - bottom: !compact && showKeyboardDismiss - ? PreferredSize( - preferredSize: const Size.fromHeight(40), - child: Align( - alignment: Alignment.centerRight, - child: TextButton.icon( - style: TextButton.styleFrom( - foregroundColor: mastheadInk, - ), - onPressed: () => FocusScope.of(context).unfocus(), - icon: const Icon(Icons.keyboard_hide_outlined), - label: Text(l.dismissKeyboard), - ), - ), - ) + : workbenchMasthead( + context, + size: size, + title: size == WorkbenchWidth.compact + ? [l.workspace, l.guide, l.about][destination] + : 'Panache', + foreground: foreground, + palette: palette, + onDismissKeyboard: keyboardDismissAt == WorkbenchWidth.medium + ? dismissKeyboard : null, - actions: [ - if (!compact) ...[ - IconButton( - key: const ValueKey('open-guide'), - tooltip: guideUnread - ? '${l.guide} · ${l.guideUnread}' - : l.guide, - onPressed: () => onDestinationSelected(1), - icon: GuideUnreadBadge( - unread: guideUnread, - child: const Icon(Icons.menu_book_outlined), - ), - ), - IconButton( - tooltip: l.about, - onPressed: () => onDestinationSelected(2), - icon: Badge( - isLabelVisible: updateAvailable, - child: const Icon(Icons.info_outline), - ), - ), - ], - Semantics( - hint: guideUnread && compact ? l.guideUnread : null, - child: TextButton.icon( - key: const ValueKey('app-preferences'), - style: TextButton.styleFrom(foregroundColor: mastheadInk), - onPressed: () => preferencesSheet(context), - icon: Badge( - isLabelVisible: - compact && (updateAvailable || guideUnread), - backgroundColor: updateAvailable - ? null - : usePaletteArt - ? colors.secondary - : NouveauColors.gold, - child: const Icon(Icons.tune), - ), - label: Text(l.appPreferences), - ), - ), - if (MediaQuery.sizeOf(context).width >= 1100) ...[ - IconButton( - tooltip: l.language, - onPressed: onToggleLocale, - icon: const Icon(Icons.translate), - ), - IconButton( - tooltip: l.theme, - onPressed: onToggleTheme, - icon: const Icon(Icons.contrast), - ), - ], - SizedBox(width: compact ? 3 : 16), - ], + actions: workbenchAppActions( + l, + size: size, + guideUnread: guideUnread, + updateAvailable: updateAvailable, + foreground: foreground, + unreadColor: palette?.secondary ?? NouveauColors.gold, + onDestinationSelected: onDestinationSelected, + onPreferences: () => preferencesSheet(context), + onToggleLocale: onToggleLocale, + onToggleTheme: onToggleTheme, + ), ), body: SafeArea( child: LayoutBuilder( builder: (context, constraints) { - final wide = !fineFullscreen && constraints.maxWidth >= 900; + final wide = + !fineFullscreen && + WorkbenchWidth.from(constraints.maxWidth) != + WorkbenchWidth.compact; final content = RetainedPaneSwitcher( index: destination == 0 ? 0 : 1, children: [ @@ -237,7 +126,7 @@ class WorkbenchShell extends StatelessWidget { ), ], ); - return dark + return colors.brightness == Brightness.dark ? DecoratedBox( decoration: BoxDecoration( gradient: NightSurfaces.backdrop(colors.surface), @@ -248,13 +137,10 @@ class WorkbenchShell extends StatelessWidget { }, ), ), - floatingActionButton: - !fineFullscreen && - MediaQuery.sizeOf(context).width < 900 && - MediaQuery.viewInsetsOf(context).bottom > 0 + floatingActionButton: keyboardDismissAt == WorkbenchWidth.compact ? FloatingActionButton.small( tooltip: l.dismissKeyboard, - onPressed: () => FocusScope.of(context).unfocus(), + onPressed: dismissKeyboard, child: const Icon(Icons.keyboard_hide_outlined), ) : null, @@ -326,31 +212,7 @@ class WorkbenchShell extends StatelessWidget { }, ), if (mcpConfig != null) - ListTile( - key: const ValueKey('connect-ai-client'), - leading: const Icon(Icons.hub_outlined), - title: Text(l.connectAiClient), - subtitle: Text(l.copyMcpConfig), - trailing: const Icon(Icons.copy_outlined), - onTap: () async { - final messenger = ScaffoldMessenger.of(context); - try { - await Clipboard.setData(ClipboardData(text: mcpConfig)); - } on PlatformException { - if (messenger.mounted) { - messenger.showSnackBar( - SnackBar(content: Text(l.mcpCopyFailed)), - ); - } - return; - } - if (!sheetContext.mounted) return; - Navigator.pop(sheetContext); - messenger.showSnackBar( - SnackBar(content: Text(l.mcpConfigCopied)), - ); - }, - ), + mcpConnectionTile(context, sheetContext, l, mcpConfig), ListTile( leading: const Icon(Icons.translate), title: Text(l.language), @@ -359,52 +221,12 @@ class WorkbenchShell extends StatelessWidget { onToggleLocale(); }, ), - ListTile( - leading: const Icon(Icons.contrast), - title: Text(l.theme), - subtitle: Text(switch (themeMode) { - ThemeMode.system => l.themeSystem, - ThemeMode.light => l.themeLight, - ThemeMode.dark => l.themeDark, - }), - trailing: onThemeModeChanged == null - ? null - : PopupMenuButton( - tooltip: l.chooseTheme, - icon: const Icon(Icons.expand_more), - initialValue: themeMode, - itemBuilder: (_) => [ - for (final (mode, label) in [ - (ThemeMode.system, l.themeSystem), - (ThemeMode.light, l.themeLight), - (ThemeMode.dark, l.themeDark), - ]) - CheckedPopupMenuItem( - value: mode, - checked: themeMode == mode, - child: Text(label), - ), - ], - onSelected: (value) { - final nextBrightness = switch (value) { - ThemeMode.system => - MediaQuery.platformBrightnessOf(sheetContext), - ThemeMode.light => Brightness.light, - ThemeMode.dark => Brightness.dark, - }; - if (Theme.of(sheetContext).brightness == - nextBrightness) { - Navigator.pop(sheetContext); - } else { - _dismissForAppearanceChange(sheetContext); - } - onThemeModeChanged!(value); - }, - ), - onTap: () { - _dismissForAppearanceChange(sheetContext); - onToggleTheme(); - }, + themePreferenceTile( + sheetContext, + l, + themeMode: themeMode, + onThemeModeChanged: onThemeModeChanged, + onToggleTheme: onToggleTheme, ), ThemeColorEditor( color: themeColor, @@ -457,10 +279,3 @@ class WorkbenchShell extends StatelessWidget { ); } } - -// The global appearance transition already blends the painted sheet into the -// new workbench. Retiring its route immediately avoids laying out and animating -// the outgoing sheet in a second theme on every frame of that same gesture. -void _dismissForAppearanceChange(BuildContext sheetContext) { - Navigator.of(sheetContext).removeRoute(ModalRoute.of(sheetContext)!); -} diff --git a/app/lib/widgets/workbench_task_status.dart b/app/lib/widgets/workbench_task_status.dart new file mode 100644 index 00000000..ada60a70 --- /dev/null +++ b/app/lib/widgets/workbench_task_status.dart @@ -0,0 +1,77 @@ +import 'package:flutter/material.dart'; + +import '../l10n/app_localizations.dart'; +import 'workbench_motion.dart'; + +List workbenchTaskStatus( + BuildContext context, { + required String error, + required int? queueWaitSeconds, + required bool generating, + required String phase, + required String stage, + required int pagesCompleted, + required VoidCallback? onCancel, + required VoidCallback onDismissError, +}) { + final l = AppLocalizations.of(context)!; + final taskStatus = generating + ? Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + const LinearProgressIndicator(), + const SizedBox(height: 8), + if (onCancel != null) + TextButton.icon( + key: const ValueKey('cancel-generation'), + onPressed: onCancel, + icon: const Icon(Icons.cancel_outlined), + label: Text(l.stopGeneration), + ), + Text(switch (phase) { + 'pending' => l.pending, + 'completed' => l.completed, + 'cancelling' => l.stoppingTask, + _ => stage == 'exporting' ? l.exportingTask : l.processing, + }), + if (pagesCompleted > 0) Text(l.generatedPages(pagesCompleted)), + ], + ), + ) + : const SizedBox(width: double.infinity); + return [ + if (error.isNotEmpty) + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 0), + child: Material( + animationDuration: Duration.zero, + color: Theme.of(context).colorScheme.errorContainer, + borderRadius: BorderRadius.circular(16), + child: ListTile( + leading: const Icon(Icons.error_outline), + title: Text( + error == 'validation' + ? l.validation + : queueWaitSeconds != null + ? '${l.queueFull} ${queueWaitSeconds}s' + : error, + ), + trailing: TextButton.icon( + label: Text(l.close), + onPressed: onDismissError, + icon: const Icon(Icons.close), + ), + ), + ), + ), + MediaQuery.disableAnimationsOf(context) + ? taskStatus + : AnimatedSize( + duration: WorkbenchMotion.pane, + curve: Curves.easeInOut, + alignment: Alignment.topCenter, + child: taskStatus, + ), + ]; +} diff --git a/app/lib/widgets/zoomable_preview_page.dart b/app/lib/widgets/zoomable_preview_page.dart new file mode 100644 index 00000000..0789c04d --- /dev/null +++ b/app/lib/widgets/zoomable_preview_page.dart @@ -0,0 +1,363 @@ +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter/gestures.dart'; + +import '../l10n/app_localizations.dart'; +import '../models/fine_edit.dart'; +import '../models/ink_page.dart'; +import '../utils/ink_effects.dart'; +import 'fine_preview.dart'; +import 'live_ink_preview.dart'; +import 'preview_image_actions.dart'; +import 'preview_zoom.dart'; +import 'workbench_motion.dart'; + +class ZoomablePreviewPage extends StatefulWidget { + const ZoomablePreviewPage({ + super.key, + required this.bytes, + required this.heroTag, + required this.active, + required this.reset, + required this.onZoomChanged, + required this.onOpen, + required this.copyImage, + required this.readerMode, + required this.ink, + required this.look, + required this.fineEdits, + required this.enlargeInitially, + }); + final Uint8List bytes; + final Object heroTag; + final bool active; + final int reset; + final ValueChanged onZoomChanged; + final VoidCallback? onOpen; + final ImageClipboardWriter copyImage; + final bool readerMode; + final InkPage? ink; + final InkLook look; + final Map fineEdits; + final bool enlargeInitially; + + @override + State createState() => _ZoomablePageState(); +} + +class _ZoomablePageState extends State + with SingleTickerProviderStateMixin { + late final _transform = TransformationController()..addListener(_changed); + late final _animation = AnimationController( + vsync: this, + duration: WorkbenchMotion.page, + )..addListener(_animate); + // Translation events leave the reader scale controls unchanged. + final _readerControls = ValueNotifier((100, true, true)); + Matrix4Tween? _tween; + bool _zoomed = false; + bool _dragging = false; + bool _manualZoom = false; + Size? _defaultZoomViewport; + Offset _doubleTapPoint = Offset.zero; + Size _viewport = Size.zero; + double get _scale => _transform.value.getMaxScaleOnAxis(); + double get _minScale => widget.readerMode ? .25 : 1; + double get _maxScale => widget.readerMode ? 8 : 5; + + void _animate() { + _transform.value = _tween!.transform( + Curves.easeOutCubic.transform(_animation.value), + ); + } + + void _to(Matrix4 destination) { + _animation.stop(); + if (MediaQuery.disableAnimationsOf(context)) { + _transform.value = destination; + } else { + _tween = Matrix4Tween(begin: _transform.value.clone(), end: destination); + _animation.forward(from: 0); + } + } + + void _zoomTo(double scale, Offset focalPoint) { + final target = scale.clamp(_minScale, _maxScale); + final scene = _transform.toScene(focalPoint); + _to( + Matrix4.identity() + ..translateByDouble( + focalPoint.dx - scene.dx * target, + focalPoint.dy - scene.dy * target, + 0, + 1, + ) + ..scaleByDouble(target, target, target, 1), + ); + } + + void _reset() => _to(Matrix4.identity()); + + void _updateReaderControls() { + if (!widget.readerMode) return; + final scale = _scale; + _readerControls.value = ( + (scale * 100).round(), + scale > _minScale + .001, + scale < _maxScale - .001, + ); + } + + void _changed() { + _updateReaderControls(); + final zoomed = widget.readerMode + ? (_scale - 1).abs() > .001 || + _transform.value.getTranslation().length > .1 + : _scale > 1.01; + if (zoomed == _zoomed) return; + setState(() => _zoomed = zoomed); + if (widget.active) widget.onZoomChanged(zoomed); + } + + @override + void didUpdateWidget(ZoomablePreviewPage oldWidget) { + super.didUpdateWidget(oldWidget); + final layoutChanged = oldWidget.enlargeInitially != widget.enlargeInitially; + if (layoutChanged || oldWidget.active != widget.active) { + _defaultZoomViewport = null; + _manualZoom = false; + } else if (oldWidget.reset != widget.reset && widget.active) { + _manualZoom = true; + } + if (layoutChanged || + oldWidget.reset != widget.reset || + oldWidget.active && !widget.active) { + // Parent already clears its zoom flag; do not notify during its build. + _animation.stop(); + _transform.removeListener(_changed); + _transform.value = Matrix4.identity(); + _zoomed = false; + _transform.addListener(_changed); + } + _updateReaderControls(); + } + + void _scheduleInitialZoom() { + if (_manualZoom || + _viewport == _defaultZoomViewport || + !widget.active || + !widget.enlargeInitially || + _viewport.isEmpty) { + return; + } + final size = previewPngSize(widget.bytes); + if (size == null) return; + _defaultZoomViewport = _viewport; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted || + _manualZoom || + !widget.active || + !widget.enlargeInitially || + _viewport.isEmpty) { + return; + } + final glyphs = widget.ink?.fine?.glyphs; + var top = size.height; + for (final glyph in glyphs ?? const []) { + if (glyph.y < top) top = glyph.y.toDouble(); + } + _transform.value = initialPreviewZoom( + _viewport, + size, + contentTop: top == size.height ? 0 : top, + ); + }); + } + + @override + void dispose() { + _animation.dispose(); + _transform.dispose(); + _readerControls.dispose(); + super.dispose(); + } + + void _pointerDown(PointerDownEvent event) { + _animation.stop(); + if (!widget.readerMode) return; + setState(() { + _dragging = + event.kind == PointerDeviceKind.mouse && + event.buttons == kPrimaryMouseButton; + }); + } + + void _pointerMove(PointerMoveEvent event) { + if (!_dragging || event.buttons != kPrimaryMouseButton) return; + // Apply even short mouse deltas below the scale gesture slop. + final matrix = _transform.value.clone(); + matrix.setEntry(0, 3, matrix.entry(0, 3) + event.localDelta.dx); + matrix.setEntry(1, 3, matrix.entry(1, 3) + event.localDelta.dy); + _transform.value = matrix; + } + + void _releasePointer(PointerEvent _) { + if (_dragging) setState(() => _dragging = false); + } + + Widget _image(AppLocalizations l) { + final ink = widget.ink; + final look = widget.look; + final copy = widget.copyImage; + if (ink?.fine != null) { + return SizedBox.expand( + child: FinePreview( + page: ink!, + look: look, + edits: widget.fineEdits, + copyImage: copy, + ), + ); + } + return PreviewImageActions( + bytes: widget.bytes, + onOpen: widget.onOpen, + copyImage: ink == null + ? copy + : (_) async => copy(await compositeInkPage(ink, look)), + child: Semantics( + identifier: widget.active ? 'preview-image' : null, + child: ink != null + ? LiveInkPreview(page: ink, look: look, label: l.preview) + : Image.memory( + widget.bytes, + fit: BoxFit.contain, + gaplessPlayback: true, + semanticLabel: l.preview, + ), + ), + ); + } + + Widget _viewer(AppLocalizations l) { + return RepaintBoundary( + child: Padding( + padding: const EdgeInsets.all(12), + child: LayoutBuilder( + builder: (context, constraints) { + _viewport = constraints.biggest; + _scheduleInitialZoom(); + return MouseRegion( + cursor: widget.readerMode + ? (_dragging + ? SystemMouseCursors.grabbing + : SystemMouseCursors.grab) + : MouseCursor.defer, + child: Listener( + onPointerDown: _pointerDown, + onPointerUp: _releasePointer, + onPointerMove: _pointerMove, + onPointerCancel: _releasePointer, + child: GestureDetector( + onDoubleTapDown: widget.readerMode + ? (details) => _doubleTapPoint = details.localPosition + : null, + onDoubleTap: widget.readerMode + ? () => _zoomed ? _reset() : _zoomTo(2.5, _doubleTapPoint) + : null, + child: InteractiveViewer( + key: widget.readerMode + ? const ValueKey('reader-canvas') + : null, + transformationController: _transform, + onInteractionStart: (_) { + _manualZoom = true; + _animation.stop(); + }, + panEnabled: _zoomed && !_dragging, + boundaryMargin: widget.readerMode + ? const EdgeInsets.all(double.infinity) + : EdgeInsets.zero, + minScale: _minScale, + maxScale: _maxScale, + child: Center( + child: HeroMode( + enabled: + widget.active && + !MediaQuery.disableAnimationsOf(context), + child: Hero( + tag: widget.heroTag, + transitionOnUserGestures: true, + child: _image(l), + ), + ), + ), + ), + ), + ), + ); + }, + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + final l = AppLocalizations.of(context)!; + final viewer = _viewer(l); + if (!widget.readerMode) return viewer; + return Column( + children: [ + Expanded(child: viewer), + ValueListenableBuilder( + valueListenable: _readerControls, + builder: (_, controls, _) => Wrap( + alignment: WrapAlignment.center, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + TextButton.icon( + key: const ValueKey('reader-zoom-out'), + onPressed: controls.$2 + ? () => _zoomTo(_scale / 1.5, _viewport.center(Offset.zero)) + : null, + icon: const Icon(Icons.zoom_out), + label: Text(l.previewZoomOut), + ), + Tooltip( + message: l.previewZoomRatioHint, + child: Text( + '${controls.$1}%', + key: const ValueKey('reader-zoom-ratio'), + ), + ), + TextButton.icon( + key: const ValueKey('reader-zoom-in'), + onPressed: controls.$3 + ? () => _zoomTo(_scale * 1.5, _viewport.center(Offset.zero)) + : null, + icon: const Icon(Icons.zoom_in), + label: Text(l.previewZoomIn), + ), + TextButton.icon( + key: const ValueKey('preview-reset-zoom'), + onPressed: _reset, + icon: const Icon(Icons.fit_screen_outlined), + label: Text(l.resetPreviewZoom), + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + child: Text( + l.previewReaderHint, + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodySmall, + ), + ), + ], + ); + } +} diff --git a/app/test/chemistry_course_test.dart b/app/test/chemistry_course_test.dart index dcf0eb59..9c9b07e0 100644 --- a/app/test/chemistry_course_test.dart +++ b/app/test/chemistry_course_test.dart @@ -80,6 +80,34 @@ void main() { expect(convertLatex(cleanMarkdown(source)), source); }); } + test('分数系数保留各位数字,分母全零才退回原文', () { + for (final denominator in ['0', '000', '0' * 128]) { + final source = '\\ce{H2 + 1/$denominator O2}'; + expect(normalizeCourseLatex(source), source); + expect( + normalizeCourseLatex( + '$source +' + r'\num{2e3}', + ), + '$source +' + r'2\times10^{3}', + ); + expect(convertLatex('\$$source\$'), '\$$source\$'); + } + for (final (numerator, denominator) in [ + ('0', '02'), + ('123456789012345678901234567890', '2'), + ('1', '9223372036854775807'), + ('1', '9223372036854775808'), + ('1', '9' * 128), + ('1', '${'0' * 32}2'), + ]) { + expect( + normalizeCourseLatex('\\ce{$numerator/$denominator O2}'), + '\\mathrm{\\frac{$numerator}{$denominator}\\,O_{2}}', + ); + } + }); test('化学长度预算和文字语境', () { final huge = r'\ce{' diff --git a/app/test/course_notation_test.dart b/app/test/course_notation_test.dart index ec5434f4..248e50b3 100644 --- a/app/test/course_notation_test.dart +++ b/app/test/course_notation_test.dart @@ -65,6 +65,32 @@ void main() { expect(normalizeCourseLatex(source), source); } }); + test('分母、前缀和幂次只作用于紧邻的单位', () { + expect( + normalizeCourseLatex( + r'\unit{\per\milli\second\squared\metre\tothe{+003}\per\volt}', + ), + r'\mathrm{m}^{3}/(\mathrm{ms}^{2}\,\mathrm{V})', + ); + for (final unit in [ + r'\metre\squared\cubed', + r'\kilo\per\metre', + r'\per\micro', + r'\metre\tothe{1000}', + r'\metre\squared{2}', + r'\metre?\per\second', + ]) { + final invalid = '\\qty {1} {$unit}'; + expect( + normalizeCourseLatex( + '$invalid + ' + r'\num{2e3}', + ), + '$invalid + ' + r'2\times10^{3}', + ); + } + }); test('表格文字不能伪装成矩阵协议,空格子显式占位', () { expect( convertLatex( diff --git a/app/test/desktop_bootstrap_recovery_test.dart b/app/test/desktop_bootstrap_recovery_test.dart new file mode 100644 index 00000000..8f41550b --- /dev/null +++ b/app/test/desktop_bootstrap_recovery_test.dart @@ -0,0 +1,111 @@ +import 'dart:async'; +import 'dart:ui' show AppExitResponse, AppExitType; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:handwriting_app/l10n/app_localizations.dart'; +import 'package:handwriting_app/services/desktop_bootstrap.dart'; +import 'package:handwriting_app/services/desktop_exit.dart'; +import 'package:panache_updater/client.dart' as updater; + +class _ExitBinding extends AutomatedTestWidgetsFlutterBinding { + final exits = >[]; + + @override + Future exitApplication( + AppExitType exitType, [ + int exitCode = 0, + ]) { + expect(exitType, AppExitType.cancelable); + expect(desktopUpdateExitRequested, isTrue); + final response = Completer(); + exits.add(response); + return response.future; + } +} + +class _Recovery extends Fake implements updater.PreparedDesktopUpdate { + int arms = 0, aborts = 0; + final released = Completer(); + + @override + void arm() => arms++; + + @override + Future abort() { + aborts++; + return released.future; + } +} + +void main() { + final binding = _ExitBinding(); + + for (final abortFails in [false, true]) { + testWidgets( + 'refused recovery exit allows a retry when helper abort ${abortFails ? 'fails' : 'succeeds'}', + (tester) async { + binding.exits.clear(); + const channel = MethodChannel('plugins.flutter.io/path_provider'); + binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, ( + call, + ) async { + expect(call.method, 'getApplicationSupportDirectory'); + return '/support'; + }); + addTearDown(() { + binding.defaultBinaryMessenger.setMockMethodCallHandler( + channel, + null, + ); + desktopUpdateExitRequested = false; + }); + final sessions = <_Recovery>[]; + await tester.pumpWidget( + DesktopBootstrap( + builder: (_) => + throw StateError('Unexpected workspace during recovery'), + recoverInterruptedUpdate: (_) async { + final session = _Recovery(); + sessions.add(session); + return session; + }, + ), + ); + await tester.pump(); + final l = AppLocalizations.of(tester.element(find.byType(Scaffold)))!; + expect(sessions.single.arms, 1); + binding.exits.single.complete(AppExitResponse.cancel); + await tester.pump(); + expect(desktopUpdateExitRequested, isFalse); + expect(sessions.single.aborts, 1); + expect(find.text(l.backendRetry), findsNothing); + + if (abortFails) { + sessions.single.released.completeError( + StateError('Helper pipe closed'), + ); + } else { + sessions.single.released.complete(); + } + await tester.pump(); + await tester.pump(); + expect(find.text(l.backendFailed), findsOneWidget); + await tester.tap(find.text(l.backendRetry)); + await tester.tap(find.text(l.backendRetry)); + await tester.pump(); + expect(sessions, hasLength(2)); + expect(sessions.last.arms, 1); + expect(binding.exits, hasLength(2)); + binding.exits.last.complete(AppExitResponse.exit); + await tester.pump(); + expect(desktopUpdateExitRequested, isTrue); + expect(find.text(l.backendStarting), findsOneWidget); + expect(find.text(l.backendRetry), findsNothing); + await tester.pumpWidget(const SizedBox.shrink()); + expect(sessions.map((s) => s.aborts), [1, 0]); + }, + ); + } +} diff --git a/app/test/desktop_update_test.dart b/app/test/desktop_update_test.dart index 7d9258ed..1c727381 100644 --- a/app/test/desktop_update_test.dart +++ b/app/test/desktop_update_test.dart @@ -204,6 +204,32 @@ void main() { expect(host.events, ['download', 'prepare', 'abort']); expect(c.phase, UpdatePhase.ready); }); + test( + 'cancelling during persistence leaves the downloaded package unarmed', + () async { + final host = Host(); + final c = await controller(host); + addTearDown(c.dispose); + final saving = Completer(); + final saved = Completer(); + final action = c.updateAndRestart( + canRestart: () => true, + persist: () { + saving.complete(); + return saved.future; + }, + requestExit: () async => fail('cancelled before the save completed'), + ); + await saving.future; + c.cancel(); + saved.complete(true); + await action; + expect(host.events, contains('abort')); + expect(host.events, isNot(contains('arm'))); + expect(c.phase, UpdatePhase.ready); + expect(c.downloadedPath, '/cache/update.zip'); + }, + ); test('cancel during download revokes complete restart chain', () async { final host = Host()..downloadHold = Completer(); final c = await controller(host); diff --git a/app/test/detected_paper_layout_test.dart b/app/test/detected_paper_layout_test.dart new file mode 100644 index 00000000..aa714d86 --- /dev/null +++ b/app/test/detected_paper_layout_test.dart @@ -0,0 +1,28 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:handwriting_app/models/detected_paper_layout.dart'; + +void main() { + test('legacy top lines and corrected dimensions use the detector coordinate system', () { + final layout = DetectedPaperLayout.fromJson({ + 'lineSpacing': 9, + 'marginTop': 21, + 'marginBottom': 19, + 'marginLeft': 50, + 'marginRight': 35, + 'imageWidth': 300, + 'imageHeight': 200, + }); + expect(layout.scaledTo(300, 200), same(layout)); + final settings = layout.scaledTo(160, 91).settings('4'); + expect(settings, { + 'width': '160', + 'height': '91', + 'top_margin': '5', + 'bottom_margin': '9', + 'left_margin': '27', + 'right_margin': '19', + 'line_spacing': '4', + 'font_size': '3', + }); + }); +} diff --git a/app/test/editor_preparation_test.dart b/app/test/editor_preparation_test.dart new file mode 100644 index 00000000..bf5d153d --- /dev/null +++ b/app/test/editor_preparation_test.dart @@ -0,0 +1,126 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:handwriting_app/screens/editor_preparation.dart'; +import 'package:handwriting_app/services/text_preparation/prepare.dart'; + +class _Job implements TextPreparationJob { + final output = Completer(); + int cancellations = 0; + + @override + Future get result => output.future; + + @override + Future cancel() async => cancellations++; +} + +void main() { + late EditorPreparation preparation; + late String text; + late List<_Job> jobs; + late List<(String, String, bool)> requests; + late List<(bool, bool)> states; + late int failures; + + setUp(() { + text = 'draft'; + jobs = []; + requests = []; + states = []; + failures = 0; + preparation = + EditorPreparation( + readText: () => text, + applyText: (value) => text = value, + onFailure: () => failures++, + start: (input, {required tableMode, required english}) { + requests.add((input, tableMode, english)); + final job = _Job(); + jobs.add(job); + return job; + }, + )..addListener(() { + states.add((preparation.running, preparation.stopping)); + }); + }); + + test( + 'reformatting starts from the original and creates one undo step', + () async { + final first = preparation.run('latex', english: true); + jobs.single.output.complete('formatted'); + await first; + expect(text, 'formatted'); + expect(preparation.undoText(text), 'draft'); + expect(preparation.redoText('draft'), 'formatted'); + await preparation.run('latex', english: false); + expect(jobs, hasLength(1)); + final next = preparation.run('plain', english: false); + jobs.last.output.complete('table'); + await next; + expect(requests, [('draft', 'latex', true), ('draft', 'plain', false)]); + expect(preparation.undoText('table'), 'draft'); + expect(preparation.redoText('draft'), 'table'); + preparation.forgetFormatting(); + expect(preparation.undoText('table'), isNull); + expect(preparation.redoText('draft'), isNull); + expect(states, [ + (true, false), + (false, false), + (true, false), + (false, false), + ]); + preparation.dispose(); + }, + ); + + test('cancel is idempotent and discards a successful late result', () async { + final pending = preparation.run('latex', english: false); + await preparation.stop(); + await preparation.stop(); + await preparation.run('plain', english: false); + expect(jobs.single.cancellations, 1); + jobs.single.output.complete('too late'); + await pending; + expect(text, 'draft'); + expect(failures, 0); + expect(states, [(true, false), (true, true), (false, false)]); + preparation.dispose(); + }); + + test( + 'changed input, cancellation, and failures retain the current draft', + () async { + final pending = preparation.run('latex', english: false); + text = 'new input'; + jobs.single.output.complete('old output'); + await pending; + for (final error in [ + const TextPreparationCancelled(), + StateError('worker'), + ]) { + final retry = preparation.run('plain', english: false); + jobs.last.output.completeError(error); + await retry; + } + expect(text, 'new input'); + expect(failures, 1); + expect(preparation.undoText(text), isNull); + preparation.dispose(); + }, + ); + + test( + 'disposing cancels work without applying results or notifying the page', + () async { + final pending = preparation.run('latex', english: true); + preparation.dispose(); + expect(jobs.single.cancellations, 1); + jobs.single.output.complete('too late'); + await pending; + expect(text, 'draft'); + expect(states, [(true, false)]); + }, + ); +} diff --git a/app/test/fine_edit_history_test.dart b/app/test/fine_edit_history_test.dart new file mode 100644 index 00000000..bb25c26f --- /dev/null +++ b/app/test/fine_edit_history_test.dart @@ -0,0 +1,63 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:handwriting_app/models/fine_edit.dart'; +import 'package:handwriting_app/models/fine_edit_history.dart'; + +FineAdjustment moved(int id, int dx) => ( + id: id, + dx: dx, + dy: 0, + scale: 100, + angle: 0, + opacity: 100, + color: null, + thickness: 0, + softness: 0, + warp: null, +); + +void main() { + test('history follows the source text and rendered layout', () { + final history = FineEditHistory(); + final key = 'a' * 64; + final newKey = 'b' * 64; + final first = moved(1, 4); + expect(history.apply('draft', key, [first]), isTrue); + expect(history.apply('draft', key, [first]), isFalse); + expect(history.forText('revised'), isNull); + expect(history.adjustmentsFor(key), {1: first}); + expect(history.adjustmentsFor(newKey), isEmpty); + expect(history.step('revised', key, redo: false), isFalse); + expect(history.step('draft', newKey, redo: false), isFalse); + expect(history.step('draft', key, redo: false), isTrue); + expect(history.forText('draft')!.glyphs, isEmpty); + expect(history.canStep('draft', key, redo: false), isFalse); + expect(history.step('draft', key, redo: true), isTrue); + expect(history.adjustmentsFor(key), {1: first}); + + final second = moved(2, 8); + expect(history.apply('revised', newKey, [second]), isTrue); + expect(history.adjustmentsFor(newKey), {2: second}); + expect(history.step('revised', newKey, redo: false), isTrue); + expect(history.adjustmentsFor(newKey), isEmpty); + expect(history.canStep('revised', newKey, redo: false), isFalse); + expect(history.apply('revised', newKey, [first]), isTrue); + expect(history.canStep('revised', newKey, redo: true), isFalse); + }); + + test('history bounds reject the whole oversized edit and preserve redo', () { + final history = FineEditHistory(); + final key = 'a' * 64; + for (var i = 1; i <= 51; i++) { + history.apply('draft', key, [moved(1, i)]); + } + for (var i = 0; i < 50; i++) { + expect(history.step('draft', key, redo: false), isTrue); + } + expect(history.step('draft', key, redo: false), isFalse); + expect(history.adjustmentsFor(key), {1: moved(1, 1)}); + final oversized = [for (var i = 0; i <= 10000; i++) moved(i, 7)]; + expect(history.apply('draft', key, oversized), isFalse); + expect(history.step('draft', key, redo: true), isTrue); + expect(history.adjustmentsFor(key), {1: moved(1, 2)}); + }); +} diff --git a/app/test/fine_selection_drag_test.dart b/app/test/fine_selection_drag_test.dart new file mode 100644 index 00000000..7a24aa77 --- /dev/null +++ b/app/test/fine_selection_drag_test.dart @@ -0,0 +1,83 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:handwriting_app/models/fine_edit.dart'; +import 'package:handwriting_app/view_models/fine_selection.dart'; +import 'package:handwriting_app/view_models/fine_selection_drag.dart'; + +void main() { + final page = FinePage('layout', Uint8List(0), const [ + FineGlyph(7, 0, 0, 20, 20, 0, 0, 20, null), + ]); + test('only the owning mouse crosses screen slop to move a new hit', () { + final selection = FineSelection(); + final drag = FineSelectionDrag.begin( + selection, + page, + const {}, + pointer: 3, + start: const Offset(10, 10), + screen: const Offset(240, 90), + touch: false, + shift: false, + ); + expect(drag.action, FineDragAction.move); + expect(drag.acceptsMove(5, const Offset(300, 90)), isFalse); + expect(drag.acceptsMove(3, const Offset(243.9, 90)), isFalse); + expect(drag.acceptsMove(3, const Offset(244, 90)), isTrue); + expect(drag.selectMoveTarget(selection, mouse: true), isTrue); + expect(selection.selected, {7}); + }); + + test('touch tap selects but a drag in tap mode leaves selection intact', () { + final selection = FineSelection(); + final drag = FineSelectionDrag.begin( + selection, + page, + const {}, + pointer: 1, + start: const Offset(10, 10), + screen: Offset.zero, + touch: true, + shift: true, + ); + expect(drag.action, FineDragAction.tap); + expect( + drag.finishSelection( + selection, + page, + const {}, + Offset.zero, + mouse: false, + ), + isTrue, + ); + expect(selection.selected, {7}); + selection.select([]); + drag.moved = true; + expect( + drag.finishSelection( + selection, + page, + const {}, + Offset.zero, + mouse: false, + ), + isFalse, + ); + expect(selection.selected, isEmpty); + }); + + test( + 'perspective handle hit includes the radius and prefers the later tie', + () { + final frame = FinePerspectiveFrame(const [ + Offset(0, 0), + Offset(10, 0), + ], {}); + final touch = FineCornerDrag.hit(1, const Offset(5, 0), frame, 5); + expect(touch?.index, 1); + expect(FineCornerDrag.hit(1, const Offset(5, 0), frame, 4.9), isNull); + }, + ); +} diff --git a/app/test/fine_selection_test.dart b/app/test/fine_selection_test.dart new file mode 100644 index 00000000..3379704b --- /dev/null +++ b/app/test/fine_selection_test.dart @@ -0,0 +1,78 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:handwriting_app/models/fine_edit.dart'; +import 'package:handwriting_app/view_models/fine_selection.dart'; + +void main() { + test( + 'source selection uses overlaps and preserves picks on unmapped pages', + () { + const first = FineGlyph(5, 0, 0, 8, 8, 0, 0, 8, (start: 0, end: 3), 5); + const detail = FineGlyph(9, 8, 0, 8, 8, 8, 0, 8, null, 5); + const next = FineGlyph(3, 16, 0, 8, 8, 16, 0, 8, (start: 3, end: 4)); + final page = FinePage('page', Uint8List(0), [first, detail, next]); + final selection = FineSelection()..selectIllustration(page, 5); + expect(selection.selected.toList(), [5, 9]); + + selection.selectSource(FinePage('unmapped', Uint8List(0), [detail]), ( + start: 3, + end: 4, + )); + expect(selection.selected.toList(), [5, 9]); + selection.selectSource(page, (start: 3, end: 4)); + expect(selection.selected.toList(), [3]); + selection.selectSource(page, (start: 2, end: 4)); + expect(selection.selected.toList(), [5, 3]); + selection.selectSource(page, (start: 4, end: 5)); + expect(selection.selected, isEmpty); + }, + ); + + test('selection adjustments keep each glyph geometry and untouched ink', () { + const previous = ( + id: 7, + dx: 2, + dy: -1, + scale: 125, + angle: 7, + opacity: 42, + color: 0xff336699, + thickness: 1, + softness: 2, + warp: (1.0, 0.1, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0), + ); + final edits = { + 7: previous, + 8: defaultFineAdjustment(8), + }; + final selection = FineSelection()..select([9, 7]); + final changed = selection.adjust(edits, opacity: 0, thickness: -2); + expect(changed.map((edit) => edit.id), [9, 7]); + expect(changed.first, ( + id: 9, + dx: 0, + dy: 0, + scale: 100, + angle: 0, + opacity: 0, + color: null, + thickness: -2, + softness: 0, + warp: null, + )); + expect(changed.last, ( + id: 7, + dx: 2, + dy: -1, + scale: 125, + angle: 7, + opacity: 0, + color: 0xff336699, + thickness: -2, + softness: 2, + warp: previous.warp, + )); + expect(edits, {7: previous, 8: defaultFineAdjustment(8)}); + }); +} diff --git a/app/test/generation_view_model_test.dart b/app/test/generation_view_model_test.dart index abed76ad..99a501aa 100644 --- a/app/test/generation_view_model_test.dart +++ b/app/test/generation_view_model_test.dart @@ -11,6 +11,7 @@ class ControlledEngine implements EngineGateway { final exited = Completer(); final cancelled = []; bool failIdentity = false; + int previewReads = 0; @override bool get supportsCancel => true; @override @@ -32,9 +33,13 @@ class ControlledEngine implements EngineGateway { Future status(String id) async => const EngineTask(phase: TaskPhase.completed, progress: 100); @override - Future> preview(String id) async => [ - Uint8List.fromList([1]), - ]; + Future> preview(String id) async { + previewReads++; + return [ + Uint8List.fromList([1]), + ]; + } + @override Future export(String id) async => Uint8List.fromList([2]); } @@ -92,6 +97,38 @@ void main() { }, ); + test('cancellation from the completed status notification prevents the result read', () async { + final model = GenerationViewModel(); + final engine = ControlledEngine(); + final previous = Uint8List.fromList([9]); + model.pages = [previous]; + final completed = Completer(); + late Future stopping; + model.addListener(() { + if (model.phase == 'completed' && !completed.isCompleted) { + stopping = model.cancel(); + completed.complete(); + } + }); + final pending = model.generate( + GenerationRequest({}, {}), + engine, + revision: 2, + preview: true, + pdf: false, + ); + engine.submitted.complete('task'); + await completed.future; + expect(await pending, isFalse); + expect(model.busy, isTrue); + expect(engine.previewReads, 0); + expect(model.pages.single, same(previous)); + engine.exited.complete(); + await stopping; + expect(model.available, isTrue); + model.dispose(); + }); + test('identity failure releases the task slot for retry', () async { final model = GenerationViewModel(); final engine = ControlledEngine()..failIdentity = true; diff --git a/app/test/latex_ast_dispatch_test.dart b/app/test/latex_ast_dispatch_test.dart new file mode 100644 index 00000000..00cf88a4 --- /dev/null +++ b/app/test/latex_ast_dispatch_test.dart @@ -0,0 +1,42 @@ +import 'package:flutter_math_fork/tex.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:handwriting_app/utils/latex_ast.dart'; + +void main() { + const settings = TexParserSettings(displayMode: true, throwOnError: true); + + test('每层子节点消耗一级嵌套预算', () { + final row = TexParser('x', settings).parse(); + expect(renderLatexNode(row, 63), 'x'); + expect( + () => renderLatexNode(row, 64), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'Math nesting limit', + ), + ), + ); + }); + + test('根式内的空白沿用外层分段模式', () { + final root = TexParser(r'\sqrt{a\quad b}', settings).parse(); + expect(renderLatexNode(root), '√(a b)'); + expect(renderLatexNode(root, 0, 'cases'), '√(a b)'); + }); + + test('无法写作上标的根指数保留原有错误', () { + final root = TexParser(r'\sqrt[q]{x}', settings).parse(); + expect( + () => renderLatexNode(root), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'Unsupported root index', + ), + ), + ); + }); +} diff --git a/app/test/live_preview_scheduler_test.dart b/app/test/live_preview_scheduler_test.dart new file mode 100644 index 00000000..597a11ed --- /dev/null +++ b/app/test/live_preview_scheduler_test.dart @@ -0,0 +1,76 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:handwriting_app/screens/live_preview_scheduler.dart'; + +void main() { + testWidgets('only the latest eligible revision is submitted once', ( + tester, + ) async { + var revision = 1; + int? rendered; + final submissions = []; + late LivePreviewScheduler scheduler; + scheduler = LivePreviewScheduler( + readDraft: () => + (revision: revision, previewRevision: rendered, full: false), + submit: () { + submissions.add(revision); + // Starting a generation synchronously notifies workspace listeners. + scheduler.refresh(); + }, + ); + addTearDown(scheduler.dispose); + scheduler.setEnabled(true); + await tester.pump(const Duration(milliseconds: 349)); + revision++; + scheduler.refresh(); + await tester.pump(const Duration(milliseconds: 349)); + expect(submissions, isEmpty); + await tester.pump(const Duration(milliseconds: 1)); + await tester.pump(const Duration(seconds: 1)); + expect(submissions, [2]); + + rendered = ++revision; + scheduler.refresh(); + await tester.pump(const Duration(seconds: 1)); + expect(submissions, [2]); + revision++; + scheduler.refresh(); + scheduler.markSubmitted(revision); + await tester.pump(const Duration(seconds: 1)); + expect(submissions, [2]); + }); + + testWidgets('a pending preview rechecks availability and stops on disposal', ( + tester, + ) async { + var available = true; + var calls = 0; + final scheduler = LivePreviewScheduler( + readDraft: () => + available ? (revision: 5, previewRevision: null, full: true) : null, + submit: () => calls++, + )..setEnabled(true); + available = false; + await tester.pump(const Duration(milliseconds: 750)); + expect(calls, 0); + available = true; + scheduler.refresh(); + await tester.pump(const Duration(milliseconds: 749)); + scheduler.setEnabled(false); + await tester.pump(const Duration(milliseconds: 1)); + expect(calls, 0); + scheduler.setEnabled(true); + await tester.pump(const Duration(milliseconds: 750)); + expect(calls, 1); + + scheduler.setEnabled(false); + scheduler.setEnabled(true); + await tester.pump(const Duration(milliseconds: 750)); + expect(calls, 2); + scheduler.setEnabled(false); + scheduler.setEnabled(true); + scheduler.dispose(); + await tester.pump(const Duration(seconds: 1)); + expect(calls, 2); + }); +} diff --git a/app/test/markdown_cleanup_regression_test.dart b/app/test/markdown_cleanup_regression_test.dart index dcfce747..4a76a1ae 100644 --- a/app/test/markdown_cleanup_regression_test.dart +++ b/app/test/markdown_cleanup_regression_test.dart @@ -1,5 +1,6 @@ import 'package:flutter_test/flutter_test.dart'; +import 'package:handwriting_app/utils/prepare_text.dart'; import 'package:handwriting_app/utils/text_tools.dart'; void main() { @@ -23,4 +24,60 @@ void main() { expect(result, contains('a*b')); expect(cleanMarkdown(result), result); }); + + test( + 'keeps literal markers in math, prose, and code at the paste boundary', + () { + const glyph = '\uE110CODE0\uE111'; + const equation = '\$\\text{$glyph / \uE110CODE17\uE111}\$'; + const source = 'Legend: `**ink**`\nFormula: $equation'; + const expected = 'Legend: **ink**\nFormula: $equation'; + expect(cleanMarkdown(source), expected); + expect(prepareHandwritingText(source), expected); + expect( + cleanMarkdown('Printed: $glyph\n~~~text\n$glyph and `**raw**`\n~~~'), + 'Printed: $glyph\n$glyph and `**raw**`', + ); + }, + ); + + test('formatting and links can join literal marker fragments', () { + // Exercise a matching index as well as a number that was never issued. + const literal = '\uFDD0'; + const end = '\uE111'; + const source = + '`**code**` ${literal}CO**D**E0$end ' + '${literal}CO[DE](guide.md)999$end ' + '$literal\uFDD1 $literal$literal'; + expect( + cleanMarkdown(source), + '**code** ${literal}CODE0$end ${literal}CODE999$end ' + '$literal\uFDD1 $literal$literal', + ); + }); + + test('table cells preserve literal markers alongside code and math', () { + const glyph = '\uE130'; + const reserve = '\uFDD0'; + const source = + '| Symbol | Value |\n| --- | --- |\n' + '| ${glyph}CE**LL**0\uE131 and \$x\$ | `**ink**` / ${reserve}CE**LL**0\uE131 |'; + expect( + cleanMarkdown(source), + contains( + '\\text{${glyph}CELL0\uE131 and }x & ' + '\\text{**ink**}\\text{ / ${reserve}CELL0\uE131}', + ), + ); + }); + + test('an unmatched backtick run leaves later complete code spans intact', () { + const source = 'Type ``` literally, then `**keep**` and finish with ``.'; + expect( + cleanMarkdown(source), + 'Type ``` literally, then **keep** and finish with ``.', + ); + const multiline = 'Type ``` here,\nthen type ```` in the margin.'; + expect(cleanMarkdown(multiline), multiline); + }); } diff --git a/app/test/markdown_table_delimiters_test.dart b/app/test/markdown_table_delimiters_test.dart new file mode 100644 index 00000000..7dc819b5 --- /dev/null +++ b/app/test/markdown_table_delimiters_test.dart @@ -0,0 +1,28 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:handwriting_app/utils/text_tools.dart'; + +void main() { + const header = 'A | B\n--- | ---\n'; + + test('数学中的代码跨过同名数学定界符,结尾竖线仍然分列', () { + for (final row in [ + r'$a`$|`|b$ | z', + r'\(a`\)|`|b\) | z', + r'``a`|b`` | z', + ]) { + final cleaned = cleanMarkdown('$header$row'); + expect(cleaned, contains(r'\begin{array}{|c|c|}'), reason: row); + expect(cleaned, contains(r' & \text{z}'), reason: row); + } + }); + + test('未闭合的代码或数学定界符吞入行尾竖线', () { + for (final row in [r'open ``a` | z', r'open $a | z', r'open \(a | z']) { + expect( + cleanMarkdown('$header$row'), + isNot(contains(r'\begin{array}')), + reason: row, + ); + } + }); +} diff --git a/app/test/mobile_workbench_test.dart b/app/test/mobile_workbench_test.dart index 30dbaad6..2d21ccdb 100644 --- a/app/test/mobile_workbench_test.dart +++ b/app/test/mobile_workbench_test.dart @@ -403,6 +403,103 @@ void main() { ); } + testWidgets('live preview waits for the IME to commit on mobile', ( + tester, + ) async { + final workspace = await openWorkbench(tester, size: const Size(390, 880)); + final api = workspace.api as MobileTestApi; + Finder keyed(String key) => find.byKey(ValueKey(key)); + await tester.tap(keyed('open-preview')); + await tester.pumpAndSettle(); + await tester.tap(keyed('live-preview')); + await tester.tap(keyed('back-to-editor')); + await tester.pumpAndSettle(); + await tester.showKeyboard(keyed('text-editor')); + const value = TextEditingValue( + text: '中文', + selection: TextSelection.collapsed(offset: 2), + composing: TextRange(start: 0, end: 2), + ); + tester.testTextInput.updateEditingValue(value); + await tester.pump(const Duration(seconds: 1)); + expect(workspace.text, value.text); + expect(api.submissions, isEmpty); + tester.testTextInput.updateEditingValue( + value.copyWith(composing: TextRange.empty), + ); + await tester.pump(const Duration(milliseconds: 349)); + expect(api.submissions, isEmpty); + await tester.pump(const Duration(milliseconds: 1)); + expect(api.submissions.single['text'], value.text); + api.terminal.complete({'task_status': 'completed'}); + await tester.pumpAndSettle(); + expect(api.previewReads, 1); + expect(keyed('text-editor'), findsOneWidget); + }); + + testWidgets('leaving the workbench pauses a pending full live preview', ( + tester, + ) async { + final workspace = await openWorkbench(tester, size: const Size(1280, 880)); + final api = workspace.api as MobileTestApi; + Finder keyed(String key) => find.byKey(ValueKey(key)); + await tester.tap(keyed('full-preview')); + await tester.pumpAndSettle(); + await tester.tap(keyed('live-preview')); + await tester.pumpAndSettle(); + await tester.enterText(keyed('text-editor'), 'before leaving'); + await tester.pump(const Duration(milliseconds: 400)); + expect(api.submissions, isEmpty); + await tester.tap(keyed('open-guide')); + await tester.pump(const Duration(seconds: 1)); + expect(keyed('beginner-guide'), findsOneWidget); + expect(api.submissions, isEmpty); + final firstStep = keyed('guide-step-1'); + await tester.ensureVisible(firstStep); + await tester.tap(firstStep); + await tester.pump(const Duration(milliseconds: 749)); + expect(api.submissions, isEmpty); + await tester.pump(const Duration(milliseconds: 1)); + expect(api.submissions.single['text'], 'before leaving'); + expect(api.submissions.single['full_preview'], 'true'); + api.terminal.complete({'task_status': 'completed'}); + await tester.pumpAndSettle(); + expect(api.previewReads, 1); + expect(keyed('text-editor'), findsOneWidget); + }); + + testWidgets('live preview resumes after text preparation unlocks editing', ( + tester, + ) async { + final workspace = await openWorkbench(tester, size: const Size(390, 880)); + final api = workspace.api as MobileTestApi; + api.terminal.complete({'task_status': 'completed'}); + Finder keyed(String key) => find.byKey(ValueKey(key)); + final l = labels(tester); + await tester.enterText(keyed('text-editor'), '### 第一段'); + await tester.tap(keyed('open-preview')); + await tester.pumpAndSettle(); + await tester.tap(keyed('live-preview')); + await tester.pump(const Duration(milliseconds: 350)); + await tester.pumpAndSettle(); + expect(api.submissions.single['text'], '### 第一段'); + await tester.tap(keyed('back-to-editor')); + await tester.pumpAndSettle(); + await tester.tap(keyed('editor-tools')); + await tester.pumpAndSettle(); + final cleanup = find.widgetWithText(ListTile, l.prepareText); + await tester.ensureVisible(cleanup); + await tester.pumpAndSettle(); + await tester.tap(cleanup); + await tester.pumpAndSettle(); + await tester.tap(find.widgetWithText(FilledButton, l.apply)); + await waitPreparation(tester); + expect(workspace.text, '第一段'); + await tester.pump(const Duration(milliseconds: 350)); + expect(api.submissions.map((fields) => fields['text']), ['### 第一段', '第一段']); + expect(workspace.previewStale, isFalse); + }); + testWidgets('generation completion respects navigation and newer edits', ( tester, ) async { diff --git a/app/test/paper_camera_test.dart b/app/test/paper_camera_test.dart index 54028e2b..e8777aab 100644 --- a/app/test/paper_camera_test.dart +++ b/app/test/paper_camera_test.dart @@ -43,6 +43,23 @@ void main() { }, ); + test('JPEG finds EXIF before scan data and ignores other APP1 segments', () { + const tiff = [73, 73, 42, 0, 8, 0, 0, 0]; + final bytes = Uint8List.fromList([ + 0xff, 0xd8, + 0xff, 0xff, 0xd0, // Fill and restart markers have no length. + 0xff, 0xe1, 0, 5, 1, 2, 3, + 0xff, 0xe1, 0, 16, 69, 120, 105, 102, 0, 0, ...tiff, + ]); + expect(paperExifSource(bytes), tiff); + expect( + paperExifSource(Uint8List.sublistView(bytes, 0, bytes.length - 1)), + isNull, + ); + bytes[4] = 0xda; // Stop at the start of the image scan. + expect(paperExifSource(bytes), isNull); + }); + testWidgets( 'saving an ink page inserts one EXIF chunk without changing pixels', (tester) async { @@ -89,6 +106,7 @@ void main() { final original = await compositeInkPage(legacy, defaultInkLook); final tagged = await compositeInkPage(page, defaultInkLook); expect(tagged, withPaperExif(original, exif)); + expect(paperExifSource(tagged), exif); final chunk = ByteData.sublistView(tagged); expect(chunk.getUint32(33), exif.length); expect(ascii.decode(tagged.sublist(37, 41)), 'eXIf'); diff --git a/app/test/pdf_export_lifecycle_test.dart b/app/test/pdf_export_lifecycle_test.dart new file mode 100644 index 00000000..b3fe73a9 --- /dev/null +++ b/app/test/pdf_export_lifecycle_test.dart @@ -0,0 +1,229 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:handwriting_app/screens/pdf_workbench.dart'; +import 'package:handwriting_app/services/api.dart'; +import 'package:handwriting_app/services/pdf_pages.dart'; + +import 'pdf_workbench_test.dart' show host, sourceJson; + +PdfSourcePage _page(int index, {List warnings = const []}) { + final source = sourceJson(index) + ..['pageWidthPt'] = index == 0 ? 150 : 180 + ..['warnings'] = warnings; + return PdfSourcePage.fromJson(source, index); +} + +Future _open( + WidgetTester tester, { + required Future Function(int) fetch, + required Future Function(Uint8List) save, +}) async { + final workbench = PdfWorkbench( + file: Upload('worksheet.pdf', Uint8List(0)), + mode: PdfImportMode.fill, + fetch: fetch, + loadFont: () async => 'Ahem', + ink: Colors.black, + save: save, + ); + await tester.pumpWidget( + host( + Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () => Navigator.push( + context, + MaterialPageRoute(builder: (_) => workbench), + ), + child: const Text('Open worksheet'), + ), + ), + ), + ), + ); + await tester.tap(find.text('Open worksheet')); + await tester.pumpAndSettle(); +} + +Future _start(WidgetTester tester) async { + await tester.runAsync(() => tester.tap(find.text('Export PDF'))); +} + +Future _until(WidgetTester tester, bool Function() ready) async { + for (var attempt = 0; attempt < 120 && !ready(); attempt++) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 25)), + ); + await tester.pump(const Duration(milliseconds: 50)); + } + expect(ready(), isTrue); +} + +void _checkPageOrder(Uint8List bytes) { + final pdf = latin1.decode(bytes); + final mediaBoxes = RegExp(r'/MediaBox\s*\[\s*0\s+0\s+(\d+)\s+(\d+)\s*\]') + .allMatches(pdf) + .map((box) => [box.group(1), box.group(2)]); + expect(mediaBoxes.toList(), [ + ['150', '200'], + ['180', '200'], + ]); +} + +void main() { + testWidgets( + 'clean export reuses the displayed page and saves in source order', + (tester) async { + final reads = []; + final saves = []; + await _open( + tester, + fetch: (i) async { + reads.add(i); + return _page(i, warnings: const ['unrelated_to_fill']); + }, + save: (data) async => saves.add(data), + ); + await tester.tap(find.byTooltip('Next')); + await tester.pumpAndSettle(); + await _start(tester); + await _until(tester, () => saves.isNotEmpty); + expect(reads, [0, 1]); + expect(saves, hasLength(1)); + _checkPageOrder(saves.single); + expect(tester.takeException(), isNull); + }, + ); + + for (final accept in [false, true]) { + testWidgets( + 'review counts affected pages and obeys ${accept ? 'confirmation' : 'rejection'}', + (tester) async { + final saves = []; + await _open( + tester, + fetch: (i) async => _page( + i, + warnings: i == 1 + ? const ['partial_render', 'partial_render'] + : const [], + ), + save: (data) async => saves.add(data), + ); + await _start(tester); + await _until( + tester, + () => find.text('Review before exporting').evaluate().isNotEmpty, + ); + expect(find.textContaining('1 page(s)'), findsOneWidget); + expect(saves, isEmpty); + await tester.runAsync( + () => tester.tap( + find.descendant( + of: find.byType(AlertDialog), + matching: find.text(accept ? 'Export PDF' : 'Cancel'), + ), + ), + ); + if (accept) { + await _until(tester, () => saves.isNotEmpty); + _checkPageOrder(saves.single); + } + await tester.pumpAndSettle(); + expect( + tester + .widget( + find.widgetWithText(FilledButton, 'Export PDF'), + ) + .onPressed, + isNotNull, + ); + expect(saves.length, accept ? 1 : 0); + expect(tester.takeException(), isNull); + }, + ); + } + + testWidgets( + 'a failed page read offers the localized error and allows retry', + (tester) async { + var fail = true; + final saves = []; + await _open( + tester, + fetch: (i) async { + if (i == 1 && fail) { + throw ApiException('read failed', code: 'invalid_document'); + } + return _page(i); + }, + save: (data) async => saves.add(data), + ); + await _start(tester); + await _until( + tester, + () => find.byType(AlertDialog).evaluate().isNotEmpty, + ); + expect( + find.textContaining('This PDF could not be read.'), + findsOneWidget, + ); + expect(saves, isEmpty); + await tester.runAsync( + () => tester.tap( + find.descendant( + of: find.byType(AlertDialog), + matching: find.text('Close'), + ), + ), + ); + await _until( + tester, + () => + tester + .widget( + find.widgetWithText(FilledButton, 'Export PDF'), + ) + .onPressed != + null, + ); + await tester.pumpAndSettle(); + fail = false; + await _start(tester); + await _until(tester, () => saves.isNotEmpty); + _checkPageOrder(saves.single); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets('closing the workbench discards a pending warned page', ( + tester, + ) async { + final delayed = Completer(); + final reads = []; + final saves = []; + await _open( + tester, + fetch: (i) async { + reads.add(i); + return i == 0 ? _page(0) : delayed.future; + }, + save: (data) async => saves.add(data), + ); + await _start(tester); + await _until(tester, () => reads.length == 2); + await tester.tap(find.byTooltip('Close')); + await tester.pumpAndSettle(); + expect(find.text('Open worksheet'), findsOneWidget); + delayed.complete(_page(1, warnings: const ['partial_render'])); + await tester.pumpAndSettle(); + expect(reads, [0, 1]); + expect(saves, isEmpty); + expect(find.byType(AlertDialog), findsNothing); + expect(tester.takeException(), isNull); + }); +} diff --git a/app/test/settings_restore_test.dart b/app/test/settings_restore_test.dart new file mode 100644 index 00000000..f6b4f499 --- /dev/null +++ b/app/test/settings_restore_test.dart @@ -0,0 +1,26 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:handwriting_app/models/settings.dart'; + +void main() { + test('legacy values win and malformed fields preserve notebook defaults', () { + final settings = Settings.notebook(); + settings.restore({ + 'font_size': 20, + 'fontSize': 44.8, + 'height': -1, + 'ink_thickness': 0.25, + 'ink_softness': 0.3, + 'full_preview': false, + 'enableFullPreview': true, + }); + expect(settings.values['font_size'], '44'); + expect(settings.values['height'], '2200'); + expect(settings.values['ink_thickness'], '0'); + expect(settings.values['ink_softness'], '0.3'); + expect(settings.fullPreview, isFalse); + expect( + (Settings()..restore(settings.toJson())).toJson(), + settings.toJson(), + ); + }); +} diff --git a/app/test/workbench_shell_test.dart b/app/test/workbench_shell_test.dart index 1b2cf2e7..bb0712c1 100644 --- a/app/test/workbench_shell_test.dart +++ b/app/test/workbench_shell_test.dart @@ -5,24 +5,27 @@ import 'package:handwriting_app/l10n/app_localizations.dart'; import 'package:handwriting_app/widgets/workbench_shell.dart'; void main() { - Widget shell({VoidCallback? onLocale, ValueChanged? onDestination}) => - MaterialApp( - locale: const Locale('en'), - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: WorkbenchShell( - destination: 0, - onDestinationSelected: onDestination ?? (_) {}, - connected: true, - managedBackend: false, - locked: false, - onConnection: () {}, - onToggleLocale: onLocale ?? () {}, - onToggleTheme: () {}, - workspaceBuilder: (_, _) => const SizedBox.expand(), - informationBuilder: () => const SizedBox.expand(), - ), - ); + Widget shell({ + VoidCallback? onLocale, + ValueChanged? onDestination, + Widget Function(bool, double)? workspaceBuilder, + }) => MaterialApp( + locale: const Locale('en'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: WorkbenchShell( + destination: 0, + onDestinationSelected: onDestination ?? (_) {}, + connected: true, + managedBackend: false, + locked: false, + onConnection: () {}, + onToggleLocale: onLocale ?? () {}, + onToggleTheme: () {}, + workspaceBuilder: workspaceBuilder ?? (_, _) => const SizedBox.expand(), + informationBuilder: () => const SizedBox.expand(), + ), + ); for (final width in [320.0, 375.0, 1280.0]) { testWidgets('repository link stays accessible at $width px', ( @@ -100,20 +103,57 @@ void main() { expect(find.byType(BottomSheet), findsNothing); }); - testWidgets('mobile keyboard hides bottom navigation and offers dismissal', ( - tester, - ) async { - tester.view.physicalSize = const Size(375, 800); - tester.view.devicePixelRatio = 1; - addTearDown(tester.view.resetPhysicalSize); - addTearDown(tester.view.resetDevicePixelRatio); - addTearDown(tester.view.resetViewInsets); - await tester.pumpWidget(shell()); - expect(find.byType(NavigationBar), findsNothing); - tester.view.viewInsets = const FakeViewPadding(bottom: 300); - await tester.pumpAndSettle(); - expect(find.byType(NavigationBar), findsNothing); - expect(find.byType(AppBar), findsOneWidget); - expect(tester.takeException(), isNull); - }); + for (final width in [899.0, 900.0, 1099.0, 1100.0]) { + testWidgets('keyboard and navigation actions at width ${width.toInt()}', ( + tester, + ) async { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = Size(width, 800); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetViewInsets); + tester.view.padding = const FakeViewPadding(left: 25, right: 25); + addTearDown(tester.view.resetPadding); + bool? bodyWide; + final focus = FocusNode(); + addTearDown(focus.dispose); + await tester.pumpWidget( + shell( + workspaceBuilder: (wide, _) { + bodyWide = wide; + return TextField(focusNode: focus); + }, + ), + ); + final labels = AppLocalizations.of( + tester.element(find.byType(WorkbenchShell)), + )!; + expect(bodyWide, width - 50 >= 900); + expect( + find.byKey(const ValueKey('open-guide')), + width >= 900 ? findsOneWidget : findsNothing, + ); + expect( + find.byTooltip(labels.language), + width >= 1100 ? findsOneWidget : findsNothing, + ); + expect(find.byIcon(Icons.keyboard_hide_outlined), findsNothing); + await tester.tap(find.byType(TextField)); + tester.view.viewInsets = const FakeViewPadding(bottom: 200); + await tester.pumpAndSettle(); + expect(focus.hasFocus, isTrue); + if (width >= 1100) { + expect(find.byIcon(Icons.keyboard_hide_outlined), findsNothing); + } else { + final button = find.widgetWithIcon( + width < 900 ? FloatingActionButton : TextButton, + Icons.keyboard_hide_outlined, + ); + expect(button, findsOneWidget); + await tester.tap(button); + await tester.pumpAndSettle(); + expect(focus.hasFocus, isFalse); + } + }); + } } diff --git a/app/test/workspace_test.dart b/app/test/workspace_test.dart index 5dd8954e..7bcded66 100644 --- a/app/test/workspace_test.dart +++ b/app/test/workspace_test.dart @@ -3,9 +3,12 @@ import 'dart:convert'; import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; +import 'package:handwriting_app/models/fine_edit.dart'; +import 'package:handwriting_app/models/ink_page.dart'; import 'package:handwriting_app/services/api.dart'; import 'package:handwriting_app/services/workspace.dart'; import 'package:handwriting_app/services/workspace_storage.dart'; +import 'package:http/http.dart' as http; class MemoryStorage implements WorkspaceStorage { final values = {}; @@ -26,6 +29,7 @@ class MemoryStorage implements WorkspaceStorage { class ControlledApi extends HandwritingApi { ControlledApi() : super('http://example.invalid'); final submission = Completer(); + Map? submittedFields; final rendered = Completer>(); final cancelled = []; final previewRequested = Completer(); @@ -39,7 +43,11 @@ class ControlledApi extends HandwritingApi { Map fields, Map files, { String? taskId, - }) => submission.future; + }) { + submittedFields = fields; + return submission.future; + } + @override Future> status(String id) async => { 'status': 'completed', @@ -50,6 +58,10 @@ class ControlledApi extends HandwritingApi { return rendered.future; } + @override + Future result(String id) async => + http.Response.bytes([1], 200); + @override Future cancelTask(String id) async => cancelled.add(id); } @@ -223,6 +235,54 @@ void main() { }, ); + test( + 'cleared edits are omitted from drafts and exported with their layout key', + () async { + final key = 'a' * 64; + final storage = MemoryStorage(); + storage.values['flutter.workspace'] = jsonEncode({ + 'text': 'draft', + 'fineEdits': { + 'key': key, + 'glyphs': [ + { + 'id': 1, + 'dx': 4, + 'dy': 0, + 'scale': 100, + 'angle': 0, + 'opacity': 100, + }, + ], + }, + }); + final api = ControlledApi(); + final w = Workspace(api: api, storage: storage); + addTearDown(w.dispose); + await w.initialize(); + final fine = FinePage(key, Uint8List(0), const []); + final page = InkPage(Uint8List(0), null, fine: fine); + w.generation + ..pages = [page.paper] + ..inkPages = [page] + ..previewRevision = w.editRevision; + expect(w.fineEnabled, isTrue); + expect(w.fineAdjustments(fine)[1]?.dx, 4); + w.applyFineEdits(fine, [defaultFineAdjustment(1)]); + await w.persist(); + final saved = jsonDecode(storage.values['flutter.workspace']!) as Map; + expect(saved.containsKey('fineEdits'), isFalse); + api.supportsFineEdit = true; + final export = w.generate(preview: false); + expect(jsonDecode(api.submittedFields!['fine_edits']!), { + 'key': key, + 'glyphs': [], + }); + api.submission.complete('export-task'); + expect(await export, isTrue); + }, + ); + test('dispose flushes last input before debounce fires', () async { final storage = MemoryStorage(); final w = Workspace(api: ControlledApi(), storage: storage); diff --git a/app/updater/bin/panache_updater.dart b/app/updater/bin/panache_updater.dart index 81a047f7..e03ae3d1 100644 --- a/app/updater/bin/panache_updater.dart +++ b/app/updater/bin/panache_updater.dart @@ -17,23 +17,7 @@ Future main(List arguments) async { if (Platform.isWindows && arguments.length == 1 && arguments.single == '--mcp') { - final root = p.dirname(Platform.resolvedExecutable); - final runtime = windowsRuntime( - root, - readJson(p.join(root, 'active.json')), - ); - final server = await Process.start( - p.join(runtime, 'backend', 'panache-mcp.exe'), - const [], - ); - // The Windows GUI launcher must explicitly bridge the client's stdio pipes. - unawaited(stdin.pipe(server.stdin).catchError((Object _) {})); - await Future.wait([ - stdout.addStream(server.stdout), - stderr.addStream(server.stderr), - ]); - await Future.wait([stdout.flush(), stderr.flush()]); - exit(await server.exitCode); + exit(await _proxyWindowsMcp()); } if (arguments.isEmpty && Platform.isWindows) { await launchWindows(p.dirname(Platform.resolvedExecutable)); @@ -43,73 +27,94 @@ Future main(List arguments) async { !{'--prepare', '--recover'}.contains(arguments[0])) { reject('invalid_arguments'); } - requireUnprivilegedProcess(); - final directory = p.normalize(p.absolute(arguments[1])), - token = arguments[2]; - final plan = UpdatePlan.read(directory, token); - final transaction = UpdateTransaction(directory, plan); - final recovering = arguments[0] == '--recover'; + await _runUpdate(arguments); + } catch (error) { + if (error is UpdaterFailure && error.osError != null) { + stderr.writeln('PANACHE_UPDATE_OS_ERROR ${error.code} ${error.osError}'); + } + stderr.writeln( + 'PANACHE_UPDATE_ERROR ${error is UpdaterFailure ? error.code : 'update_failed'}', + ); + exit(1); + } +} - try { - if (recovering) { - transaction.prepareRecovery(); - } else { - await transaction.prepare(); - } - stdout.writeln('PANACHE_UPDATE_READY $token'); - await stdout.flush(); - var armed = false, aborted = false; - await for (final line - in stdin.transform(utf8.decoder).transform(const LineSplitter())) { - if (line == 'ARM $token') { - armed = true; - } else { - aborted = true; - break; - } - } - if (!armed || aborted) { - if (recovering) { - transaction.cancelRecovery(); - } else { - await transaction.abort(); - } - return; - } - if (recovering) { - await transaction.recover(); - } else { - await transaction.applyAfterExit(); - } - exit(0); - } catch (error) { - final reason = error is UpdaterFailure ? error.code : 'update_failed'; - try { - File(p.join(directory, 'update.log')).writeAsStringSync( - '${DateTime.now().toUtc().toIso8601String()} failure $error\n', - mode: FileMode.append, - flush: true, - ); - } catch (_) { - /* Recovery remains mandatory when diagnostics cannot be written. */ - } +Future _proxyWindowsMcp() async { + final root = p.dirname(Platform.resolvedExecutable); + final runtime = windowsRuntime(root, readJson(p.join(root, 'active.json'))); + final server = await Process.start( + p.join(runtime, 'backend', 'panache-mcp.exe'), + const [], + ); + // The Windows GUI launcher must explicitly bridge the client's stdio pipes. + unawaited(stdin.pipe(server.stdin).catchError((Object _) {})); + await Future.wait([ + stdout.addStream(server.stdout), + stderr.addStream(server.stderr), + ]); + await Future.wait([stdout.flush(), stderr.flush()]); + return server.exitCode; +} + +Future _runUpdate(List arguments) async { + requireUnprivilegedProcess(); + final directory = p.normalize(p.absolute(arguments[1])), token = arguments[2]; + final plan = UpdatePlan.read(directory, token); + final transaction = UpdateTransaction(directory, plan); + final recovering = arguments[0] == '--recover'; + + try { + if (recovering) { + transaction.prepareRecovery(); + } else { + await transaction.prepare(); + } + stdout.writeln('PANACHE_UPDATE_READY $token'); + await stdout.flush(); + if (!await _armedAtEof(token)) { if (recovering) { transaction.cancelRecovery(); - } else if (transaction.ownsInstallation && - (transaction.parentConfirmedExited || transaction.isApplied())) { - await transaction.rollback(reason); } else { await transaction.abort(); } - rethrow; + return; + } + if (recovering) { + await transaction.recover(); + } else { + await transaction.applyAfterExit(); } + exit(0); } catch (error) { - if (error is UpdaterFailure && error.osError != null) { - stderr.writeln('PANACHE_UPDATE_OS_ERROR ${error.code} ${error.osError}'); + final reason = error is UpdaterFailure ? error.code : 'update_failed'; + try { + File(p.join(directory, 'update.log')).writeAsStringSync( + '${DateTime.now().toUtc().toIso8601String()} failure $error\n', + mode: FileMode.append, + flush: true, + ); + } catch (_) { + /* Recovery remains mandatory when diagnostics cannot be written. */ } - stderr.writeln( - 'PANACHE_UPDATE_ERROR ${error is UpdaterFailure ? error.code : 'update_failed'}', - ); - exit(1); + if (recovering) { + transaction.cancelRecovery(); + } else if (transaction.ownsInstallation && + (transaction.parentConfirmedExited || transaction.isApplied())) { + await transaction.rollback(reason); + } else { + await transaction.abort(); + } + rethrow; + } +} + +/// EOF authorizes the switch only after a matching ARM and no other command. +Future _armedAtEof(String token) async { + var armed = false; + await for (final line + in stdin.transform(utf8.decoder).transform(const LineSplitter())) { + if (line != 'ARM $token') return false; + armed = true; } + return armed; } diff --git a/app/updater/lib/process_identity.dart b/app/updater/lib/process_identity.dart index ad2da3d8..617507e9 100644 --- a/app/updater/lib/process_identity.dart +++ b/app/updater/lib/process_identity.dart @@ -6,7 +6,11 @@ import 'dart:typed_data'; import 'package:ffi/ffi.dart'; import 'package:path/path.dart' as p; -import 'protocol.dart'; +import 'updater_failure.dart'; + +part 'process_identity/linux.dart'; +part 'process_identity/macos.dart'; +part 'process_identity/windows.dart'; /// Persistent identity includes creation time, never just a reusable PID. class ProcessIdentity { @@ -24,34 +28,19 @@ class ProcessIdentity { static List matchingExecutable(String executable) { final wanted = p.normalize(executable); - final ids = Platform.isWindows - ? _Windows.pids() - : Platform.isMacOS - ? _Mac.pids() - : Platform.isLinux - ? Directory('/proc') - .listSync(followLinks: false) - .map((entry) => int.tryParse(p.basename(entry.path))) - .whereType() - .toList() - : reject('unsupported_platform'); final matches = []; - for (final candidate in ids.where((value) => value > 0)) { + for (final candidate in _systemPids().where((value) => value > 0)) { try { final identity = capture(candidate); if (identity == null) continue; - final same = Platform.isWindows - ? p.normalize(identity.executable).toLowerCase() == - wanted.toLowerCase() - : p.equals(identity.executable, wanted); - if (same && identity.matchesLive()) matches.add(identity); + if (_sameExecutable(identity.executable, wanted) && + identity.matchesLive()) { + matches.add(identity); + } } on UpdaterFailure catch (error) { // System/protected processes can be inaccessible and are not app instances. // A process exiting during enumeration is equally unrelated to this result. - if (!{ - 'process_identity_denied', - 'process_identity_changed', - }.contains(error.code)) { + if (!_isUncertainIdentity(error)) { rethrow; } } @@ -90,10 +79,7 @@ class ProcessIdentity { other != null && pid == other.pid && started == other.started && - (Platform.isWindows - ? p.normalize(executable).toLowerCase() == - p.normalize(other.executable).toLowerCase() - : p.equals(executable, other.executable)); + _sameExecutable(executable, other.executable); bool matchesLive() => _same(capture(pid)); @@ -106,10 +92,7 @@ class ProcessIdentity { if (!matchesLive()) return true; } on UpdaterFailure catch (error) { // An access error while a process exits is not evidence it has gone. - if (!{ - 'process_identity_denied', - 'process_identity_changed', - }.contains(error.code)) { + if (!_isUncertainIdentity(error)) { rethrow; } } @@ -124,10 +107,7 @@ class ProcessIdentity { try { return matchesLive(); } on UpdaterFailure catch (error) { - if (!{ - 'process_identity_denied', - 'process_identity_changed', - }.contains(error.code)) { + if (!_isUncertainIdentity(error)) { rethrow; } // An unreadable snapshot is unknown, never gone and never a signal @@ -167,305 +147,23 @@ class ProcessIdentity { int get currentPid => pid; -class _Windows { - static final _library = DynamicLibrary.open('kernel32.dll'); - static final _open = _library - .lookupFunction< - Pointer Function(Uint32, Int32, Uint32), - Pointer Function(int, int, int) - >('OpenProcess'); - static final _close = _library - .lookupFunction< - Int32 Function(Pointer), - int Function(Pointer) - >('CloseHandle'); - static final _error = _library - .lookupFunction('GetLastError'); - static final _enumerate = _library - .lookupFunction< - Int32 Function(Pointer, Uint32, Pointer), - int Function(Pointer, int, Pointer) - >('K32EnumProcesses'); - static final _times = _library - .lookupFunction< - Int32 Function( - Pointer, - Pointer, - Pointer, - Pointer, - Pointer, - ), - int Function( - Pointer, - Pointer, - Pointer, - Pointer, - Pointer, - ) - >('GetProcessTimes'); - static final _path = _library - .lookupFunction< - Int32 Function(Pointer, Uint32, Pointer, Pointer), - int Function(Pointer, int, Pointer, Pointer) - >('QueryFullProcessImageNameW'); - static final _terminate = _library - .lookupFunction< - Int32 Function(Pointer, Uint32), - int Function(Pointer, int) - >('TerminateProcess'); - static final _wait = _library - .lookupFunction< - Uint32 Function(Pointer, Uint32), - int Function(Pointer, int) - >('WaitForSingleObject'); - - static Pointer _handle(int pid, int access) { - final handle = _open(access, 0, pid); - if (handle == nullptr) { - final error = _error(); - if ({87, 1168}.contains(error)) return nullptr; - if (error == 5 && !_listed(pid)) return nullptr; - reject('process_identity_denied'); - } - return handle; - } - - static bool _listed(int pid) => pids().contains(pid); - - static List pids() { - for (var count = 1024; count <= 262144; count *= 2) { - final processes = calloc(count), needed = calloc(); - try { - if (_enumerate(processes, count * 4, needed) == 0) { - reject('process_identity_denied'); - } - if (needed.value < count * 4) { - return processes.asTypedList(needed.value ~/ 4).toList(); - } - } finally { - calloc.free(processes); - calloc.free(needed); - } - } - reject('process_identity_denied'); - } - - static ProcessIdentity? _read(Pointer handle, int pid) { - if (_wait(handle, 0) == 0) return null; - final times = calloc(8), length = calloc(); - final path = calloc(32768).cast(); - try { - length.value = 32768; - if (_times(handle, times, times + 2, times + 4, times + 6) == 0 || - _path(handle, 0, path, length) == 0) { - if (_wait(handle, 0) == 0) return null; - reject('process_identity_denied'); - } - final started = (BigInt.from(times[1]) << 32) | BigInt.from(times[0]); - return ProcessIdentity( - pid, - p.normalize(path.toDartString(length: length.value)), - 'windows:$started', - ); - } finally { - calloc.free(times); - calloc.free(length); - calloc.free(path); - } - } - - static ProcessIdentity? capture(int pid) { - final handle = _handle(pid, 0x1000 | 0x100000); - if (handle == nullptr) return null; - try { - return _read(handle, pid); - } finally { - _close(handle); - } - } - - static Future stop(ProcessIdentity identity, Duration timeout) async { - Pointer handle; - try { - handle = _handle(identity.pid, 0x1000 | 0x100000 | 0x1); - } on UpdaterFailure catch (error) { - // Windows briefly denies opening a process after it has terminated but - // before its PID leaves enumeration. Never turn that into a broad kill. - if (error.code == 'process_identity_denied' && - await identity.waitGone(timeout: timeout)) { - return; - } - rethrow; - } - if (handle == nullptr) return; - try { - if (!identity._same(_read(handle, identity.pid))) return; - if (_terminate(handle, 1) == 0 && _wait(handle, 0) != 0) { - reject('process_stop_failed'); - } - final clock = Stopwatch()..start(); - while (_wait(handle, 0) != 0) { - if (clock.elapsed >= timeout) reject('process_stop_failed'); - await Future.delayed(const Duration(milliseconds: 50)); - } - } finally { - _close(handle); - } - } +List _systemPids() { + if (Platform.isWindows) return _Windows.pids(); + if (Platform.isMacOS) return _Mac.pids(); + if (Platform.isLinux) { + return Directory('/proc') + .listSync(followLinks: false) + .map((entry) => int.tryParse(p.basename(entry.path))) + .whereType() + .toList(); + } + reject('unsupported_platform'); } -String? _linuxStart(int pid) { - final text = File('/proc/$pid/stat').readAsStringSync(); - final boundary = text.lastIndexOf(') '); - if (boundary < 0) reject('process_identity_denied'); - final fields = text.substring(boundary + 2).split(RegExp(r'\s+')); - if (fields.length < 20 || !RegExp(r'^\d+$').hasMatch(fields[19])) { - reject('process_identity_denied'); - } - if (fields[0] == 'Z' || fields[0] == 'X') return null; - return fields[19]; -} +bool _sameExecutable(String first, String second) => Platform.isWindows + ? p.normalize(first).toLowerCase() == p.normalize(second).toLowerCase() + : p.equals(first, second); -ProcessIdentity? _linuxCapture(int pid) { - String? sampled; - try { - final start = _linuxStart(pid); - sampled = start; - if (start == null) return null; - final executable = Link('/proc/$pid/exe').resolveSymbolicLinksSync(); - final after = _linuxStart(pid); - if (after == null) return null; - if (after != start) reject('process_identity_changed'); - final boot = File('/proc/sys/kernel/random/boot_id') - .readAsStringSync() - .trim(); - if (!RegExp(r'^[a-f0-9-]{36}$').hasMatch(boot)) { - reject('process_identity_denied'); - } - return ProcessIdentity(pid, executable, 'linux:$boot:$start'); - } on FileSystemException catch (error) { - if ({2, 3}.contains(error.osError?.errorCode)) { - // Linux drops /proc/PID/exe before the task directory disappears. A - // zombie/dead stat is conclusive; an unreadable live executable is not. - try { - final after = _linuxStart(pid); - if (after == null) return null; - if (sampled != null && after != sampled) { - reject('process_identity_changed'); - } - } on FileSystemException catch (recheck) { - if ({2, 3}.contains(recheck.osError?.errorCode)) return null; - } - } - reject('process_identity_denied'); - } -} - -Future _linuxStop(ProcessIdentity identity, Duration timeout) async { - final library = DynamicLibrary.process(); - // All supported Linux packages use x86_64. pidfds bind the signal target to - // the kernel process object, closing the PID-reuse race after verification. - if (Abi.current() != Abi.linuxX64) reject('unsupported_platform'); - final call = library - .lookupFunction< - IntPtr Function(IntPtr, IntPtr, IntPtr, IntPtr, IntPtr), - int Function(int, int, int, int, int) - >('syscall'); - final close = library - .lookupFunction('close'); - final fd = call(434, identity.pid, 0, 0, 0); - if (fd < 0) { - if (!await identity._matchesForSignal(timeout)) return; - reject('process_identity_denied'); - } - try { - if (!await identity._matchesForSignal(timeout)) return; - if (call(424, fd, 15, 0, 0) < 0 && - await identity._matchesForSignal(timeout)) { - reject('process_stop_failed'); - } - if (await identity.waitGone(timeout: timeout)) return; - if (call(424, fd, 9, 0, 0) < 0 && - await identity._matchesForSignal(timeout)) { - reject('process_stop_failed'); - } - if (!await identity.waitGone(timeout: const Duration(seconds: 2))) { - reject('process_stop_failed'); - } - } finally { - close(fd); - } -} - -class _Mac { - static final _library = DynamicLibrary.open('/usr/lib/libproc.dylib'); - static final _info = _library - .lookupFunction< - Int32 Function(Int32, Int32, Uint64, Pointer, Int32), - int Function(int, int, int, Pointer, int) - >('proc_pidinfo'); - static final _path = _library - .lookupFunction< - Int32 Function(Int32, Pointer, Uint32), - int Function(int, Pointer, int) - >('proc_pidpath'); - static final _errno = DynamicLibrary.process() - .lookupFunction Function(), Pointer Function()>( - '__error', - ); - - static List pids() { - final list = _library - .lookupFunction< - Int32 Function(Pointer, Int32), - int Function(Pointer, int) - >('proc_listallpids'); - for (var count = 1024; count <= 262144; count *= 2) { - final buffer = calloc(count); - try { - final length = list(buffer.cast(), count * 4); - if (length < 0) reject('process_identity_denied'); - if (length < count) return buffer.asTypedList(length).toList(); - } finally { - calloc.free(buffer); - } - } - reject('process_identity_denied'); - } - - static String? _start(int pid, Pointer buffer) { - final result = _info(pid, 3, 0, buffer.cast(), 136); - if (result != 136) { - if ({2, 3}.contains(_errno().value)) return null; - reject('process_identity_denied'); - } - // Public XNU proc_bsdinfo: 12 uint32s, 48 chars, six uint32s, - // followed by the two uint64 creation-time values (offsets 120/128). - final data = ByteData.sublistView(buffer.asTypedList(136)); - if (data.getUint32(12, Endian.host) != pid) { - reject('process_identity_changed'); - } - if (data.getUint32(4, Endian.host) == 5) return null; - return 'macos:${data.getUint64(120, Endian.host)}:${data.getUint64(128, Endian.host)}'; - } - - static ProcessIdentity? capture(int pid) { - final buffer = calloc(136), path = calloc(4096); - try { - final started = _start(pid, buffer); - if (started == null) return null; - if (_path(pid, path.cast(), 4096) < 1) { - if (_start(pid, buffer) == null) return null; - reject('process_identity_denied'); - } - final executable = path.cast().toDartString(); - final after = _start(pid, buffer); - if (after == null) return null; - if (after != started) reject('process_identity_changed'); - return ProcessIdentity(pid, executable, started); - } finally { - calloc.free(buffer); - calloc.free(path); - } - } -} +bool _isUncertainIdentity(UpdaterFailure error) => + error.code == 'process_identity_denied' || + error.code == 'process_identity_changed'; diff --git a/app/updater/lib/process_identity/linux.dart b/app/updater/lib/process_identity/linux.dart new file mode 100644 index 00000000..df2f1b19 --- /dev/null +++ b/app/updater/lib/process_identity/linux.dart @@ -0,0 +1,84 @@ +part of '../process_identity.dart'; + +String? _linuxStart(int pid) { + final text = File('/proc/$pid/stat').readAsStringSync(); + final boundary = text.lastIndexOf(') '); + if (boundary < 0) reject('process_identity_denied'); + final fields = text.substring(boundary + 2).split(RegExp(r'\s+')); + if (fields.length < 20 || !RegExp(r'^\d+$').hasMatch(fields[19])) { + reject('process_identity_denied'); + } + if (fields[0] == 'Z' || fields[0] == 'X') return null; + return fields[19]; +} + +ProcessIdentity? _linuxCapture(int pid) { + String? sampled; + try { + final start = _linuxStart(pid); + sampled = start; + if (start == null) return null; + final executable = Link('/proc/$pid/exe').resolveSymbolicLinksSync(); + final after = _linuxStart(pid); + if (after == null) return null; + if (after != start) reject('process_identity_changed'); + final boot = File('/proc/sys/kernel/random/boot_id') + .readAsStringSync() + .trim(); + if (!RegExp(r'^[a-f0-9-]{36}$').hasMatch(boot)) { + reject('process_identity_denied'); + } + return ProcessIdentity(pid, executable, 'linux:$boot:$start'); + } on FileSystemException catch (error) { + if ({2, 3}.contains(error.osError?.errorCode)) { + // Linux drops /proc/PID/exe before the task directory disappears. A + // zombie/dead stat is conclusive; an unreadable live executable is not. + try { + final after = _linuxStart(pid); + if (after == null) return null; + if (sampled != null && after != sampled) { + reject('process_identity_changed'); + } + } on FileSystemException catch (recheck) { + if ({2, 3}.contains(recheck.osError?.errorCode)) return null; + } + } + reject('process_identity_denied'); + } +} + +Future _linuxStop(ProcessIdentity identity, Duration timeout) async { + final library = DynamicLibrary.process(); + // All supported Linux packages use x86_64. pidfds bind the signal target to + // the kernel process object, closing the PID-reuse race after verification. + if (Abi.current() != Abi.linuxX64) reject('unsupported_platform'); + final call = library + .lookupFunction< + IntPtr Function(IntPtr, IntPtr, IntPtr, IntPtr, IntPtr), + int Function(int, int, int, int, int) + >('syscall'); + final close = library + .lookupFunction('close'); + final fd = call(434, identity.pid, 0, 0, 0); + if (fd < 0) { + if (!await identity._matchesForSignal(timeout)) return; + reject('process_identity_denied'); + } + try { + if (!await identity._matchesForSignal(timeout)) return; + if (call(424, fd, 15, 0, 0) < 0 && + await identity._matchesForSignal(timeout)) { + reject('process_stop_failed'); + } + if (await identity.waitGone(timeout: timeout)) return; + if (call(424, fd, 9, 0, 0) < 0 && + await identity._matchesForSignal(timeout)) { + reject('process_stop_failed'); + } + if (!await identity.waitGone(timeout: const Duration(seconds: 2))) { + reject('process_stop_failed'); + } + } finally { + close(fd); + } +} diff --git a/app/updater/lib/process_identity/macos.dart b/app/updater/lib/process_identity/macos.dart new file mode 100644 index 00000000..6eb754ed --- /dev/null +++ b/app/updater/lib/process_identity/macos.dart @@ -0,0 +1,74 @@ +part of '../process_identity.dart'; + +class _Mac { + static final _library = DynamicLibrary.open('/usr/lib/libproc.dylib'); + static final _info = _library + .lookupFunction< + Int32 Function(Int32, Int32, Uint64, Pointer, Int32), + int Function(int, int, int, Pointer, int) + >('proc_pidinfo'); + static final _path = _library + .lookupFunction< + Int32 Function(Int32, Pointer, Uint32), + int Function(int, Pointer, int) + >('proc_pidpath'); + static final _errno = DynamicLibrary.process() + .lookupFunction Function(), Pointer Function()>( + '__error', + ); + + static List pids() { + final list = _library + .lookupFunction< + Int32 Function(Pointer, Int32), + int Function(Pointer, int) + >('proc_listallpids'); + for (var count = 1024; count <= 262144; count *= 2) { + final buffer = calloc(count); + try { + final length = list(buffer.cast(), count * 4); + if (length < 0) reject('process_identity_denied'); + if (length < count) return buffer.asTypedList(length).toList(); + } finally { + calloc.free(buffer); + } + } + reject('process_identity_denied'); + } + + static String? _start(int pid, Pointer buffer) { + final result = _info(pid, 3, 0, buffer.cast(), 136); + if (result != 136) { + if ({2, 3}.contains(_errno().value)) return null; + reject('process_identity_denied'); + } + // Public XNU proc_bsdinfo: 12 uint32s, 48 chars, six uint32s, + // followed by the two uint64 creation-time values (offsets 120/128). + final data = ByteData.sublistView(buffer.asTypedList(136)); + if (data.getUint32(12, Endian.host) != pid) { + reject('process_identity_changed'); + } + if (data.getUint32(4, Endian.host) == 5) return null; + return 'macos:${data.getUint64(120, Endian.host)}:${data.getUint64(128, Endian.host)}'; + } + + static ProcessIdentity? capture(int pid) { + final buffer = calloc(136), path = calloc(4096); + try { + final started = _start(pid, buffer); + if (started == null) return null; + if (_path(pid, path.cast(), 4096) < 1) { + if (_start(pid, buffer) == null) return null; + reject('process_identity_denied'); + } + final executable = path.cast().toDartString(); + final after = _start(pid, buffer); + if (after == null) return null; + if (after != started) reject('process_identity_changed'); + return ProcessIdentity(pid, executable, started); + } finally { + calloc.free(buffer); + calloc.free(path); + } + } +} diff --git a/app/updater/lib/process_identity/windows.dart b/app/updater/lib/process_identity/windows.dart new file mode 100644 index 00000000..bf595c5f --- /dev/null +++ b/app/updater/lib/process_identity/windows.dart @@ -0,0 +1,148 @@ +part of '../process_identity.dart'; + +class _Windows { + static final _library = DynamicLibrary.open('kernel32.dll'); + static final _open = _library + .lookupFunction< + Pointer Function(Uint32, Int32, Uint32), + Pointer Function(int, int, int) + >('OpenProcess'); + static final _close = _library + .lookupFunction< + Int32 Function(Pointer), + int Function(Pointer) + >('CloseHandle'); + static final _error = _library + .lookupFunction('GetLastError'); + static final _enumerate = _library + .lookupFunction< + Int32 Function(Pointer, Uint32, Pointer), + int Function(Pointer, int, Pointer) + >('K32EnumProcesses'); + static final _times = _library + .lookupFunction< + Int32 Function( + Pointer, + Pointer, + Pointer, + Pointer, + Pointer, + ), + int Function( + Pointer, + Pointer, + Pointer, + Pointer, + Pointer, + ) + >('GetProcessTimes'); + static final _path = _library + .lookupFunction< + Int32 Function(Pointer, Uint32, Pointer, Pointer), + int Function(Pointer, int, Pointer, Pointer) + >('QueryFullProcessImageNameW'); + static final _terminate = _library + .lookupFunction< + Int32 Function(Pointer, Uint32), + int Function(Pointer, int) + >('TerminateProcess'); + static final _wait = _library + .lookupFunction< + Uint32 Function(Pointer, Uint32), + int Function(Pointer, int) + >('WaitForSingleObject'); + + static Pointer _handle(int pid, int access) { + final handle = _open(access, 0, pid); + if (handle == nullptr) { + final error = _error(); + if ({87, 1168}.contains(error)) return nullptr; + if (error == 5 && !_listed(pid)) return nullptr; + reject('process_identity_denied'); + } + return handle; + } + + static bool _listed(int pid) => pids().contains(pid); + + static List pids() { + for (var count = 1024; count <= 262144; count *= 2) { + final processes = calloc(count), needed = calloc(); + try { + if (_enumerate(processes, count * 4, needed) == 0) { + reject('process_identity_denied'); + } + if (needed.value < count * 4) { + return processes.asTypedList(needed.value ~/ 4).toList(); + } + } finally { + calloc.free(processes); + calloc.free(needed); + } + } + reject('process_identity_denied'); + } + + static ProcessIdentity? _read(Pointer handle, int pid) { + if (_wait(handle, 0) == 0) return null; + final times = calloc(8), length = calloc(); + final path = calloc(32768).cast(); + try { + length.value = 32768; + if (_times(handle, times, times + 2, times + 4, times + 6) == 0 || + _path(handle, 0, path, length) == 0) { + if (_wait(handle, 0) == 0) return null; + reject('process_identity_denied'); + } + final started = (BigInt.from(times[1]) << 32) | BigInt.from(times[0]); + return ProcessIdentity( + pid, + p.normalize(path.toDartString(length: length.value)), + 'windows:$started', + ); + } finally { + calloc.free(times); + calloc.free(length); + calloc.free(path); + } + } + + static ProcessIdentity? capture(int pid) { + final handle = _handle(pid, 0x1000 | 0x100000); + if (handle == nullptr) return null; + try { + return _read(handle, pid); + } finally { + _close(handle); + } + } + + static Future stop(ProcessIdentity identity, Duration timeout) async { + Pointer handle; + try { + handle = _handle(identity.pid, 0x1000 | 0x100000 | 0x1); + } on UpdaterFailure catch (error) { + // Windows briefly denies opening a process after it has terminated but + // before its PID leaves enumeration. Never turn that into a broad kill. + if (error.code == 'process_identity_denied' && + await identity.waitGone(timeout: timeout)) { + return; + } + rethrow; + } + if (handle == nullptr) return; + try { + if (!identity._same(_read(handle, identity.pid))) return; + if (_terminate(handle, 1) == 0 && _wait(handle, 0) != 0) { + reject('process_stop_failed'); + } + final clock = Stopwatch()..start(); + while (_wait(handle, 0) != 0) { + if (clock.elapsed >= timeout) reject('process_stop_failed'); + await Future.delayed(const Duration(milliseconds: 50)); + } + } finally { + _close(handle); + } + } +} diff --git a/app/updater/lib/protocol.dart b/app/updater/lib/protocol.dart index 1539e2f1..9a3f8b85 100644 --- a/app/updater/lib/protocol.dart +++ b/app/updater/lib/protocol.dart @@ -6,24 +6,15 @@ import 'package:crypto/crypto.dart'; import 'package:path/path.dart' as p; import 'process_identity.dart'; +import 'updater_failure.dart'; + +export 'updater_failure.dart'; const protocolVersion = 1; const product = 'Panache'; const markerName = 'panache-install.json'; const supportedPlatforms = {'windows-x64', 'macos-arm64', 'linux-x64'}; -class UpdaterFailure implements Exception { - const UpdaterFailure(this.code, {this.osError}); - final int? osError; - final String code; - @override - String toString() => - 'UpdaterFailure($code${osError == null ? '' : ', osError: $osError'})'; -} - -Never reject(String code, {int? osError}) => - throw UpdaterFailure(code, osError: osError); - /// Prefix only an ordinary local absolute path at the Win32 FFI boundary. /// Protocol paths stay canonical and never contain a device/UNC namespace. String windowsExtendedPath(String path) { diff --git a/app/updater/lib/safe_archive.dart b/app/updater/lib/safe_archive.dart index 86d76953..c34bb16d 100644 --- a/app/updater/lib/safe_archive.dart +++ b/app/updater/lib/safe_archive.dart @@ -105,6 +105,40 @@ void _preflightTar(String path) { } } +void _validateZipHeaders(InputFileStream input) { + final names = {}; + final directory = ZipDirectory()..read(input); + for (final header in directory.fileHeaders) { + final local = header.file!; + if (header.filename != local.filename || + header.uncompressedSize > maxEntryBytes || + (header.uncompressedSize > 1024 * 1024 && + header.uncompressedSize > (header.compressedSize + 1) * 300)) { + reject('invalid_zip'); + } + final type = header.externalFileAttributes >> 16 & 0xf000; + if (!_supportedEntryMode(type)) { + reject('archive_link_or_special'); + } + if (type == 0xa000 && header.versionMadeBy >> 8 != 3) { + reject('archive_link_or_special'); + } + if (type == 0xa000 && header.uncompressedSize > 4096) { + reject('archive_too_large'); + } + final name = archivePath(header.filename); + if (!names.add(name.toLowerCase())) { + reject('duplicate_archive_entry'); + } + } +} + +bool _macMetadata(String name) => + name == '__MACOSX' || name.startsWith('__MACOSX/'); + +bool _supportedEntryMode(int mode) => + mode == 0 || mode == 0x8000 || mode == 0x4000 || mode == 0xa000; + class _Entries { _Entries(this.platform); final String platform; @@ -117,7 +151,7 @@ class _Entries { reject('duplicate_archive_entry'); } final mode = entry.mode & 0xf000; - if (mode != 0 && mode != 0x8000 && mode != 0x4000 && mode != 0xa000) { + if (!_supportedEntryMode(mode)) { reject('archive_link_or_special'); } if (entry.size < 0 || @@ -134,10 +168,37 @@ class _Entries { files[name] = entry; } + void writeTo(String destination) { + final regular = Archive(); + for (final MapEntry(key: name, value: entry) in files.entries) { + if (!entry.isSymbolicLink && !_macMetadata(name)) { + regular.add(entry); + } + } + extractArchiveToDiskSync(regular, destination, maxSize: maxExtractedBytes); + for (final MapEntry(key: name, value: entry) in files.entries) { + if (_macMetadata(name)) continue; + final target = p.joinAll([destination, ...name.split('/')]); + if (entry.isSymbolicLink) { + Link(target).createSync(entry.symbolicLink!, recursive: true); + } else { + if (entry.isFile && File(target).lengthSync() != entry.size) { + reject('truncated_archive'); + } + setMode( + target, + entry.isDirectory + ? 0x1ed + : (entry.unixPermissions == 0 ? 0x1a4 : entry.unixPermissions), + ); + } + } + } + void validate() { final root = platform == 'macos-arm64' ? 'Panache.app' : 'Panache'; for (final MapEntry(key: name, value: entry) in files.entries) { - if (name == '__MACOSX' || name.startsWith('__MACOSX/')) { + if (_macMetadata(name)) { if (platform != 'macos-arm64') reject('unexpected_archive_root'); continue; } @@ -209,31 +270,7 @@ Future extractPackage( if (source.endsWith('.zip')) { _preflightZip(source); input = InputFileStream(source); - final directory = ZipDirectory()..read(input); - for (final header in directory.fileHeaders) { - final local = header.file!; - if (header.filename != local.filename || - header.uncompressedSize > maxEntryBytes || - (header.uncompressedSize > 1024 * 1024 && - header.uncompressedSize > (header.compressedSize + 1) * 300)) { - reject('invalid_zip'); - } - final type = header.externalFileAttributes >> 16 & 0xf000; - if (type != 0 && type != 0x8000 && type != 0x4000 && type != 0xa000) { - reject('archive_link_or_special'); - } - if (type == 0xa000 && header.versionMadeBy >> 8 != 3) { - reject('archive_link_or_special'); - } - if (type == 0xa000 && header.uncompressedSize > 4096) { - reject('archive_too_large'); - } - final name = archivePath(header.filename); - if (!entries.folded.add(name.toLowerCase())) { - reject('duplicate_archive_entry'); - } - } - entries.folded.clear(); + _validateZipHeaders(input); input.closeSync(); input = InputFileStream(source); archive = ZipDecoder().decodeStream( @@ -267,32 +304,7 @@ Future extractPackage( reject('unsupported_archive'); } entries.validate(); - final regular = Archive(); - for (final MapEntry(key: name, value: entry) in entries.files.entries) { - if (!entry.isSymbolicLink && - name != '__MACOSX' && - !name.startsWith('__MACOSX/')) { - regular.add(entry); - } - } - extractArchiveToDiskSync(regular, destination, maxSize: maxExtractedBytes); - for (final MapEntry(key: name, value: entry) in entries.files.entries) { - if (name == '__MACOSX' || name.startsWith('__MACOSX/')) continue; - final target = p.joinAll([destination, ...name.split('/')]); - if (entry.isSymbolicLink) { - Link(target).createSync(entry.symbolicLink!, recursive: true); - } else { - if (entry.isFile && File(target).lengthSync() != entry.size) { - reject('truncated_archive'); - } - setMode( - target, - entry.isDirectory - ? 0x1ed - : (entry.unixPermissions == 0 ? 0x1a4 : entry.unixPermissions), - ); - } - } + entries.writeTo(destination); return p.join( destination, platform == 'macos-arm64' ? 'Panache.app' : 'Panache', diff --git a/app/updater/lib/transaction.dart b/app/updater/lib/transaction.dart index 971e89f3..9e5d9f7c 100644 --- a/app/updater/lib/transaction.dart +++ b/app/updater/lib/transaction.dart @@ -61,6 +61,24 @@ class UpdateTransaction { } Future prepare() async { + await _verifyRunningInstallation(); + _lock = InstallationLock(plan.target); + if (ProcessIdentity.matchingExecutable(plan.parent.executable) + .any((instance) => instance.pid != plan.parent.pid)) { + reject('another_instance_running'); + } + if (File(pendingPath(plan.target)).existsSync()) { + reject('recovery_required'); + } + record('preparing'); + final snapshot = await _snapshotArchive(); + final payload = await extractPackage(snapshot, unpack, plan.platform); + await _stagePayload(payload); + if (await hashFile(snapshot) != plan.sha256) reject('package_changed'); + record('prepared'); + } + + Future _verifyRunningInstallation() async { verifyWritableInstallation(plan.target, plan.platform); final installed = currentInstall(plan); if (installed.version != plan.currentVersion || @@ -94,15 +112,9 @@ class UpdateTransaction { reject('invalid_process'); } } - _lock = InstallationLock(plan.target); - if (ProcessIdentity.matchingExecutable(plan.parent.executable) - .any((instance) => instance.pid != plan.parent.pid)) { - reject('another_instance_running'); - } - if (File(pendingPath(plan.target)).existsSync()) { - reject('recovery_required'); - } - record('preparing'); + } + + Future _snapshotArchive() async { final suffix = plan.platform == 'linux-x64' ? 'linux-x64.tar.gz' : '${plan.platform}.zip'; @@ -120,7 +132,10 @@ class UpdateTransaction { } await File(plan.archive).copy(snapshot); if (await hashFile(snapshot) != plan.sha256) reject('package_changed'); - final payload = await extractPackage(snapshot, unpack, plan.platform); + return snapshot; + } + + Future _stagePayload(String payload) async { final next = InstallInfo.read(payload, plan.platform); if (next.version != plan.version || next.build != plan.build) { reject('package_version_mismatch'); @@ -149,8 +164,6 @@ class UpdateTransaction { await verifyMacBundle(stage, quarantineFrom: plan.archive); } } - if (await hashFile(snapshot) != plan.sha256) reject('package_changed'); - record('prepared'); } Future applyAfterExit() async { diff --git a/app/updater/lib/updater_failure.dart b/app/updater/lib/updater_failure.dart new file mode 100644 index 00000000..139bab06 --- /dev/null +++ b/app/updater/lib/updater_failure.dart @@ -0,0 +1,11 @@ +class UpdaterFailure implements Exception { + const UpdaterFailure(this.code, {this.osError}); + final int? osError; + final String code; + @override + String toString() => + 'UpdaterFailure($code${osError == null ? '' : ', osError: $osError'})'; +} + +Never reject(String code, {int? osError}) => + throw UpdaterFailure(code, osError: osError); diff --git a/app/windows/runner/flutter_window.cpp b/app/windows/runner/flutter_window.cpp index 955ee303..b0f663d8 100644 --- a/app/windows/runner/flutter_window.cpp +++ b/app/windows/runner/flutter_window.cpp @@ -1,6 +1,7 @@ #include "flutter_window.h" #include +#include #include "flutter/generated_plugin_registrant.h" @@ -18,12 +19,13 @@ bool FlutterWindow::OnCreate() { // The size here must match the window dimensions to avoid unnecessary surface // creation / destruction in the startup path. - flutter_controller_ = std::make_unique( + auto controller = std::make_unique( frame.right - frame.left, frame.bottom - frame.top, project_); // Ensure that basic setup of the controller was successful. - if (!flutter_controller_->engine() || !flutter_controller_->view()) { + if (!controller->engine() || !controller->view()) { return false; } + flutter_controller_ = std::move(controller); RegisterPlugins(flutter_controller_->engine()); SetChildContent(flutter_controller_->view()->GetNativeWindow()); @@ -61,10 +63,8 @@ FlutterWindow::MessageHandler(HWND hwnd, UINT const message, } } - switch (message) { - case WM_FONTCHANGE: - flutter_controller_->engine()->ReloadSystemFonts(); - break; + if (message == WM_FONTCHANGE && flutter_controller_) { + flutter_controller_->engine()->ReloadSystemFonts(); } return Win32Window::MessageHandler(hwnd, message, wparam, lparam); diff --git a/app/windows/runner/utils.cpp b/app/windows/runner/utils.cpp index 3cb71466..313ee201 100644 --- a/app/windows/runner/utils.cpp +++ b/app/windows/runner/utils.cpp @@ -9,15 +9,19 @@ void CreateAndAttachConsole() { if (::AllocConsole()) { - FILE *unused; - if (freopen_s(&unused, "CONOUT$", "w", stdout)) { - _dup2(_fileno(stdout), 1); + FILE* reopened; + const bool stdout_open = freopen_s(&reopened, "CONOUT$", "w", stdout) == 0; + if (stdout_open) { + _dup2(_fileno(reopened), 1); } - if (freopen_s(&unused, "CONOUT$", "w", stderr)) { - _dup2(_fileno(stdout), 2); + const bool stderr_open = freopen_s(&reopened, "CONOUT$", "w", stderr) == 0; + if (stderr_open) { + _dup2(_fileno(reopened), 2); } std::ios::sync_with_stdio(); - FlutterDesktopResyncOutputStreams(); + if (stdout_open && stderr_open) { + FlutterDesktopResyncOutputStreams(); + } } } diff --git a/crates/handwriting-bridge/src/api.rs b/crates/handwriting-bridge/src/api.rs index e3d909d4..8b4769d8 100644 --- a/crates/handwriting-bridge/src/api.rs +++ b/crates/handwriting-bridge/src/api.rs @@ -1,8 +1,5 @@ -use handwriting_core::{ - Cancellation, Error, FontBook, Limits, Parameters, RenderRequest, Result, document, - generation::{self, Event, Output}, - imaging, -}; +mod worker; +use handwriting_core::{Cancellation, Error, Limits, Result, document, imaging}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use std::{ @@ -259,36 +256,7 @@ fn submit(request: Request) -> Result { let worker = task.clone(); if let Err(error) = std::thread::Builder::new() .name("handwriting-mobile".into()) - .spawn(move || { - let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - generate(request, &worker) - })) - .unwrap_or_else(|_| Err(Error::new("worker_failed", "引擎任务异常"))); - if let Ok(mut state) = worker.lock() { - state.running = false; - match outcome.and_then(|()| state.cancel.check()) { - Ok(()) => { - state.task_status = "completed".into(); - state.task_progress = 100; - state.task_stage = "completed".into(); - } - Err(error) => { - state.task_status = if error.code == "cancelled" { - "cancelled" - } else { - "failed" - } - .into(); - state.task_stage = state.task_status.clone(); - state.error_code = Some(error.code.into()); - state.error_message = Some(error.message); - state.pages.clear(); - state.result = None; - let _ = fs::remove_dir_all(&state.directory); - } - } - } - }) + .spawn(move || worker::run(request, &worker)) { registry.remove(&id); let _ = fs::remove_dir_all(&task.lock().map_err(io_error)?.directory); @@ -296,126 +264,3 @@ fn submit(request: Request) -> Result { } Ok(json!({"task_id":id})) } -fn generate(request: Request, task: &Arc>) -> Result<()> { - let state = task.lock().map_err(io_error)?; - let cancel = state.cancel.clone(); - let directory = state.directory.clone(); - drop(state); - cancel.check()?; - let mut params = Parameters::from_form(&request.fields)?; - if !request.fields.contains_key("seed") && !params.fine_edit { - params.seed = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_err(io_error)? - .as_nanos() as u64; - } - let text = request - .fields - .get("text") - .cloned() - .ok_or_else(|| Error::new("invalid_parameter", "缺少 text"))?; - handwriting_core::validate_document(&text, &limits())?; - let names = fonts(&request.font_dir)?; - let primary = if let Some(upload) = request.files.get("font_file") { - FontBook::load(&read(&upload.path)?)? - } else { - let name = request.fields.get("font_option").unwrap_or(&names[0]); - if !names.contains(name) { - return Err(Error::new("invalid_font", "字体不存在")); - } - FontBook::load(&fs::read(request.font_dir.join(name)).map_err(io_error)?)? - }; - let fonts = FontBook::with_text_fallbacks(primary, &text, |name| { - if names.iter().any(|available| available == name) { - FontBook::load(&fs::read(request.font_dir.join(name)).map_err(io_error)?).map(Some) - } else { - Ok(None) - } - })?; - cancel.check()?; - let background = request - .files - .get("background_image") - .map(|upload| read(&upload.path)) - .transpose()?; - let render_request = RenderRequest { - text, - params: params.clone(), - background, - fonts, - limits: limits(), - }; - let progress = |event| { - let mut state = task.lock().map_err(io_error)?; - match event { - Event::Rendering => state.task_stage = "rendering".into(), - Event::PageReady(pages) => { - state.pages_completed = pages; - state.task_progress = (pages * 5).min(95) as u32; - } - Event::Exporting => state.task_stage = "exporting".into(), - } - Ok(()) - }; - let result = if params.pdf_save || !params.preview { - let (name, mime) = if params.pdf_save { - ("export.pdf", "application/pdf") - } else { - ("export.zip", "application/zip") - }; - let path = directory.join(name); - let partial = path.with_extension("partial"); - let mut file = fs::File::create(&partial).map_err(io_error)?; - let output = if params.pdf_save { - Output::Pdf(&mut file) - } else { - Output::Zip(&mut file) - }; - generation::generate(&render_request, &cancel, output, progress)?; - file.sync_all().map_err(io_error)?; - drop(file); - cancel.check()?; - fs::rename(&partial, &path).map_err(io_error)?; - Some((path, mime)) - } else if params.ink_layers { - generation::generate( - &render_request, - &cancel, - Output::InkLayers(&mut |index, page| { - let path = directory.join(format!("{index}.json")); - fs::write(&path, serde_json::to_vec(&page).map_err(io_error)?).map_err(io_error)?; - task.lock().map_err(io_error)?.pages.push(path); - Ok(()) - }), - progress, - )?; - None - } else { - generation::generate( - &render_request, - &cancel, - Output::Preview(&mut |index, bytes| { - let path = directory.join(format!("{index}.png")); - fs::write(&path, bytes).map_err(io_error)?; - task.lock().map_err(io_error)?.pages.push(path); - Ok(()) - }), - progress, - )?; - None - }; - let mut state = task.lock().map_err(io_error)?; - cancel.check()?; - if let Some((path, mime)) = result { - state.result = Some(path); - state.content_type = mime.into(); - } else { - state.content_type = if params.ink_layers { - "application/json" - } else { - "image/png" - } - .into(); - } - Ok(()) -} diff --git a/crates/handwriting-bridge/src/api/worker.rs b/crates/handwriting-bridge/src/api/worker.rs new file mode 100644 index 00000000..b6935825 --- /dev/null +++ b/crates/handwriting-bridge/src/api/worker.rs @@ -0,0 +1,180 @@ +//! Mobile worker lifecycle and publication of completed artifacts. +use super::{Request, Task, fonts, io_error, limits, read}; +use handwriting_core::{ + Cancellation, Error, FontBook, Parameters, RenderRequest, Result, + generation::{self, Event, Output}, +}; +use std::{ + fs, + path::{Path, PathBuf}, + sync::Mutex, +}; + +pub(super) fn run(request: Request, worker: &Mutex) { + let outcome = + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| generate(request, worker))) + .unwrap_or_else(|_| Err(Error::new("worker_failed", "引擎任务异常"))); + if let Ok(mut state) = worker.lock() { + state.running = false; + match outcome.and_then(|()| state.cancel.check()) { + Ok(()) => { + state.task_status = "completed".into(); + state.task_progress = 100; + state.task_stage = "completed".into(); + } + Err(error) => { + state.task_status = if error.code == "cancelled" { + "cancelled" + } else { + "failed" + } + .into(); + state.task_stage = state.task_status.clone(); + state.error_code = Some(error.code.into()); + state.error_message = Some(error.message); + state.pages.clear(); + state.result = None; + let _ = fs::remove_dir_all(&state.directory); + } + } + } +} + +fn prepare(request: &Request, cancel: &Cancellation) -> Result { + let mut params = Parameters::from_form(&request.fields)?; + if !request.fields.contains_key("seed") && !params.fine_edit { + params.seed = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(io_error)? + .as_nanos() as u64; + } + let text = request + .fields + .get("text") + .cloned() + .ok_or_else(|| Error::new("invalid_parameter", "缺少 text"))?; + handwriting_core::validate_document(&text, &limits())?; + let names = fonts(&request.font_dir)?; + let primary = if let Some(upload) = request.files.get("font_file") { + FontBook::load(&read(&upload.path)?)? + } else { + let name = request.fields.get("font_option").unwrap_or(&names[0]); + if !names.contains(name) { + return Err(Error::new("invalid_font", "字体不存在")); + } + FontBook::load(&fs::read(request.font_dir.join(name)).map_err(io_error)?)? + }; + let fonts = FontBook::with_text_fallbacks(primary, &text, |name| { + if names.iter().any(|available| available == name) { + FontBook::load(&fs::read(request.font_dir.join(name)).map_err(io_error)?).map(Some) + } else { + Ok(None) + } + })?; + cancel.check()?; + let background = request + .files + .get("background_image") + .map(|upload| read(&upload.path)) + .transpose()?; + Ok(RenderRequest { + text, + params, + background, + fonts, + limits: limits(), + }) +} + +fn generate(request: Request, task: &Mutex) -> Result<()> { + let state = task.lock().map_err(io_error)?; + let cancel = state.cancel.clone(); + let directory = state.directory.clone(); + drop(state); + cancel.check()?; + let render_request = prepare(&request, &cancel)?; + let params = &render_request.params; + let progress = |event| { + let mut state = task.lock().map_err(io_error)?; + match event { + Event::Rendering => state.task_stage = "rendering".into(), + Event::PageReady(pages) => { + state.pages_completed = pages; + state.task_progress = (pages * 5).min(95) as u32; + } + Event::Exporting => state.task_stage = "exporting".into(), + } + Ok(()) + }; + let result = if params.pdf_save || !params.preview { + Some(export(&render_request, &directory, &cancel, progress)?) + } else if params.ink_layers { + generation::generate( + &render_request, + &cancel, + Output::InkLayers(&mut |index, page| { + let bytes = serde_json::to_vec(&page).map_err(io_error)?; + publish_page(task, directory.join(format!("{index}.json")), &bytes) + }), + progress, + )?; + None + } else { + generation::generate( + &render_request, + &cancel, + Output::Preview(&mut |index, bytes| { + publish_page(task, directory.join(format!("{index}.png")), &bytes) + }), + progress, + )?; + None + }; + let mut state = task.lock().map_err(io_error)?; + cancel.check()?; + if let Some((path, mime)) = result { + state.result = Some(path); + state.content_type = mime.into(); + } else { + state.content_type = if params.ink_layers { + "application/json" + } else { + "image/png" + } + .into(); + } + Ok(()) +} + +fn export( + request: &RenderRequest, + directory: &Path, + cancel: &Cancellation, + progress: impl FnMut(Event) -> Result<()>, +) -> Result<(PathBuf, &'static str)> { + let (name, mime) = if request.params.pdf_save { + ("export.pdf", "application/pdf") + } else { + ("export.zip", "application/zip") + }; + let path = directory.join(name); + let partial = path.with_extension("partial"); + let mut file = fs::File::create(&partial).map_err(io_error)?; + let output = if request.params.pdf_save { + Output::Pdf(&mut file) + } else { + Output::Zip(&mut file) + }; + generation::generate(request, cancel, output, progress)?; + file.sync_all().map_err(io_error)?; + drop(file); + cancel.check()?; + fs::rename(&partial, &path).map_err(io_error)?; + Ok((path, mime)) +} + +fn publish_page(task: &Mutex, path: PathBuf, bytes: &[u8]) -> Result<()> { + fs::write(&path, bytes).map_err(io_error)?; + task.lock().map_err(io_error)?.pages.push(path); + Ok(()) +} diff --git a/crates/handwriting-bridge/src/tests.rs b/crates/handwriting-bridge/src/tests.rs index c5cd6b3c..761ab19a 100644 --- a/crates/handwriting-bridge/src/tests.rs +++ b/crates/handwriting-bridge/src/tests.rs @@ -105,24 +105,6 @@ fn local_engine_lifecycle_and_abi() { assert_eq!(identified, serde_json::to_value(&expected).unwrap()); assert!(identified["correctedBackground"].as_str().unwrap().len() > 100); assert_eq!(identified["lineSpacing"], 60); - let fields: HashMap = [ - ( - "text", - "第一页 √((a)/(b)) + xₙ²\n---\n第二页 ((a)/(b))/((c)/(d)) + (AB)⃗", - ), - ("width", "420"), - ("height", "320"), - ("font_size", "32"), - ("line_spacing", "45"), - ("left_margin", "20"), - ("right_margin", "20"), - ("top_margin", "20"), - ("bottom_margin", "20"), - ("seed", "42"), - ] - .into_iter() - .map(|(k, v)| (k.into(), v.into())) - .collect(); let wait = |id: &str| -> Value { for _ in 0..600 { let state = simple("status", id).unwrap(); @@ -144,34 +126,9 @@ fn local_engine_lifecycle_and_abi() { "cancel", "invalid", ] { - let mut fields = fields.clone(); - if mode == "pdf" || mode == "zip" { - fields.insert("preview".into(), "false".into()); - fields.insert("pdf_save".into(), (mode == "pdf").to_string()); - } - if mode == "cancel" { - fields.insert("text".into(), "取消\n".repeat(1000)); - } - if mode == "invalid" { - fields.insert("width".into(), "1000000".into()); - } - if mode == "image" { - fields.insert("text".into(), image_support::image_document()); - } - if mode == "layered" { - fields.insert("ink_layers".into(), "true".into()); - } - if mode == "text_limit" { - fields.insert("text".into(), "字".repeat(20_001)); - } + let fields = fields_for(mode); // 2026-10-15:公式经移动端同一 C ABI 进入真实 worker,不只测试直接 Rust 函数。 let submitted = if mode == "math" || mode == "image" { - if mode == "math" { - fields.insert( - "text".into(), - "√((a)/(b)) + xₙ²\n---\n((a)/(b))/((c)/(d)) + (AB)⃗".into(), - ); - } let input = CString::new( json!({ "command":"submit", "data_dir":root.path(), "font_dir":font_dir, @@ -180,12 +137,7 @@ fn local_engine_lifecycle_and_abi() { .to_string(), ) .unwrap(); - let response: Value = unsafe { - let output = handwriting_bridge_call(input.as_ptr()); - let response = serde_json::from_slice(CStr::from_ptr(output).to_bytes()).unwrap(); - handwriting_bridge_free(output); - response - }; + let response = bridge_response(Some(&input)); assert_eq!(response["ok"], true, "{response}"); response["data"].clone() } else { @@ -219,25 +171,7 @@ fn local_engine_lifecycle_and_abi() { .is_some_and(|code| !code.is_empty()) ); } - "preview" | "math" | "image" | "layered" => { - assert_eq!(state["task_status"], "completed", "{state}"); - assert_eq!(state["task_stage"], "completed"); - assert_eq!(state["pages_completed"], 2); - assert!(state["error_code"].is_null()); - assert_eq!(state["pages"].as_array().unwrap().len(), 2); - let bytes = std::fs::read(state["pages"][0].as_str().unwrap()).unwrap(); - if mode == "layered" { - use base64::{Engine, engine::general_purpose::STANDARD}; - - let page: Value = serde_json::from_slice(&bytes).unwrap(); - for layer in ["paper", "ink"] { - let png = STANDARD.decode(page[layer].as_str().unwrap()).unwrap(); - assert!(png.starts_with(b"\x89PNG\r\n\x1a\n")); - } - } else { - assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n"); - } - } + "preview" | "math" | "image" | "layered" => assert_preview(&state, mode == "layered"), _ => { assert_eq!(state["task_status"], "completed", "{state}"); let bytes = std::fs::read(state["result"].as_str().unwrap()).unwrap(); @@ -247,24 +181,103 @@ fn local_engine_lifecycle_and_abi() { } simple("reset", "").unwrap(); assert!(!root.path().join("tasks").exists()); - for request in [ - "not-json".to_owned(), - json!({"command":"version", "data_dir":root.path(), "font_dir":font_dir}).to_string(), - ] { - let input = CString::new(request).unwrap(); - unsafe { - let output = handwriting_bridge_call(input.as_ptr()); - let response: Value = - serde_json::from_slice(CStr::from_ptr(output).to_bytes()).unwrap(); - assert!(response.get("ok").unwrap().is_boolean()); - handwriting_bridge_free(output); - } - } +} + +#[test] +fn abi_returns_json_for_valid_malformed_and_null_requests() { + let root = tempfile::tempdir().unwrap(); + let version = CString::new( + json!({ + "command":"version", "data_dir":root.path(), "font_dir":root.path() + }) + .to_string(), + ) + .unwrap(); + assert_eq!(bridge_response(Some(&version))["ok"], true); + assert_eq!( + bridge_response(Some(c"not-json"))["code"], + "invalid_request" + ); + assert_eq!(bridge_response(None)["code"], "invalid_request"); + unsafe { handwriting_bridge_free(std::ptr::null_mut()) }; +} + +fn bridge_response(input: Option<&CStr>) -> Value { unsafe { - let output = handwriting_bridge_call(std::ptr::null()); - let response: Value = serde_json::from_slice(CStr::from_ptr(output).to_bytes()).unwrap(); - assert_eq!(response["code"], "invalid_request"); + let output = handwriting_bridge_call(input.map_or(std::ptr::null(), CStr::as_ptr)); + let response = serde_json::from_slice(CStr::from_ptr(output).to_bytes()); handwriting_bridge_free(output); - handwriting_bridge_free(std::ptr::null_mut()); + response.unwrap() + } +} + +fn fields_for(mode: &str) -> HashMap { + let mut fields: HashMap = [ + ( + "text", + "第一页 √((a)/(b)) + xₙ²\n---\n第二页 ((a)/(b))/((c)/(d)) + (AB)⃗", + ), + ("width", "420"), + ("height", "320"), + ("font_size", "32"), + ("line_spacing", "45"), + ("left_margin", "20"), + ("right_margin", "20"), + ("top_margin", "20"), + ("bottom_margin", "20"), + ("seed", "42"), + ] + .into_iter() + .map(|(k, v)| (k.into(), v.into())) + .collect(); + match mode { + "pdf" | "zip" => { + fields.insert("preview".into(), "false".into()); + fields.insert("pdf_save".into(), (mode == "pdf").to_string()); + } + "cancel" => { + fields.insert("text".into(), "取消\n".repeat(1000)); + } + "invalid" => { + fields.insert("width".into(), "1000000".into()); + } + "image" => { + fields.insert("text".into(), image_support::image_document()); + } + "math" => { + fields.insert( + "text".into(), + "√((a)/(b)) + xₙ²\n---\n((a)/(b))/((c)/(d)) + (AB)⃗".into(), + ); + } + "layered" => { + fields.insert("ink_layers".into(), "true".into()); + } + "text_limit" => { + fields.insert("text".into(), "字".repeat(20_001)); + } + "preview" => (), + _ => panic!("unexpected scenario {mode}"), + } + fields +} + +fn assert_preview(state: &Value, layered: bool) { + assert_eq!(state["task_status"], "completed", "{state}"); + assert_eq!(state["task_stage"], "completed"); + assert_eq!(state["pages_completed"], 2); + assert!(state["error_code"].is_null()); + assert_eq!(state["pages"].as_array().unwrap().len(), 2); + let bytes = std::fs::read(state["pages"][0].as_str().unwrap()).unwrap(); + if layered { + use base64::{Engine, engine::general_purpose::STANDARD}; + + let page: Value = serde_json::from_slice(&bytes).unwrap(); + for layer in ["paper", "ink"] { + let png = STANDARD.decode(page[layer].as_str().unwrap()).unwrap(); + assert!(png.starts_with(b"\x89PNG\r\n\x1a\n")); + } + } else { + assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n"); } } diff --git a/crates/handwriting-core/src/document.rs b/crates/handwriting-core/src/document.rs index 6473ee65..89fcd7fc 100644 --- a/crates/handwriting-core/src/document.rs +++ b/crates/handwriting-core/src/document.rs @@ -1,7 +1,9 @@ use crate::{Error, Limits, Result}; -use quick_xml::{NsReader, events::Event, name::ResolveResult}; +use std::fmt::Display; use std::io::{Cursor, Read}; +mod word_xml; + pub fn extract(name: &str, bytes: &[u8], limits: &Limits) -> Result { if bytes.len() > limits.max_file_bytes { return Err(Error::new("upload_limit", "文档文件过大")); @@ -12,8 +14,7 @@ pub fn extract(name: &str, bytes: &[u8], limits: &Limits) -> Result { .trim_start_matches('\u{feff}') .to_owned(), "docx" => docx(bytes, limits)?, - "pdf" => pdf_extract::extract_text_from_mem(bytes) - .map_err(|e| Error::new("invalid_document", e.to_string()))?, + "pdf" => pdf_extract::extract_text_from_mem(bytes).map_err(invalid_document)?, "doc" => { return Err(Error::new( "unsupported_document", @@ -27,171 +28,33 @@ pub fn extract(name: &str, bytes: &[u8], limits: &Limits) -> Result { } Ok(text) } + +fn invalid_document(error: impl Display) -> Error { + Error::new("invalid_document", error.to_string()) +} + fn docx(bytes: &[u8], limits: &Limits) -> Result { - let mut archive = zip::ZipArchive::new(Cursor::new(bytes)) - .map_err(|e| Error::new("invalid_document", e.to_string()))?; + let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).map_err(invalid_document)?; if archive.len() > 4096 { return Err(Error::new("archive_limit", "DOCX 文件条目过多")); } let mut size = 0u64; for i in 0..archive.len() { - size = size.saturating_add( - archive - .by_index(i) - .map_err(|e| Error::new("invalid_document", e.to_string()))? - .size(), - ); + size = size.saturating_add(archive.by_index(i).map_err(invalid_document)?.size()); } if size > limits.max_archive_bytes { return Err(Error::new("archive_limit", "DOCX 解压大小超出限制")); } let entry = archive .by_name("word/document.xml") - .map_err(|e| Error::new("invalid_document", e.to_string()))?; + .map_err(invalid_document)?; let mut xml = Vec::new(); entry .take(limits.max_archive_bytes + 1) .read_to_end(&mut xml) - .map_err(|e| Error::new("invalid_document", e.to_string()))?; + .map_err(invalid_document)?; if xml.len() as u64 > limits.max_archive_bytes { return Err(Error::new("archive_limit", "XML 过大")); } - let mut reader = NsReader::from_reader(xml.as_slice()); - let mut paragraphs = Vec::new(); - let mut rows = Vec::new(); - let mut paragraph = String::new(); - let mut cell = String::new(); - let mut cells = Vec::new(); - let mut table_depth = 0; - let mut text_depth = 0; - let mut depth = 0usize; - let mut horizontal_span = 1usize; - let mut vertical_continue = false; - let mut previous_row: Vec = Vec::new(); - let byte_budget = limits.max_text_chars.saturating_mul(4); - let mut produced = 0usize; - loop { - if produced - .saturating_add(paragraph.len()) - .saturating_add(cell.len()) - > byte_budget - { - return Err(Error::new("text_limit", "提取文本过长")); - } - let (namespace, event) = reader - .read_resolved_event() - .map_err(|e| Error::new("invalid_document", e.to_string()))?; - let known = matches!(namespace, ResolveResult::Bound(ns) if matches!(ns.as_ref(), - "http://schemas.openxmlformats.org/wordprocessingml/2006/main" - | "http://schemas.openxmlformats.org/officeDocument/2006/math" - | "http://purl.oclc.org/ooxml/wordprocessingml/main" - | "http://purl.oclc.org/ooxml/officeDocument/math")); - match event { - Event::Start(e) => { - depth += 1; - if depth > 256 { - return Err(Error::new("archive_limit", "XML 嵌套过深")); - } - if !known { - continue; - } - match e.local_name().as_ref() { - "tbl" => table_depth += 1, - "p" => paragraph.clear(), - "tc" => { - cell.clear(); - horizontal_span = 1; - vertical_continue = false; - } - "tr" => cells.clear(), - "t" => text_depth += 1, - _ => (), - } - } - Event::Empty(e) if known => match e.local_name().as_ref() { - "tab" => paragraph.push('\t'), - "br" | "cr" => paragraph.push('\n'), - "gridSpan" => { - for a in e.attributes().flatten() { - if a.key.local_name().as_ref() == "val" { - horizontal_span = a.value.parse().ok().unwrap_or(1).clamp(1, 1024); - } - } - } - "vMerge" => { - vertical_continue = !e.attributes().flatten().any(|a| { - a.key.local_name().as_ref() == "val" && a.value.as_ref() == "restart" - }); - } - _ => (), - }, - Event::Text(e) if text_depth > 0 => { - paragraph.push_str(&e.xml_content(quick_xml::XmlVersion::Implicit1_0)) - } - Event::GeneralRef(e) if text_depth > 0 => { - if let Some(c) = e - .resolve_char_ref() - .map_err(|e| Error::new("invalid_document", e.to_string()))? - { - paragraph.push(c); - } else { - match e.as_ref() { - "amp" => paragraph.push('&'), - "lt" => paragraph.push('<'), - "gt" => paragraph.push('>'), - "quot" => paragraph.push('"'), - "apos" => paragraph.push('\''), - _ => return Err(Error::new("invalid_document", "不支持 XML 实体")), - } - } - } - Event::End(e) => { - depth = depth.saturating_sub(1); - if !known { - continue; - } - match e.local_name().as_ref() { - "t" => text_depth -= 1, - "p" => { - if table_depth == 0 { - produced = produced.saturating_add(paragraph.len() + 1); - paragraphs.push(std::mem::take(&mut paragraph)); - } else { - cell.push_str(¶graph); - paragraph.clear(); - } - } - "tc" => { - let value = if vertical_continue { - previous_row.get(cells.len()).cloned().unwrap_or_default() - } else { - cell.trim().to_string() - }; - let added = value - .len() - .saturating_add(1) - .saturating_mul(horizontal_span); - if produced.saturating_add(added) > byte_budget { - return Err(Error::new("text_limit", "表格文本过长")); - } - produced = produced.saturating_add(added); - for _ in 0..horizontal_span { - cells.push(value.clone()); - } - } - "tr" => { - rows.push(cells.join("\t")); - previous_row = cells.clone(); - } - "tbl" => table_depth -= 1, - _ => (), - } - } - Event::DocType(_) => return Err(Error::new("invalid_document", "DOCX 不允许 DTD")), - Event::Eof => break, - _ => (), - } - } - paragraphs.extend(rows); - Ok(paragraphs.join("\n")) + word_xml::extract(&xml, limits.max_text_chars) } diff --git a/crates/handwriting-core/src/document/word_xml.rs b/crates/handwriting-core/src/document/word_xml.rs new file mode 100644 index 00000000..6bc75ae3 --- /dev/null +++ b/crates/handwriting-core/src/document/word_xml.rs @@ -0,0 +1,174 @@ +use super::invalid_document; +use crate::{Error, Result}; +use quick_xml::{ + NsReader, + escape::resolve_xml_entity, + events::{BytesRef, BytesStart, Event}, + name::ResolveResult, +}; + +pub(super) fn extract(xml: &[u8], max_chars: usize) -> Result { + let mut reader = NsReader::from_reader(xml); + let mut text = DocumentText { + horizontal_span: 1, + byte_budget: max_chars.saturating_mul(4), + ..Default::default() + }; + let mut depth = 0usize; + loop { + text.check_budget()?; + let (namespace, event) = reader.read_resolved_event().map_err(invalid_document)?; + let known = matches!(namespace, ResolveResult::Bound(ns) if matches!(ns.as_ref(), + "http://schemas.openxmlformats.org/wordprocessingml/2006/main" + | "http://schemas.openxmlformats.org/officeDocument/2006/math" + | "http://purl.oclc.org/ooxml/wordprocessingml/main" + | "http://purl.oclc.org/ooxml/officeDocument/math")); + match event { + Event::Start(e) => { + depth += 1; + if depth > 256 { + return Err(Error::new("archive_limit", "XML 嵌套过深")); + } + if known { + text.start(e.local_name().as_ref()); + } + } + Event::Empty(e) if known => text.empty(&e), + Event::Text(e) if text.text_depth > 0 => text + .paragraph + .push_str(&e.xml_content(quick_xml::XmlVersion::Implicit1_0)), + Event::GeneralRef(e) if text.text_depth > 0 => text.push_entity(&e)?, + Event::End(e) => { + depth = depth.saturating_sub(1); + if known { + text.end(e.local_name().as_ref())?; + } + } + Event::DocType(_) => return Err(Error::new("invalid_document", "DOCX 不允许 DTD")), + Event::Eof => break, + _ => (), + } + } + text.paragraphs.extend(text.rows); + Ok(text.paragraphs.join("\n")) +} + +#[derive(Default)] +struct DocumentText { + paragraphs: Vec, + paragraph: String, + text_depth: usize, + table_depth: usize, + rows: Vec, + previous_row: Vec, + cells: Vec, + cell: String, + horizontal_span: usize, + vertical_continue: bool, + produced: usize, + byte_budget: usize, +} + +impl DocumentText { + fn check_budget(&self) -> Result<()> { + let bytes = self + .produced + .saturating_add(self.paragraph.len()) + .saturating_add(self.cell.len()); + if bytes > self.byte_budget { + return Err(Error::new("text_limit", "提取文本过长")); + } + Ok(()) + } + + fn push_entity(&mut self, entity: &BytesRef<'_>) -> Result<()> { + if let Some(c) = entity.resolve_char_ref().map_err(invalid_document)? { + self.paragraph.push(c); + } else { + let value = resolve_xml_entity(entity) + .ok_or_else(|| Error::new("invalid_document", "不支持 XML 实体"))?; + self.paragraph.push_str(value); + } + Ok(()) + } + + fn start(&mut self, name: &str) { + match name { + "t" => self.text_depth += 1, + "p" => self.paragraph.clear(), + "tbl" => self.table_depth += 1, + "tr" => self.cells.clear(), + "tc" => { + self.cell.clear(); + self.horizontal_span = 1; + self.vertical_continue = false; + } + _ => (), + } + } + + fn empty(&mut self, element: &BytesStart<'_>) { + match element.local_name().as_ref() { + "tab" => self.paragraph.push('\t'), + "br" | "cr" => self.paragraph.push('\n'), + "gridSpan" => { + for attr in element.attributes().flatten() { + if attr.key.local_name().as_ref() == "val" { + self.horizontal_span = attr.value.parse().unwrap_or(1).clamp(1, 1024); + } + } + } + "vMerge" => { + self.vertical_continue = !element.attributes().flatten().any(|attr| { + attr.key.local_name().as_ref() == "val" && attr.value.as_ref() == "restart" + }); + } + _ => (), + } + } + + fn end(&mut self, name: &str) -> Result<()> { + match name { + "t" => self.text_depth -= 1, + "p" if self.table_depth == 0 => { + self.produced = self.produced.saturating_add(self.paragraph.len() + 1); + self.paragraphs.push(std::mem::take(&mut self.paragraph)); + } + "p" => { + self.cell.push_str(&self.paragraph); + self.paragraph.clear(); + } + "tc" => self.finish_cell()?, + "tr" => { + self.rows.push(self.cells.join("\t")); + self.previous_row.clone_from(&self.cells); + } + "tbl" => self.table_depth -= 1, + _ => (), + } + Ok(()) + } + + fn finish_cell(&mut self) -> Result<()> { + let value = if self.vertical_continue { + self.previous_row + .get(self.cells.len()) + .cloned() + .unwrap_or_default() + } else { + self.cell.trim().to_owned() + }; + let added = value + .len() + .saturating_add(1) + .saturating_mul(self.horizontal_span); + let produced = self.produced.saturating_add(added); + if produced > self.byte_budget { + return Err(Error::new("text_limit", "表格文本过长")); + } + self.produced = produced; + self.cells + .extend(std::iter::repeat_n(value, self.horizontal_span)); + Ok(()) + } +} diff --git a/crates/handwriting-core/src/imaging.rs b/crates/handwriting-core/src/imaging.rs index b1b12412..173a4937 100644 --- a/crates/handwriting-core/src/imaging.rs +++ b/crates/handwriting-core/src/imaging.rs @@ -5,6 +5,8 @@ use rand_chacha::ChaCha8Rng; use serde::Serialize; use std::io::Cursor; +mod rulings; + pub fn decode(bytes: &[u8], limits: &Limits) -> Result { if bytes.len() > limits.max_file_bytes { return Err(Error::new("upload_limit", "图片文件过大")); @@ -65,8 +67,7 @@ pub fn fit(image: &RgbaImage, width: u32, height: u32, scale: f32) -> RgbaImage image::imageops::FilterType::Lanczos3, ) } -// 2026-10-12:高斯局部阈值、低频位移场、线条附近墨滴和透明墨色。 -pub fn handdrawn(image: &DynamicImage, seed: u64, cancel: &Cancellation) -> Result { +fn over_white(image: &DynamicImage) -> RgbaImage { // 2026-10-16:透明像素须先合成白底,否则黑色透明底会吞掉黑线。 let mut opaque = image.to_rgba8(); for pixel in opaque.pixels_mut() { @@ -76,6 +77,12 @@ pub fn handdrawn(image: &DynamicImage, seed: u64, cancel: &Cancellation) -> Resu } pixel[3] = 255; } + opaque +} + +// 2026-10-12:高斯局部阈值、低频位移场、线条附近墨滴和透明墨色。 +pub fn handdrawn(image: &DynamicImage, seed: u64, cancel: &Cancellation) -> Result { + let opaque = over_white(image); let gray = DynamicImage::ImageRgba8(opaque).to_luma8(); let (w, h) = gray.dimensions(); let blurred = imageproc::filter::gaussian_blur_f32(&gray, 0.85); @@ -235,386 +242,40 @@ fn has_printed_header(image: &RgbaImage, first: u32, spacing: u32) -> bool { && columns.iter().filter(|&&ink| ink).count() * 100 >= width as usize * 12 } -fn strip_centers(rows: &[u32], threshold: u32) -> Vec { - let mut centers = Vec::new(); - let gap = (rows.len() / 220).max(2); - let (mut first, mut last, mut count, mut weighted) = (0, 0, 0., 0.); - for (y, value) in rows - .iter() - .copied() - .enumerate() - .filter(|(_, n)| *n >= threshold) - { - if count == 0. || y - last > gap { - if count > 0. && last - first <= gap * 2 { - centers.push(weighted / count); +fn dominant_rows(points: &[(f32, f32)], h: u32) -> (f32, Vec) { + let mut best_score = 0.; + let mut best_angle = 0.; + let mut best_rows = vec![0; h as usize]; + for (steps, increment) in [(24, 0.5), (9, 0.05)] { + let center = best_angle; + for step in -steps..=steps { + let angle = center + (step as f32 * increment).to_radians(); + let (score, rows) = projected_rows(points, h, angle); + if score > best_score { + best_score = score; + best_angle = angle; + best_rows = rows; } - first = y; - count = 0.; - weighted = 0.; } - last = y; - count += value as f32; - weighted += y as f32 * value as f32; } - if count > 0. && last - first <= gap * 2 { - centers.push(weighted / count); - } - centers + (best_angle, best_rows) } -fn nearest_ruling(strip: &[f32], y: f32, tolerance: f32) -> f32 { - if strip.is_empty() || !y.is_finite() { - return f32::NAN; - } - let next = strip.partition_point(|candidate| *candidate < y); - let left = strip[next.saturating_sub(1)]; - let right = strip[next.min(strip.len() - 1)]; - let matched = if (y - left).abs() < (right - y).abs() { - left - } else { - right - }; - if (matched - y).abs() <= tolerance { - matched - } else { - f32::NAN - } +struct MeasuredBands { + bands: Vec<(u32, u32)>, + spacing: f32, + confidence: f32, } -fn smooth_ruling_run(centers: &[f32]) -> &[f32] { - let mut start = 0; - let mut best = ¢ers[..0]; - for (i, window) in centers.windows(3).enumerate() { - let previous = window[1] - window[0]; - let next = window[2] - window[1]; - if next < 0.75 * previous || next > 1.33 * previous { - if i + 2 - start > best.len() { - best = ¢ers[start..i + 2]; - } - start = i + 1; - } - } - if centers.len() - start > best.len() { - ¢ers[start..] - } else { - best - } +fn band_center(&(start, end): &(u32, u32)) -> f32 { + (start + end) as f32 / 2. } -// Track the same rulings across the page before applying any global rotation. -fn flatten_rulings( - opaque: &RgbaImage, - points: &[(f32, f32)], - w: u32, - h: u32, - ratio: f32, - camera: Option<&crate::export::CameraMetadata>, -) -> Result> { - use base64::Engine; - const STRIPS: usize = 9; - const MID: usize = STRIPS / 2; - const MIN_TRACKED_LINES: usize = 6; - let columns: [f32; STRIPS] = std::array::from_fn(|i| w as f32 * (0.22 + i as f32 * 0.07)); - let radius = (w / 120).max(4) as f32; - let mut rows = vec![[0; STRIPS]; h as usize]; - for &(x, y) in points { - let x = x + w as f32 / 2.; - let index = ((x / w as f32 - 0.22) / 0.07).round() as usize; - if index < STRIPS && (x - columns[index]).abs() < radius { - rows[(y + h as f32 / 2.) as usize][index] += 1; - } - } - let strips: [Vec; STRIPS] = std::array::from_fn(|index| { - let profile: Vec<_> = rows.iter().map(|row| row[index]).collect(); - strip_centers(&profile, (radius * 0.8).ceil() as u32) - }); - let sequence = smooth_ruling_run(&strips[MID]); - if sequence.len() < MIN_TRACKED_LINES || sequence.windows(2).any(|pair| pair[1] - pair[0] < 5.) - { - return Ok(None); - } - let mut tracks: [Vec; STRIPS] = std::array::from_fn(|_| Vec::new()); - tracks[MID] = sequence.to_vec(); - let tolerance = |i: usize| { - let previous = if i == 0 { - f32::INFINITY - } else { - sequence[i] - sequence[i - 1] - }; - let next = sequence - .get(i + 1) - .map_or(f32::INFINITY, |y| y - sequence[i]); - previous.min(next) * 0.42 - }; - for walk in [ - (0..MID).rev().collect::>(), - (MID + 1..STRIPS).collect(), - ] { - let mut previous = sequence.to_vec(); - for index in walk { - tracks[index] = previous - .iter_mut() - .enumerate() - .map(|(i, y)| { - let matched = nearest_ruling(&strips[index], *y, tolerance(i)); - if matched.is_finite() { - *y = matched; - } - matched - }) - .collect(); - } - } - // Interpolate only an isolated missing sample with measured neighbors. - for index in 1..STRIPS - 1 { - let (before, rest) = tracks.split_at_mut(index); - let (middle, after) = rest.split_at_mut(1); - for (i, y) in middle[0].iter_mut().enumerate() { - let (left, right) = (before[index - 1][i], after[0][i]); - if !y.is_finite() && (left - right).abs() <= tolerance(i) { - *y = (left + right) / 2.; - } - } - } - let mut start = 0; - let mut run = 0..0; - for i in 0..=sequence.len() { - if i == sequence.len() || tracks.iter().any(|track| !track[i].is_finite()) { - if i - start > run.len() { - run = start..i; - } - start = i + 1; - } - } - if run.len() < MIN_TRACKED_LINES || run.len() * 4 < sequence.len() * 3 { - return Ok(None); - } - let best = &sequence[run.clone()]; - let tracks = tracks.each_ref().map(|track| &track[run.clone()]); - let spacing = (best[best.len() - 1] - best[0]) / (best.len() - 1) as f32; - // Leave flat or uniformly rotated paper on the existing affine path. - let slope = (tracks[STRIPS - 1][0] - tracks[0][0]) / (columns[STRIPS - 1] - columns[0]); - let nonlinear = tracks.iter().zip(columns).any(|(track, x)| { - track.iter().enumerate().any(|(i, y)| { - (y - (best[0] + spacing * i as f32 + slope * (x - columns[MID]))).abs() > 3. - }) - }); - if !nonlinear && camera.is_some() { - return Ok(None); - } - let (ow, oh) = opaque.dimensions(); - let geometry = |x: f32, i: usize| { - let j = columns - .partition_point(|column| *column < x) - .saturating_sub(1) - .min(STRIPS - 2); - let t = (x - columns[j]) / (columns[j + 1] - columns[j]); - tracks[j][i] + t * (tracks[j + 1][i] - tracks[j][i]) - }; - let step = (spacing / ratio).round() as u32; - let top = (best[0] / ratio).round() as u32; - let last = top + (best.len() - 1) as u32 * step; - if top == 0 || last >= oh - 1 { - return Ok(None); - } - let analysis_tracks: Vec> = (0..w) - .map(|x| (0..best.len()).map(|i| geometry(x as f32, i)).collect()) - .collect(); - if analysis_tracks - .iter() - .any(|track| track.windows(2).any(|pair| pair[0] >= pair[1])) - { - return Ok(None); - } - let mut support = vec![vec![false; best.len()]; w as usize]; - for &(x, y) in points { - let x = (x + w as f32 / 2.) as usize; - let y = y + h as f32 / 2.; - let track = &analysis_tracks[x]; - let first = track.partition_point(|line| *line < y - 3.); - if track.get(first).is_some_and(|line| *line <= y + 3.) { - support[x][first] = true; - } - } - // Use the shared writing area when perspective makes the lower rows wider. - let mut left_edges = Vec::new(); - let mut right_edges = Vec::new(); - for i in 0..best.len() { - let ink: Vec<_> = support - .iter() - .enumerate() - .filter_map(|(x, column)| column[i].then_some(x)) - .collect(); - let max_gap = (w as usize / 30).max(3); - let Some(continuous) = ink - .chunk_by(|a, b| b - a <= max_gap) - .max_by_key(|run| run.len()) - else { - return Ok(None); - }; - if continuous.len() < w as usize / 3 { - return Ok(None); - } - let trim = continuous.len() / 40; - left_edges.push(continuous[trim]); - right_edges.push(continuous[continuous.len() - 1 - trim]); - } - if !nonlinear { - // Parallel rulings can still sit in a sheared box. Compare several row ends to - // avoid treating a short or interrupted individual ruling as a paper edge. - let quarter = (best.len() / 4).max(1); - let drift = |edges: &[usize]| { - let mean = |slice: &[usize]| slice.iter().sum::() as f32 / slice.len() as f32; - (mean(&edges[..quarter]) - mean(&edges[edges.len() - quarter..])).abs() - }; - if drift(&left_edges).max(drift(&right_edges)) < w as f32 * 0.025 { - return Ok(None); - } - } - // The end points carry the horizontal foreshortening as well as the varying line pitch. - let measured_rows = (0..best.len()) - .map(|i| crate::photo::Ruling { - edges: [left_edges[i] as f32 / ratio, right_edges[i] as f32 / ratio], - heights: std::array::from_fn(|j| tracks[j][i] / ratio), - }) - .collect(); - left_edges.sort_unstable(); - right_edges.sort_unstable(); - let trim = best.len() / 10; - let left = left_edges[best.len() - 1 - trim]; - let right = right_edges[trim]; - if right.saturating_sub(left) < w as usize / 3 { - return Ok(None); - } - let mut corrected = RgbaImage::new(ow, oh); - for x in 0..ow { - let source: Vec<_> = std::iter::once(0.) - .chain((0..best.len()).map(|i| geometry(x as f32 * ratio, i) / ratio)) - .chain([(oh - 1) as f32]) - .collect(); - if source.windows(2).any(|pair| pair[0] >= pair[1]) { - return Ok(None); - } - let destination = |i: usize| match i { - 0 => 0, - i if i > best.len() => oh - 1, - i => top + (i - 1) as u32 * step, - }; - for (i, pair) in source.windows(2).enumerate() { - let start = destination(i); - let end = destination(i + 1); - for y in start..=end { - let weight = (y - start) as f32 / (end - start) as f32; - let source_y = (pair[0] + weight * (pair[1] - pair[0])).clamp(0., (oh - 1) as f32); - let before = source_y.floor() as u32; - let after = (before + 1).min(oh - 1); - let fraction = source_y - before as f32; - corrected[(x, y)] = Rgba(std::array::from_fn(|channel| { - let a = opaque[(x, before)][channel] as f32; - let b = opaque[(x, after)][channel] as f32; - (a + fraction * (b - a)).round() as u8 - })); - } - } - } - let bottom = oh - last; - let first_writable = if top >= step && !has_printed_header(&corrected, top, step) { - top - } else { - top + step - }; - Ok(Some(Identification { - margin_left: (left as f32 / ratio).round() as u32, - margin_right: ((w as usize - 1 - right) as f32 / ratio).round() as u32, - margin_top: top, - margin_bottom: bottom, - layout_top_margin: first_writable - step, - layout_bottom_margin: bottom.saturating_sub(step.div_ceil(4)), - image_width: ow, - image_height: oh, - line_spacing: step, - deskew_angle_degrees: 0., - confidence: best.len() as f32 / sequence.len() as f32, - projection: Some(crate::photo::PaperProjection::Rulings { - first: top as f32, - step: step as f32, - layout_edges: [ - (left as f32 / ratio).round(), - ow as f32 - ((w as usize - 1 - right) as f32 / ratio).round(), - ], - columns: columns.map(|x| x / ratio), - rows: measured_rows, - }), - corrected_background: camera - .map(|camera| camera.png(&corrected)) - .transpose()? - .map(|png| base64::engine::general_purpose::STANDARD.encode(png)), - })) -} -// 2026-10-24:分析坐标和返回的实际背景使用相同旋转,粗线按整条线带中心计距。 -pub fn identify(image: &DynamicImage) -> Result { - identify_with_output(image, Some(&Default::default())) -} -/// Keep the background camera tags when flattening a photograph into a new PNG. -pub fn identify_paper(image: &DynamicImage, bytes: &[u8]) -> Result { - let camera = crate::export::CameraMetadata::from_paper(Some(bytes), &Default::default())?; - identify_with_output(image, Some(&camera)) -} -/// Identify a paper-space layout while keeping the original photograph for compositing. -pub fn identify_photo(image: &DynamicImage) -> Result { - identify_with_output(image, None) -} -fn identify_with_output( - image: &DynamicImage, - camera: Option<&crate::export::CameraMetadata>, -) -> Result { - use base64::Engine; - use imageproc::geometric_transformations::{ - Border, Interpolation, rotate_about_center_no_crop, - }; - let mut opaque = image.to_rgba8(); - for pixel in opaque.pixels_mut() { - let alpha = u16::from(pixel[3]); - for channel in &mut pixel.0[..3] { - *channel = ((u16::from(*channel) * alpha + 255 * (255 - alpha) + 127) / 255) as u8; - } - pixel[3] = 255; - } - let original = DynamicImage::ImageRgba8(opaque.clone()).to_luma8(); - let (ow, oh) = original.dimensions(); - let ratio = (1200. / ow.max(oh) as f32).min(1.); - let gray = image::imageops::resize( - &original, - (ow as f32 * ratio).max(1.) as u32, - (oh as f32 * ratio).max(1.) as u32, - image::imageops::FilterType::Triangle, - ); - let (w, h) = gray.dimensions(); - let points = ruling_points(&gray); - if let Some(corrected) = flatten_rulings(&opaque, &points, w, h, ratio, camera)? { - return Ok(corrected); - } - let mut best = (0f64, 0f32, vec![0; h as usize]); - for step in -24..=24 { - let angle = (step as f32 * 0.5).to_radians(); - let (score, rows) = projected_rows(&points, h, angle); - if score > best.0 { - best = (score, angle, rows); - } - } - let coarse = best.1; - for step in -9..=9 { - let angle = coarse + (step as f32 * 0.05).to_radians(); - let (score, rows) = projected_rows(&points, h, angle); - if score > best.0 { - best = (score, angle, rows); - } - } +fn measured_bands(rows: &[u32], w: u32) -> Result { let threshold = (w as f32 * 0.3).max(20.) as u32; let mut bands = Vec::<(u32, u32)>::new(); let mut start = None; - for (y, count) in best.2.iter().enumerate() { + for (y, count) in rows.iter().enumerate() { if *count >= threshold { start.get_or_insert(y as u32); } else if let Some(s) = start.take() { @@ -622,7 +283,7 @@ fn identify_with_output( } } if let Some(s) = start { - bands.push((s, h - 1)); + bands.push((s, rows.len() as u32 - 1)); } if bands.len() < 3 { return Err(Error::new( @@ -634,10 +295,9 @@ fn identify_with_output( widths.sort_unstable(); let typical_width = widths[widths.len() / 2]; bands.retain(|(a, b)| b - a < (typical_width * 3).max(6)); - let centers: Vec<_> = bands.iter().map(|(a, b)| (*a + *b) as f32 / 2.).collect(); - let mut gaps: Vec<_> = centers + let mut gaps: Vec<_> = bands .windows(2) - .map(|v| v[1] - v[0]) + .map(|pair| band_center(&pair[1]) - band_center(&pair[0])) .filter(|v| *v > 2.) .collect(); gaps.sort_by(f32::total_cmp); @@ -659,25 +319,75 @@ fn identify_with_output( // 2026-10-24:照片边缘和阴影可能形成长条,只保留等距横线的最长连续序列。 let mut best_run = (0, 1); let mut run_start = 0; - for i in 1..centers.len() { - if (centers[i] - centers[i - 1] - spacing).abs() >= spacing * 0.08 { + for (index, pair) in bands.windows(2).enumerate() { + let i = index + 1; + if (band_center(&pair[1]) - band_center(&pair[0]) - spacing).abs() >= spacing * 0.08 { run_start = i; } if i + 1 - run_start > best_run.1 - best_run.0 { best_run = (run_start, i + 1); } } - bands = bands[best_run.0..best_run.1].to_vec(); - let centers = ¢ers[best_run.0..best_run.1]; + bands.truncate(best_run.1); + bands.drain(..best_run.0); if bands.len() < 3 || bands.iter().any(|(a, b)| (b - a) as f32 > spacing * 0.4) { return Err(Error::new( "identification_unreliable", "没有足够连续等距的横线", )); } + Ok(MeasuredBands { + bands, + spacing, + confidence: stable, + }) +} + +// 2026-10-24:分析坐标和返回的实际背景使用相同旋转,粗线按整条线带中心计距。 +pub fn identify(image: &DynamicImage) -> Result { + identify_with_output(image, Some(&Default::default())) +} +/// Keep the background camera tags when flattening a photograph into a new PNG. +pub fn identify_paper(image: &DynamicImage, bytes: &[u8]) -> Result { + let camera = crate::export::CameraMetadata::from_paper(Some(bytes), &Default::default())?; + identify_with_output(image, Some(&camera)) +} +/// Identify a paper-space layout while keeping the original photograph for compositing. +pub fn identify_photo(image: &DynamicImage) -> Result { + identify_with_output(image, None) +} +fn identify_with_output( + image: &DynamicImage, + camera: Option<&crate::export::CameraMetadata>, +) -> Result { + use base64::Engine; + use imageproc::geometric_transformations::{ + Border, Interpolation, rotate_about_center_no_crop, + }; + let opaque = over_white(image); + let original = DynamicImage::ImageRgba8(opaque.clone()).to_luma8(); + let (ow, oh) = original.dimensions(); + let ratio = (1200. / ow.max(oh) as f32).min(1.); + let gray = image::imageops::resize( + &original, + (ow as f32 * ratio).max(1.) as u32, + (oh as f32 * ratio).max(1.) as u32, + image::imageops::FilterType::Triangle, + ); + let (w, h) = gray.dimensions(); + let points = ruling_points(&gray); + if let Some(corrected) = rulings::flatten(&opaque, &points, w, h, ratio, camera)? { + return Ok(corrected); + } + let (rotation, rows) = dominant_rows(&points, h); + let MeasuredBands { + bands, + spacing, + confidence, + } = measured_bands(&rows, w)?; let mut left = w; let mut right = 0; - let (sin, cos) = best.1.sin_cos(); + let (sin, cos) = rotation.sin_cos(); for &(x, y) in &points { let xx = (x * cos + y * sin + w as f32 / 2.) .round() @@ -691,7 +401,7 @@ fn identify_with_output( right = right.max(xx); } } - let angle = best.1.to_degrees(); + let angle = rotation.to_degrees(); let corrected = if angle.abs() >= 0.1 { let fill = opaque[(0, 0)]; let rotated_width = (oh as f32 * sin.abs() + ow as f32 * cos.abs()).ceil() as u32; @@ -701,7 +411,7 @@ fn identify_with_output( } Some(rotate_about_center_no_crop( &opaque, - -best.1, + -rotation, Interpolation::Bilinear, Border::Constant(fill), )) @@ -712,16 +422,17 @@ fn identify_with_output( let (image_width, image_height) = layout_image.dimensions(); let offset_x = (image_width - ow) as f32 / 2.; let offset_y = (image_height - oh) as f32 / 2.; - let first = centers[0] / ratio + offset_y; + let first = band_center(&bands[0]) / ratio + offset_y; let line_spacing = (spacing / ratio).round() as u32; let header = has_printed_header(layout_image, first.round() as u32, line_spacing); - let first_writable = centers + let first_writable = bands .iter() .skip(usize::from(header)) - .map(|y| y / ratio + offset_y) + .map(|band| band_center(band) / ratio + offset_y) .find(|y| *y >= line_spacing as f32) .ok_or_else(|| Error::new("identification_unreliable", "纸张没有足够书写空间"))?; - let margin_bottom = (oh as f32 - centers.last().unwrap() / ratio + offset_y).round() as u32; + let margin_bottom = + (oh as f32 - band_center(bands.last().unwrap()) / ratio + offset_y).round() as u32; let corrected_background = corrected .as_ref() .zip(camera) @@ -740,11 +451,11 @@ fn identify_with_output( image_width, image_height, deskew_angle_degrees: angle, - confidence: stable, + confidence, projection: corrected .as_ref() .map(|_| crate::photo::PaperProjection::Rotated { - angle: best.1, + angle: rotation, photo_center: [ow as f32 / 2., oh as f32 / 2.], layout_center: [image_width as f32 / 2., image_height as f32 / 2.], }), diff --git a/crates/handwriting-core/src/imaging/rulings.rs b/crates/handwriting-core/src/imaging/rulings.rs new file mode 100644 index 00000000..21eff7eb --- /dev/null +++ b/crates/handwriting-core/src/imaging/rulings.rs @@ -0,0 +1,402 @@ +//! Track printed rulings across a photograph and flatten the writing area. +use super::{Identification, has_printed_header}; +use crate::{ + Result, + export::CameraMetadata, + photo::{PaperProjection, Ruling}, +}; +use base64::Engine; +use image::{Rgba, RgbaImage}; + +const STRIPS: usize = 9; +const MID: usize = STRIPS / 2; +const MIN_TRACKED_LINES: usize = 6; + +fn strip_centers(rows: &[u32], threshold: u32) -> Vec { + let mut centers = Vec::new(); + let gap = (rows.len() / 220).max(2); + let (mut first, mut last, mut count, mut weighted) = (0, 0, 0., 0.); + for (y, value) in rows + .iter() + .copied() + .enumerate() + .filter(|(_, n)| *n >= threshold) + { + if count == 0. || y - last > gap { + if count > 0. && last - first <= gap * 2 { + centers.push(weighted / count); + } + first = y; + count = 0.; + weighted = 0.; + } + last = y; + count += value as f32; + weighted += y as f32 * value as f32; + } + if count > 0. && last - first <= gap * 2 { + centers.push(weighted / count); + } + centers +} + +fn nearest_ruling(strip: &[f32], y: f32, tolerance: f32) -> f32 { + if strip.is_empty() || !y.is_finite() { + return f32::NAN; + } + let next = strip.partition_point(|candidate| *candidate < y); + let left = strip[next.saturating_sub(1)]; + let right = strip[next.min(strip.len() - 1)]; + let matched = if (y - left).abs() < (right - y).abs() { + left + } else { + right + }; + if (matched - y).abs() <= tolerance { + matched + } else { + f32::NAN + } +} + +fn smooth_ruling_run(centers: &[f32]) -> &[f32] { + let mut start = 0; + let mut best = ¢ers[..0]; + for (i, window) in centers.windows(3).enumerate() { + let previous = window[1] - window[0]; + let next = window[2] - window[1]; + if next < 0.75 * previous || next > 1.33 * previous { + if i + 2 - start > best.len() { + best = ¢ers[start..i + 2]; + } + start = i + 1; + } + } + if centers.len() - start > best.len() { + ¢ers[start..] + } else { + best + } +} + +fn sample_strips( + points: &[(f32, f32)], + w: u32, + h: u32, + columns: &[f32; STRIPS], +) -> [Vec; STRIPS] { + let radius = (w / 120).max(4) as f32; + let mut rows = vec![[0; STRIPS]; h as usize]; + for &(x, y) in points { + let x = x + w as f32 / 2.; + let index = ((x / w as f32 - 0.22) / 0.07).round() as usize; + if index < STRIPS && (x - columns[index]).abs() < radius { + rows[(y + h as f32 / 2.) as usize][index] += 1; + } + } + std::array::from_fn(|index| { + let profile: Vec<_> = rows.iter().map(|row| row[index]).collect(); + strip_centers(&profile, (radius * 0.8).ceil() as u32) + }) +} + +fn follow_strips( + indices: impl Iterator, + strips: &[Vec; STRIPS], + tracks: &mut [Vec; STRIPS], + sequence: &[f32], + tolerances: &[f32], +) { + let mut previous = sequence.to_vec(); + for index in indices { + tracks[index] = previous + .iter_mut() + .zip(tolerances) + .map(|(y, &tolerance)| { + let matched = nearest_ruling(&strips[index], *y, tolerance); + if matched.is_finite() { + *y = matched; + } + matched + }) + .collect(); + } +} + +fn track_sequence(strips: &[Vec; STRIPS], sequence: &[f32]) -> [Vec; STRIPS] { + let mut tracks: [Vec; STRIPS] = std::array::from_fn(|_| Vec::new()); + tracks[MID] = sequence.to_vec(); + let tolerances: Vec<_> = (0..sequence.len()) + .map(|i| { + let previous = if i == 0 { + f32::INFINITY + } else { + sequence[i] - sequence[i - 1] + }; + let next = sequence + .get(i + 1) + .map_or(f32::INFINITY, |y| y - sequence[i]); + previous.min(next) * 0.42 + }) + .collect(); + follow_strips((0..MID).rev(), strips, &mut tracks, sequence, &tolerances); + follow_strips(MID + 1..STRIPS, strips, &mut tracks, sequence, &tolerances); + // Interpolate only an isolated missing sample with measured neighbors. + for index in 1..STRIPS - 1 { + let (before, rest) = tracks.split_at_mut(index); + let (middle, after) = rest.split_at_mut(1); + for (i, y) in middle[0].iter_mut().enumerate() { + let (left, right) = (before[index - 1][i], after[0][i]); + if !y.is_finite() && (left - right).abs() <= tolerances[i] { + *y = (left + right) / 2.; + } + } + } + tracks +} + +struct RulingGrid { + columns: [f32; STRIPS], + tracks: [Vec; STRIPS], + confidence: f32, +} + +impl RulingGrid { + fn detect(points: &[(f32, f32)], w: u32, h: u32) -> Option { + let columns: [f32; STRIPS] = std::array::from_fn(|i| w as f32 * (0.22 + i as f32 * 0.07)); + let strips = sample_strips(points, w, h, &columns); + let sequence = smooth_ruling_run(&strips[MID]); + if sequence.len() < MIN_TRACKED_LINES + || sequence.windows(2).any(|pair| pair[1] - pair[0] < 5.) + { + return None; + } + let mut tracks = track_sequence(&strips, sequence); + let mut start = 0; + let mut run = 0..0; + for i in 0..=sequence.len() { + if i == sequence.len() || tracks.iter().any(|track| !track[i].is_finite()) { + if i - start > run.len() { + run = start..i; + } + start = i + 1; + } + } + if run.len() < MIN_TRACKED_LINES || run.len() * 4 < sequence.len() * 3 { + return None; + } + let confidence = run.len() as f32 / sequence.len() as f32; + for track in &mut tracks { + track.truncate(run.end); + track.drain(..run.start); + } + Some(Self { + columns, + tracks, + confidence, + }) + } + + fn nonlinear(&self, spacing: f32) -> bool { + let first = self.tracks[MID][0]; + let slope = (self.tracks[STRIPS - 1][0] - self.tracks[0][0]) + / (self.columns[STRIPS - 1] - self.columns[0]); + self.tracks.iter().zip(self.columns).any(|(track, x)| { + track.iter().enumerate().any(|(i, y)| { + (y - (first + spacing * i as f32 + slope * (x - self.columns[MID]))).abs() > 3. + }) + }) + } + + fn heights_at(&self, x: f32) -> impl Iterator { + let j = self + .columns + .partition_point(|column| *column < x) + .saturating_sub(1) + .min(STRIPS - 2); + let t = (x - self.columns[j]) / (self.columns[j + 1] - self.columns[j]); + self.tracks[j] + .iter() + .zip(&self.tracks[j + 1]) + .map(move |(&left, &right)| left + t * (right - left)) + } +} + +fn writing_edges( + grid: &RulingGrid, + points: &[(f32, f32)], + w: u32, + h: u32, +) -> Option<(Vec, Vec)> { + let analysis_tracks: Vec> = (0..w) + .map(|x| grid.heights_at(x as f32).collect()) + .collect(); + if analysis_tracks + .iter() + .any(|track| track.windows(2).any(|pair| pair[0] >= pair[1])) + { + return None; + } + let mut support = vec![vec![false; w as usize]; grid.tracks[MID].len()]; + for &(x, y) in points { + let x = (x + w as f32 / 2.) as usize; + let y = y + h as f32 / 2.; + let track = &analysis_tracks[x]; + let first = track.partition_point(|line| *line < y - 3.); + if track.get(first).is_some_and(|line| *line <= y + 3.) { + support[first][x] = true; + } + } + // Use the shared writing area when perspective makes the lower rows wider. + let mut left_edges = Vec::new(); + let mut right_edges = Vec::new(); + let max_gap = (w as usize / 30).max(3); + for row in support { + let ink: Vec<_> = row + .iter() + .enumerate() + .filter_map(|(x, &present)| present.then_some(x)) + .collect(); + let continuous = ink + .chunk_by(|a, b| b - a <= max_gap) + .max_by_key(|run| run.len())?; + if continuous.len() < w as usize / 3 { + return None; + } + let trim = continuous.len() / 40; + left_edges.push(continuous[trim]); + right_edges.push(continuous[continuous.len() - 1 - trim]); + } + Some((left_edges, right_edges)) +} + +fn edge_drift(edges: &[usize]) -> f32 { + let quarter = (edges.len() / 4).max(1); + let mean = |slice: &[usize]| slice.iter().sum::() as f32 / slice.len() as f32; + (mean(&edges[..quarter]) - mean(&edges[edges.len() - quarter..])).abs() +} + +fn straighten_columns( + opaque: &RgbaImage, + grid: &RulingGrid, + ratio: f32, + top: u32, + step: u32, +) -> Option { + let (ow, oh) = opaque.dimensions(); + let destinations: Vec<_> = std::iter::once(0) + .chain((0..grid.tracks[MID].len()).map(|i| top + i as u32 * step)) + .chain([oh - 1]) + .collect(); + let mut corrected = RgbaImage::new(ow, oh); + for x in 0..ow { + let source: Vec<_> = std::iter::once(0.) + .chain(grid.heights_at(x as f32 * ratio).map(|y| y / ratio)) + .chain([(oh - 1) as f32]) + .collect(); + if source.windows(2).any(|pair| pair[0] >= pair[1]) { + return None; + } + for (pair, dest) in source.windows(2).zip(destinations.windows(2)) { + let (start, end) = (dest[0], dest[1]); + for y in start..=end { + let weight = (y - start) as f32 / (end - start) as f32; + let source_y = (pair[0] + weight * (pair[1] - pair[0])).clamp(0., (oh - 1) as f32); + let before = source_y.floor() as u32; + let after = (before + 1).min(oh - 1); + let fraction = source_y - before as f32; + corrected[(x, y)] = Rgba(std::array::from_fn(|channel| { + let a = opaque[(x, before)][channel] as f32; + let b = opaque[(x, after)][channel] as f32; + (a + fraction * (b - a)).round() as u8 + })); + } + } + } + Some(corrected) +} + +pub(super) fn flatten( + opaque: &RgbaImage, + points: &[(f32, f32)], + w: u32, + h: u32, + ratio: f32, + camera: Option<&CameraMetadata>, +) -> Result> { + let Some(grid) = RulingGrid::detect(points, w, h) else { + return Ok(None); + }; + let best = &grid.tracks[MID]; + let spacing = (best[best.len() - 1] - best[0]) / (best.len() - 1) as f32; + // Leave flat or uniformly rotated paper on the existing affine path. + let nonlinear = grid.nonlinear(spacing); + if !nonlinear && camera.is_some() { + return Ok(None); + } + let (ow, oh) = opaque.dimensions(); + let step = (spacing / ratio).round() as u32; + let top = (best[0] / ratio).round() as u32; + let last = top + (best.len() - 1) as u32 * step; + if top == 0 || last >= oh - 1 { + return Ok(None); + } + let Some((mut left_edges, mut right_edges)) = writing_edges(&grid, points, w, h) else { + return Ok(None); + }; + // Parallel rulings can still sit inside a sheared box. + if !nonlinear && edge_drift(&left_edges).max(edge_drift(&right_edges)) < w as f32 * 0.025 { + return Ok(None); + } + // The end points carry the horizontal foreshortening as well as the varying line pitch. + let measured_rows = (0..best.len()) + .map(|i| Ruling { + edges: [left_edges[i] as f32 / ratio, right_edges[i] as f32 / ratio], + heights: std::array::from_fn(|j| grid.tracks[j][i] / ratio), + }) + .collect(); + left_edges.sort_unstable(); + right_edges.sort_unstable(); + let trim = best.len() / 10; + let left = left_edges[best.len() - 1 - trim]; + let right = right_edges[trim]; + if right.saturating_sub(left) < w as usize / 3 { + return Ok(None); + } + let Some(corrected) = straighten_columns(opaque, &grid, ratio, top, step) else { + return Ok(None); + }; + let bottom = oh - last; + let first_writable = if top >= step && !has_printed_header(&corrected, top, step) { + top + } else { + top + step + }; + Ok(Some(Identification { + margin_left: (left as f32 / ratio).round() as u32, + margin_right: ((w as usize - 1 - right) as f32 / ratio).round() as u32, + margin_top: top, + margin_bottom: bottom, + layout_top_margin: first_writable - step, + layout_bottom_margin: bottom.saturating_sub(step.div_ceil(4)), + image_width: ow, + image_height: oh, + line_spacing: step, + deskew_angle_degrees: 0., + confidence: grid.confidence, + projection: Some(PaperProjection::Rulings { + first: top as f32, + step: step as f32, + layout_edges: [ + (left as f32 / ratio).round(), + ow as f32 - ((w as usize - 1 - right) as f32 / ratio).round(), + ], + columns: grid.columns.map(|x| x / ratio), + rows: measured_rows, + }), + corrected_background: camera + .map(|camera| camera.png(&corrected)) + .transpose()? + .map(|png| base64::engine::general_purpose::STANDARD.encode(png)), + })) +} diff --git a/crates/handwriting-core/src/pdf_page/text.rs b/crates/handwriting-core/src/pdf_page/text.rs index 5e7bac14..31ec6509 100644 --- a/crates/handwriting-core/src/pdf_page/text.rs +++ b/crates/handwriting-core/src/pdf_page/text.rs @@ -53,8 +53,8 @@ struct Collector<'a> { visibility: Visibility, } -fn show(operator: &str) -> bool { - matches!(operator, "Tj" | "TJ" | "'" | "\"") +fn shows_text(operator: &[u8]) -> bool { + matches!(operator, b"Tj" | b"TJ" | b"'" | b"\"") } pub(super) fn extract( @@ -96,76 +96,9 @@ pub(super) fn extract( visibility: Visibility::new(target.height()), }; // 2026-11-23:直接文字指令独立标记。嵌套表单、批注和不支持的字形仍由原 PDF 绘制。 - let mut original = page.operations(); - let mut has_inline_image = false; - let mut has_text = false; - let mut operators = 0usize; - while let Some(op) = original.next() { - operators += 1; - if operators > 200_000 { - return Err(Error::new("archive_limit", "PDF 页面绘图指令过多")); - } - let name: &[u8] = op.operator; - has_inline_image |= name == b"BI"; - has_text |= matches!(name, b"Tj" | b"TJ" | b"'" | b"\""); - } - let mut content = if has_text && !has_inline_image { - Content::decode(stream).ok() - } else { - None - }; - if let Some(parsed) = content.as_ref() { - // 2026-11-23:两种解析器必须读到相同的指令,才允许重写页面内容。 - let mut original = page.operations(); - if !parsed.operations.iter().all(|op| { - original - .next() - .is_some_and(|raw| &**raw.operator == op.operator.as_bytes()) - }) || original.next().is_some() - { - content = None; - } - } + let content = checked_content(page, stream)?; if let Some(parsed) = content.as_ref() { - let mut marked = Vec::new(); - let mut mode = 0; - let mut saved = Vec::new(); - for (index, op) in parsed.operations.iter().enumerate() { - match op.operator.as_str() { - "Tr" => { - mode = op - .operands - .first() - .and_then(|o| o.as_i64().ok()) - .unwrap_or(-1) - } - "q" => saved.push(mode), - "Q" => mode = saved.pop().unwrap_or(0), - _ => {} - } - if show(&op.operator) && matches!(mode, 0 | 1) { - let number = device.candidates.len(); - device.candidates.push(Candidate { - index, - mode, - lines: Vec::new(), - supported: true, - }); - marked.push(Operation::new( - "BMC", - vec![Object::Name( - format!("{}{number}", device.marker_prefix).into_bytes(), - )], - )); - marked.push(op.clone()); - marked.push(Operation::new("EMC", vec![])); - } else { - marked.push(op.clone()); - } - } - let annotated = Content { operations: marked } - .encode() - .map_err(|e| Error::new("invalid_document", e.to_string()))?; + let annotated = mark_candidates(parsed, &device.marker_prefix, &mut device.candidates)?; interpret( TypedIter::new(&annotated), page.resources(), @@ -197,36 +130,11 @@ pub(super) fn extract( return Err(Error::new("text_limit", "PDF 页面文字过长")); } let mut lines = Vec::new(); - let mut background = None; - let mut accepted = device - .candidates - .into_iter() - .filter(|c| c.supported && !c.lines.is_empty()) - .peekable(); - if accepted.peek().is_some() - && let Some(content) = content - { - let mut output = Vec::new(); - for (index, op) in content.operations.into_iter().enumerate() { - if accepted.peek().is_some_and(|c| c.index == index) { - let item = accepted.next().unwrap(); - for line in item.lines { - append(&mut lines, line); - } - // 2026-11-23:让字形不可见但保留原字距、推进量和文字状态。 - output.push(Operation::new("Tr", vec![3.into()])); - output.push(op); - output.push(Operation::new("Tr", vec![item.mode.into()])); - } else { - output.push(op); - } - } - background = Some( - Content { operations: output } - .encode() - .map_err(|e| Error::new("invalid_document", e.to_string()))?, - ); - } + let background = if let Some(content) = content { + rewrite_background(content, device.candidates, &mut lines)? + } else { + None + }; lines.retain(|line| !line.text.trim().is_empty()); Ok(Extraction { lines, @@ -235,6 +143,113 @@ pub(super) fn extract( }) } +fn checked_content(page: &Page<'_>, stream: &[u8]) -> Result> { + let mut original = page.operations(); + let mut has_inline_image = false; + let mut has_text = false; + let mut operators = 0usize; + while let Some(op) = original.next() { + operators += 1; + if operators > 200_000 { + return Err(Error::new("archive_limit", "PDF 页面绘图指令过多")); + } + let name: &[u8] = op.operator; + has_inline_image |= name == b"BI"; + has_text |= shows_text(name); + } + if !has_text || has_inline_image { + return Ok(None); + } + let Ok(parsed) = Content::decode(stream) else { + return Ok(None); + }; + // 两种解析器必须读到相同的指令,才允许重写页面内容。 + let mut original = page.operations(); + let same_operators = parsed.operations.iter().all(|op| { + original + .next() + .is_some_and(|raw| &**raw.operator == op.operator.as_bytes()) + }) && original.next().is_none(); + Ok(same_operators.then_some(parsed)) +} + +fn mark_candidates( + parsed: &Content, + prefix: &str, + candidates: &mut Vec, +) -> Result> { + let mut marked = Vec::with_capacity(parsed.operations.len()); + let mut mode = 0; + let mut saved = Vec::new(); + for (index, op) in parsed.operations.iter().enumerate() { + match op.operator.as_str() { + "Tr" => { + mode = op + .operands + .first() + .and_then(|o| o.as_i64().ok()) + .unwrap_or(-1) + } + "q" => saved.push(mode), + "Q" => mode = saved.pop().unwrap_or(0), + _ => {} + } + if shows_text(op.operator.as_bytes()) && matches!(mode, 0 | 1) { + let number = candidates.len(); + candidates.push(Candidate { + index, + mode, + lines: Vec::new(), + supported: true, + }); + marked.push(Operation::new( + "BMC", + vec![Object::Name(format!("{prefix}{number}").into_bytes())], + )); + marked.push(op.clone()); + marked.push(Operation::new("EMC", vec![])); + } else { + marked.push(op.clone()); + } + } + encode_operations(marked) +} + +fn rewrite_background( + content: Content, + candidates: Vec, + lines: &mut Vec, +) -> Result>> { + let mut accepted = candidates + .into_iter() + .filter(|c| c.supported && !c.lines.is_empty()) + .peekable(); + if accepted.peek().is_none() { + return Ok(None); + } + let mut output = Vec::new(); + for (index, op) in content.operations.into_iter().enumerate() { + if let Some(item) = accepted.next_if(|candidate| candidate.index == index) { + for line in item.lines { + append(lines, line); + } + // 2026-11-23:让字形不可见但保留原字距、推进量和文字状态。 + output.push(Operation::new("Tr", vec![3.into()])); + output.push(op); + output.push(Operation::new("Tr", vec![item.mode.into()])); + } else { + output.push(op); + } + } + encode_operations(output).map(Some) +} + +fn encode_operations(operations: Vec) -> Result> { + Content { operations } + .encode() + .map_err(|e| Error::new("invalid_document", e.to_string())) +} + fn append(lines: &mut Vec, next: TextLine) { if let Some(prev) = lines.last_mut() { let gap = next.x - (prev.x + prev.width); diff --git a/crates/handwriting-core/src/render.rs b/crates/handwriting-core/src/render.rs index 877554cb..74c60587 100644 --- a/crates/handwriting-core/src/render.rs +++ b/crates/handwriting-core/src/render.rs @@ -4,7 +4,7 @@ use crate::{ }; use base64::{Engine, engine::general_purpose::STANDARD}; use image::{GrayImage, RgbaImage}; -use rand::{RngExt, SeedableRng}; +use rand::SeedableRng; use rand_chacha::ChaCha8Rng; use std::sync::{ Arc, @@ -33,11 +33,14 @@ pub struct RenderRequest { pub fonts: FontBook, pub limits: Limits, } +mod composition; mod fine; mod glyph; mod homework; mod illustration; mod ink; +mod line; +mod paragraph; mod units; use glyph::{Glyph, Glyphs}; use ink::{blank_paper, normal, paint_math_unit, paste_mask, perturb}; @@ -140,114 +143,17 @@ impl) -> Result<()>> Pages<'_, F> { return Ok(()); } let mut units = std::mem::take(&mut self.line); - let top = self.p.top_margin; - let bottom = self.canvas.height() as f32 - self.p.bottom_margin; - let available = (bottom - top).max(1.); - let ruled = ((self.p.underlined || self.p.paper_pattern.is_some()) - && self.p.width.is_some()) - || self.p.background_ruled; - let standard_ruled = ruled && self.p.layout_style == LayoutStyle::Standard; - let mut gap = (self.p.font_size * 0.12).round().max(2.); - if standard_ruled { - gap = gap.min((self.p.line_spacing - self.p.font_size).max(2.)); - } - let bounds = |units: &[LineUnit]| { - let visible: Vec<_> = units.iter().filter(|u| u.glyph.ink).collect(); - ( - visible - .iter() - .map(|u| u.glyph.top + u.dy) - .min() - .unwrap_or(0), - visible - .iter() - .map(|u| u.glyph.bottom() + u.dy) - .max() - .unwrap_or(0), - ) - }; - let (mut min_y, mut max_y) = bounds(&units); - if (max_y - min_y) as f32 > available { - let factor = available / (max_y - min_y) as f32; - for u in &mut units { - let old_top = u.glyph.top; - let old_dy = u.dy; - u.glyph = u.glyph.clone().fit( - u.glyph.mask.width() as f32 * factor, - (u.glyph.mask.height() as f32 * factor).max(1.), - ); - u.dy = ((old_top + old_dy - min_y) as f32 * factor).floor() as i32 - u.glyph.top; - } - (min_y, max_y) = bounds(&units); - } - if standard_ruled { - let height = (self.p.line_spacing - gap).floor() as i32; - let descent = (self.p.font_size * 0.30).round() as i32; - fit_standard_ruled_row(&mut units, min_y, max_y, height, descent); - (min_y, max_y) = bounds(&units); - } - // 2026-10-17:公式可占多格,后续基线仍须落在原纸张横线上。 - let align = |anchor: f32| { - if ruled { - top + (((anchor - top) / self.p.line_spacing) - 0.00001) - .ceil() - .max(1.) - * self.p.line_spacing - } else { - anchor - } - }; - let mut anchor = self.y.max(top - min_y as f32); - if self.dirty { - anchor = anchor.max(self.previous_bottom + gap - min_y as f32); - } - anchor = align(anchor); - if anchor + max_y as f32 > bottom && self.dirty { + let mut layout = line::LineLayout::fit(&mut units, self.p, self.canvas.height()); + let mut anchor = layout.baseline(self.y, self.dirty.then_some(self.previous_bottom)); + if layout.overflows(anchor) && self.dirty { self.emit_page(false)?; if self.stopped { return Ok(()); } - anchor = align(self.y.max(top - min_y as f32)); + anchor = layout.baseline(self.y, None); } - if anchor + max_y as f32 > bottom { - if ruled { - // 2026-10-17:仅空页也装不下的极高公式缩至实际横线,不把基线移到页底。 - let mut best = (0f32, top + self.p.line_spacing); - let mut row = 1usize; - loop { - let baseline = top + row as f32 * self.p.line_spacing; - if baseline >= bottom { - break; - } - let above = if min_y < 0 { - ((baseline - top - 1.) / -(min_y as f32)).max(0.) - } else { - 1. - }; - let below = if max_y > 0 { - ((bottom - baseline - 1.) / max_y as f32).max(0.) - } else { - 1. - }; - let factor = above.min(below).min(1.); - if factor > best.0 { - best = (factor, baseline); - } - row += 1; - } - anchor = best.1; - for u in &mut units { - let offset = u.glyph.top + u.dy; - u.glyph = u.glyph.clone().fit( - u.glyph.mask.width() as f32 * best.0, - (u.glyph.mask.height() as f32 * best.0).max(1.), - ); - u.dy = (offset as f32 * best.0).round() as i32 - u.glyph.top; - } - (_, max_y) = bounds(&units); - } else { - anchor = bottom - max_y as f32; - } + if layout.overflows(anchor) { + anchor = layout.fit_empty_page(&mut units); } for u in units { let origin = ( @@ -273,40 +179,12 @@ impl) -> Result<()>> Pages<'_, F> { } } self.written_lines += 1; - self.previous_bottom = anchor + max_y as f32; + self.previous_bottom = layout.ink_bottom(anchor); self.y = anchor + self.p.line_spacing; self.x = self.p.left_margin; self.dirty = true; Ok(()) } - // 2026-10-24:将末尾短语整体移至续行,已渲染的结构化公式保持原子性。 - fn homework_wrap(&mut self, continuation: f32, right: f32) -> Result<()> { - let cutoff = self.p.left_margin + (right - self.p.left_margin) * 0.4; - let split = self - .line - .iter() - .enumerate() - .rev() - .find(|(i, u)| u.break_after && *i + 1 < self.line.len() && u.x as f32 >= cutoff) - .map(|(i, _)| i + 1); - self.wrap_at(split, continuation) - } - fn wrap_at(&mut self, split: Option, continuation: f32) -> Result<()> { - let mut tail = split.map(|at| self.line.split_off(at)).unwrap_or_default(); - let old_cursor = self.x; - self.finish_line()?; - if let Some(first) = tail.first() { - let shift = continuation - first.x as f32; - for unit in &mut tail { - unit.x += shift.round() as i32; - } - self.x = old_cursor + shift; - self.line = tail; - } else { - self.x = continuation; - } - Ok(()) - } fn flush(&mut self, force: bool) -> Result<()> { self.finish_line()?; self.emit_page(force) @@ -414,44 +292,6 @@ pub(crate) fn render_output Result<()>>( }) } -fn fit_standard_ruled_row( - units: &mut [LineUnit], - min_y: i32, - max_y: i32, - height: i32, - descent: i32, -) { - let ink_height = max_y - min_y; - let top = descent - height; - if height <= 0 - || ink_height <= 0 - || ink_height as f32 > height as f32 * 1.2 - || (min_y >= top && max_y <= descent) - { - return; - } - // 2026-11-17:轻微越界先在同一行格内纵向适配,保留横向字距和高公式的跨行避让。 - let fit_height = height.min(ink_height); - let start = min_y.clamp(top, descent - fit_height); - for unit in units.iter_mut().filter(|unit| unit.glyph.ink) { - let offset = unit.glyph.top + unit.dy - min_y; - let end = offset + unit.glyph.mask.height() as i32; - let first = offset * fit_height / ink_height; - let last = (end * fit_height + ink_height - 1) / ink_height; - let new_height = (last - first) as u32; - if new_height != unit.glyph.mask.height() { - let mut mask = GrayImage::new(unit.glyph.mask.width(), new_height); - // 2026-11-17:合并缩小后落在同一行的像素,保留分数线等细笔画。 - for (x, y, pixel) in unit.glyph.mask.enumerate_pixels() { - let row = (y * new_height) / unit.glyph.mask.height(); - mask[(x, row)][0] = mask[(x, row)][0].max(pixel[0]); - } - unit.glyph.mask = mask; - } - unit.dy = start + first - unit.glyph.top; - } -} - pub(crate) fn render_pages( r: &RenderRequest, cancel: &Cancellation, @@ -547,6 +387,7 @@ fn render_planes( } else { layout_units(&nodes) }; + let mut composer = composition::UnitComposer::new(p, &r.text, source.as_deref(), (w, h)); let mut glyphs = Glyphs::with_parameters(&r.fonts, p)?; let mut pages = Pages { canvas: background.clone(), @@ -575,74 +416,19 @@ fn render_planes( stopped: false, }; let right = w as f32 - p.effective_right_margin(); - let mut i = 0; - let mut node_index = 0; - let mut paragraph_start = true; - let mut group_start = 0; - let mut section_line_start = 0; - let mut continuation = p.left_margin; - while i < units.len() && !pages.stopped { - cancel.check()?; - if homework_mode && paragraph_start && !matches!(units[i][0], Node::Newline | Node::Break) { - let style = homework::paragraph(&units[i..], p.font_size); - let available = right - p.left_margin; - let indent = if p.first_line_indent - && !matches!( - units[i][0], - Node::RightAlign | Node::Char(' ' | '\t' | '\u{3000}') - ) { - (2. * p.font_size).min(available - p.font_size) - } else { - style.indent.min(available * 0.15) - }; - let prefix: Vec<_> = units[i..] - .iter() - .flat_map(|u| u.iter()) - .take(style.prefix_chars) - .cloned() - .collect(); - let hanging = if prefix.is_empty() { - 0. - } else { - glyphs.unit(&prefix, p.font_size, i)?.advance + p.word_spacing - }; - continuation = p.left_margin + indent + hanging.min(available * 0.25); - pages.x = p.left_margin + indent; - if style.gap_before - && (style.title || pages.written_lines - section_line_start >= 3) - && pages.dirty - && i >= 2 - && !matches!(units[i - 2][0], Node::Newline | Node::Break) - { - pages.y += p.line_spacing; - } - if style.gap_before { - section_line_start = pages.written_lines; - } - paragraph_start = false; - } else if !homework_mode - && paragraph_start - && !matches!(units[i][0], Node::Newline | Node::Break) - { - if p.first_line_indent - && !matches!( - units[i][0], - Node::RightAlign | Node::Char(' ' | '\t' | '\u{3000}') - ) - { - pages.x = (p.left_margin + 2. * p.font_size).min(right - p.font_size); - } - paragraph_start = false; + let mut paragraph = paragraph::ParagraphLayout::new(&nodes, &units, p.left_margin, right); + let mut next_node_index = 0; + for (i, &unit) in units.iter().enumerate() { + if pages.stopped { + break; } - match &units[i][0] { - Node::Break => { - pages.flush(false)?; - paragraph_start = true; - } - Node::Newline => { - pages.newline()?; - paragraph_start = true; - } + cancel.check()?; + let node_index = next_node_index; + next_node_index += unit.len(); + paragraph.begin_unit(&mut pages, &mut glyphs, i)?; + match &unit[0] { + Node::Break => pages.flush(false)?, + Node::Newline => pages.newline()?, Node::RightAlign => { let rest = units[i + 1..] .iter() @@ -728,180 +514,41 @@ fn render_planes( pages.y = pages.previous_bottom + p.line_spacing; } node => { - let size = - (p.font_size + normal(&mut pages.rng, p.font_size_sigma)).clamp(1., 2048.); - let mut fine_parts = None; - let mut g = if p.fine_edit - && units[i].len() > 1 - && units[i].iter().all(|node| matches!(node, Node::Char(_))) - { - let (advance, children) = glyphs.sequence_parts(units[i], size, 0)?; - let composed = Glyphs::compose(advance, children.clone(), vec![])?; - fine_parts = Some(fine::Parts::new( - &composed, - children, - node_index, - source.as_deref(), - )); - composed - } else { - glyphs.unit(units[i], size, i)? - }; - let mut compound = units[i].len() > 1 - || !matches!(node, Node::Char(_)) - || matches!(node,Node::Char(c) if glyph::is_circled(*c)); - if !p.monospaced - && pages.rng.random::() < p.strikethrough_probability - && !matches!(node,Node::Char(c) if c.is_whitespace()) - { - let candidates: Vec<_> = r - .text - .chars() - .filter(|c| !c.is_whitespace() && !",。!?,.!?".contains(*c)) - .take(1024) - .collect(); - if !candidates.is_empty() { - let wrong = glyphs.glyph( - candidates[pages.rng.random_range(0..candidates.len())], - size, - )?; - let length = (p.font_size * 2f32.sqrt() - + normal(&mut pages.rng, p.strikethrough_length_sigma)) - .clamp(0., (w as f32 + h as f32).min(16384.)); - let angle = (45. + normal(&mut pages.rng, p.strikethrough_angle_sigma)) - .to_radians(); - let width = (p.strikethrough_width - + normal(&mut pages.rng, p.strikethrough_width_sigma)) - .clamp(1., (w.min(h) as f32).clamp(1., 256.)) - as i32; - let sy = wrong.top as f32 + length / 7.; - let path = vec![ - ((length / 7.).round() as i32, sy.round() as i32), - ( - (length / 7. + length * angle.cos() * 5. / 7.).round() as i32, - (sy + length * angle.sin() * 5. / 7.).round() as i32, - ), - ]; - // 2026-10-15:正确字写在错字和完整删除线之后,不能让较长删除线划到正确内容。 - let stroke_right = - path.iter().map(|p| p.0).max().unwrap_or(0) + width / 2 + 2; - let shift = (wrong.advance + p.word_spacing) - .max(wrong.right() as f32) - .max(stroke_right as f32) - .round() as i32; - g = Glyphs::compose( - g.advance + shift as f32, - vec![(wrong, 0, 0), (g, shift, 0)], - vec![(path, width)], - )?; - compound = true; - fine_parts = None; - } - } + let composition::PreparedGlyph { + glyph, + compound, + fine_parts, + } = composer.prepare(&mut glyphs, &mut pages.rng, unit, i, node_index)?; if homework_mode - && homework::break_before(units[i]) + && homework::break_before(unit) && let Some(previous) = pages.line.last_mut() { previous.break_after = true; } - let usable_width = right - - if homework_mode { - continuation - } else { - p.left_margin - }; let usable_height = h as f32 - p.top_margin - p.bottom_margin; - let cell = fixed_cell(units[i], p); - g = g.fit(usable_width, usable_height); + let cell = fixed_cell(unit, p); + let mut g = glyph.fit(paragraph.usable_width(), usable_height); if let Some(cell) = cell { g = g.place_in_cell(cell); } - let jitter_x = if cell.is_none() && p.grid_layout && keeps_grid_cell(units[i]) { + let jitter_x = if cell.is_none() && p.grid_layout && keeps_grid_cell(unit) { normal(&mut pages.rng, p.word_spacing_sigma) } else { 0. }; - let mut x = (pages.x + jitter_x) - .round() - .max(p.left_margin - g.left as f32); - let footprint = cell.unwrap_or_else(|| g.right() as f32); - let separator = matches!(units[i], [Node::Char(' ' | '\t')]); - let closing = matches!(units[i], [Node::Char(c)] if units::closing_punctuation(*c)); - if !homework_mode && (pages.line.is_empty() || units::starts_wrap_group(&units, i)) - { - group_start = pages.line.len(); - } - if !homework_mode - && closing - && x + footprint > right - && i > 0 - && matches!(units[i - 1], [Node::Char(c)] if c.is_whitespace()) - && let Some(last) = pages.line.iter().rev().find(|u| u.glyph.ink) - && (last.x + last.glyph.right()) as f32 <= right - footprint - { - // Use spare trailing whitespace before moving a closing mark to another line. - x = right - footprint; - } - if !homework_mode && separator && x + footprint > right && !pages.line.is_empty() { - // A separator at the right edge does not need a line of its own. - pages.x = right; - node_index += units[i].len(); - i += 1; + let Some(x) = paragraph.position(&mut pages, i, &g, cell, jitter_x)? else { continue; - } - if !pages.line.is_empty() && x + footprint > right { - if homework_mode { - pages.homework_wrap(continuation, right)?; - if !pages.line.is_empty() && pages.x + g.right() as f32 > right { - pages.finish_line()?; - pages.x = continuation; - } - } else { - // Move the buffered prefix with its measured advances and fine-edit IDs. - // A word wider than a fresh line falls back to character boundaries. - let fits = |at: usize| { - pages.line.get(at).is_some_and(|first| { - // Reclaim an indented first word's offset before splitting it. - let left = p.left_margin - first.glyph.left.min(0) as f32; - (at > 0 || first.x as f32 > left.round()) - && x + footprint - - first.x as f32 - - first.glyph.left.min(0) as f32 - <= usable_width - }) - }; - let mut split = fits(group_start).then_some(group_start); - if split.is_none() && closing { - split = pages - .line - .iter() - .rposition(|u| u.glyph.ink && !matches!(nodes[u.id as usize], Node::Char(c) if units::closing_punctuation(c))) - .filter(|&at| fits(at)); - } - let bearing = split.map_or(0, |at| pages.line[at].glyph.left.min(0)); - pages.wrap_at(split, p.left_margin - bearing as f32)?; - group_start = 0; - } - if pages.stopped { - break; - } - x = (pages.x + jitter_x) - .round() - .max(p.left_margin - g.left as f32); - } - x = x - .min(right - g.right() as f32) - .max(p.left_margin - g.left as f32); + }; let dy = normal(&mut pages.rng, p.line_spacing_sigma) .round() .clamp(-usable_height * 0.25, usable_height * 0.25) as i32; - let extra = if p.grid_layout && keeps_grid_cell(units[i]) { + let extra = if p.grid_layout && keeps_grid_cell(unit) { 0. } else { normal(&mut pages.rng, p.word_spacing_sigma) }; - let advance = g.step(units[i], p, extra, compound); + let advance = g.step(unit, p, extra, compound); pages.x = x + advance; pages.line.push(LineUnit { glyph: g, @@ -910,20 +557,15 @@ fn render_planes( && (p.background_ruled || p.underlined || p.paper_pattern.is_some()), x: x.round() as i32, dy, - break_after: homework_mode && homework::break_after(units[i]), + break_after: homework_mode && homework::break_after(unit), id: node_index as u32, - source: source.as_ref().map(|positions| { - [ - positions[node_index], - positions[node_index + units[i].len()], - ] - }), + source: source + .as_ref() + .map(|positions| [positions[node_index], positions[next_node_index]]), fine_parts, }); } } - node_index += units[i].len(); - i += 1; } if !pages.stopped { pages.flush(pages.count == 0)?; diff --git a/crates/handwriting-core/src/render/composition.rs b/crates/handwriting-core/src/render/composition.rs new file mode 100644 index 00000000..b9ee6c71 --- /dev/null +++ b/crates/handwriting-core/src/render/composition.rs @@ -0,0 +1,129 @@ +//! Build the ink for one document unit before measuring it for the current line. +use super::{Glyph, Glyphs, fine, glyph, normal}; +use crate::{Parameters, Result, text::Node}; +use rand::RngExt; +use rand_chacha::ChaCha8Rng; + +pub(super) struct PreparedGlyph { + pub(super) glyph: Glyph, + pub(super) compound: bool, + pub(super) fine_parts: Option, +} + +pub(super) struct UnitComposer<'a> { + p: &'a Parameters, + text: &'a str, + source: Option<&'a [u32]>, + page_size: (u32, u32), + // Captured on the first simulated mistake; repeated mistakes use the same candidate order. + candidates: Option>, +} + +impl<'a> UnitComposer<'a> { + pub(super) fn new( + p: &'a Parameters, + text: &'a str, + source: Option<&'a [u32]>, + page_size: (u32, u32), + ) -> Self { + Self { + p, + text, + source, + page_size, + candidates: None, + } + } + + pub(super) fn prepare( + &mut self, + glyphs: &mut Glyphs<'_>, + rng: &mut ChaCha8Rng, + unit: &[Node], + index: usize, + node_index: usize, + ) -> Result { + let p = self.p; + let size = (p.font_size + normal(rng, p.font_size_sigma)).clamp(1., 2048.); + let (glyph, fine_parts) = if p.fine_edit + && unit.len() > 1 + && unit.iter().all(|node| matches!(node, Node::Char(_))) + { + let (advance, children) = glyphs.sequence_parts(unit, size, 0)?; + let glyph = Glyphs::compose(advance, children.clone(), vec![])?; + let parts = fine::Parts::new(&glyph, children, node_index, self.source); + (glyph, Some(parts)) + } else { + (glyphs.unit(unit, size, index)?, None) + }; + let node = &unit[0]; + // Proportional text draws the probability for whitespace too, to preserve the seed stream. + if !p.monospaced + && rng.random::() < p.strikethrough_probability + && !matches!(node, Node::Char(c) if c.is_whitespace()) + && let Some(c) = self.wrong_character(rng) + { + let wrong = glyphs.glyph(c, size)?; + return Ok(PreparedGlyph { + glyph: cross_out(wrong, glyph, p, self.page_size, rng)?, + compound: true, + fine_parts: None, + }); + } + let compound = unit.len() > 1 + || !matches!(node, Node::Char(_)) + || matches!(node, Node::Char(c) if glyph::is_circled(*c)); + Ok(PreparedGlyph { + glyph, + compound, + fine_parts, + }) + } + + fn wrong_character(&mut self, rng: &mut ChaCha8Rng) -> Option { + let candidates = self.candidates.get_or_insert_with(|| { + self.text + .chars() + .filter(|c| !c.is_whitespace() && !",。!?,.!?".contains(*c)) + .take(1024) + .collect() + }); + if candidates.is_empty() { + return None; + } + Some(candidates[rng.random_range(0..candidates.len())]) + } +} + +fn cross_out( + wrong: Glyph, + correct: Glyph, + p: &Parameters, + (w, h): (u32, u32), + rng: &mut ChaCha8Rng, +) -> Result { + let length = (p.font_size * 2f32.sqrt() + normal(rng, p.strikethrough_length_sigma)) + .clamp(0., (w as f32 + h as f32).min(16384.)); + let angle = (45. + normal(rng, p.strikethrough_angle_sigma)).to_radians(); + let width = (p.strikethrough_width + normal(rng, p.strikethrough_width_sigma)) + .clamp(1., (w.min(h) as f32).clamp(1., 256.)) as i32; + let sy = wrong.top as f32 + length / 7.; + let path = vec![ + ((length / 7.).round() as i32, sy.round() as i32), + ( + (length / 7. + length * angle.cos() * 5. / 7.).round() as i32, + (sy + length * angle.sin() * 5. / 7.).round() as i32, + ), + ]; + // 2026-10-15:正确字写在错字和完整删除线之后,不能让较长删除线划到正确内容。 + let stroke_right = path.iter().map(|point| point.0).max().unwrap_or(0) + width / 2 + 2; + let shift = (wrong.advance + p.word_spacing) + .max(wrong.right() as f32) + .max(stroke_right as f32) + .round() as i32; + Glyphs::compose( + correct.advance + shift as f32, + vec![(wrong, 0, 0), (correct, shift, 0)], + vec![(path, width)], + ) +} diff --git a/crates/handwriting-core/src/render/glyph.rs b/crates/handwriting-core/src/render/glyph.rs index f0ea2039..3d8082b6 100644 --- a/crates/handwriting-core/src/render/glyph.rs +++ b/crates/handwriting-core/src/render/glyph.rs @@ -66,6 +66,11 @@ impl Glyph { glyph } pub fn fit(mut self, width: f32, height: f32) -> Self { + self.fit_in_place(width, height); + self + } + + pub(super) fn fit_in_place(&mut self, width: f32, height: f32) { let footprint = self.advance.max(self.right() as f32) - self.left.min(0) as f32; let ratio = (width / footprint.max(1.)) .min(height / self.mask.height() as f32) @@ -85,7 +90,6 @@ impl Glyph { self.top = (self.top as f32 * ratio).floor() as i32; self.advance = (self.advance * ratio).floor().max(1.); } - self } } pub(super) struct Glyphs<'a> { diff --git a/crates/handwriting-core/src/render/glyph/circuit.rs b/crates/handwriting-core/src/render/glyph/circuit.rs index 38ca3d66..7a861c4f 100644 --- a/crates/handwriting-core/src/render/glyph/circuit.rs +++ b/crates/handwriting-core/src/render/glyph/circuit.rs @@ -5,6 +5,8 @@ use rand::RngExt; use rand_chacha::ChaCha8Rng; use std::f32::consts::{PI, TAU}; +mod branch; + #[derive(Clone, Copy)] enum Stroke { Pen, @@ -291,172 +293,7 @@ impl Glyphs<'_> { }; let mut labels: Vec<(String, Point, i32)> = Vec::new(); for segment in &circuit.segments { - let a = segment.start; - let b = segment.end; - let dx = b.0 - a.0; - let dy = b.1 - a.1; - let length = dx.hypot(dy); - let ux = dx / length; - let uy = dy / length; - let mid = Point((a.0 + b.0) / 2., (a.1 + b.1) / 2.); - let half = 0.38f32.min(length * 0.32); - let h = 0.15f32.min(half * 0.6); - let p = |x: f32, y: f32| Point(mid.0 + ux * x - uy * y, mid.1 + uy * x + ux * y); - let kind = segment.kind.as_str(); - if kind == "short" { - draw.line(a, b); - if segment.end_arrow { - draw.arrowhead(a, b); - } - } else if kind != "open" { - draw.line(a, p(-half, 0.)); - draw.line(p(half, 0.), b); - match kind { - "R" if circuit.american => { - let mut points = vec![p(-half, 0.)]; - for i in 0..7 { - points.push(p( - -half + half * (i as f32 + 0.5) / 3.5, - if i % 2 == 0 { h } else { -h }, - )); - } - points.push(p(half, 0.)); - draw.path(points); - } - "R" => draw.path(vec![ - p(-half, 0.), - p(-half, h), - p(half, h), - p(half, 0.), - p(half, -h), - p(-half, -h), - p(-half, 0.), - ]), - "C" => { - draw.line(p(-half, 0.), p(-0.055, 0.)); - draw.line(p(0.055, 0.), p(half, 0.)); - draw.line_through(p(-0.055, -h * 1.5), p(-0.055, 0.), p(-0.055, h * 1.5)); - draw.line_through(p(0.055, -h * 1.5), p(0.055, 0.), p(0.055, h * 1.5)); - } - "L" => { - let radius = half / 4.; - let mut points = Vec::new(); - for loop_index in 0..4 { - for i in 0..=12 { - let t = PI - i as f32 * PI / 12.; - points.push(p( - -half - + radius * (2. * loop_index as f32 + 1.) - + radius * t.cos(), - radius * t.sin() * 1.9, - )); - } - } - draw.path(points); - } - "V" | "I" | "sV" => { - let radius = 0.32f32.min(half); - draw.line(p(-half, 0.), p(-radius, 0.)); - draw.line(p(radius, 0.), p(half, 0.)); - draw.contact_circle(mid, radius, uy.atan2(ux)); - if kind == "I" { - draw.arrow(p(-radius * 0.55, 0.), p(radius * 0.55, 0.)); - } else if kind == "V" { - let plus = p(radius * 0.48, 0.); - let minus = p(-radius * 0.48, 0.); - let mark = h * 0.36; - draw.line(Point(plus.0 - mark, plus.1), Point(plus.0 + mark, plus.1)); - draw.line(Point(plus.0, plus.1 - mark), Point(plus.0, plus.1 + mark)); - draw.line( - Point(minus.0 - mark, minus.1), - Point(minus.0 + mark, minus.1), - ); - } else { - draw.path( - (0..=24) - .map(|i| { - let x = -radius * 0.6 + i as f32 * radius * 1.2 / 24.; - // 2026-10-22:交流波形保持正立,仅支路引线与端子随方向旋转。 - Point( - mid.0 + x, - mid.1 + (i as f32 * 2. * PI / 24.).sin() * h * 0.7, - ) - }) - .collect(), - ); - } - } - "battery1" => { - draw.line(p(-half, 0.), p(-0.055, 0.)); - draw.line(p(0.055, 0.), p(half, 0.)); - draw.line_through(p(0.055, -h * 1.5), p(0.055, 0.), p(0.055, h * 1.5)); - draw.line_through(p(-0.055, -h * 0.75), p(-0.055, 0.), p(-0.055, h * 0.75)); - } - "D" | "led" => { - draw.line(p(-half, 0.), p(-h, 0.)); - draw.line(p(h, 0.), p(half, 0.)); - draw.path(vec![p(-h, -h), p(h, 0.), p(-h, h), p(-h, 0.), p(-h, -h)]); - draw.line_through(p(h, -h), p(h, 0.), p(h, h)); - if kind == "led" { - draw.arrow(p(0., h * 1.7), p(h * 0.9, h * 2.6)); - draw.arrow(p(h * 0.9, h * 1.7), p(h * 1.8, h * 2.6)); - } - } - "switch" | "closing switch" | "opening switch" => { - draw.dot(p(-half, 0.), true); - draw.dot(p(half, 0.), true); - draw.line(p(-half + 0.055, 0.), p(half - 0.055, h * 1.7)); - if kind != "switch" { - let (a, b) = if kind == "closing switch" { - (p(0., h * 2.5), p(0., h * 0.8)) - } else { - (p(0., h * 0.8), p(0., h * 2.5)) - }; - draw.arrow(a, b); - } - } - _ => return Err(Error::new("invalid_layout", "不支持的电路元件")), - } - } - for (point, mark) in [(a, segment.marks.0), (b, segment.marks.1)] { - if mark == '*' || mark == 'o' { - draw.dot(point, mark == 'o'); - } - } - let mut lanes = std::collections::HashMap::::new(); - for label in &segment.labels { - let side = if label.kind == 'a' { - -label.side - } else { - label.side - }; - let occupied = lanes.entry(if side > 0. { 1 } else { -1 }).or_default(); - let base = - if side > 0. && matches!(kind, "led" | "closing switch" | "opening switch") { - 0.85 - } else { - 0.48 - }; - let offset = base + *occupied as f32 * 0.55; - *occupied += 1; - let pos = if matches!(label.kind, 'i' | 'v') { - p(0., (offset + 0.34) * side) - } else { - p(0., offset * side) - }; - let anchor = if uy.abs() > 0.5 { - if -uy * side < 0. { -1 } else { 1 } - } else { - 0 - }; - labels.push((label.text.clone(), pos, anchor)); - if matches!(label.kind, 'i' | 'v') { - draw.arrow( - p(-half * 1.1 * label.direction, (offset + 0.05) * side), - p(half * 1.1 * label.direction, (offset + 0.05) * side), - ); - } - } + branch::draw(&mut draw, segment, circuit.american, &mut labels)?; } for decoration in &circuit.decorations { let p = decoration.point; diff --git a/crates/handwriting-core/src/render/glyph/circuit/branch.rs b/crates/handwriting-core/src/render/glyph/circuit/branch.rs new file mode 100644 index 00000000..4ac769c5 --- /dev/null +++ b/crates/handwriting-core/src/render/glyph/circuit/branch.rs @@ -0,0 +1,240 @@ +//! Circuit symbols and annotations use coordinates relative to the directed branch. +use super::{Drawing, Point}; +use crate::{Error, Result, text::circuit::Segment}; +use std::f32::consts::PI; + +pub(super) fn draw( + draw: &mut Drawing, + segment: &Segment, + american: bool, + labels: &mut Vec<(String, Point, i32)>, +) -> Result<()> { + let a = segment.start; + let b = segment.end; + let frame = BranchFrame::between(a, b); + match segment.kind.as_str() { + "short" => { + draw.line(a, b); + if segment.end_arrow { + draw.arrowhead(a, b); + } + } + "open" => (), + kind => { + draw.line(a, frame.point(-frame.half, 0.)); + draw.line(frame.point(frame.half, 0.), b); + frame.symbol(draw, kind, american)?; + } + } + for (point, mark) in [(a, segment.marks.0), (b, segment.marks.1)] { + if mark == '*' || mark == 'o' { + draw.dot(point, mark == 'o'); + } + } + frame.annotate(draw, segment, labels); + Ok(()) +} + +struct BranchFrame { + mid: Point, + ux: f32, + uy: f32, + half: f32, + height: f32, +} + +impl BranchFrame { + fn between(a: Point, b: Point) -> Self { + let dx = b.0 - a.0; + let dy = b.1 - a.1; + let length = dx.hypot(dy); + let half = 0.38f32.min(length * 0.32); + Self { + mid: Point((a.0 + b.0) / 2., (a.1 + b.1) / 2.), + ux: dx / length, + uy: dy / length, + half, + height: 0.15f32.min(half * 0.6), + } + } + + fn point(&self, x: f32, y: f32) -> Point { + Point( + self.mid.0 + self.ux * x - self.uy * y, + self.mid.1 + self.uy * x + self.ux * y, + ) + } + + fn symbol(&self, draw: &mut Drawing, kind: &str, american: bool) -> Result<()> { + let (half, h) = (self.half, self.height); + match kind { + "R" if american => { + let mut points = vec![self.point(-half, 0.)]; + for i in 0..7 { + points.push(self.point( + -half + half * (i as f32 + 0.5) / 3.5, + if i % 2 == 0 { h } else { -h }, + )); + } + points.push(self.point(half, 0.)); + draw.path(points); + } + "R" => draw.path(vec![ + self.point(-half, 0.), + self.point(-half, h), + self.point(half, h), + self.point(half, 0.), + self.point(half, -h), + self.point(-half, -h), + self.point(-half, 0.), + ]), + "C" => self.plates(draw, [(-0.055, h * 1.5), (0.055, h * 1.5)]), + "L" => self.coil(draw), + "V" | "I" | "sV" => self.source(draw, kind), + "battery1" => self.plates(draw, [(0.055, h * 1.5), (-0.055, h * 0.75)]), + "D" | "led" => { + draw.line(self.point(-half, 0.), self.point(-h, 0.)); + draw.line(self.point(h, 0.), self.point(half, 0.)); + draw.path(vec![ + self.point(-h, -h), + self.point(h, 0.), + self.point(-h, h), + self.point(-h, 0.), + self.point(-h, -h), + ]); + draw.line_through(self.point(h, -h), self.point(h, 0.), self.point(h, h)); + if kind == "led" { + draw.arrow(self.point(0., h * 1.7), self.point(h * 0.9, h * 2.6)); + draw.arrow(self.point(h * 0.9, h * 1.7), self.point(h * 1.8, h * 2.6)); + } + } + "switch" | "closing switch" | "opening switch" => { + draw.dot(self.point(-half, 0.), true); + draw.dot(self.point(half, 0.), true); + draw.line( + self.point(-half + 0.055, 0.), + self.point(half - 0.055, h * 1.7), + ); + if kind != "switch" { + let (a, b) = if kind == "closing switch" { + (self.point(0., h * 2.5), self.point(0., h * 0.8)) + } else { + (self.point(0., h * 0.8), self.point(0., h * 2.5)) + }; + draw.arrow(a, b); + } + } + _ => return Err(Error::new("invalid_layout", "不支持的电路元件")), + } + Ok(()) + } + + fn plates(&self, draw: &mut Drawing, plates: [(f32, f32); 2]) { + draw.line(self.point(-self.half, 0.), self.point(-0.055, 0.)); + draw.line(self.point(0.055, 0.), self.point(self.half, 0.)); + for (x, height) in plates { + draw.line_through( + self.point(x, -height), + self.point(x, 0.), + self.point(x, height), + ); + } + } + + fn coil(&self, draw: &mut Drawing) { + let half = self.half; + let radius = half / 4.; + let mut points = Vec::new(); + for loop_index in 0..4 { + for i in 0..=12 { + let t = PI - i as f32 * PI / 12.; + points.push(self.point( + -half + radius * (2. * loop_index as f32 + 1.) + radius * t.cos(), + radius * t.sin() * 1.9, + )); + } + } + draw.path(points); + } + + fn source(&self, draw: &mut Drawing, kind: &str) { + let (half, h) = (self.half, self.height); + let radius = 0.32f32.min(half); + draw.line(self.point(-half, 0.), self.point(-radius, 0.)); + draw.line(self.point(radius, 0.), self.point(half, 0.)); + draw.contact_circle(self.mid, radius, self.uy.atan2(self.ux)); + if kind == "I" { + draw.arrow( + self.point(-radius * 0.55, 0.), + self.point(radius * 0.55, 0.), + ); + } else if kind == "V" { + let plus = self.point(radius * 0.48, 0.); + let minus = self.point(-radius * 0.48, 0.); + let mark = h * 0.36; + draw.line(Point(plus.0 - mark, plus.1), Point(plus.0 + mark, plus.1)); + draw.line(Point(plus.0, plus.1 - mark), Point(plus.0, plus.1 + mark)); + draw.line( + Point(minus.0 - mark, minus.1), + Point(minus.0 + mark, minus.1), + ); + } else { + draw.path( + (0..=24) + .map(|i| { + let x = -radius * 0.6 + i as f32 * radius * 1.2 / 24.; + // 2026-10-22:交流波形保持正立,仅支路引线与端子随方向旋转。 + Point( + self.mid.0 + x, + self.mid.1 + (i as f32 * 2. * PI / 24.).sin() * h * 0.7, + ) + }) + .collect(), + ); + } + } + + fn annotate( + &self, + draw: &mut Drawing, + segment: &Segment, + labels: &mut Vec<(String, Point, i32)>, + ) { + let kind = segment.kind.as_str(); + let half = self.half; + let mut lanes = [0usize; 2]; + for label in &segment.labels { + let side = if label.kind == 'a' { + -label.side + } else { + label.side + }; + let occupied = &mut lanes[usize::from(side > 0.)]; + let base = if side > 0. && matches!(kind, "led" | "closing switch" | "opening switch") { + 0.85 + } else { + 0.48 + }; + let offset = base + *occupied as f32 * 0.55; + *occupied += 1; + let has_arrow = matches!(label.kind, 'i' | 'v'); + let pos = if has_arrow { + self.point(0., (offset + 0.34) * side) + } else { + self.point(0., offset * side) + }; + let anchor = if self.uy.abs() > 0.5 { + if -self.uy * side < 0. { -1 } else { 1 } + } else { + 0 + }; + labels.push((label.text.clone(), pos, anchor)); + if has_arrow { + draw.arrow( + self.point(-half * 1.1 * label.direction, (offset + 0.05) * side), + self.point(half * 1.1 * label.direction, (offset + 0.05) * side), + ); + } + } + } +} diff --git a/crates/handwriting-core/src/render/glyph/pen.rs b/crates/handwriting-core/src/render/glyph/pen.rs index b65eb6af..2a78cb53 100644 --- a/crates/handwriting-core/src/render/glyph/pen.rs +++ b/crates/handwriting-core/src/render/glyph/pen.rs @@ -3,6 +3,8 @@ use super::{Glyph, Glyphs, Path}; use crate::Result; use image::GrayImage; +mod sample; + pub(super) struct MathPen { width: f32, axis: f32, @@ -15,121 +17,9 @@ pub(super) struct MathPen { } impl MathPen { - pub fn sample(font: &fontdue::Font) -> Self { - let size = 96.; - let mut widths = Vec::new(); - for c in ['n', 'x', '1', '十', '口'] { - if font.lookup_glyph_index(c) == 0 { - continue; - } - let (m, data) = font.rasterize(c, size); - let mut area = 0.; - let mut perimeter = 0.; - for y in 0..m.height { - for x in 0..m.width { - if data[y * m.width + x] < 96 { - continue; - } - area += 1.; - for (dx, dy) in [(-1, 0), (1, 0), (0, -1), (0, 1)] { - let (xx, yy) = (x as i32 + dx, y as i32 + dy); - if xx < 0 - || yy < 0 - || xx >= m.width as i32 - || yy >= m.height as i32 - || data[yy as usize * m.width + xx as usize] < 96 - { - perimeter += 1.; - } - } - } - } - if perimeter > 0. { - widths.push(2. * area / perimeter / size); - } - } - widths.sort_by(f32::total_cmp); - let width = widths - .get(widths.len() / 2) - .copied() - .unwrap_or(0.025) - .clamp(0.009, 0.065); - let (x, _) = font.rasterize('x', size); - let height = if x.height > 0 { - (x.height as f32 / size).clamp(0.30, 0.70) - } else { - 0.48 - }; - let axis = if x.height > 0 { - -(x.height as f32 / 2. + x.ymin as f32) / size - } else { - -0.27 - }; - let (m, data) = font.rasterize('1', size); - let mut centers = Vec::new(); - for y in m.height / 3..m.height * 2 / 3 { - let xs: Vec<_> = (0..m.width) - .filter(|x| data[y * m.width + x] >= 128) - .collect(); - if !xs.is_empty() { - centers.push((y as f32, xs.iter().sum::() as f32 / xs.len() as f32)); - } - } - let slant = if let (Some(a), Some(b)) = (centers.first(), centers.last()) { - ((a.1 - b.1) / (b.0 - a.0).max(1.)).clamp(-0.12, 0.12) - } else { - 0. - }; - Self { - width, - axis: axis.clamp(-0.4, -0.16), - height, - slant, - chevrons: ['<', '>'].map(|c| Self::sample_chevron(font, c)), - root: super::radical::RootShape::sample(font), - naturalness: 0., - seed: 0, - } - } pub fn thickness(&self, size: f32) -> f32 { (self.width * size).max(0.75) } - fn sample_chevron(font: &fontdue::Font, c: char) -> Option { - if font.lookup_glyph_index(c) == 0 { - return None; - } - let (m, data) = font.rasterize(c, 96.); - if m.width < 3 || m.height < 3 { - return None; - } - let g = Glyphs::trim(Glyph { - mask: GrayImage::from_raw(m.width as u32, m.height as u32, data)?, - advance: m.advance_width, - left: 0, - top: 0, - ink: true, - }); - let mask = g.mask; - let mut bands = [(0., 0.); 3]; - for (x, y, p) in mask.enumerate_pixels() { - if p[0] >= 96 { - let band = (y * 3 / mask.height()).min(2) as usize; - bands[band].0 += x as f32; - bands[band].1 += 1.; - } - } - if bands.iter().any(|b| b.1 == 0.) { - return None; - } - let outer = (bands[0].0 / bands[0].1 + bands[2].0 / bands[2].1) / 2.; - let middle = bands[1].0 / bands[1].1; - let direction = if c == '<' { - outer - middle - } else { - middle - outer - }; - (direction > mask.width() as f32 * 0.12).then_some(mask) - } fn inequality(&self, c: char, size: f32) -> Result> { let Some(source) = &self.chevrons[usize::from(c == '≥')] else { return Ok(None); @@ -219,10 +109,8 @@ impl MathPen { } '≤' | '≥' => { width = w * 0.74; - let less = "<≤".contains(c); - let equal = "≤≥".contains(c); - let center = axis - if equal { h * 0.35 } else { 0. }; - let tip = if less { 0. } else { width }; + let center = axis - h * 0.35; + let tip = if c == '≤' { 0. } else { width }; let end = width - tip; // 2026-10-24:缺字回退也保留不对称收笔,避免理想镜面对称的印刷折角。 paths.push(vec![ @@ -230,10 +118,8 @@ impl MathPen { (tip, center + h * 0.08), (end - width * 0.04, center + h), ]); - if equal { - let bar = center + h + (h * 0.85).max(self.thickness(size) + 2.5); - paths.push(vec![(0., bar), (width, bar)]); - } + let bar = center + h + (h * 0.85).max(self.thickness(size) + 2.5); + paths.push(vec![(0., bar), (width, bar)]); } '≠' => { width = w * 0.78; diff --git a/crates/handwriting-core/src/render/glyph/pen/sample.rs b/crates/handwriting-core/src/render/glyph/pen/sample.rs new file mode 100644 index 00000000..b353a646 --- /dev/null +++ b/crates/handwriting-core/src/render/glyph/pen/sample.rs @@ -0,0 +1,129 @@ +//! Sample the primary font once to choose the geometry of the mathematical pen. +use super::super::radical::RootShape; +use super::{Glyph, Glyphs, GrayImage, MathPen}; +use fontdue::Font; + +const SAMPLE_SIZE: f32 = 96.; + +impl MathPen { + pub fn sample(font: &Font) -> Self { + let mut widths: Vec<_> = ['n', 'x', '1', '十', '口'] + .into_iter() + .filter_map(|c| stroke_width(font, c)) + .collect(); + widths.sort_by(f32::total_cmp); + let width = widths + .get(widths.len() / 2) + .copied() + .unwrap_or(0.025) + .clamp(0.009, 0.065); + let (x, _) = font.rasterize('x', SAMPLE_SIZE); + let (height, axis) = if x.height > 0 { + ( + (x.height as f32 / SAMPLE_SIZE).clamp(0.30, 0.70), + -(x.height as f32 / 2. + x.ymin as f32) / SAMPLE_SIZE, + ) + } else { + (0.48, -0.27) + }; + Self { + width, + axis: axis.clamp(-0.4, -0.16), + height, + slant: slant(font), + chevrons: ['<', '>'].map(|c| sample_chevron(font, c)), + root: RootShape::sample(font), + naturalness: 0., + seed: 0, + } + } +} + +fn stroke_width(font: &Font, c: char) -> Option { + if font.lookup_glyph_index(c) == 0 { + return None; + } + let (m, data) = font.rasterize(c, SAMPLE_SIZE); + let mut area = 0.; + let mut perimeter = 0.; + for y in 0..m.height { + for x in 0..m.width { + if data[y * m.width + x] < 96 { + continue; + } + area += 1.; + for (dx, dy) in [(-1, 0), (1, 0), (0, -1), (0, 1)] { + let (xx, yy) = (x as i32 + dx, y as i32 + dy); + if xx < 0 + || yy < 0 + || xx >= m.width as i32 + || yy >= m.height as i32 + || data[yy as usize * m.width + xx as usize] < 96 + { + perimeter += 1.; + } + } + } + } + + (perimeter > 0.).then(|| 2. * area / perimeter / SAMPLE_SIZE) +} + +fn slant(font: &Font) -> f32 { + let (m, data) = font.rasterize('1', SAMPLE_SIZE); + // The first and last occupied scan lines determine the slope of the digit's middle third. + let mut centers = (m.height / 3..m.height * 2 / 3).filter_map(|y| { + let row = &data[y * m.width..(y + 1) * m.width]; + let mut sum = 0; + let mut count: usize = 0; + for (x, &alpha) in row.iter().enumerate() { + if alpha >= 128 { + sum += x; + count += 1; + } + } + (count > 0).then(|| (y as f32, sum as f32 / count as f32)) + }); + let Some(first) = centers.next() else { + return 0.; + }; + let last = centers.next_back().unwrap_or(first); + ((first.1 - last.1) / (last.0 - first.0).max(1.)).clamp(-0.12, 0.12) +} + +fn sample_chevron(font: &Font, c: char) -> Option { + if font.lookup_glyph_index(c) == 0 { + return None; + } + let (m, data) = font.rasterize(c, SAMPLE_SIZE); + if m.width < 3 || m.height < 3 { + return None; + } + let g = Glyphs::trim(Glyph { + mask: GrayImage::from_raw(m.width as u32, m.height as u32, data)?, + advance: m.advance_width, + left: 0, + top: 0, + ink: true, + }); + let mask = g.mask; + let mut bands = [(0., 0.); 3]; + for (x, y, p) in mask.enumerate_pixels() { + if p[0] >= 96 { + let band = (y * 3 / mask.height()).min(2) as usize; + bands[band].0 += x as f32; + bands[band].1 += 1.; + } + } + if bands.iter().any(|b| b.1 == 0.) { + return None; + } + let outer = (bands[0].0 / bands[0].1 + bands[2].0 / bands[2].1) / 2.; + let middle = bands[1].0 / bands[1].1; + let direction = if c == '<' { + outer - middle + } else { + middle - outer + }; + (direction > mask.width() as f32 * 0.12).then_some(mask) +} diff --git a/crates/handwriting-core/src/render/glyph/radical.rs b/crates/handwriting-core/src/render/glyph/radical.rs index 39493988..0b7b5c3e 100644 --- a/crates/handwriting-core/src/render/glyph/radical.rs +++ b/crates/handwriting-core/src/render/glyph/radical.rs @@ -8,6 +8,13 @@ pub(super) struct RootShape { lead_y: f32, foot_x: f32, } +fn mean(values: impl Iterator) -> f32 { + let (sum, count) = values.fold((0.0, 0usize), |(sum, count), value| { + (sum + value, count + 1) + }); + sum / count as f32 +} + impl RootShape { pub fn sample(font: &fontdue::Font) -> Self { let fallback = Self { @@ -35,15 +42,12 @@ impl RootShape { let max_y = ink.iter().map(|p| p.1).fold(0., f32::max); // 多数手写字库的√只有钩部,并不自带顶线;从上升臂最高点取得接点。 let roof_y = ink.iter().map(|p| p.1).fold(f32::INFINITY, f32::min); - let upper: Vec<_> = ink.iter().filter(|p| p.1 <= roof_y + 1.).collect(); - let roof_x = upper.iter().map(|p| p.0).sum::() / upper.len() as f32; + let roof_x = mean(ink.iter().filter(|p| p.1 <= roof_y + 1.).map(|p| p.0)); if max_y - roof_y < 8. || roof_x - min_x < 4. { return fallback; } - let left: Vec<_> = ink.iter().filter(|p| p.0 <= min_x + 1.).collect(); - let start_y = left.iter().map(|p| p.1).sum::() / left.len() as f32; - let lowest: Vec<_> = ink.iter().filter(|p| p.1 >= max_y - 1.).collect(); - let foot = lowest.iter().map(|p| p.0).sum::() / lowest.len() as f32; + let start_y = mean(ink.iter().filter(|p| p.0 <= min_x + 1.).map(|p| p.1)); + let foot = mean(ink.iter().filter(|p| p.1 >= max_y - 1.).map(|p| p.0)); let lead_x = min_x + (foot - min_x) * 0.45; let lead_y = ink .iter() @@ -147,31 +151,8 @@ impl Glyphs<'_> { ink: true, }; let join = (origin + cx, top + cy); - let bar = if let Some(source) = self.native_stroke('-', size) { - let mask = stretch_bar(&source, (right - join.0 + 1).max(2) as u32); - let contact = mask - .enumerate_pixels() - .filter(|(_, _, p)| p[0] >= 128) - .min_by_key(|(x, y, _)| (*x, *y)) - .map(|(x, y, _)| (x as i32, y as i32)); - if let Some((x, y)) = contact { - Glyph { - mask, - advance: right as f32, - left: join.0 - x, - top: join.1 - y, - ink: true, - } - } else { - self.pen.draw( - size, - right as f32, - &[vec![ - (join.0 as f32, join.1 as f32), - (right as f32, top as f32), - ]], - )? - } + let bar = if let Some(bar) = self.native_bar(size, join, right) { + bar } else { self.pen.draw( size, @@ -190,6 +171,23 @@ impl Glyphs<'_> { .map(Some) } + fn native_bar(&self, size: f32, join: (i32, i32), right: i32) -> Option { + let source = self.native_stroke('-', size)?; + let mask = stretch_bar(&source, (right - join.0 + 1).max(2) as u32); + let (x, y) = mask + .enumerate_pixels() + .filter(|(_, _, p)| p[0] >= 128) + .min_by_key(|(x, y, _)| (*x, *y)) + .map(|(x, y, _)| (x as i32, y as i32))?; + Some(Glyph { + mask, + advance: right as f32, + left: join.0 - x, + top: join.1 - y, + ink: true, + }) + } + fn native_stroke(&self, c: char, size: f32) -> Option { let font = self.book.primary(); if font.lookup_glyph_index(c) == 0 { diff --git a/crates/handwriting-core/src/render/glyph/table.rs b/crates/handwriting-core/src/render/glyph/table.rs index 23584cb0..094e637b 100644 --- a/crates/handwriting-core/src/render/glyph/table.rs +++ b/crates/handwriting-core/src/render/glyph/table.rs @@ -4,8 +4,16 @@ use crate::text::{Table, TableKind, TableRule}; use rand::RngExt; pub(super) mod matrix; -impl Glyphs<'_> { - pub(super) fn table(&mut self, table: &Table, size: f32, depth: usize) -> Result { +/// Every row has the same height, while columns follow the widest ink in each column. +struct TableCells { + rows: Vec>, + column_edges: Vec, + row_height: i32, + pad: i32, +} + +impl TableCells { + fn measure(glyphs: &mut Glyphs<'_>, table: &Table, size: f32, depth: usize) -> Result { let columns = table.vertical.len().saturating_sub(1); if !(1..=32).contains(&columns) || table.rows.is_empty() @@ -16,7 +24,6 @@ impl Glyphs<'_> { return Err(Error::new("invalid_layout", "表格行列结构无效")); } let pad = (size * 0.26).round().max(3.) as i32; - let grid_thickness = (size * 0.025).round().max(1.) as i32; let mut widths = vec![(size * 0.35).round() as i32; columns]; let mut row_height = (size * 0.77).round() as i32; @@ -25,7 +32,7 @@ impl Glyphs<'_> { for row in &table.rows { let mut cells = Vec::new(); for (column, cell) in row.iter().enumerate() { - let g = self.sequence_at(cell, size, depth + 1)?; + let g = glyphs.sequence_at(cell, size, depth + 1)?; bytes = bytes.saturating_add(g.mask.len()); if bytes > 16_000_000 { return Err(Error::new("invalid_layout", "表格子结构超过内存预算")); @@ -34,100 +41,125 @@ impl Glyphs<'_> { row_height = row_height.max(g.mask.height() as i32); cells.push(g); } - rendered.push(cells); } - let mut xs = vec![0]; + let mut column_edges = vec![0]; for width in widths { - xs.push(xs.last().unwrap() + width + pad * 2); - } - let mut ys = vec![0]; - for _ in &table.rows { - ys.push(ys.last().unwrap() + row_height + pad * 2); + column_edges.push(column_edges.last().unwrap() + width + pad * 2); } - let width = *xs.last().unwrap(); - let height = *ys.last().unwrap(); - Self::check_size(width as u32 + 4, height as u32 + 4)?; - let offset = if table.kind == TableKind::Grid { - -height / 2 - } else { - let x = self.glyph('x', size)?; - (x.top + x.bottom()) / 2 - height / 2 - }; - let (inset, delimiters) = matrix::delimiters(table.kind, width, height, size); + Ok(Self { + rows: rendered, + column_edges, + row_height: row_height + pad * 2, + pad, + }) + } + + fn width(&self) -> i32 { + *self.column_edges.last().unwrap() + } + + fn height(&self) -> i32 { + self.rows.len() as i32 * self.row_height + } + + fn positioned(self, kind: TableKind, inset: i32, offset: i32) -> Vec { let mut children = Vec::new(); - for (row, cells) in rendered.into_iter().enumerate() { - for (column, g) in cells.into_iter().enumerate() { - let x = inset - + if table.kind == TableKind::Cases { - xs[column] + pad - g.left - } else { - (xs[column] + xs[column + 1] - g.mask.width() as i32) / 2 - g.left - }; - // 2026-10-20:以实际墨迹居中,避免字体基线差异让数字和分数上下漂移。 - let y = offset + (ys[row] + ys[row + 1] - g.mask.height() as i32) / 2 - g.top; - children.push((g, x, y)); + for (row, cells) in self.rows.into_iter().enumerate() { + for (g, edges) in cells.into_iter().zip(self.column_edges.windows(2)) { + let x = if kind == TableKind::Cases { + edges[0] + self.pad + } else { + (edges[0] + edges[1] - g.mask.width() as i32) / 2 + }; + let y = + row as i32 * self.row_height + (self.row_height - g.mask.height() as i32) / 2; + let (left, top) = (inset + x - g.left, offset + y - g.top); + children.push((g, left, top)); } } + children + } + + fn rules( + &self, + table: &Table, + inset: i32, + offset: i32, + size: f32, + thickness: i32, + ) -> Vec { + let dash = (size * 0.12).round().max(3.) as i32; let mut paths = Vec::new(); - let mut draw = |rule, start: (i32, i32), end: (i32, i32)| { - if table.kind != TableKind::Grid && rule == TableRule::None { - return; - } - let thickness = grid_thickness; - let length = (end.0 - start.0).abs().max((end.1 - start.1).abs()); - if rule != TableRule::Dashed { - paths.push((vec![start, end], thickness)); - } else { - let dash = (size * 0.12).round().max(3.) as i32; - for at in (0..length).step_by((dash * 2) as usize) { - let to = (at + dash).min(length); - let p = |v| { - if start.0 == end.0 { - (start.0, start.1 + v) - } else { - (start.0 + v, start.1) - } - }; - paths.push((vec![p(at), p(to)], thickness)); + let mut draw = |rule, start: (i32, i32), direction: (i32, i32), length| { + let point = |v| (start.0 + direction.0 * v, start.1 + direction.1 * v); + match rule { + TableRule::None if table.kind != TableKind::Grid => (), + TableRule::Dashed => { + for at in (0..length).step_by((dash * 2) as usize) { + paths.push((vec![point(at), point((at + dash).min(length))], thickness)); + } } + _ => paths.push((vec![start, point(length)], thickness)), } }; - for (index, rule) in table.vertical.iter().enumerate() { - draw( - *rule, - (inset + xs[index], offset), - (inset + xs[index], offset + height), - ); + for (&x, &rule) in self.column_edges.iter().zip(&table.vertical) { + draw(rule, (inset + x, offset), (0, 1), self.height()); } - for (index, rule) in table.horizontal.iter().enumerate() { + for (row, &rule) in table.horizontal.iter().enumerate() { draw( - *rule, - (inset, offset + ys[index]), - (inset + width, offset + ys[index]), + rule, + (inset, offset + row as i32 * self.row_height), + (1, 0), + self.width(), ); } + paths + } +} + +impl Glyphs<'_> { + pub(super) fn table(&mut self, table: &Table, size: f32, depth: usize) -> Result { + let cells = TableCells::measure(self, table, size, depth)?; + let (width, height) = (cells.width(), cells.height()); + Self::check_size(width as u32 + 4, height as u32 + 4)?; + let offset = if table.kind == TableKind::Grid { + -height / 2 + } else { + let x = self.glyph('x', size)?; + (x.top + x.bottom()) / 2 - height / 2 + }; + let (inset, delimiters) = matrix::delimiters(table.kind, width, height, size); + let thickness = (size * 0.025).round().max(1.) as i32; + let mut paths = cells.rules(table, inset, offset, size, thickness); let reach = (size * 0.105).min(5.) * self.pen.naturalness; - if table.kind == TableKind::Grid && corner_tails_fit(width, height, grid_thickness, reach) { - // 横竖两笔都经过交点,只让其中一笔沿原方向多走一点。 + if table.kind == TableKind::Grid && corner_tails_fit(width, height, thickness, reach) { + // Draw corner extensions in row order so the pen consumes the same random sequence. let mut rng = self.next_drawing_rng(); - for (row, dy) in [(0, -1), (ys.len() - 1, 1)] { - for (col, dx) in [(0, -1), (columns, 1)] { - if table.horizontal[row] == TableRule::Dashed - || table.vertical[col] == TableRule::Dashed - { + let rows = [ + (0, -1, table.horizontal[0]), + (height, 1, *table.horizontal.last().unwrap()), + ]; + let columns = [ + (0, -1, table.vertical[0]), + (width, 1, *table.vertical.last().unwrap()), + ]; + for (y, dy, horizontal) in rows { + for (x, dx, vertical) in columns { + if horizontal == TableRule::Dashed || vertical == TableRule::Dashed { continue; } let tail = (rng.random_range(-1.0f32..1.) * reach).round() as i32; - if tail != 0 { - let corner = (inset + xs[col], offset + ys[row]); - let tip = if tail > 0 { - (corner.0 + dx * tail, corner.1) - } else { - (corner.0, corner.1 + dy * tail.abs()) - }; - paths.push((vec![corner, tip], grid_thickness)); + if tail == 0 { + continue; } + let corner = (inset + x, offset + y); + let tip = if tail > 0 { + (corner.0 + dx * tail, corner.1) + } else { + (corner.0, corner.1 + dy * tail.abs()) + }; + paths.push((vec![corner, tip], thickness)); } } } @@ -142,7 +174,9 @@ impl Glyphs<'_> { } else { inset }; - let mut result = Self::compose((width + inset + right + pad) as f32, children, paths)?; + let advance = (width + inset + right + cells.pad) as f32; + let mut result = + Self::compose(advance, cells.positioned(table.kind, inset, offset), paths)?; if table.kind == TableKind::Matrix { let axis = self.glyph('x', size)?; result.top += (axis.top + axis.bottom() - result.top - result.bottom()) / 2; diff --git a/crates/handwriting-core/src/render/homework.rs b/crates/handwriting-core/src/render/homework.rs index f7225d93..69677b3a 100644 --- a/crates/handwriting-core/src/render/homework.rs +++ b/crates/handwriting-core/src/render/homework.rs @@ -15,103 +15,84 @@ pub(super) fn parameters(source: &Parameters, width: u32, height: u32) -> Parame p } -pub(super) fn units(nodes: &[Node]) -> Vec<&[Node]> { - let original = layout_units(nodes); - let mut output: Vec<&[Node]> = Vec::new(); - let mut offset = 0; - let mut i = 0; - while i < original.len() { - let mut end = i + 1; - if matches!(original[i].first(),Some(Node::Char(c)) if c.is_ascii_alphanumeric()) { - while end < original.len() - && end - i < 24 - && matches!(original[end].first(),Some(Node::Char(c)) if c.is_ascii_alphanumeric()) - { - end += 1; - } - } else if let Some(Node::Char(open @ ('(' | '[' | '('))) = original[i].first() { - let close = match open { - '(' => ')', - '[' => ']', - _ => ')', - }; - let mut depth = 1; - for (j, unit) in original.iter().enumerate().skip(i + 1).take(24) { - match unit.first() { - Some( - Node::Newline - | Node::Break - | Node::Image { .. } - | Node::Table(_) - | Node::Circuit(_), - ) => break, - Some(Node::Char(c)) if c == open => depth += 1, - Some(Node::Char(c)) if *c == close => { - depth -= 1; - if depth == 0 { - end = j + 1; - break; - } - } - _ => (), +fn structural(node: &Node) -> bool { + matches!( + node, + Node::Break | Node::Newline | Node::Image { .. } | Node::Table(_) | Node::Circuit(_) + ) +} + +/// Count base units, keeping scripts attached to their base throughout the bounded lookahead. +fn cluster_len(units: &[&[Node]]) -> usize { + let ascii_word = |unit: &[Node]| matches!(unit[0], Node::Char(c) if c.is_ascii_alphanumeric()); + if ascii_word(units[0]) { + return units.iter().take(24).take_while(|u| ascii_word(u)).count(); + } + let Node::Char(open @ ('(' | '[' | '(')) = units[0][0] else { + return 1; + }; + let close = match open { + '(' => ')', + '[' => ']', + _ => ')', + }; + let mut depth = 1; + for (i, unit) in units.iter().enumerate().skip(1).take(24) { + match &unit[0] { + node if structural(node) => break, + Node::Char(c) if *c == open => depth += 1, + Node::Char(c) if *c == close => { + depth -= 1; + if depth == 0 { + return i + 1; } } + _ => (), } - let length: usize = original[i..end].iter().map(|u| u.len()).sum(); - let slice = &nodes[offset..offset + length]; - if matches!(slice,[Node::Char(c)] if ",。;:!?、,.!?;:)])】".contains(*c)) - && output.last().is_some_and(|u| { - u.len() + slice.len() <= 64 && { - !matches!( - u[0], - Node::Newline - | Node::Break - | Node::Image { .. } - | Node::Table(_) - | Node::Circuit(_) - ) - } - }) - { - let previous = output.pop().unwrap(); - output.push(&nodes[offset - previous.len()..offset + length]); - } else { - output.push(slice); - } - offset += length; - i = end; } - // 2026-10-24:关系符与首个右侧单元一起换行,空格不能把箭头孤立在上一行。 + 1 +} + +fn word_groups(mut units: &[&[Node]]) -> impl Iterator> { + let mut end = 0; + std::iter::from_fn(move || { + let first = units.first()?; + let start = end; + let (group, remaining) = units.split_at(cluster_len(units)); + end += group.iter().map(|unit| unit.len()).sum::(); + units = remaining; + // Closing punctuation attaches to the preceding group, up to 64 source nodes. + if !structural(&first[0]) { + while end - start < 64 + && matches!(units.first(), Some(&[Node::Char(c)]) if ",。;:!?、,.!?;:)])】".contains(*c)) + { + end += 1; + units = &units[1..]; + } + } + Some(start..end) + }) +} + +pub(super) fn units(nodes: &[Node]) -> Vec<&[Node]> { + let bases = layout_units(nodes); + let mut groups = word_groups(&bases).peekable(); let mut joined = Vec::new(); - let mut i = 0; - let mut offset = 0; - while i < output.len() { - let mut end = i + 1; - if break_before(output[i]) { - while end < output.len() - && output[end] + while let Some(mut span) = groups.next() { + if break_before(&nodes[span.clone()]) { + // The relation, any spaces, and its first right-hand group wrap together. + while let Some(space) = groups.next_if(|r| { + nodes[r.clone()] .iter() .all(|n| matches!(n,Node::Char(c) if c.is_whitespace())) - { - end += 1; + }) { + span.end = space.end; } - if end < output.len() - && !matches!( - output[end][0], - Node::Break - | Node::Newline - | Node::Image { .. } - | Node::Table(_) - | Node::Circuit(_) - ) - { - end += 1; + if let Some(rhs) = groups.next_if(|r| !structural(&nodes[r.start])) { + span.end = rhs.end; } } - let length: usize = output[i..end].iter().map(|u| u.len()).sum(); - joined.push(&nodes[offset..offset + length]); - offset += length; - i = end; + joined.push(&nodes[span]); } joined } @@ -221,6 +202,17 @@ mod tests { } } #[test] + fn word_and_punctuation_limits_apply_before_joining_relations() { + let source = format!("{}{}⇒ a,b\n。", "x".repeat(25), ",".repeat(64)); + let nodes = text::parse(&source); + let groups = units(&nodes); + assert_eq!( + groups.iter().map(|g| g.len()).collect::>(), + [24, 64, 1, 5, 1, 1, 1] + ); + assert_eq!(groups[3], text::parse("⇒ a,")); + } + #[test] fn paragraphs_identify_questions_and_subitems_without_guessing_equations() { for (source, sub, heading) in [ ("1. 邻域", false, true), diff --git a/crates/handwriting-core/src/render/line.rs b/crates/handwriting-core/src/render/line.rs new file mode 100644 index 00000000..aab7e283 --- /dev/null +++ b/crates/handwriting-core/src/render/line.rs @@ -0,0 +1,165 @@ +//! Vertical placement of buffered ink, including formulas spanning multiple paper rulings. +use super::LineUnit; +use crate::{LayoutStyle, Parameters}; +use image::GrayImage; + +pub(super) struct LineLayout { + top: f32, + bottom: f32, + gap: f32, + spacing: f32, + ruled: bool, + min_y: i32, + max_y: i32, +} + +impl LineLayout { + pub(super) fn fit(units: &mut [LineUnit], p: &Parameters, page_height: u32) -> Self { + let top = p.top_margin; + let bottom = page_height as f32 - p.bottom_margin; + let available = (bottom - top).max(1.); + let ruled = ((p.underlined || p.paper_pattern.is_some()) && p.width.is_some()) + || p.background_ruled; + let mut gap = (p.font_size * 0.12).round().max(2.); + let (mut min_y, mut max_y) = ink_bounds(units); + if (max_y - min_y) as f32 > available { + let factor = available / (max_y - min_y) as f32; + scale_units(units, min_y, factor, f32::floor); + (min_y, max_y) = ink_bounds(units); + } + if ruled && p.layout_style == LayoutStyle::Standard { + gap = gap.min((p.line_spacing - p.font_size).max(2.)); + let height = (p.line_spacing - gap).floor() as i32; + let descent = (p.font_size * 0.30).round() as i32; + if fit_standard_ruled_row(units, min_y, max_y, height, descent) { + (min_y, max_y) = ink_bounds(units); + } + } + Self { + top, + bottom, + gap, + spacing: p.line_spacing, + ruled, + min_y, + max_y, + } + } + + pub(super) fn baseline(&self, cursor: f32, previous_bottom: Option) -> f32 { + let mut anchor = cursor.max(self.top - self.min_y as f32); + if let Some(bottom) = previous_bottom { + anchor = anchor.max(bottom + self.gap - self.min_y as f32); + } + if self.ruled { + // A tall formula can span several rows. The following baseline stays on the paper grid. + self.top + + (((anchor - self.top) / self.spacing) - 0.00001) + .ceil() + .max(1.) + * self.spacing + } else { + anchor + } + } + + pub(super) fn ink_bottom(&self, anchor: f32) -> f32 { + anchor + self.max_y as f32 + } + + pub(super) fn overflows(&self, anchor: f32) -> bool { + self.ink_bottom(anchor) > self.bottom + } + + pub(super) fn fit_empty_page(&mut self, units: &mut [LineUnit]) -> f32 { + if !self.ruled { + return self.bottom - self.max_y as f32; + } + // Use the first ruling that allows the largest scale on an otherwise empty page. + let mut best = (0f32, self.top + self.spacing); + for row in 1usize.. { + let baseline = self.top + row as f32 * self.spacing; + if baseline >= self.bottom { + break; + } + let above = if self.min_y < 0 { + ((baseline - self.top - 1.) / -(self.min_y as f32)).max(0.) + } else { + 1. + }; + let below = if self.max_y > 0 { + ((self.bottom - baseline - 1.) / self.max_y as f32).max(0.) + } else { + 1. + }; + let factor = above.min(below).min(1.); + if factor > best.0 { + best = (factor, baseline); + } + } + scale_units(units, 0, best.0, f32::round); + (self.min_y, self.max_y) = ink_bounds(units); + best.1 + } +} + +fn ink_bounds(units: &[LineUnit]) -> (i32, i32) { + units + .iter() + .filter(|unit| unit.glyph.ink) + .map(|unit| (unit.glyph.top + unit.dy, unit.glyph.bottom() + unit.dy)) + .reduce(|(top, bottom), (next_top, next_bottom)| { + (top.min(next_top), bottom.max(next_bottom)) + }) + .unwrap_or((0, 0)) +} + +// Page-height fitting starts at the visible top; fitting to a ruling preserves the baseline. +fn scale_units(units: &mut [LineUnit], origin: i32, factor: f32, round: fn(f32) -> f32) { + for unit in units { + let offset = unit.glyph.top + unit.dy - origin; + let width = unit.glyph.mask.width() as f32 * factor; + let height = (unit.glyph.mask.height() as f32 * factor).max(1.); + unit.glyph.fit_in_place(width, height); + unit.dy = round(offset as f32 * factor) as i32 - unit.glyph.top; + } +} + +fn fit_standard_ruled_row( + units: &mut [LineUnit], + min_y: i32, + max_y: i32, + height: i32, + descent: i32, +) -> bool { + let ink_height = max_y - min_y; + let top = descent - height; + if height <= 0 + || ink_height <= 0 + || ink_height as f32 > height as f32 * 1.2 + || (min_y >= top && max_y <= descent) + { + return false; + } + // 2026-11-17:轻微越界先在同一行格内纵向适配,保留横向字距和高公式的跨行避让。 + let fit_height = height.min(ink_height); + let start = min_y.clamp(top, descent - fit_height); + for unit in units.iter_mut().filter(|unit| unit.glyph.ink) { + let offset = unit.glyph.top + unit.dy - min_y; + let end = offset + unit.glyph.mask.height() as i32; + let first = offset * fit_height / ink_height; + let last = (end * fit_height + ink_height - 1) / ink_height; + let new_height = (last - first) as u32; + if new_height != unit.glyph.mask.height() { + let mut mask = GrayImage::new(unit.glyph.mask.width(), new_height); + // 2026-11-17:合并缩小后落在同一行的像素,保留分数线等细笔画。 + for (x, y, pixel) in unit.glyph.mask.enumerate_pixels() { + let row = (y * new_height) / unit.glyph.mask.height(); + mask[(x, row)][0] = mask[(x, row)][0].max(pixel[0]); + } + unit.glyph.mask = mask; + } + unit.dy = start + first - unit.glyph.top; + } + true +} diff --git a/crates/handwriting-core/src/render/paragraph.rs b/crates/handwriting-core/src/render/paragraph.rs new file mode 100644 index 00000000..9cdadba7 --- /dev/null +++ b/crates/handwriting-core/src/render/paragraph.rs @@ -0,0 +1,215 @@ +//! 段首缩进、作业续行和标准排版的词组断行共享同一条行缓冲。 +use super::{Glyph, Glyphs, LineUnit, PageInk, Pages, homework, units}; +use crate::{LayoutStyle, Result, text::Node}; +use image::RgbaImage; + +pub(super) struct ParagraphLayout<'a> { + nodes: &'a [Node], + units: &'a [&'a [Node]], + right: f32, + continuation: f32, + group_start: usize, + section_line_start: usize, +} + +impl<'a> ParagraphLayout<'a> { + pub(super) fn new(nodes: &'a [Node], units: &'a [&'a [Node]], left: f32, right: f32) -> Self { + Self { + nodes, + units, + right, + continuation: left, + group_start: 0, + section_line_start: 0, + } + } + + pub(super) fn usable_width(&self) -> f32 { + self.right - self.continuation + } + + pub(super) fn begin_unit( + &mut self, + pages: &mut Pages<'_, F>, + glyphs: &mut Glyphs<'_>, + i: usize, + ) -> Result<()> + where + F: FnMut(usize, RgbaImage, Option) -> Result<()>, + { + let node = &self.units[i][0]; + if matches!(node, Node::Newline | Node::Break) + || (i > 0 && !matches!(self.units[i - 1][0], Node::Newline | Node::Break)) + { + return Ok(()); + } + let p = pages.p; + let indent_first = p.first_line_indent + && !matches!(node, Node::RightAlign | Node::Char(' ' | '\t' | '\u{3000}')); + if p.layout_style == LayoutStyle::Standard { + if indent_first { + pages.x = (p.left_margin + 2. * p.font_size).min(self.right - p.font_size); + } + } else { + let style = homework::paragraph(&self.units[i..], p.font_size); + let available = self.right - p.left_margin; + let indent = if indent_first { + (2. * p.font_size).min(available - p.font_size) + } else { + style.indent.min(available * 0.15) + }; + let prefix: Vec<_> = self.units[i..] + .iter() + .flat_map(|unit| unit.iter()) + .take(style.prefix_chars) + .cloned() + .collect(); + let hanging = if prefix.is_empty() { + 0. + } else { + glyphs.unit(&prefix, p.font_size, i)?.advance + p.word_spacing + }; + self.continuation = p.left_margin + indent + hanging.min(available * 0.25); + pages.x = p.left_margin + indent; + if style.gap_before { + if (style.title || pages.written_lines - self.section_line_start >= 3) + && pages.dirty + && i >= 2 + && !matches!(self.units[i - 2][0], Node::Newline | Node::Break) + { + pages.y += p.line_spacing; + } + self.section_line_start = pages.written_lines; + } + } + Ok(()) + } + + /// An overflowing separator or a finished page prefix consumes the unit without drawing it. + pub(super) fn position( + &mut self, + pages: &mut Pages<'_, F>, + i: usize, + glyph: &Glyph, + cell: Option, + jitter_x: f32, + ) -> Result> + where + F: FnMut(usize, RgbaImage, Option) -> Result<()>, + { + let p = pages.p; + let right = self.right; + let origin = |cursor: f32| { + (cursor + jitter_x) + .round() + .max(p.left_margin - glyph.left as f32) + }; + let mut x = origin(pages.x); + let footprint = cell.unwrap_or_else(|| glyph.right() as f32); + + if p.layout_style == LayoutStyle::Homework { + if !pages.line.is_empty() && x + footprint > right { + pages.homework_wrap(self.continuation, right)?; + if !pages.line.is_empty() && pages.x + glyph.right() as f32 > right { + pages.finish_line()?; + pages.x = self.continuation; + } + x = origin(pages.x); + } + } else { + if pages.line.is_empty() || units::starts_wrap_group(self.units, i) { + self.group_start = pages.line.len(); + } + let closing = + matches!(self.units[i], [Node::Char(c)] if units::closing_punctuation(*c)); + // Use spare trailing whitespace before moving a closing mark to another line. + if closing + && x + footprint > right + && i > 0 + && matches!(self.units[i - 1], [Node::Char(c)] if c.is_whitespace()) + && let Some(last) = pages.line.iter().rev().find(|u| u.glyph.ink) + && (last.x + last.glyph.right()) as f32 <= right - footprint + { + x = right - footprint; + } + if !pages.line.is_empty() && x + footprint > right { + if matches!(self.units[i], [Node::Char(' ' | '\t')]) { + pages.x = right; + return Ok(None); + } + let split = self.standard_split(&pages.line, p.left_margin, x + footprint, closing); + let bearing = split.map_or(0, |at| pages.line[at].glyph.left.min(0)); + pages.wrap_at(split, p.left_margin - bearing as f32)?; + self.group_start = 0; + x = origin(pages.x); + } + } + if pages.stopped { + return Ok(None); + } + Ok(Some( + x.min(right - glyph.right() as f32) + .max(p.left_margin - glyph.left as f32), + )) + } + + fn standard_split( + &self, + line: &[LineUnit], + margin: f32, + end: f32, + closing: bool, + ) -> Option { + let fits = |at: usize| { + line.get(at).is_some_and(|first| { + // Reclaim the indent of a first word before falling back to character boundaries. + let bearing = first.glyph.left.min(0) as f32; + (at > 0 || first.x as f32 > (margin - bearing).round()) + && end - first.x as f32 - bearing <= self.usable_width() + }) + }; + if fits(self.group_start) { + return Some(self.group_start); + } + if !closing { + return None; + } + line.iter() + .rposition(|unit| { + let node = &self.nodes[unit.id as usize]; + unit.glyph.ink && !matches!(node, Node::Char(c) if units::closing_punctuation(*c)) + }) + .filter(|&at| fits(at)) + } +} + +impl) -> Result<()>> Pages<'_, F> { + // 2026-10-24:将末尾短语整体移至续行,已渲染的结构化公式保持原子性。 + fn homework_wrap(&mut self, continuation: f32, right: f32) -> Result<()> { + let cutoff = self.p.left_margin + (right - self.p.left_margin) * 0.4; + let split = self + .line + .iter() + .enumerate() + .rev() + .find(|(i, u)| u.break_after && *i + 1 < self.line.len() && u.x as f32 >= cutoff) + .map(|(i, _)| i + 1); + self.wrap_at(split, continuation) + } + fn wrap_at(&mut self, split: Option, continuation: f32) -> Result<()> { + let mut tail = split.map(|at| self.line.split_off(at)).unwrap_or_default(); + let old_cursor = self.x; + self.finish_line()?; + if let Some(first) = tail.first() { + let shift = continuation - first.x as f32; + for unit in &mut tail { + unit.x += shift.round() as i32; + } + self.x = old_cursor + shift; + self.line = tail; + } else { + self.x = continuation; + } + Ok(()) + } +} diff --git a/crates/handwriting-core/src/text.rs b/crates/handwriting-core/src/text.rs index f7692ccc..a2bd8e93 100644 --- a/crates/handwriting-core/src/text.rs +++ b/crates/handwriting-core/src/text.rs @@ -38,6 +38,7 @@ pub enum TableKind { Cases, } pub mod circuit; +mod math; mod table; pub fn normalize(text: &str, english_spacing: bool) -> String { @@ -385,88 +386,13 @@ fn parse_inline(s: &str, depth: usize) -> Vec { continue; } } - let mut rad_start = None; - let mut index = Vec::new(); - if cs[i] == '√' || cs[i] == '∛' || cs[i] == '∜' { - if cs[i] != '√' { - index.push(Node::Char(if cs[i] == '∛' { '3' } else { '4' })); - } - rad_start = Some(i + 1); - } else if cs[i..].starts_with(&['\\', 's', 'q', 'r', 't']) - && cs.get(i + 5).is_none_or(|c| !c.is_ascii_alphabetic()) - { - let mut p = i + 5; - while cs.get(p) == Some(&' ') { - p += 1; - } - if cs.get(p) == Some(&'[') - && let Some(e) = pairs.get(p).copied().flatten() - { - index = nodes(&cs[p + 1..e], depth); - p = e + 1; - } - while cs.get(p) == Some(&' ') { - p += 1; - } - rad_start = Some(p); - } else if "⁰¹²³⁴⁵⁶⁷⁸⁹ⁿ".contains(cs[i]) { - let mut p = i; - while p < cs.len() && "⁰¹²³⁴⁵⁶⁷⁸⁹ⁿ".contains(cs[p]) { - p += 1; - } - if cs.get(p) == Some(&'√') { - index = cs[i..p] - .iter() - .map(|&c| Node::Char(script_char(c).map_or(c, |(v, _)| v))) - .collect(); - rad_start = Some(p + 1); - } - } - if let Some(mut p) = rad_start { - while cs.get(p) == Some(&' ') { - p += 1; - } - if let Some(&open) = cs.get(p) - && (open == '(' || open == '{') - && let Some(e) = pairs.get(p).copied().flatten() - { - out.push(Node::Radical(nodes(&cs[p + 1..e], depth), index)); - i = e + 1; - continue; - } - let start = p; - while p < cs.len() && (token(cs[p]) || ('α'..='ω').contains(&cs[p])) { - p += 1; - } - if p > start { - out.push(Node::Radical(nodes(&cs[start..p], depth), index)); - i = p; - continue; - } + if let Some((radical, end)) = math::radical(&cs, &pairs, i, depth) { + out.push(radical); + i = end; + continue; } - let vulgar = match cs[i] { - '½' => Some(("1", "2")), - '⅓' => Some(("1", "3")), - '⅔' => Some(("2", "3")), - '¼' => Some(("1", "4")), - '¾' => Some(("3", "4")), - '⅕' => Some(("1", "5")), - '⅖' => Some(("2", "5")), - '⅗' => Some(("3", "5")), - '⅘' => Some(("4", "5")), - '⅙' => Some(("1", "6")), - '⅚' => Some(("5", "6")), - '⅛' => Some(("1", "8")), - '⅜' => Some(("3", "8")), - '⅝' => Some(("5", "8")), - '⅞' => Some(("7", "8")), - _ => None, - }; - if let Some((n, d)) = vulgar { - out.push(Node::Fraction( - parse_inline(n, depth + 1), - parse_inline(d, depth + 1), - )); + if let Some(fraction) = math::vulgar_fraction(cs[i]) { + out.push(fraction); i += 1; continue; } @@ -531,50 +457,10 @@ fn parse_inline(s: &str, depth: usize) -> Vec { i = end; continue; } - // 括号表达式或连续 token 的分式,嵌套结构受深度上限约束。 - let mut end = i; - let mut numerator = None; - if cs[i] == '(' { - if let Some(e) = pairs.get(i).copied().flatten() { - end = e + 1; - numerator = Some(&cs[i + 1..e]); - } - } else if token(cs[i]) && (i == 0 || !token(cs[i - 1])) { - while end < cs.len() && token(cs[end]) { - end += 1; - } - numerator = Some(&cs[i..end]); - } - // 斜线紧邻两侧操作数时才视为分式简写。 - if let Some(num) = numerator - && cs.get(end) == Some(&'/') - { - let start = end + 1; - let mut den_end = start; - let mut denominator = None; - if cs.get(start) == Some(&'(') { - if let Some(e) = pairs.get(start).copied().flatten() { - den_end = e + 1; - denominator = Some(&cs[start + 1..e]); - } - } else { - while den_end < cs.len() && token(cs[den_end]) { - den_end += 1; - } - if den_end > start { - if cs.get(den_end) == Some(&'(') - && let Some(e) = pairs.get(den_end).copied().flatten() - { - den_end = e + 1; - } - denominator = Some(&cs[start..den_end]); - } - } - if let Some(den) = denominator { - out.push(Node::Fraction(nodes(num, depth), nodes(den, depth))); - i = den_end; - continue; - } + if let Some((fraction, end)) = math::slash_fraction(&cs, &pairs, i, depth) { + out.push(fraction); + i = end; + continue; } out.push(Node::Char(cs[i])); i += 1; diff --git a/crates/handwriting-core/src/text/circuit.rs b/crates/handwriting-core/src/text/circuit.rs index 230768cb..8f39b13e 100644 --- a/crates/handwriting-core/src/text/circuit.rs +++ b/crates/handwriting-core/src/text/circuit.rs @@ -34,25 +34,16 @@ pub struct Circuit { pub const BEGIN: &str = "\\begin{circuitikz}"; pub const END: &str = "\\end{circuitikz}"; -fn component_name(name: &str) -> Option<&str> { - Some(match name { - "R" | "resistor" => "R", - "C" | "capacitor" => "C", - "L" | "inductor" => "L", - "V" | "vsource" => "V", - "I" | "isource" => "I", - "sV" | "sinusoidal voltage source" => "sV", - "battery" | "battery1" => "battery1", - "D" | "diode" => "D", - "led" => "led", - "short" => "short", - "open" => "open", - "switch" => "switch", - "closing switch" => "closing switch", - "opening switch" => "opening switch", - _ => return None, - }) +mod labels; +mod options; +use options::{Component, split_options}; + +enum Route { + Direct, + VerticalFirst, + HorizontalFirst, } + struct Parser<'a> { source: &'a str, at: usize, @@ -198,27 +189,21 @@ impl<'a> Parser<'a> { text: if text.is_empty() { String::new() } else { - label_text(&text)? + labels::normalize(&text)? }, }); Some(()) } - fn segment( - &mut self, - kind: String, - labels: Vec